code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/* Copyright (C) 2022, Specify Collections Consortium
*
* Specify Collections Consortium, Biodiversity Institute, University of Kansas,
* 1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA, support@specifysoftware.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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package edu.ku.brc.af.ui.forms.persist;
import static edu.ku.brc.helpers.XMLHelper.getAttr;
import static edu.ku.brc.ui.UIHelper.createDuplicateJGoodiesDef;
import static edu.ku.brc.ui.UIRegistry.getResourceString;
import static org.apache.commons.lang.StringUtils.isEmpty;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.table.DefaultTableModel;
import org.apache.commons.betwixt.XMLIntrospector;
import org.apache.commons.betwixt.io.BeanWriter;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Element;
import org.dom4j.Node;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import edu.ku.brc.af.core.db.DBFieldInfo;
import edu.ku.brc.af.core.db.DBRelationshipInfo;
import edu.ku.brc.af.core.db.DBTableChildIFace;
import edu.ku.brc.af.core.db.DBTableIdMgr;
import edu.ku.brc.af.core.db.DBTableInfo;
import edu.ku.brc.af.prefs.AppPreferences;
import edu.ku.brc.af.ui.forms.FormDataObjIFace;
import edu.ku.brc.af.ui.forms.FormHelper;
import edu.ku.brc.af.ui.forms.formatters.UIFieldFormatterIFace;
import edu.ku.brc.af.ui.forms.formatters.UIFieldFormatterMgr;
import edu.ku.brc.af.ui.forms.validation.TypeSearchForQueryFactory;
import edu.ku.brc.ui.CustomFrame;
import edu.ku.brc.ui.UIHelper;
import edu.ku.brc.ui.UIRegistry;
import edu.ku.brc.helpers.XMLHelper;
/**
* Factory that creates Views from ViewSet files. This class uses the singleton ViewSetMgr to verify the View Set Name is unique.
* If it is not unique than it throws an exception.<br> In this case a "form" is really the definition of a form. The form's object hierarchy
* is used to creates the forms using Swing UI objects. The classes will also be used by the forms editor.
* @code_status Beta
**
* @author rods
*/
public class ViewLoader
{
public static final int DEFAULT_ROWS = 4;
public static final int DEFAULT_COLS = 10;
public static final int DEFAULT_SUBVIEW_ROWS = 5;
// Statics
private static final Logger log = Logger.getLogger(ViewLoader.class);
private static final ViewLoader instance = new ViewLoader();
private static final String ID = "id";
private static final String NAME = "name";
private static final String TYPE = "type";
private static final String LABEL = "label";
private static final String DESC = "desc";
private static final String TITLE = "title";
private static final String CLASSNAME = "class";
private static final String GETTABLE = "gettable";
private static final String SETTABLE = "settable";
private static final String INITIALIZE = "initialize";
private static final String DSPUITYPE = "dspuitype";
private static final String VALIDATION = "validation";
private static final String ISREQUIRED = "isrequired";
private static final String RESOURCELABELS = "useresourcelabels";
// Data Members
protected boolean doingResourceLabels = false;
protected String viewSetName = null;
// Members needed for verification
protected static boolean doFieldVerification = true;
protected static boolean isTreeClass = false;
protected static DBTableInfo fldVerTableInfo = null;
protected static FormViewDef fldVerFormViewDef = null;
protected static String colDefType = null;
protected static CustomFrame verifyDlg = null;
protected FieldVerifyTableModel fldVerTableModel = null;
// Debug
//protected static ViewDef gViewDef = null;
static
{
doFieldVerification = AppPreferences.getLocalPrefs().getBoolean("verify_field_names", false);
}
/**
* Default Constructor
*
*/
protected ViewLoader()
{
// do nothing
}
/**
* Creates the view.
* @param element the element to build the View from
* @param altViewsViewDefName the hashtable to track the AltView's ViewDefName
* @return the View
* @throws Exception
*/
protected static ViewIFace createView(final Element element,
final Hashtable<AltViewIFace, String> altViewsViewDefName) throws Exception
{
String name = element.attributeValue(NAME);
String objTitle = getAttr(element, "objtitle", null);
String className = element.attributeValue(CLASSNAME);
String desc = getDesc(element);
String businessRules = getAttr(element, "busrules", null);
boolean isInternal = getAttr(element, "isinternal", true);
DBTableInfo ti = DBTableIdMgr.getInstance().getByClassName(className);
if (ti != null && StringUtils.isEmpty(objTitle))
{
objTitle = ti.getTitle();
}
View view = new View(instance.viewSetName,
name,
objTitle,
className,
businessRules != null ? businessRules.trim() : null,
getAttr(element, "usedefbusrule", true),
isInternal,
desc);
// Later we should get this from a properties file.
if (ti != null)
{
view.setTitle(ti.getTitle());
}
/*if (!isInternal)
{
System.err.println(StringUtils.replace(name, " ", "_")+"="+UIHelper.makeNamePretty(name));
}*/
Element altviews = (Element)element.selectSingleNode("altviews");
if (altviews != null)
{
AltViewIFace defaultAltView = null;
AltView.CreationMode defaultMode = AltView.parseMode(getAttr(altviews, "mode", ""), AltViewIFace.CreationMode.VIEW);
String selectorName = altviews.attributeValue("selector");
view.setDefaultMode(defaultMode);
view.setSelectorName(selectorName);
Hashtable<String, Boolean> nameCheckHash = new Hashtable<String, Boolean>();
// iterate through child elements
for ( Iterator<?> i = altviews.elementIterator( "altview" ); i.hasNext(); )
{
Element altElement = (Element) i.next();
AltView.CreationMode mode = AltView.parseMode(getAttr(altElement, "mode", ""), AltViewIFace.CreationMode.VIEW);
String altName = altElement.attributeValue(NAME);
String viewDefName = altElement.attributeValue("viewdef");
String title = altElement.attributeValue(TITLE);
boolean isValidated = getAttr(altElement, "validated", mode == AltViewIFace.CreationMode.EDIT);
boolean isDefault = getAttr(altElement, "default", false);
// Make sure we only have one default view
if (defaultAltView != null && isDefault)
{
isDefault = false;
}
// Check to make sure all the AlViews have different names.
Boolean nameExists = nameCheckHash.get(altName);
if (nameExists == null) // no need to check the boolean
{
AltView altView = new AltView(view, altName, title, mode, isValidated, isDefault, null); // setting a null viewdef
altViewsViewDefName.put(altView, viewDefName);
if (StringUtils.isNotEmpty(selectorName))
{
altView.setSelectorName(selectorName);
String selectorValue = altElement.attributeValue("selector_value");
if (StringUtils.isNotEmpty(selectorValue))
{
altView.setSelectorValue(selectorValue);
} else
{
FormDevHelper.appendFormDevError("Selector Value is missing for viewDefName["+viewDefName+"] altName["+altName+"]");
}
}
if (defaultAltView == null && isDefault)
{
defaultAltView = altView;
}
view.addAltView(altView);
nameCheckHash.put(altName, true);
} else
{
log.error("The altView name["+altName+"] already exists!");
}
nameCheckHash.clear(); // why not?
}
// No default Alt View was indicated, so choose the first one (if there is one)
if (defaultAltView == null && view.getAltViews() != null && view.getAltViews().size() > 0)
{
view.getAltViews().get(0).setDefault(true);
}
}
return view;
}
/**
* Creates a ViewDef
* @param element the element to build the ViewDef from
* @return a viewdef
* @throws Exception
*/
private static ViewDef createViewDef(final Element element) throws Exception
{
String name = element.attributeValue(NAME);
String className = element.attributeValue(CLASSNAME);
String gettableClassName = element.attributeValue(GETTABLE);
String settableClassName = element.attributeValue(SETTABLE);
String desc = getDesc(element);
String resLabels = getAttr(element, RESOURCELABELS, "false");
boolean useResourceLabels = resLabels.equals("true");
if (isEmpty(name))
{
FormDevHelper.appendFormDevError("Name is null for element["+element.asXML()+"]");
return null;
}
if (isEmpty(className))
{
FormDevHelper.appendFormDevError("className is null. name["+name+"] for element["+element.asXML()+"]");
return null;
}
if (isEmpty(gettableClassName))
{
FormDevHelper.appendFormDevError("gettableClassName Name is null.name["+name+"] classname["+className+"]");
return null;
}
DBTableInfo tableinfo = DBTableIdMgr.getInstance().getByClassName(className);
ViewDef.ViewType type = null;
try
{
type = ViewDefIFace.ViewType.valueOf(element.attributeValue(TYPE));
} catch (Exception ex)
{
String msg = "view["+name+"] has illegal type["+element.attributeValue(TYPE)+"]";
log.error(msg, ex);
FormDevHelper.appendFormDevError(msg, ex);
return null;
}
ViewDef viewDef = null;//new ViewDef(type, name, className, gettableClassName, settableClassName, desc);
switch (type)
{
case rstable:
case formtable :
case form :
viewDef = createFormViewDef(element, type, name, className, gettableClassName, settableClassName, desc, useResourceLabels, tableinfo);
break;
case table :
//view = createTableView(element, id, name, className, gettableClassName, settableClassName,
// desc, instance.doingResourceLabels, isValidated);
break;
case field :
//view = createFormView(FormView.ViewType.field, element, id, name, gettableClassName, settableClassName,
// className, desc, instance.doingResourceLabels, isValidated);
break;
case iconview:
viewDef = createIconViewDef(type, name, className, gettableClassName, settableClassName, desc, useResourceLabels);
break;
}
return viewDef;
}
/**
* Gets the optional description text
* @param element the parent element of the desc node
* @return the string of the text or null
*/
protected static String getDesc(final Element element)
{
String desc = null;
Element descElement = (Element)element.selectSingleNode(DESC);
if (descElement != null)
{
desc = descElement.getTextTrim();
}
return desc;
}
/**
* Fill the Vector with all the views from the DOM document
* @param doc the DOM document conforming to form.xsd
* @param views the list to be filled
* @throws Exception for duplicate view set names or if a Form ID is not unique
*/
public static String getViews(final Element doc,
final Hashtable<String, ViewIFace> views,
final Hashtable<AltViewIFace, String> altViewsViewDefName) throws Exception
{
instance.viewSetName = doc.attributeValue(NAME);
/*
System.err.println("#################################################");
System.err.println("# "+instance.viewSetName);
System.err.println("#################################################");
*/
Element viewsElement = (Element)doc.selectSingleNode("views");
if (viewsElement != null)
{
for ( Iterator<?> i = viewsElement.elementIterator( "view" ); i.hasNext(); )
{
Element element = (Element) i.next(); // assume element is NOT null, if it is null it will cause an exception
ViewIFace view = createView(element, altViewsViewDefName);
if (view != null)
{
if (views.get(view.getName()) == null)
{
views.put(view.getName(), view);
} else
{
String msg = "View Set ["+instance.viewSetName+"] ["+view.getName()+"] is not unique.";
log.error(msg);
FormDevHelper.appendFormDevError(msg);
}
}
}
}
return instance.viewSetName;
}
/**
* Fill the Vector with all the views from the DOM document
* @param doc the DOM document conforming to form.xsd
* @param viewDefs the list to be filled
* @param doMapDefinitions tells it to map and clone the definitions for formtables (use false for the FormEditor)
* @return the viewset name
* @throws Exception for duplicate view set names or if a ViewDef name is not unique
*/
public static String getViewDefs(final Element doc,
final Hashtable<String, ViewDefIFace> viewDefs,
@SuppressWarnings("unused") final Hashtable<String, ViewIFace> views,
final boolean doMapDefinitions) throws Exception
{
colDefType = AppPreferences.getLocalPrefs().get("ui.formatting.formtype", UIHelper.getOSTypeAsStr());
instance.viewSetName = doc.attributeValue(NAME);
Element viewDefsElement = (Element)doc.selectSingleNode("viewdefs");
if (viewDefsElement != null)
{
for ( Iterator<?> i = viewDefsElement.elementIterator( "viewdef" ); i.hasNext(); )
{
Element element = (Element) i.next(); // assume element is NOT null, if it is null it will cause an exception
ViewDef viewDef = createViewDef(element);
if (viewDef != null)
{
if (viewDefs.get(viewDef.getName()) == null)
{
viewDefs.put(viewDef.getName(), viewDef);
} else
{
String msg = "View Set ["+instance.viewSetName+"] the View Def Name ["+viewDef.getName()+"] is not unique.";
log.error(msg);
FormDevHelper.appendFormDevError(msg);
}
}
}
if (doMapDefinitions)
{
mapDefinitionViewDefs(viewDefs);
}
}
return instance.viewSetName;
}
/**
* Re-maps and clones the definitions.
* @param viewDefs the hash table to be mapped
* @throws Exception
*/
public static void mapDefinitionViewDefs(final Hashtable<String, ViewDefIFace> viewDefs) throws Exception
{
// Now that all the definitions have been read in
// cycle thru and have all the tableform objects clone there definitions
for (ViewDefIFace viewDef : new Vector<ViewDefIFace>(viewDefs.values()))
{
if (viewDef.getType() == ViewDefIFace.ViewType.formtable)
{
String viewDefName = ((FormViewDefIFace)viewDef).getDefinitionName();
if (viewDefName != null)
{
//log.debug(viewDefName);
ViewDefIFace actualDef = viewDefs.get(viewDefName);
if (actualDef != null)
{
viewDefs.remove(viewDef.getName());
actualDef = (ViewDef)actualDef.clone();
actualDef.setType(ViewDefIFace.ViewType.formtable);
actualDef.setName(viewDef.getName());
viewDefs.put(actualDef.getName(), actualDef);
} else
{
String msg = "Couldn't find the ViewDef for formtable definition name["+((FormViewDefIFace)viewDef).getDefinitionName()+"]";
log.error(msg);
FormDevHelper.appendFormDevError(msg);
}
}
}
}
}
/**
* Processes all the AltViews
* @param aFormView the form they should be associated with
* @param aElement the element to process
*/
public static Hashtable<String, String> getEnableRules(final Element element)
{
Hashtable<String, String> rulesList = new Hashtable<String, String>();
if (element != null)
{
Element enableRules = (Element)element.selectSingleNode("enableRules");
if (enableRules != null)
{
// iterate through child elements of root with element name "foo"
for ( Iterator<?> i = enableRules.elementIterator( "rule" ); i.hasNext(); )
{
Element ruleElement = (Element) i.next();
String id = getAttr(ruleElement, ID, "");
if (isNotEmpty(id))
{
rulesList.put(id, ruleElement.getTextTrim());
} else
{
String msg = "The name is missing for rule["+ruleElement.getTextTrim()+"] is missing.";
log.error(msg);
FormDevHelper.appendFormDevError(msg);
}
}
}
} else
{
log.error("View Set ["+instance.viewSetName+"] element ["+element+"] is null.");
}
return rulesList;
}
/**
* Gets the string (or creates one) from a columnDef
* @param element the DOM element to process
* @param attrName the name of the element to go get all the elements (strings) from
* @param numRows the number of rows
* @param item
* @return the String representing the column definition for JGoodies
*/
protected static String createDef(final Element element,
final String attrName,
final int numRows,
final FormViewDef.JGDefItem item)
{
Element cellDef = null;
if (attrName.equals("columnDef"))
{
// For columnDef(s) we can mark one or more as being platform specific
// but if we can't find a default one (no 'os' defined)
// then we ultimately pick the first one.
List<?> list = element.selectNodes(attrName);
if (list.size() == 1)
{
cellDef = (Element)list.get(0); // pick the first one if there is only one.
} else
{
String osTypeStr = UIHelper.getOSTypeAsStr();
Element defCD = null;
Element defOSCD = null;
Element ovrOSCD = null;
for (Object obj : list)
{
Element ce = (Element)obj;
String osType = getAttr(ce, "os", null);
if (osType == null)
{
defCD = ce; // ok we found the default one
} else
{
if (osType.equals(osTypeStr))
{
defOSCD = ce; // we found the matching our OS
}
if (colDefType != null && osType.equals(colDefType))
{
ovrOSCD = ce; // we found the one matching prefs
}
}
}
if (ovrOSCD != null)
{
cellDef = ovrOSCD;
} else if (defOSCD != null)
{
cellDef = defOSCD;
} else if (defCD != null)
{
cellDef = defCD;
} else
{
// ok, we couldn't find one for our platform, so use the default
// or pick the first one.
cellDef = (Element)list.get(0);
}
}
} else
{
// this is for rowDef
cellDef = (Element)element.selectSingleNode(attrName);
}
if (cellDef != null)
{
String cellText = cellDef.getText();
String cellStr = getAttr(cellDef, "cell", null);
String sepStr = getAttr(cellDef, "sep", null);
item.setDefStr(cellText);
item.setCellDefStr(cellStr);
item.setSepDefStr(sepStr);
if (StringUtils.isNotEmpty(cellStr) && StringUtils.isNotEmpty(sepStr))
{
boolean auto = getAttr(cellDef, "auto", false);
item.setAuto(auto);
if (auto)
{
String autoStr = createDuplicateJGoodiesDef(cellStr, sepStr, numRows) +
(StringUtils.isNotEmpty(cellText) ? ("," + cellText) : "");
item.setDefStr(autoStr);
return autoStr;
}
// else
FormDevHelper.appendFormDevError("Element ["+element.getName()+"] Cell or Sep is null for 'dup' or 'auto 'on column def.");
return "";
}
// else
item.setAuto(false);
return cellText;
}
// else
String msg = "Element ["+element.getName()+"] must have a columnDef";
log.error(msg);
FormDevHelper.appendFormDevError(msg);
return "";
}
/**
* Returns a resource string if it is suppose to
* @param label the label or the label key
* @return Returns a resource string if it is suppose to
*/
protected static String getResourceLabel(final String label)
{
if (isNotEmpty(label) && StringUtils.deleteWhitespace(label).length() > 0)
{
return instance.doingResourceLabels ? getResourceString(label) : label;
}
// else
return "";
}
/**
* Returns a Label from the cell and gets the resource string for it if necessary
* @param cellElement the cell
* @param labelId the Id of the resource or the string
* @return the localized string (if necessary)
*/
protected static String getLabel(final Element cellElement)
{
String lbl = getAttr(cellElement, LABEL, null);
if (lbl == null || lbl.equals("##"))
{
return "##";
}
return getResourceLabel(lbl);
}
/**
* Processes all the rows
* @param element the parent DOM element of the rows
* @param cellRows the list the rows are to be added to
*/
protected static void processRows(final Element element,
final List<FormRowIFace> cellRows,
final DBTableInfo tableinfo)
{
Element rowsElement = (Element)element.selectSingleNode("rows");
if (rowsElement != null)
{
byte rowNumber = 0;
for ( Iterator<?> i = rowsElement.elementIterator( "row" ); i.hasNext(); )
{
Element rowElement = (Element) i.next();
FormRow formRow = new FormRow();
formRow.setRowNumber(rowNumber);
for ( Iterator<?> cellIter = rowElement.elementIterator( "cell" ); cellIter.hasNext(); )
{
Element cellElement = (Element)cellIter.next();
String cellId = getAttr(cellElement, ID, "");
String cellName = getAttr(cellElement, NAME, cellId); // let the name default to the id if it doesn't have a name
int colspan = getAttr(cellElement, "colspan", 1);
int rowspan = getAttr(cellElement, "rowspan", 1);
/*boolean isReq = getAttr(cellElement, ISREQUIRED, false);
if (isReq)
{
System.err.println(String.format("%s\t%s\t%s\t%s", gViewDef.getName(), cellId, cellName, tableinfo != null ? tableinfo.getTitle() : "N/A"));
}*/
FormCell.CellType cellType = null;
FormCellIFace cell = null;
try
{
cellType = FormCellIFace.CellType.valueOf(cellElement.attributeValue(TYPE));
} catch (java.lang.IllegalArgumentException ex)
{
FormDevHelper.appendFormDevError(ex.toString());
FormDevHelper.appendFormDevError(String.format("Cell Name[%s] Id[%s] Type[%s]", cellName, cellId, cellElement.attributeValue(TYPE)));
return;
}
if (doFieldVerification &&
fldVerTableInfo != null &&
cellType == FormCellIFace.CellType.field &&
StringUtils.isNotEmpty(cellId) &&
!cellName.equals("this"))
{
processFieldVerify(cellName, cellId, rowNumber);
}
switch (cellType)
{
case label:
{
cell = formRow.addCell(new FormCellLabel(cellId,
cellName,
getLabel(cellElement),
getAttr(cellElement, "labelfor", ""),
getAttr(cellElement, "icon", null),
getAttr(cellElement, "recordobj", false),
colspan));
String initialize = getAttr(cellElement, INITIALIZE, null);
if (StringUtils.isNotEmpty(initialize))
{
cell.setProperties(UIHelper.parseProperties(initialize));
}
break;
}
case separator:
{
cell = formRow.addCell(new FormCellSeparator(cellId,
cellName,
getLabel(cellElement),
getAttr(cellElement, "collapse", ""),
colspan));
String initialize = getAttr(cellElement, INITIALIZE, null);
if (StringUtils.isNotEmpty(initialize))
{
cell.setProperties(UIHelper.parseProperties(initialize));
}
break;
}
case field:
{
String uitypeStr = getAttr(cellElement, "uitype", "");
String format = getAttr(cellElement, "format", "");
String formatName = getAttr(cellElement, "formatname", "");
String uiFieldFormatterName = getAttr(cellElement, "uifieldformatter", "");
int cols = getAttr(cellElement, "cols", DEFAULT_COLS); // XXX PREF for default width of text field
int rows = getAttr(cellElement, "rows", DEFAULT_ROWS); // XXX PREF for default heightof text area
String validationType = getAttr(cellElement, "valtype", "Changed");
String validationRule = getAttr(cellElement, VALIDATION, "");
String initialize = getAttr(cellElement, INITIALIZE, "");
boolean isRequired = getAttr(cellElement, ISREQUIRED, false);
String pickListName = getAttr(cellElement, "picklist", "");
if (isNotEmpty(format) && isNotEmpty(formatName))
{
String msg = "Both format and formatname cannot both be set! ["+cellName+"] ignoring format";
log.error(msg);
FormDevHelper.appendFormDevError(msg);
format = "";
}
Properties properties = UIHelper.parseProperties(initialize);
if (isEmpty(uitypeStr))
{
// XXX DEBUG ONLY PLease REMOVE LATER
//log.debug("***************************************************************************");
//log.debug("***** Cell Id["+cellId+"] Name["+cellName+"] uitype is empty and should be 'text'. (Please Fix!)");
//log.debug("***************************************************************************");
uitypeStr = "text";
}
// THis switch is used to get the "display type" and
// set up other vars needed for creating the controls
FormCellFieldIFace.FieldType uitype = null;
try
{
uitype = FormCellFieldIFace.FieldType.valueOf(uitypeStr);
} catch (java.lang.IllegalArgumentException ex)
{
FormDevHelper.appendFormDevError(ex.toString());
FormDevHelper.appendFormDevError(String.format("Cell Name[%s] Id[%s] uitype[%s] is in error", cellName, cellId, uitypeStr));
uitype = FormCellFieldIFace.FieldType.text; // default to text
}
String dspUITypeStr = null;
switch (uitype)
{
case textarea:
dspUITypeStr = getAttr(cellElement, DSPUITYPE, "dsptextarea");
break;
case textareabrief:
dspUITypeStr = getAttr(cellElement, DSPUITYPE, "textareabrief");
break;
case querycbx:
{
dspUITypeStr = getAttr(cellElement, DSPUITYPE, "textfieldinfo");
String fmtName = TypeSearchForQueryFactory.getInstance().getDataObjFormatterName(properties.getProperty("name"));
if (isEmpty(formatName) && isNotEmpty(fmtName))
{
formatName = fmtName;
}
break;
}
case formattedtext:
{
validationRule = getAttr(cellElement, VALIDATION, "formatted"); // XXX Is this OK?
dspUITypeStr = getAttr(cellElement, DSPUITYPE, "formattedtext");
//-------------------------------------------------------
// This part should be moved to the ViewFactory
// because it is the only part that need the Schema Information
//-------------------------------------------------------
if (isNotEmpty(uiFieldFormatterName))
{
UIFieldFormatterIFace uiFormatter = UIFieldFormatterMgr.getInstance().getFormatter(uiFieldFormatterName);
if (uiFormatter == null)
{
String msg = "Couldn't find formatter["+uiFieldFormatterName+"]";
log.error(msg);
FormDevHelper.appendFormDevError(msg);
uiFieldFormatterName = "";
uitype = FormCellFieldIFace.FieldType.text;
}
} else // ok now check the schema for the UI formatter
{
if (tableinfo != null)
{
DBFieldInfo fieldInfo = tableinfo.getFieldByName(cellName);
if (fieldInfo != null)
{
if (fieldInfo.getFormatter() != null)
{
uiFieldFormatterName = fieldInfo.getFormatter().getName();
} else if (fieldInfo.getDataClass().isAssignableFrom(Date.class) ||
fieldInfo.getDataClass().isAssignableFrom(Calendar.class))
{
String msg = "Missing Date Formatter for ["+cellName+"]";
log.error(msg);
FormDevHelper.appendFormDevError(msg);
uiFieldFormatterName = "Date";
UIFieldFormatterIFace uiFormatter = UIFieldFormatterMgr.getInstance().getFormatter(uiFieldFormatterName);
if (uiFormatter == null)
{
uiFieldFormatterName = "";
uitype = FormCellFieldIFace.FieldType.text;
}
} else
{
uiFieldFormatterName = "";
uitype = FormCellFieldIFace.FieldType.text;
}
}
}
}
break;
}
case url:
dspUITypeStr = getAttr(cellElement, DSPUITYPE, uitypeStr);
properties = UIHelper.parseProperties(initialize);
break;
case list:
case image:
case tristate:
case checkbox:
case password:
dspUITypeStr = getAttr(cellElement, DSPUITYPE, uitypeStr);
break;
case plugin:
case button:
dspUITypeStr = getAttr(cellElement, DSPUITYPE, uitypeStr);
properties = UIHelper.parseProperties(initialize);
String ttl = properties.getProperty(TITLE);
if (ttl != null)
{
properties.put(TITLE, getResourceLabel(ttl));
}
break;
case spinner:
dspUITypeStr = getAttr(cellElement, DSPUITYPE, "dsptextfield");
properties = UIHelper.parseProperties(initialize);
break;
case combobox:
dspUITypeStr = getAttr(cellElement, DSPUITYPE, "textpl");
if (tableinfo != null)
{
DBFieldInfo fieldInfo = tableinfo.getFieldByName(cellName);
if (fieldInfo != null)
{
if (StringUtils.isNotEmpty(pickListName))
{
fieldInfo.setPickListName(pickListName);
} else
{
pickListName = fieldInfo.getPickListName();
}
}
}
break;
default:
dspUITypeStr = getAttr(cellElement, DSPUITYPE, "dsptextfield");
break;
} //switch
FormCellFieldIFace.FieldType dspUIType = FormCellFieldIFace.FieldType.valueOf(dspUITypeStr);
try
{
dspUIType = FormCellFieldIFace.FieldType.valueOf(dspUITypeStr);
} catch (java.lang.IllegalArgumentException ex)
{
FormDevHelper.appendFormDevError(ex.toString());
FormDevHelper.appendFormDevError(String.format("Cell Name[%s] Id[%s] dspuitype[%s] is in error", cellName, cellId, dspUIType));
uitype = FormCellFieldIFace.FieldType.label; // default to text
}
// check to see see if the validation is a node in the cell
if (isEmpty(validationRule))
{
Element valNode = (Element)cellElement.selectSingleNode(VALIDATION);
if (valNode != null)
{
String str = valNode.getTextTrim();
if (isNotEmpty(str))
{
validationRule = str;
}
}
}
boolean isEncrypted = getAttr(cellElement, "isencrypted", false);
boolean isReadOnly = uitype == FormCellFieldIFace.FieldType.dsptextfield ||
uitype == FormCellFieldIFace.FieldType.dsptextarea ||
uitype == FormCellFieldIFace.FieldType.label;
FormCellField field = new FormCellField(FormCellIFace.CellType.field, cellId,
cellName, uitype, dspUIType, format, formatName, uiFieldFormatterName, isRequired,
cols, rows, colspan, rowspan, validationType, validationRule, isEncrypted);
String labelStr = uitype == FormCellFieldIFace.FieldType.checkbox ? getLabel(cellElement) : getAttr(cellElement, "label", "");
field.setLabel(labelStr);
field.setReadOnly(getAttr(cellElement, "readonly", isReadOnly));
field.setDefaultValue(getAttr(cellElement, "default", ""));
field.setPickListName(pickListName);
field.setChangeListenerOnly(getAttr(cellElement, "changesonly", true) && !isRequired);
field.setProperties(properties);
cell = formRow.addCell(field);
break;
}
case command:
{
cell = formRow.addCell(new FormCellCommand(cellId, cellName,
getLabel(cellElement),
getAttr(cellElement, "commandtype", ""),
getAttr(cellElement, "action", "")));
String initialize = getAttr(cellElement, INITIALIZE, null);
if (StringUtils.isNotEmpty(initialize))
{
cell.setProperties(UIHelper.parseProperties(initialize));
}
break;
}
case panel:
{
FormCellPanel cellPanel = new FormCellPanel(cellId, cellName,
getAttr(cellElement, "paneltype", ""),
getAttr(cellElement, "coldef", "p"),
getAttr(cellElement, "rowdef", "p"),
colspan, rowspan);
String initialize = getAttr(cellElement, INITIALIZE, null);
if (StringUtils.isNotEmpty(initialize))
{
cellPanel.setProperties(UIHelper.parseProperties(initialize));
}
processRows(cellElement, cellPanel.getRows(), tableinfo);
fixLabels(cellPanel.getName(), cellPanel.getRows(), tableinfo);
cell = formRow.addCell(cellPanel);
break;
}
case subview:
{
Properties properties = UIHelper.parseProperties(getAttr(cellElement, INITIALIZE, null));
String svViewSetName = cellElement.attributeValue("viewsetname");
if (isEmpty(svViewSetName))
{
svViewSetName = null;
}
if (instance.doingResourceLabels && properties != null)
{
String title = properties.getProperty(TITLE);
if (title != null)
{
properties.setProperty(TITLE, UIRegistry.getResourceString(title));
}
}
String viewName = getAttr(cellElement, "viewname", null);
cell = formRow.addCell(new FormCellSubView(cellId,
cellName,
svViewSetName,
viewName,
cellElement.attributeValue("class"),
getAttr(cellElement, "desc", ""),
getAttr(cellElement, "defaulttype", null),
getAttr(cellElement, "rows", DEFAULT_SUBVIEW_ROWS),
colspan,
rowspan,
getAttr(cellElement, "single", false)));
cell.setProperties(properties);
break;
}
case iconview:
{
String vsName = cellElement.attributeValue("viewsetname");
if (isEmpty(vsName))
{
vsName = instance.viewSetName;
}
String viewName = getAttr(cellElement, "viewname", null);
cell = formRow.addCell(new FormCellSubView(cellId, cellName,
vsName,
viewName,
cellElement.attributeValue("class"),
getAttr(cellElement, "desc", ""),
colspan,
rowspan));
break;
}
case statusbar:
{
cell = formRow.addCell(new FormCell(FormCellIFace.CellType.statusbar, cellId, cellName, colspan, rowspan));
break;
}
default:
{
// what is this?
log.error("Encountered unknown cell type");
continue;
}
} // switch
cell.setIgnoreSetGet(getAttr(cellElement, "ignore", false));
}
cellRows.add(formRow);
rowNumber++;
}
}
}
/**
* @param cellName
* @param cellId
* @param rowNumber
*/
private static void processFieldVerify(final String cellName, final String cellId, final int rowNumber)
{
try
{
boolean isOK = false;
if (StringUtils.contains(cellName, '.'))
{
DBTableInfo tblInfo = fldVerTableInfo;
String[] fieldNames = StringUtils.split(cellName, ".");
for (int i=0;i<fieldNames.length-1;i++)
{
String type = null;
DBTableChildIFace child = tblInfo.getItemByName(fieldNames[i]);
if (child instanceof DBFieldInfo)
{
DBFieldInfo fldInfo = (DBFieldInfo)child;
type = fldInfo.getType();
if (type != null)
{
DBTableInfo tInfo = DBTableIdMgr.getInstance().getByClassName(type);
tblInfo = tInfo != null ? tInfo : tblInfo;
}
isOK = tblInfo.getItemByName(fieldNames[fieldNames.length-1]) != null;
} else if (child instanceof DBRelationshipInfo)
{
DBRelationshipInfo relInfo = (DBRelationshipInfo)child;
type = relInfo.getDataClass().getName();
if (type != null)
{
tblInfo = DBTableIdMgr.getInstance().getByClassName(type);
}
}
//System.out.println(type);
}
if (tblInfo != null)
{
isOK = tblInfo.getItemByName(fieldNames[fieldNames.length-1]) != null;
}
} else
{
isOK = fldVerTableInfo.getItemByName(cellName) != null;
}
if (!isOK)
{
String msg = " ViewSet["+instance.viewSetName+"]\n ViewDef["+fldVerFormViewDef.getName()+"]\n The cell name ["+cellName+"] for cell with Id ["+cellId+"] is not a field\n in Data Object["+fldVerTableInfo.getName()+"]\n on Row ["+rowNumber+"]";
if (!isTreeClass)
{
instance.fldVerTableModel.addRow(instance.viewSetName, fldVerFormViewDef.getName(), cellId, cellName, Integer.toString(rowNumber));
}
log.error(msg);
}
} catch (Exception ex)
{
log.error(ex);
}
}
/**
* @param element the DOM element for building the form
* @param type the type of form to be built
* @param id the id of the form
* @param name the name of the form
* @param className the class name of the data object
* @param gettableClassName the class name of the getter
* @param settableClassName the class name of the setter
* @param desc the description
* @param useResourceLabels whether to use resource labels
* @param tableinfo table info
* @return a form view of type "form"
*/
protected static FormViewDef createFormViewDef(final Element element,
final ViewDef.ViewType type,
final String name,
final String className,
final String gettableClassName,
final String settableClassName,
final String desc,
final boolean useResourceLabels,
final DBTableInfo tableinfo)
{
FormViewDef formViewDef = new FormViewDef(type, name, className, gettableClassName, settableClassName, desc,
useResourceLabels, XMLHelper.getAttr(element, "editableDlg", true));
fldVerTableInfo = null;
if (type != ViewDefIFace.ViewType.formtable)
{
if (doFieldVerification)
{
if (instance.fldVerTableModel == null)
{
instance.createFieldVerTableModel();
}
try
{
//log.debug(className);
Class<?> classObj = Class.forName(className);
if (FormDataObjIFace.class.isAssignableFrom(classObj))
{
fldVerTableInfo = DBTableIdMgr.getInstance().getByClassName(className);
isTreeClass = fldVerTableInfo != null && fldVerTableInfo.getFieldByName("highestChildNodeNumber") != null;
fldVerFormViewDef = formViewDef;
}
} catch (ClassNotFoundException ex)
{
String msg = "ClassNotFoundException["+className+"] Name["+name+"]";
log.error(msg);
FormDevHelper.appendFormDevError(msg);
//edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
//edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ViewLoader.class, comments, ex);
} catch (Exception ex)
{
edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ViewLoader.class, ex);
}
}
List<FormRowIFace> rows = formViewDef.getRows();
instance.doingResourceLabels = useResourceLabels;
//gViewDef = formViewDef;
processRows(element, rows, tableinfo);
instance.doingResourceLabels = false;
createDef(element, "columnDef", rows.size(), formViewDef.getColumnDefItem());
createDef(element, "rowDef", rows.size(), formViewDef.getRowDefItem());
formViewDef.setEnableRules(getEnableRules(element));
fixLabels(formViewDef.getName(), rows, tableinfo);
} else
{
Node defNode = element.selectSingleNode("definition");
if (defNode != null) {
String defName = defNode.getText();
if (StringUtils.isNotEmpty(defName)) {
formViewDef.setDefinitionName(defName);
return formViewDef;
}
}
String msg = "formtable is missing or has empty <defintion> node";
log.error(msg);
FormDevHelper.appendFormDevError(msg);
return null;
}
return formViewDef;
}
/**
* @param fieldName
* @param tableInfo
* @return
*/
protected static String getTitleFromFieldName(final String fieldName,
final DBTableInfo tableInfo)
{
DBTableChildIFace derivedCI = null;
if (fieldName.indexOf(".") > -1)
{
derivedCI = FormHelper.getChildInfoFromPath(fieldName, tableInfo);
if (derivedCI == null)
{
String msg = "The name 'path' ["+fieldName+"] was not valid in ViewSet ["+instance.viewSetName+"]";
FormDevHelper.appendFormDevError(msg);
log.error(msg);
return "";
}
}
DBTableChildIFace tblChild = derivedCI != null ? derivedCI : tableInfo.getItemByName(fieldName);
if (tblChild == null)
{
String msg = "The Field Name ["+fieldName+"] was not in the Table ["+tableInfo.getTitle()+"] in ViewSet ["+instance.viewSetName+"]";
log.error(msg);
FormDevHelper.appendFormDevError(msg);
return "";
}
return tblChild.getTitle();
}
/**
* @param rows
* @param tableInfo
*/
protected static void fixLabels(final String name,
final List<FormRowIFace> rows,
final DBTableInfo tableInfo)
{
if (tableInfo == null)
{
return;
}
Hashtable<String, String> fldIdMap = new Hashtable<String, String>();
for (FormRowIFace row : rows)
{
for (FormCellIFace cell : row.getCells())
{
if (cell.getType() == FormCellIFace.CellType.field ||
cell.getType() == FormCellIFace.CellType.subview)
{
fldIdMap.put(cell.getIdent(), cell.getName());
}/* else
{
System.err.println("Skipping ["+cell.getIdent()+"] " + cell.getType());
}*/
}
}
for (FormRowIFace row : rows)
{
for (FormCellIFace cell : row.getCells())
{
if (cell.getType() == FormCellIFace.CellType.label)
{
FormCellLabelIFace lblCell = (FormCellLabelIFace)cell;
String label = lblCell.getLabel();
if (label.length() == 0 || label.equals("##"))
{
String idFor = lblCell.getLabelFor();
if (StringUtils.isNotEmpty(idFor))
{
String fieldName = fldIdMap.get(idFor);
if (StringUtils.isNotEmpty(fieldName))
{
if (!fieldName.equals("this"))
{
//FormCellFieldIFace fcf = get
lblCell.setLabel(getTitleFromFieldName(fieldName, tableInfo));
}
} else
{
String msg = "Setting Label - Form control with id["+idFor+"] is not in ViewDef or Panel ["+name+"] in ViewSet ["+instance.viewSetName+"]";
log.error(msg);
FormDevHelper.appendFormDevError(msg);
}
}
}
} else if (cell.getType() == FormCellIFace.CellType.field && cell instanceof FormCellFieldIFace &&
((((FormCellFieldIFace)cell).getUiType() == FormCellFieldIFace.FieldType.checkbox) ||
(((FormCellFieldIFace)cell).getUiType() == FormCellFieldIFace.FieldType.tristate)))
{
FormCellFieldIFace fcf = (FormCellFieldIFace)cell;
if (fcf.getLabel().equals("##"))
{
fcf.setLabel(getTitleFromFieldName(cell.getName(), tableInfo));
}
}
}
}
}
/**
* @param type the type of form to be built
* @param name the name of the form
* @param className the class name of the data object
* @param gettableClassName the class name of the getter
* @param settableClassName the class name of the setter
* @param desc the description
* @param useResourceLabels whether to use resource labels
* @return a form view of type "form"
*/
protected static ViewDef createIconViewDef(final ViewDef.ViewType type,
final String name,
final String className,
final String gettableClassName,
final String settableClassName,
final String desc,
final boolean useResourceLabels)
{
ViewDef formView = new ViewDef(type, name, className, gettableClassName, settableClassName, desc, useResourceLabels);
//formView.setEnableRules(getEnableRules(element));
return formView;
}
/**
* Creates a Table Form View
* @param typeName the type of form to be built
* @param element the DOM element for building the form
* @param name the name of the form
* @param className the class name of the data object
* @param gettableClassName the class name of the getter
* @param settableClassName the class name of the setter
* @param desc the description
* @param useResourceLabels whether to use resource labels
* @return a form view of type "table"
*/
protected static TableViewDefIFace createTableView(final Element element,
final String name,
final String className,
final String gettableClassName,
final String settableClassName,
final String desc,
final boolean useResourceLabels)
{
TableViewDefIFace tableView = new TableViewDef( name, className, gettableClassName, settableClassName, desc, useResourceLabels);
//tableView.setResourceLabels(resLabels);
Element columns = (Element)element.selectSingleNode("columns");
if (columns != null)
{
for ( Iterator<?> i = columns.elementIterator( "column" ); i.hasNext(); ) {
Element colElement = (Element) i.next();
FormColumn column = new FormColumn(colElement.attributeValue(NAME),
colElement.attributeValue(LABEL),
getAttr(colElement, "dataobjformatter", null),
getAttr(colElement, "format", null)
);
tableView.addColumn(column);
}
}
return tableView;
}
/**
* Save out a viewSet to a file
* @param viewSet the viewSet to save
* @param filename the filename (full path) as to where to save it
*/
public static void save(final ViewSet viewSet, final String filename)
{
try
{
Vector<ViewSet> viewsets = new Vector<ViewSet>();
viewsets.add(viewSet);
File file = new File(filename);
FileWriter fw = new FileWriter(file);
fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
BeanWriter beanWriter = new BeanWriter(fw);
XMLIntrospector introspector = beanWriter.getXMLIntrospector();
introspector.getConfiguration().setWrapCollectionsInElement(false);
beanWriter.getBindingConfiguration().setMapIDs(false);
beanWriter.setWriteEmptyElements(false);
beanWriter.enablePrettyPrint();
beanWriter.write(viewSet);
fw.close();
} catch(Exception ex)
{
log.error("error writing views", ex);
}
}
//--------------------------------------------------------------------------------------------
//-- Field Verify Methods, Classes, Helpers
//--------------------------------------------------------------------------------------------
public void createFieldVerTableModel()
{
fldVerTableModel = new FieldVerifyTableModel();
}
/**
* @return the doFieldVerification
*/
public static boolean isDoFieldVerification()
{
return doFieldVerification;
}
/**
* @param doFieldVerification the doFieldVerification to set
*/
public static void setDoFieldVerification(boolean doFieldVerification)
{
ViewLoader.doFieldVerification = doFieldVerification;
}
public static void clearFieldVerInfo()
{
if (instance.fldVerTableModel != null)
{
instance.fldVerTableModel.clear();
}
}
/**
* Di
*/
public static void displayFieldVerInfo()
{
if (verifyDlg != null)
{
verifyDlg.setVisible(false);
verifyDlg.dispose();
verifyDlg = null;
}
System.err.println("------------- "+(instance.fldVerTableModel != null ? instance.fldVerTableModel.getRowCount() : "null"));
if (instance.fldVerTableModel != null && instance.fldVerTableModel.getRowCount() > 0)
{
JLabel lbl = UIHelper.createLabel("<html><i>(Some of fields are special buttons or labal names. Review them to make sure you have not <br>mis-named any of the fields you are working with.)");
final JTable table = new JTable(instance.fldVerTableModel);
UIHelper.calcColumnWidths(table);
CellConstraints cc = new CellConstraints();
JScrollPane sp = new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "f:p:g,4px,p"));
pb.add(sp, cc.xy(1, 1));
pb.add(lbl, cc.xy(1, 3));
pb.setDefaultDialogBorder();
verifyDlg = new CustomFrame("Field Names on Form, but not in Database : "+instance.fldVerTableModel.getRowCount(), CustomFrame.OK_BTN, pb.getPanel())
{
@Override
protected void okButtonPressed()
{
super.okButtonPressed();
table.setModel(new DefaultTableModel());
dispose();
verifyDlg = null;
}
};
verifyDlg.setOkLabel(getResourceString("CLOSE"));
verifyDlg.createUI();
verifyDlg.setVisible(true);
}
}
class FieldVerifyTableModel extends DefaultTableModel
{
protected Vector<List<String>> rowData = new Vector<List<String>>();
protected String[] colNames = {"ViewSet", "View Def", "Cell Id", "Cell Name", "Row"};
protected Hashtable<String, Boolean> nameHash = new Hashtable<String, Boolean>();
public FieldVerifyTableModel()
{
super();
}
public void clear()
{
for (List<String> list : rowData)
{
list.clear();
}
rowData.clear();
nameHash.clear();
}
public void addRow(final String viewSet,
final String viewDef,
final String cellId,
final String cellName,
final String rowInx)
{
String key = viewSet + viewDef + cellId;
if (nameHash.get(key) == null)
{
List<String> row = new ArrayList<String>(5);
row.add(viewSet);
row.add(viewDef);
row.add(cellId);
row.add(cellName);
row.add(rowInx);
rowData.add(row);
nameHash.put(key, true);
}
}
/* (non-Javadoc)
* @see javax.swing.table.DefaultTableModel#getColumnCount()
*/
@Override
public int getColumnCount()
{
return colNames.length;
}
/* (non-Javadoc)
* @see javax.swing.table.DefaultTableModel#getColumnName(int)
*/
@Override
public String getColumnName(int column)
{
return colNames[column];
}
/* (non-Javadoc)
* @see javax.swing.table.DefaultTableModel#getRowCount()
*/
@Override
public int getRowCount()
{
return rowData == null ? 0 : rowData.size();
}
/* (non-Javadoc)
* @see javax.swing.table.DefaultTableModel#getValueAt(int, int)
*/
@Override
public Object getValueAt(int row, int column)
{
List<String> rowList = rowData.get(row);
return rowList.get(column);
}
}
}
| specify/specify6 | src/edu/ku/brc/af/ui/forms/persist/ViewLoader.java | Java | gpl-2.0 | 72,771 |
/*
Copyright: © 2011 Thomas Stein, CodeLounge.de
<mailto:info@codelounge.de> <http://www.codelounge.de/>
Released under the terms of the GNU General Public License.
You should have received a copy of the GNU General Public License,
along with this software. In the main directory, see: licence.txt
If not, see: <http://www.gnu.org/licenses/>.
*/
/*
* MBP - Mobile boilerplate helper functions
*/
(function(document){
window.MBP = window.MBP || {};
// Fix for iPhone viewport scale bug
// http://www.blog.highub.com/mobile-2/a-fix-for-iphone-viewport-scale-bug/
MBP.viewportmeta = document.querySelector && document.querySelector('meta[name="viewport"]');
MBP.ua = navigator.userAgent;
MBP.scaleFix = function () {
if (MBP.viewportmeta && /iPhone|iPad/.test(MBP.ua) && !/Opera Mini/.test(MBP.ua)) {
MBP.viewportmeta.content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0";
document.addEventListener("gesturestart", MBP.gestureStart, false);
}
};
MBP.gestureStart = function () {
MBP.viewportmeta.content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6";
};
// Hide URL Bar for iOS
// http://remysharp.com/2010/08/05/doing-it-right-skipping-the-iphone-url-bar/
MBP.hideUrlBar = function () {
/iPhone/.test(MBP.ua) && !pageYOffset && !location.hash && setTimeout(function () {
window.scrollTo(0, 1);
}, 1000),
/iPad/.test(MBP.ua) && !pageYOffset && !location.hash && setTimeout(function () {
window.scrollTo(0, 1);
}, 1000);
};
});
jQuery( function() {
$("a.facebox").fancybox();
//$("a.fancybox").prettyPhoto({
// social_tools: false
//});
jQuery('.entenlogo').click(function() {
$('.entenlogo').hide();
});
var current_url = $(location).attr('href');
//console.log($(location).attr('href'));
jQuery('body').bind( 'taphold', function( e ) {
//$('#next_post_link').attr('refresh');
//$('#previous_post_link').attr('refresh');
$('#page').page('refresh');
var next_url = $('#next_post_link').attr('href');
var previous_url = $('#previous_post_link').attr('href');
console.log(next_url + ' --- ' + previous_url);
e.stopImmediatePropagation();
return false;
} );
jQuery('body').bind( 'swipeleft', function( e ) {
var next_url = $('.ui-page-active #next_post_link').attr('href');
var previous_url = $('.ui-page-active #previous_post_link').attr('href');
console.log("Swiped Left: " + next_url + ' --- ' + previous_url);
if (undefined != previous_url) {
//$.mobile.changePage( previous_url,"slide", true);
$.mobile.changePage( previous_url, {
transition: "slide",
reverse: false,
changeHash: true
});
e.stopImmediatePropagation();
return false;
}
} );
jQuery('body').bind( 'swiperight', function( e ) {
var next_url = $('.ui-page-active #next_post_link').attr('href');
var previous_url = $('.ui-page-active #previous_post_link').attr('href');
console.log("Swiped Right: " + next_url + ' --- ' + previous_url);
if (undefined != next_url) {
//$.mobile.changePage( next_url, "slide", true);
$.mobile.changePage( next_url, {
transition: "slide",
reverse: true,
changeHash: true
});
e.stopImmediatePropagation();
return false;
}
} );
} );
| codelounge/codelounge-exposure-theme | js/exposure.js | JavaScript | gpl-2.0 | 3,408 |
#include "tacticattacker.h"
TacticAttacker::TacticAttacker(WorldModel *worldmodel, QObject *parent) :
Tactic("TacticAttacker", worldmodel, parent)
{
everyOneInTheirPos = false;
maxDistance = sqrt(pow(Field::MaxX*2,2)+pow(Field::MaxY*2,2));
}
RobotCommand TacticAttacker::getCommand()
{
RobotCommand rc;
if(!wm->ourRobot[id].isValid) return rc;
if(wm->ourRobot[id].Status == AgentStatus::FollowingBall)
{
rc.maxSpeed = 2;
tANDp target = findTarget();
// OperatingPosition p = BallControl(target.pos, target.prob, this->id, rc.maxSpeed);
OperatingPosition p = BallControl(target.pos, target.prob, this->id, rc.maxSpeed,3);
if( p.readyToShoot )
// rc.kickspeedx = detectKickSpeed(kickType::Shoot, p.shootSensor);
{
rc.kickspeedz = detectChipSpeed(/*kickType::Shoot, */p.shootSensor);
}
rc.fin_pos = p.pos;
rc.useNav = p.useNav;
rc.isBallObs = true;
rc.isKickObs = true;
}
else if(wm->ourRobot[id].Status == AgentStatus::Kicking)
{
// if(wm->gs == STATE_Indirect_Free_kick_Our)
// {
// rc = KickTheBallIndirect();
// }
// else if(wm->gs == STATE_Free_kick_Our)
// {
// rc = KickTheBallDirect();
// }
// else if(wm->gs == STATE_Start)
// {
// rc = StartTheGame();
// }
if(wm->gs == STATE_Start)
{
rc = StartTheGame();
}
else
{
rc = KickTheBallIndirect();
}
rc.isBallObs = true;
rc.isKickObs = true;
}
else if(wm->ourRobot[id].Status == AgentStatus::Chiping)
{
rc = ChipTheBallIndirect();
rc.isBallObs = true;
rc.isKickObs = true;
}
else if(wm->ourRobot[id].Status == AgentStatus::RecievingPass)
{
rc.fin_pos = idlePosition;
rc.maxSpeed = 2.5;
rc.useNav = true;
rc.isBallObs = true;
rc.isKickObs = true;
}
else if(wm->ourRobot[id].Status == AgentStatus::BlockingRobot)
{
AngleDeg desiredDeg = (wm->oppRobot[playerToKeep].pos.loc-Field::ourGoalCenter).dir();
Position final;
final.loc.x = wm->oppRobot[playerToKeep].pos.loc.x - (300*cos(desiredDeg.radian()));
final.loc.y = wm->oppRobot[playerToKeep].pos.loc.y - (300*sin(desiredDeg.radian()));
final.dir = desiredDeg.radian();
if( wm->gs == GameStateType::STATE_Free_kick_Opp || wm->gs == GameStateType::STATE_Indirect_Free_kick_Opp)
{
if( wm->kn->IsInsideSecureArea(final.loc,wm->ball.pos.loc) )
{
Vector2D fstInt,secInt;
Circle2D secArea(wm->ball.pos.loc,ALLOW_NEAR_BALL_RANGE);
Line2D connectedLine(wm->ball.pos.loc,Field::ourGoalCenter);
int numberOfIntersections = secArea.intersection(connectedLine,&fstInt,&secInt);
rc.fin_pos.dir = (wm->oppRobot[playerToKeep].pos.loc - Field::ourGoalCenter).dir().radian();
if( numberOfIntersections == 2 )
{
if( (fstInt-final.loc).length() > (secInt-final.loc).length() )
rc.fin_pos.loc = secInt;
else
rc.fin_pos.loc = fstInt;
}
else if( numberOfIntersections == 1 )
{
rc.fin_pos.loc = fstInt;
}
else
rc.fin_pos = wm->ourRobot[this->id].pos;
}
else
{
rc.fin_pos = final;
}
}
else
{
rc.fin_pos = final;
}
if( wm->opp_vel > 3 )
rc.maxSpeed = 3;
else
rc.maxSpeed = wm->opp_vel;
rc.useNav = true;
rc.isBallObs = true;
rc.isKickObs = true;
}
else if(wm->ourRobot[id].Status == AgentStatus::Idle)
{
rc.fin_pos = idlePosition;
rc.maxSpeed = 2;
rc.useNav = true;
rc.isBallObs = true;
rc.isKickObs = true;
if( wm->gs == STATE_Stop )
return rc;
}
if( wm->kn->IsInsideGolieArea(rc.fin_pos.loc) )
{
Circle2D attackerCircles(Field::ourGoalCenter , Field::goalCircle_R+300);
Line2D robotRay(rc.fin_pos.loc,wm->ourRobot[this->id].pos.loc);
Vector2D firstPoint,secondPoint;
attackerCircles.intersection(robotRay,&firstPoint,&secondPoint);
if( (wm->ourRobot[this->id].pos.loc-firstPoint).length() < (wm->ourRobot[this->id].pos.loc-secondPoint).length() )
rc.fin_pos.loc = firstPoint;
else
rc.fin_pos.loc = secondPoint;
}
if( wm->kn->IsInsideOppGolieArea(rc.fin_pos.loc) && !wm->cmgs.ourPenaltyKick() /*&& wm->defenceMode*/)
{
Circle2D attackerCircles(Field::oppGoalCenter , Field::goalCircle_R+300);
Line2D robotRay(rc.fin_pos.loc, wm->ourRobot[this->id].pos.loc);
Vector2D firstPoint,secondPoint;
attackerCircles.intersection(robotRay,&firstPoint,&secondPoint);
if( (wm->ourRobot[this->id].pos.loc-firstPoint).length() < (wm->ourRobot[this->id].pos.loc-secondPoint).length() )
rc.fin_pos.loc = firstPoint;
else
rc.fin_pos.loc = secondPoint;
}
return rc;
}
RobotCommand TacticAttacker::goBehindBall()
{
RobotCommand rc;
canKick=false;
rc.maxSpeed = 1;
float deg=atan((0-wm->ball.pos.loc.y)/(3025-wm->ball.pos.loc.x));
if(!wm->kn->ReachedToPos(wm->ourRobot[id].pos, rc.fin_pos, 30, 180))
{
rc.fin_pos.loc= {wm->ball.pos.loc.x-110*cos(deg),wm->ball.pos.loc.y-110*sin(deg)};
rc.fin_pos.dir=atan((0-wm->ball.pos.loc.y)/(3025-wm->ball.pos.loc.x));
}
if(!wm->kn->ReachedToPos(wm->ourRobot[id].pos, rc.fin_pos, 20, 2))
{
//double test=findBestPoint();
//rc.fin_pos.dir=test;
}
rc.fin_pos.loc= {wm->ball.pos.loc.x-100*cos(deg),wm->ball.pos.loc.y-100*sin(deg)};
if(wm->kn->ReachedToPos(wm->ourRobot[id].pos, rc.fin_pos, 10, 4))
{
canKick=true;
}
return rc;
}
RobotCommand TacticAttacker::KickTheBallIndirect()
{
RobotCommand rc;
rc.maxSpeed = 0.5;
Vector2D target = receiverPos;
Line2D b2g(target,Field::oppGoalCenter);
Circle2D cir(target,300);
Vector2D goal,first,second;
int numOfPoints = cir.intersection(b2g,&first,&second);
// if( numOfPoints == 2)
// {
// if( first.x > target.x )
// goal = first;
// else if( second.x > target.x )
// goal = second;
// else
// goal = target;
// }
// else if( numOfPoints == 1)
// goal = first;
// else
goal = target;
wm->passPoints.clear();
wm->passPoints.push_back(goal);
OperatingPosition kickPoint = BallControl(goal,100,this->id,rc.maxSpeed);
rc.fin_pos = kickPoint.pos;
rc.useNav = kickPoint.useNav;
qDebug()<<"readyToShoot : "<<kickPoint.readyToShoot<<" , everyOneInTheirPos : "<<everyOneInTheirPos;
if( kickPoint.readyToShoot && everyOneInTheirPos)
{
rc.kickspeedx = detectKickSpeed(freeKickType, kickPoint.shootSensor);
// Line2D ball2Target(wm->ball.pos.loc,goal);
// QList<int> activeOpp = wm->kn->ActiveOppAgents();
// bool wayIsClear = true;
// for(int i=0;i<activeOpp.size();i++)
// {
// double distance = ball2Target.dist(wm->oppRobot[activeOpp.at(i)].pos.loc);
// if( distance < ROBOT_RADIUS+BALL_RADIUS )
// {
// wayIsClear = false;
// break;
// }
// }
// if( wayIsClear )
// {
// rc.kickspeedx = 255;// detectKickSpeed(goal);
// qDebug()<<"Kickk...";
// }
// else
// {
// rc.kickspeedx = 3;//255;// detectKickSpeed(goal);
// rc.kickspeedz = 3;
// qDebug()<<"CHIP...";
// }
}
return rc;
}
RobotCommand TacticAttacker::KickTheBallDirect()
{
RobotCommand rc;
rc.maxSpeed = 0.5;
tANDp target = findTarget();
OperatingPosition kickPoint = BallControl(target.pos, target.prob, this->id, rc.maxSpeed);
rc.fin_pos = kickPoint.pos;
if( kickPoint.readyToShoot )
{
rc.kickspeedx = detectKickSpeed(kickType::Shoot, kickPoint.shootSensor);
qDebug()<<"Kickk...";
}
rc.useNav = kickPoint.useNav;
return rc;
}
RobotCommand TacticAttacker::StartTheGame()
{
RobotCommand rc;
rc.maxSpeed = 0.5;
Vector2D target(Field::oppGoalCenter.x,Field::oppGoalCenter.y);
OperatingPosition kickPoint = BallControl(target, 100, this->id, rc.maxSpeed);
rc.fin_pos = kickPoint.pos;
rc.useNav = kickPoint.useNav;
if( kickPoint.readyToShoot )
{
//rc.kickspeedz = 2.5;//50;
rc.kickspeedx = detectKickSpeed(kickType::Shoot, kickPoint.shootSensor);
qDebug()<<"Kickk...";
}
return rc;
}
RobotCommand TacticAttacker::ChipTheBallIndirect()
{
RobotCommand rc;
rc.maxSpeed = 0.5;
Vector2D target = receiverPos;
Vector2D goal(target.x,target.y);
OperatingPosition kickPoint = BallControl(goal, 100, this->id, rc.maxSpeed);
rc.fin_pos = kickPoint.pos;
rc.useNav = kickPoint.useNav;
if( kickPoint.readyToShoot && everyOneInTheirPos)
{
rc.kickspeedz = detectChipSpeed(kickPoint.shootSensor);
qDebug()<<"Chip...";
}
return rc;
}
int TacticAttacker::findBestPlayerForPass()
{
QList<int> ourAgents = wm->kn->findAttackers();
ourAgents.removeOne(this->id);
QList<int> freeAgents , busyAgents;
while( !ourAgents.isEmpty() )
{
int index = ourAgents.takeFirst();
if(isFree(index))
freeAgents.append(index);
else
busyAgents.append(index);
}
QList<double> weights;
for(int i=0;i<freeAgents.size();i++)
{
double weight = -1000000;
if( wm->ourRobot[freeAgents.at(i)].isValid )
{
double dist = 1 - ((wm->ball.pos.loc - wm->ourRobot[freeAgents.at(i)].pos.loc).length()/maxDistance);
double prob = wm->kn->scoringChance(wm->ourRobot[freeAgents.at(i)].pos.loc) / 100;
weight = (20 * prob) + (10*dist);
}
weights.append(weight);
}
int index = -1;
double max = -10000;
for(int i=0;i<weights.size();i++)
{
if( max < weights.at(i) )
{
max = weights.at(i);
index = freeAgents.at(i);
}
}
return index;
}
void TacticAttacker::isKicker()
{
wm->ourRobot[this->id].Status = AgentStatus::Kicking;
findReciever = true;
}
void TacticAttacker::isChiper()
{
wm->ourRobot[this->id].Status = AgentStatus::Chiping;
findReciever = true;
}
void TacticAttacker::isKicker(int recieverID)
{
wm->ourRobot[this->id].Status = AgentStatus::Kicking;
findReciever = false;
this->receiverPos = wm->ourRobot[recieverID].pos.loc;
}
void TacticAttacker::isKicker(Vector2D pos)
{
wm->ourRobot[this->id].Status = AgentStatus::Kicking;
findReciever = false;
this->receiverPos = pos;
}
void TacticAttacker::isChiper(Vector2D pos)
{
wm->ourRobot[this->id].Status = AgentStatus::Chiping;
findReciever = false;
this->receiverPos = pos;
}
void TacticAttacker::setGameOnPositions(Position pos)
{
setIdlePosition(pos);
}
void TacticAttacker::setGameOnPositions(Vector2D pos)
{
Position position = wm->kn->AdjustKickPoint(pos,Field::oppGoalCenter);
setIdlePosition(position);
}
void TacticAttacker::setIdlePosition(Position pos)
{
this->idlePosition = pos;
}
void TacticAttacker::setIdlePosition(Vector2D pos)
{
this->idlePosition.loc = pos;
this->idlePosition.dir = ( wm->ball.pos.loc - pos).dir().radian();
}
void TacticAttacker::youHavePermissionForKick()
{
everyOneInTheirPos = true;
if( findReciever )
{
int indexOfReciever = findBestPlayerForPass();
if( indexOfReciever != -1 )
receiverPos = wm->ourRobot[indexOfReciever].pos.loc;
}
}
void TacticAttacker::setFreeKickType(kickType type)
{
this->freeKickType = type;
}
bool TacticAttacker::isFree(int index)
{
QList<int> oppAgents = wm->kn->ActiveOppAgents();
while( !oppAgents.isEmpty() )
{
int indexOPP = oppAgents.takeFirst();
if( (wm->ourRobot[index].pos.loc-wm->oppRobot[indexOPP].pos.loc).length() < DangerDist &&
fabs((wm->ourRobot[index].vel.loc - wm->oppRobot[indexOPP].vel.loc).length())<0.3 )
{
return false;
}
}
return true;
}
| mohsen-raoufi/Guidance | src/ai/tactic/tacticattacker.cpp | C++ | gpl-2.0 | 13,212 |
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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.
*
* The Benchmark 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
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest04982")
public class BenchmarkTest04982 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request );
String param = scr.getTheParameter("foo");
String bar;
String guess = "ABC";
char switchTarget = guess.charAt(1); // condition 'B', which is safe
// Simple case statement that assigns param to bar on conditions 'A' or 'C'
switch (switchTarget) {
case 'A':
bar = param;
break;
case 'B':
bar = "bob";
break;
case 'C':
case 'D':
bar = param;
break;
default:
bar = "bob's your uncle";
break;
}
Object[] obj = { bar, "b"};
response.getWriter().printf("notfoo",obj);
}
}
| iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest04982.java | Java | gpl-2.0 | 2,239 |
<?php
/*
Copyright (c) 2007 BeVolunteer
This file is part of BW Rox.
BW Rox 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.
BW Rox 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/> or
write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
$words = new MOD_words();
?>
<div id="teaser" class="clearfix">
<div class="subcolumns">
<div class="c62l">
<div class="subcl">
<h1 class="slogan"><span id="something" ><?php echo $words->get('IndexPageTeaserReal1a');?></span> <span id="real" ><?php echo $words->get('IndexPageTeaserReal1b');?></span> </h1>
<h2><?php echo $words->get('IndexPageTeaserReal2');?></h2>
<a class="bigbutton float_left" href="signup" onclick="this.blur();"><span><?php echo $words->get('signup_now');?></span></a>
<a class="bigbutton float_left" href="tour" onclick="this.blur();"><span><?php echo $words->get('tour_take');?></span></a>
</div> <!-- subcl -->
</div> <!-- c50l -->
<div class="c38r">
<div class="subcr">
<div id="slideshow-content">
<div class="slide" id="slide1">
<img src="images/tour/share4_small.jpg" alt="share" />
</div>
<div class="slide" id="slide2" style="display: none;">
<img src="images/tour/syrien.jpg" alt="syria" />
</div>
<div class="slide" id="slide3" style="display: none;">
<img src="images/tour/mountain1.jpg" alt="mountain" />
</div>
<div class="slide" id="slide4" style="display: none;">
<img src="images/tour/river.jpg" alt="river" />
</div>
<div class="slide" id="slide5" style="display: none;">
<img src="images/tour/dancing2.jpg" alt="dancing" />
</div>
<div class="slide" id="slide6" style="display: none;">
<img src="images/tour/mountain2.jpg" alt="river" />
</div>
<div class="slide" id="slide7" style="display: none;">
<img src="images/tour/people.jpg" alt="river" />
</div>
<div class="slide" id="slide8" style="display: none;">
<img src="images/tour/people2.jpg" alt="river" />
</div>
<p class="small photodesc">
(cc)
<?=$words->get('StartPageListofPhotographers');?>
</p>
</div>
</div> <!-- subcr -->
</div> <!-- c50r -->
</div> <!-- subcolumns -->
<script type="text/javascript">
<!--
function realeffect() {
new Effect.toggle('real', 'appear', {duration: 2})
}
$('real').hide();
$('something').hide();
window.onload = function () {
new Effect.toggle('something', 'appear', {duration: 2});
setTimeout('realeffect()',2000);
start_slideshow(1, 8, 10000);
};
// -->
</script>
<script type="text/javascript">
function start_slideshow(start_frame, end_frame, delay) {
setTimeout(switch_slides(start_frame,start_frame,end_frame, delay), delay);
}
function switch_slides(frame, start_frame, end_frame, delay) {
return (function() {
Effect.Fade('slide' + frame);
if (frame == end_frame) { frame = start_frame; } else { frame = frame + 1; }
setTimeout("Effect.Appear('slide" + frame + "');", 950);
setTimeout(switch_slides(frame, start_frame, end_frame, delay), delay + 950);
})
}
</script>
</div>
| BeWelcome/rox.prototypes | templates/apps/rox/teaser.php | PHP | gpl-2.0 | 4,007 |
using UnityEngine;
using System.Collections;
public class MapCollisionsDetector : MonoBehaviour {
// Use this for initialization
void Start () {
}
void FixedUpdate()
{
}
/*void OnCollisionEnter(Collision collision) {
foreach(var contact in collision.contacts)
print (contact.otherCollider.gameObject.name);
}*/
}
| Reminouche/TCG | Assets/MapCollisionsDetector.cs | C# | gpl-2.0 | 340 |
/**************************************************************************************
* Copyright (C) 2008 EsperTech, Inc. All rights reserved. *
* http://esper.codehaus.org *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
**************************************************************************************/
package com.espertech.esper.epl.join.pollindex;
import com.espertech.esper.epl.join.table.EventTable;
import com.espertech.esper.epl.join.table.UnindexedEventTableList;
import com.espertech.esper.epl.join.table.PropertyIndexedEventTable;
import com.espertech.esper.client.EventBean;
import com.espertech.esper.client.EventType;
import java.util.Arrays;
import java.util.List;
/**
* Strategy for building an index out of poll-results knowing the properties to base the index on.
*/
public class PollResultIndexingStrategyIndex implements PollResultIndexingStrategy
{
private final int streamNum;
private final EventType eventType;
private final String[] propertyNames;
/**
* Ctor.
* @param streamNum is the stream number of the indexed stream
* @param eventType is the event type of the indexed stream
* @param propertyNames is the property names to be indexed
*/
public PollResultIndexingStrategyIndex(int streamNum, EventType eventType, String[] propertyNames)
{
this.streamNum = streamNum;
this.eventType = eventType;
this.propertyNames = propertyNames;
}
public EventTable index(List<EventBean> pollResult, boolean isActiveCache)
{
if (!isActiveCache)
{
return new UnindexedEventTableList(pollResult);
}
PropertyIndexedEventTable table = new PropertyIndexedEventTable(streamNum, eventType, propertyNames);
table.add(pollResult.toArray(new EventBean[pollResult.size()]));
return table;
}
public String toQueryPlan() {
return this.getClass().getSimpleName() + " properties " + Arrays.toString(propertyNames);
}
}
| intelie/esper | esper/src/main/java/com/espertech/esper/epl/join/pollindex/PollResultIndexingStrategyIndex.java | Java | gpl-2.0 | 2,448 |
package com.ht.halo.hibernate3.base;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map.Entry;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.ht.halo.hibernate3.HaloDao;
import com.ht.halo.map.HaloMap;
public class MyEntityUtils {
private static final Log logger = LogFactory.getLog(MyEntityUtils.class);
/**
* @Title: setEntity
* @Description: TODO Action层 设置实体某字段值 map转entity
* @param entity
* @param parameters
*/
public static Object setEntity(Object entity,HaloMap parameter){
if(null!=parameter){
for (Entry<String, ?> entry : parameter.entrySet()) {
try {
BeanUtils.setProperty(entity, entry.getKey(), entry.getValue());
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// MyBeanUtils.setFieldValue(entity, entry.getKey(), entry.getValue());
}
}
return entity;
}
public static <T> T toEntity(Class<T> clazz, HaloMap map) {
T obj = null;
try {
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
obj = clazz.newInstance(); // 创建 JavaBean 对象
// 给 JavaBean 对象的属性赋值
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (map.containsKey(propertyName)) {
// 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
Object value = map.get(propertyName);
if ("".equals(value)) {
value = null;
}
Object[] args = new Object[1];
args[0] = value;
try {
descriptor.getWriteMethod().invoke(obj, args);
} catch (InvocationTargetException e) {
logger.warn("字段映射失败");
}
}
}
} catch (IllegalAccessException e) {
logger.error("实例化 JavaBean 失败");
} catch (IntrospectionException e) {
logger.error("分析类属性失败");
} catch (IllegalArgumentException e) {
logger.error("映射错误");
} catch (InstantiationException e) {
logger.error("实例化 JavaBean 失败");
}
return (T) obj;
}
public static HaloMap toHaloMap(Object bean) {
Class<? extends Object> clazz = bean.getClass();
HaloMap returnMap = new HaloMap();
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(clazz);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!propertyName.equals("class")) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
if (null != propertyName) {
propertyName = propertyName.toString();
}
if(null==result){
continue;
}
if (null != result) {
result = result.toString();
}
returnMap.put(propertyName, result);
}
}
} catch (IntrospectionException e) {
logger.error("分析类属性失败");
} catch (IllegalAccessException e) {
logger.error("实例化 JavaBean 失败");
} catch (IllegalArgumentException e) {
logger.error("映射错误");
} catch (InvocationTargetException e) {
logger.error("调用属性的 setter 方法失败");
}
return returnMap;
}
public static HaloMap toFindHaloMap(Object bean) {
Class<? extends Object> clazz = bean.getClass();
HaloMap returnMap = new HaloMap();
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(clazz);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!propertyName.equals("class")) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
if (null != propertyName) {
propertyName = propertyName.toString();
}
if(null==result){
continue;
}
if (null != result) {
result = result.toString();
}
if(propertyName.equals("json")){
continue;
}
returnMap.put(propertyName+HaloDao.MYSPACE+HaloDao.PRM, result);
}
}
} catch (IntrospectionException e) {
logger.error("分析类属性失败");
} catch (IllegalAccessException e) {
logger.error("实例化 JavaBean 失败");
} catch (IllegalArgumentException e) {
logger.error("映射错误");
} catch (InvocationTargetException e) {
logger.error("调用属性的 setter 方法失败");
}
return returnMap;
}
}
| VonChange/haloDao-Hibernate3 | src/main/java/com/ht/halo/hibernate3/base/MyEntityUtils.java | Java | gpl-2.0 | 6,670 |
import os
import unittest
import tempfile
from git import Repo
from oeqa.utils.commands import get_bb_var
from oe.buildhistory_analysis import blob_to_dict, compare_dict_blobs
class TestBlobParsing(unittest.TestCase):
def setUp(self):
import time
self.repo_path = tempfile.mkdtemp(prefix='selftest-buildhistory',
dir=get_bb_var('TOPDIR'))
self.repo = Repo.init(self.repo_path)
self.test_file = "test"
self.var_map = {}
def tearDown(self):
import shutil
shutil.rmtree(self.repo_path)
def commit_vars(self, to_add={}, to_remove = [], msg="A commit message"):
if len(to_add) == 0 and len(to_remove) == 0:
return
for k in to_remove:
self.var_map.pop(x,None)
for k in to_add:
self.var_map[k] = to_add[k]
with open(os.path.join(self.repo_path, self.test_file), 'w') as repo_file:
for k in self.var_map:
repo_file.write("%s = %s\n" % (k, self.var_map[k]))
self.repo.git.add("--all")
self.repo.git.commit(message=msg)
def test_blob_to_dict(self):
"""
Test convertion of git blobs to dictionary
"""
valuesmap = { "foo" : "1", "bar" : "2" }
self.commit_vars(to_add = valuesmap)
blob = self.repo.head.commit.tree.blobs[0]
self.assertEqual(valuesmap, blob_to_dict(blob),
"commit was not translated correctly to dictionary")
def test_compare_dict_blobs(self):
"""
Test comparisson of dictionaries extracted from git blobs
"""
changesmap = { "foo-2" : ("2", "8"), "bar" : ("","4"), "bar-2" : ("","5")}
self.commit_vars(to_add = { "foo" : "1", "foo-2" : "2", "foo-3" : "3" })
blob1 = self.repo.heads.master.commit.tree.blobs[0]
self.commit_vars(to_add = { "foo-2" : "8", "bar" : "4", "bar-2" : "5" })
blob2 = self.repo.heads.master.commit.tree.blobs[0]
change_records = compare_dict_blobs(os.path.join(self.repo_path, self.test_file),
blob1, blob2, False, False)
var_changes = { x.fieldname : (x.oldvalue, x.newvalue) for x in change_records}
self.assertEqual(changesmap, var_changes, "Changes not reported correctly")
def test_compare_dict_blobs_default(self):
"""
Test default values for comparisson of git blob dictionaries
"""
defaultmap = { x : ("default", "1") for x in ["PKG", "PKGE", "PKGV", "PKGR"]}
self.commit_vars(to_add = { "foo" : "1" })
blob1 = self.repo.heads.master.commit.tree.blobs[0]
self.commit_vars(to_add = { "PKG" : "1", "PKGE" : "1", "PKGV" : "1", "PKGR" : "1" })
blob2 = self.repo.heads.master.commit.tree.blobs[0]
change_records = compare_dict_blobs(os.path.join(self.repo_path, self.test_file),
blob1, blob2, False, False)
var_changes = {}
for x in change_records:
oldvalue = "default" if ("default" in x.oldvalue) else x.oldvalue
var_changes[x.fieldname] = (oldvalue, x.newvalue)
self.assertEqual(defaultmap, var_changes, "Defaults not set properly")
| schleichdi2/OPENNFR-6.1-CORE | opennfr-openembedded-core/meta/lib/oeqa/selftest/oelib/buildhistory.py | Python | gpl-2.0 | 3,191 |
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# 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 re
from PyQt5 import QtWidgets
from picard import config
from picard.plugin import ExtensionPoint
class OptionsCheckError(Exception):
def __init__(self, title, info):
self.title = title
self.info = info
class OptionsPage(QtWidgets.QWidget):
PARENT = None
SORT_ORDER = 1000
ACTIVE = True
STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }"
STYLESHEET = "QLabel { qproperty-wordWrap: true; }"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet(self.STYLESHEET)
def info(self):
raise NotImplementedError
def check(self):
pass
def load(self):
pass
def save(self):
pass
def restore_defaults(self):
try:
options = self.options
except AttributeError:
return
old_options = {}
for option in options:
if option.section == 'setting':
old_options[option.name] = config.setting[option.name]
config.setting[option.name] = option.default
self.load()
# Restore the config values incase the user doesn't save after restoring defaults
for key in old_options:
config.setting[key] = old_options[key]
def display_error(self, error):
dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self)
dialog.exec_()
def init_regex_checker(self, regex_edit, regex_error):
"""
regex_edit : a widget supporting text() and textChanged() methods, ie
QLineEdit
regex_error : a widget supporting setStyleSheet() and setText() methods,
ie. QLabel
"""
def check():
try:
re.compile(regex_edit.text())
except re.error as e:
raise OptionsCheckError(_("Regex Error"), string_(e))
def live_checker(text):
regex_error.setStyleSheet("")
regex_error.setText("")
try:
check()
except OptionsCheckError as e:
regex_error.setStyleSheet(self.STYLESHEET_ERROR)
regex_error.setText(e.info)
regex_edit.textChanged.connect(live_checker)
_pages = ExtensionPoint()
def register_options_page(page_class):
_pages.register(page_class.__module__, page_class)
| samj1912/picard | picard/ui/options/__init__.py | Python | gpl-2.0 | 3,282 |
<?php
/*
* DynamicHub
*
* Copyright (C) 2015-2016 LegendsOfMCPE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author LegendsOfMCPE
*/
namespace DynamicHub\Module\Match;
class MatchBaseConfig{
// players
public $maxPlayers;
public $semiMaxPlayers;
public $minPlayers;
// time, in seconds
public $minWaitTime;
public $maxWaitTime;
public $maxMatchTime;
public $maxPrepTime;
// positions
public $playerJoinPositions = [];
public $spectatorJoinPositions = [];
public function getNextPlayerJoinPosition(){
if(next($this->playerJoinPositions) === false){
reset($this->playerJoinPositions);
}
return current($this->playerJoinPositions);
}
public function getNextSpectatorJoinPosition(){
if(next($this->spectatorJoinPositions) === false){
reset($this->spectatorJoinPositions);
}
return current($this->spectatorJoinPositions);
}
}
| LegendOfMCPE/DynamicHub | DynamicHub/src/DynamicHub/Module/Match/MatchBaseConfig.php | PHP | gpl-2.0 | 1,090 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LogicaDeNegocios")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Intel Corporation")]
[assembly: AssemblyProduct("LogicaDeNegocios")]
[assembly: AssemblyCopyright("Copyright © Intel Corporation 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("979b681f-8f57-479b-a119-c830ef08f826")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| pabloariasmora/BattlePong | BattlePong/LogicaDeNegocios/Properties/AssemblyInfo.cs | C# | gpl-2.0 | 1,442 |
<?php
/*
* Copyright 2010 Google Inc.
*
* 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.
*/
/**
* Service definition for Pagespeedonline (v1).
*
* <p>
* Lets you analyze the performance of a web page and get tailored suggestions to make that page faster.
* </p>
*
* <p>
* For more information about this service, see the API
* <a href="https://developers.google.com/speed/docs/insights/v1/getting_started" target="_blank">Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class GoogleGAL_Service_Pagespeedonline extends GoogleGAL_Service
{
public $pagespeedapi;
/**
* Constructs the internal representation of the Pagespeedonline service.
*
* @param GoogleGAL_Client $client
*/
public function __construct(GoogleGAL_Client $client)
{
parent::__construct($client);
$this->servicePath = 'pagespeedonline/v1/';
$this->version = 'v1';
$this->serviceName = 'pagespeedonline';
$this->pagespeedapi = new GoogleGAL_Service_Pagespeedonline_Pagespeedapi_Resource(
$this,
$this->serviceName,
'pagespeedapi',
array(
'methods' => array(
'runpagespeed' => array(
'path' => 'runPagespeed',
'httpMethod' => 'GET',
'parameters' => array(
'url' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'screenshot' => array(
'location' => 'query',
'type' => 'boolean',
),
'locale' => array(
'location' => 'query',
'type' => 'string',
),
'snapshots' => array(
'location' => 'query',
'type' => 'boolean',
),
'strategy' => array(
'location' => 'query',
'type' => 'string',
),
'rule' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'filter_third_party_resources' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),
)
)
);
}
}
/**
* The "pagespeedapi" collection of methods.
* Typical usage is:
* <code>
* $pagespeedonlineService = new GoogleGAL_Service_Pagespeedonline(...);
* $pagespeedapi = $pagespeedonlineService->pagespeedapi;
* </code>
*/
class GoogleGAL_Service_Pagespeedonline_Pagespeedapi_Resource extends GoogleGAL_Service_Resource
{
/**
* Runs Page Speed analysis on the page at the specified URL, and returns a Page
* Speed score, a list of suggestions to make that page faster, and other
* information. (pagespeedapi.runpagespeed)
*
* @param string $url
* The URL to fetch and analyze
* @param array $optParams Optional parameters.
*
* @opt_param bool screenshot
* Indicates if binary data containing a screenshot should be included
* @opt_param string locale
* The locale used to localize formatted results
* @opt_param bool snapshots
* Indicates if binary data containing snapshot images should be included
* @opt_param string strategy
* The analysis strategy to use
* @opt_param string rule
* A Page Speed rule to run; if none are given, all rules are run
* @opt_param bool filter_third_party_resources
* Indicates if third party resources should be filtered out before PageSpeed analysis.
* @return GoogleGAL_Service_Pagespeedonline_Result
*/
public function runpagespeed($url, $optParams = array())
{
$params = array('url' => $url);
$params = array_merge($params, $optParams);
return $this->call('runpagespeed', array($params), "GoogleGAL_Service_Pagespeedonline_Result");
}
}
class GoogleGAL_Service_Pagespeedonline_Result extends GoogleGAL_Collection
{
protected $formattedResultsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResults';
protected $formattedResultsDataType = '';
public $id;
public $invalidRules;
public $kind;
protected $pageStatsType = 'GoogleGAL_Service_Pagespeedonline_ResultPageStats';
protected $pageStatsDataType = '';
public $responseCode;
public $score;
protected $screenshotType = 'GoogleGAL_Service_Pagespeedonline_ResultScreenshot';
protected $screenshotDataType = '';
public $title;
protected $versionType = 'GoogleGAL_Service_Pagespeedonline_ResultVersion';
protected $versionDataType = '';
public function setFormattedResults(GoogleGAL_Service_Pagespeedonline_ResultFormattedResults $formattedResults)
{
$this->formattedResults = $formattedResults;
}
public function getFormattedResults()
{
return $this->formattedResults;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setInvalidRules($invalidRules)
{
$this->invalidRules = $invalidRules;
}
public function getInvalidRules()
{
return $this->invalidRules;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setPageStats(GoogleGAL_Service_Pagespeedonline_ResultPageStats $pageStats)
{
$this->pageStats = $pageStats;
}
public function getPageStats()
{
return $this->pageStats;
}
public function setResponseCode($responseCode)
{
$this->responseCode = $responseCode;
}
public function getResponseCode()
{
return $this->responseCode;
}
public function setScore($score)
{
$this->score = $score;
}
public function getScore()
{
return $this->score;
}
public function setScreenshot(GoogleGAL_Service_Pagespeedonline_ResultScreenshot $screenshot)
{
$this->screenshot = $screenshot;
}
public function getScreenshot()
{
return $this->screenshot;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
public function setVersion(GoogleGAL_Service_Pagespeedonline_ResultVersion $version)
{
$this->version = $version;
}
public function getVersion()
{
return $this->version;
}
}
class GoogleGAL_Service_Pagespeedonline_ResultFormattedResults extends GoogleGAL_Model
{
public $locale;
protected $ruleResultsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElement';
protected $ruleResultsDataType = 'map';
public function setLocale($locale)
{
$this->locale = $locale;
}
public function getLocale()
{
return $this->locale;
}
public function setRuleResults($ruleResults)
{
$this->ruleResults = $ruleResults;
}
public function getRuleResults()
{
return $this->ruleResults;
}
}
class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElement extends GoogleGAL_Collection
{
public $localizedRuleName;
public $ruleImpact;
protected $urlBlocksType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocks';
protected $urlBlocksDataType = 'array';
public function setLocalizedRuleName($localizedRuleName)
{
$this->localizedRuleName = $localizedRuleName;
}
public function getLocalizedRuleName()
{
return $this->localizedRuleName;
}
public function setRuleImpact($ruleImpact)
{
$this->ruleImpact = $ruleImpact;
}
public function getRuleImpact()
{
return $this->ruleImpact;
}
public function setUrlBlocks($urlBlocks)
{
$this->urlBlocks = $urlBlocks;
}
public function getUrlBlocks()
{
return $this->urlBlocks;
}
}
class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocks extends GoogleGAL_Collection
{
protected $headerType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksHeader';
protected $headerDataType = '';
protected $urlsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrls';
protected $urlsDataType = 'array';
public function setHeader(GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksHeader $header)
{
$this->header = $header;
}
public function getHeader()
{
return $this->header;
}
public function setUrls($urls)
{
$this->urls = $urls;
}
public function getUrls()
{
return $this->urls;
}
}
class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksHeader extends GoogleGAL_Collection
{
protected $argsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksHeaderArgs';
protected $argsDataType = 'array';
public $format;
public function setArgs($args)
{
$this->args = $args;
}
public function getArgs()
{
return $this->args;
}
public function setFormat($format)
{
$this->format = $format;
}
public function getFormat()
{
return $this->format;
}
}
class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksHeaderArgs extends GoogleGAL_Model
{
public $type;
public $value;
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
public function setValue($value)
{
$this->value = $value;
}
public function getValue()
{
return $this->value;
}
}
class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrls extends GoogleGAL_Collection
{
protected $detailsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsDetails';
protected $detailsDataType = 'array';
protected $resultType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsResult';
protected $resultDataType = '';
public function setDetails($details)
{
$this->details = $details;
}
public function getDetails()
{
return $this->details;
}
public function setResult(GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsResult $result)
{
$this->result = $result;
}
public function getResult()
{
return $this->result;
}
}
class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsDetails extends GoogleGAL_Collection
{
protected $argsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsDetailsArgs';
protected $argsDataType = 'array';
public $format;
public function setArgs($args)
{
$this->args = $args;
}
public function getArgs()
{
return $this->args;
}
public function setFormat($format)
{
$this->format = $format;
}
public function getFormat()
{
return $this->format;
}
}
class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsDetailsArgs extends GoogleGAL_Model
{
public $type;
public $value;
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
public function setValue($value)
{
$this->value = $value;
}
public function getValue()
{
return $this->value;
}
}
class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsResult extends GoogleGAL_Collection
{
protected $argsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsResultArgs';
protected $argsDataType = 'array';
public $format;
public function setArgs($args)
{
$this->args = $args;
}
public function getArgs()
{
return $this->args;
}
public function setFormat($format)
{
$this->format = $format;
}
public function getFormat()
{
return $this->format;
}
}
class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsResultArgs extends GoogleGAL_Model
{
public $type;
public $value;
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
public function setValue($value)
{
$this->value = $value;
}
public function getValue()
{
return $this->value;
}
}
class GoogleGAL_Service_Pagespeedonline_ResultPageStats extends GoogleGAL_Model
{
public $cssResponseBytes;
public $flashResponseBytes;
public $htmlResponseBytes;
public $imageResponseBytes;
public $javascriptResponseBytes;
public $numberCssResources;
public $numberHosts;
public $numberJsResources;
public $numberResources;
public $numberStaticResources;
public $otherResponseBytes;
public $textResponseBytes;
public $totalRequestBytes;
public function setCssResponseBytes($cssResponseBytes)
{
$this->cssResponseBytes = $cssResponseBytes;
}
public function getCssResponseBytes()
{
return $this->cssResponseBytes;
}
public function setFlashResponseBytes($flashResponseBytes)
{
$this->flashResponseBytes = $flashResponseBytes;
}
public function getFlashResponseBytes()
{
return $this->flashResponseBytes;
}
public function setHtmlResponseBytes($htmlResponseBytes)
{
$this->htmlResponseBytes = $htmlResponseBytes;
}
public function getHtmlResponseBytes()
{
return $this->htmlResponseBytes;
}
public function setImageResponseBytes($imageResponseBytes)
{
$this->imageResponseBytes = $imageResponseBytes;
}
public function getImageResponseBytes()
{
return $this->imageResponseBytes;
}
public function setJavascriptResponseBytes($javascriptResponseBytes)
{
$this->javascriptResponseBytes = $javascriptResponseBytes;
}
public function getJavascriptResponseBytes()
{
return $this->javascriptResponseBytes;
}
public function setNumberCssResources($numberCssResources)
{
$this->numberCssResources = $numberCssResources;
}
public function getNumberCssResources()
{
return $this->numberCssResources;
}
public function setNumberHosts($numberHosts)
{
$this->numberHosts = $numberHosts;
}
public function getNumberHosts()
{
return $this->numberHosts;
}
public function setNumberJsResources($numberJsResources)
{
$this->numberJsResources = $numberJsResources;
}
public function getNumberJsResources()
{
return $this->numberJsResources;
}
public function setNumberResources($numberResources)
{
$this->numberResources = $numberResources;
}
public function getNumberResources()
{
return $this->numberResources;
}
public function setNumberStaticResources($numberStaticResources)
{
$this->numberStaticResources = $numberStaticResources;
}
public function getNumberStaticResources()
{
return $this->numberStaticResources;
}
public function setOtherResponseBytes($otherResponseBytes)
{
$this->otherResponseBytes = $otherResponseBytes;
}
public function getOtherResponseBytes()
{
return $this->otherResponseBytes;
}
public function setTextResponseBytes($textResponseBytes)
{
$this->textResponseBytes = $textResponseBytes;
}
public function getTextResponseBytes()
{
return $this->textResponseBytes;
}
public function setTotalRequestBytes($totalRequestBytes)
{
$this->totalRequestBytes = $totalRequestBytes;
}
public function getTotalRequestBytes()
{
return $this->totalRequestBytes;
}
}
class GoogleGAL_Service_Pagespeedonline_ResultScreenshot extends GoogleGAL_Model
{
public $data;
public $height;
public $mimeType;
public $width;
public function setData($data)
{
$this->data = $data;
}
public function getData()
{
return $this->data;
}
public function setHeight($height)
{
$this->height = $height;
}
public function getHeight()
{
return $this->height;
}
public function setMimeType($mimeType)
{
$this->mimeType = $mimeType;
}
public function getMimeType()
{
return $this->mimeType;
}
public function setWidth($width)
{
$this->width = $width;
}
public function getWidth()
{
return $this->width;
}
}
class GoogleGAL_Service_Pagespeedonline_ResultVersion extends GoogleGAL_Model
{
public $major;
public $minor;
public function setMajor($major)
{
$this->major = $major;
}
public function getMajor()
{
return $this->major;
}
public function setMinor($minor)
{
$this->minor = $minor;
}
public function getMinor()
{
return $this->minor;
}
}
| mrengy/flip2014 | wp-content/plugins/google-apps-login/core/Google/Service/Pagespeedonline.php | PHP | gpl-2.0 | 17,220 |
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="<?php gp_keywords(); ?>">
<meta name="keywords" content="<?php gp_keywords(); ?>" />
<meta name="description" itemprop="description" content="<?php gp_description(); ?>" />
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/dist/css/main.css"/>
<title><?php wp_title( '_', true, 'right' ); bloginfo( 'name' ); ?></title>
</head>
<body>
<header class="head-s">
<div class="r">
<a href="/book_tag" class="l" title="搜索"><i class="icon-search"></i></a>
<a href="/" class="l" title="首页"><i class="icon-home"></i></a>
</div>
<a href="/" class="l"><i class="icon-pre"></i></a>
<h3>帮助文档</h3>
</header>
<div class="content">
<div class="help-box">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php the_content( __( '<p class="serif">Read the rest of this page →</p>', 'gampress' ) ); ?>
<?php endwhile; endif; ?>
</div>
</div>
<?php get_footer();?> | kuibobo/GamPress | wp-content/plugins/gampress-ext/themes/eBooks/page.php | PHP | gpl-2.0 | 1,338 |
<?php
class departamento extends controller {
public function __construct() {
parent::__construct();
include 'controllers/loginController.php';
$valida = new login();
$valida->sessao_valida();
}
public function index_action($pagina = 1) {
//list all records
$_SESSION['pagina'] = $pagina;
$this->smarty->assign('paginador', $this->mostraGrid());
$this->smarty->assign('title', 'Departamento');
//call the smarty
$this->smarty->display('departamento/index.tpl');
}
public function add() {
$this->smarty->assign('title', 'Novo Departamento');
$this->smarty->display('departamento/new.tpl');
}
public function save() {
$modeldepartamento = new departamentoModel();
$dados['departamento'] = $_POST['name'];
//$dados['created'] = date("Y-m-d H:i:s");
//$dados['active'] = 1;
$modeldepartamento->setDepartamento($dados);
header('Location: /departamento');
}
public function update() {
$id = $this->getParam('id');
$modeldepartamento = new departamentoModel();
$dados['codigo'] = $id;
$dados['departamento'] = $_POST['name'];
$modeldepartamento->updDepartamento($dados);
header('Location: /departamento');
}
public function detalhes() {
$id = $this->getParam('id');
$modeldepartamento = new departamentoModel();
$resdepartamento = $modeldepartamento->getDepartamento('codigo=' . $id);
$this->smarty->assign('registro', $resdepartamento[0]);
$this->smarty->assign('title', 'Detalhes do Departamento');
//call the smarty
$this->smarty->display('departamento/detail.tpl');
}
public function edit() {
//die();
$id = $this->getParam('id');
$modeldepartamento = new departamentoModel();
$resdepartamento = $modeldepartamento->getDepartamento('codigo=' . $id);
$this->smarty->assign('registro', $resdepartamento[0]);
$this->smarty->assign('title', 'Editar Departamento');
//call the smarty
$this->smarty->display('departamento/edit.tpl');
}
public function delete() {
$id = $this->getParam('id');
$modeldepartamento = new departamentoModel();
$dados['codigo'] = $id;
$modeldepartamento->delDepartamento($dados);
header('Location: /departamento');
}
public function mostraGrid(){
$total_reg = "10"; // número de registros por página
$pagina = $_SESSION['pagina'];
if (!$pagina) {
$pc = "1";
} else {
$pc = $pagina;
}
$inicio = $pc - 1;
$inicio = $inicio * $total_reg;
//list all records
$model_departamentos = new departamentoModel();
$departamentos_res = $model_departamentos->getDepartamentoLimit(null,$inicio,$total_reg); //Full table Scan :( or :)
//send the records to template sytem
$this->smarty->assign('listdepartamento', $departamentos_res);
$query_total = $model_departamentos->getCountDepartamento();
$total_registros = $query_total[0]['total']; //pega o valor
$html = $this->paginador($pc, $total_registros, 'departamento');
return $html;
}
public function paginacao() {
$this->index_action($this->getParam('pagina'));
}
}
?>
| suspecie/controle-eventos-php-thepowerpuffgirls | controllers/departamentoController.php | PHP | gpl-2.0 | 3,526 |
<?php // $Id: oci8po.class.php 68 2009-07-31 18:23:01Z dlandau $
///////////////////////////////////////////////////////////////////////////
// //
// NOTICE OF COPYRIGHT //
// //
// Moodle - Modular Object-Oriented Dynamic Learning Environment //
// http://moodle.com //
// //
// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
// (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.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 //
// //
///////////////////////////////////////////////////////////////////////////
/// This class generate SQL code to be used against Oracle
/// It extends XMLDBgenerator so everything can be
/// overriden as needed to generate correct SQL.
class XMLDBoci8po extends XMLDBgenerator {
/// Only set values that are different from the defaults present in XMLDBgenerator
var $statement_end = "\n/"; // String to be automatically added at the end of each statement
// Using "/" because the standard ";" isn't good for stored procedures (triggers)
var $number_type = 'NUMBER'; // Proper type for NUMBER(x) in this DB
var $unsigned_allowed = false; // To define in the generator must handle unsigned information
var $default_for_char = ' '; // To define the default to set for NOT NULLs CHARs without default (null=do nothing)
// Using this whitespace here because Oracle doesn't distinguish empty and null! :-(
var $drop_default_clause_required = true; //To specify if the generator must use some DEFAULT clause to drop defaults
var $drop_default_clause = 'NULL'; //The DEFAULT clause required to drop defaults
var $default_after_null = false; //To decide if the default clause of each field must go after the null clause
var $sequence_extra_code = true; //Does the generator need to add extra code to generate the sequence fields
var $sequence_name = ''; //Particular name for inline sequences in this generator
var $drop_table_extra_code = true; //Does the generator need to add code after table drop
var $rename_table_extra_code = true; //Does the generator need to add code after table rename
var $rename_column_extra_code = true; //Does the generator need to add code after field rename
var $enum_inline_code = false; //Does the generator need to add inline code in the column definition
var $alter_column_sql = 'ALTER TABLE TABLENAME MODIFY (COLUMNSPECS)'; //The SQL template to alter columns
/**
* Creates one new XMLDBoci8po
*/
function XMLDBoci8po() {
parent::XMLDBgenerator();
$this->prefix = '';
$this->reserved_words = $this->getReservedWords();
}
/**
* Given one XMLDB Type, lenght and decimals, returns the DB proper SQL type
*/
function getTypeSQL ($xmldb_type, $xmldb_length=null, $xmldb_decimals=null) {
switch ($xmldb_type) {
case XMLDB_TYPE_INTEGER: // From http://www.postgresql.org/docs/7.4/interactive/datatype.html
if (empty($xmldb_length)) {
$xmldb_length = 10;
}
$dbtype = 'NUMBER(' . $xmldb_length . ')';
break;
case XMLDB_TYPE_NUMBER:
$dbtype = $this->number_type;
/// 38 is the max allowed
if ($xmldb_length > 38) {
$xmldb_length = 38;
}
if (!empty($xmldb_length)) {
$dbtype .= '(' . $xmldb_length;
if (!empty($xmldb_decimals)) {
$dbtype .= ',' . $xmldb_decimals;
}
$dbtype .= ')';
}
break;
case XMLDB_TYPE_FLOAT:
$dbtype = 'NUMBER';
break;
case XMLDB_TYPE_CHAR:
$dbtype = 'VARCHAR2';
if (empty($xmldb_length)) {
$xmldb_length='255';
}
$dbtype .= '(' . $xmldb_length . ')';
break;
case XMLDB_TYPE_TEXT:
$dbtype = 'CLOB';
break;
case XMLDB_TYPE_BINARY:
$dbtype = 'BLOB';
break;
case XMLDB_TYPE_DATETIME:
$dbtype = 'DATE';
break;
}
return $dbtype;
}
/**
* Returns the code needed to create one enum for the xmldb_table and xmldb_field passes
*/
function getEnumExtraSQL ($xmldb_table, $xmldb_field) {
$sql = 'CONSTRAINT ' . $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'ck');
$sql.= ' CHECK (' . $this->getEncQuoted($xmldb_field->getName()) . ' IN (' . implode(', ', $xmldb_field->getEnumValues()) . '))';
return $sql;
}
/**
* Returns the code needed to create one sequence for the xmldb_table and xmldb_field passes
*/
function getCreateSequenceSQL ($xmldb_table, $xmldb_field) {
$results = array();
$sequence_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'seq');
$sequence = "CREATE SEQUENCE " . $sequence_name;
$sequence.= "\n START WITH 1";
$sequence.= "\n INCREMENT BY 1";
$sequence.= "\n NOMAXVALUE";
$results[] = $sequence;
$results = array_merge($results, $this->getCreateTriggerSQL ($xmldb_table, $xmldb_field));
return $results;
}
/**
* Returns the code needed to create one trigger for the xmldb_table and xmldb_field passed
*/
function getCreateTriggerSQL ($xmldb_table, $xmldb_field) {
$trigger_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'trg');
$sequence_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'seq');
$trigger = "CREATE TRIGGER " . $trigger_name;
$trigger.= "\n BEFORE INSERT";
$trigger.= "\nON " . $this->getTableName($xmldb_table);
$trigger.= "\n FOR EACH ROW";
$trigger.= "\nBEGIN";
$trigger.= "\n IF :new." . $this->getEncQuoted($xmldb_field->getName()) . ' IS NULL THEN';
$trigger.= "\n SELECT " . $sequence_name . '.nextval INTO :new.' . $this->getEncQuoted($xmldb_field->getName()) . " FROM dual;";
$trigger.= "\n END IF;";
$trigger.= "\nEND;";
return array($trigger);
}
/**
* Returns the code needed to drop one sequence for the xmldb_table and xmldb_field passed
* Can, optionally, specify if the underlying trigger will be also dropped
*/
function getDropSequenceSQL ($xmldb_table, $xmldb_field, $include_trigger=false) {
$sequence_name = $this->getSequenceFromDB($xmldb_table);
$sequence = "DROP SEQUENCE " . $sequence_name;
$trigger_name = $this->getTriggerFromDB($xmldb_table);
$trigger = "DROP TRIGGER " . $trigger_name;
if ($include_trigger) {
$result = array($sequence, $trigger);
} else {
$result = array($sequence);
}
return $result;
}
/**
* Returns the code (in array) needed to add one comment to the table
*/
function getCommentSQL ($xmldb_table) {
$comment = "COMMENT ON TABLE " . $this->getTableName($xmldb_table);
$comment.= " IS '" . addslashes(substr($xmldb_table->getComment(), 0, 250)) . "'";
return array($comment);
}
/**
* Returns the code (array of statements) needed to execute extra statements on field rename
*/
function getRenameFieldExtraSQL ($xmldb_table, $xmldb_field, $newname) {
$results = array();
/// If the field is enum, drop and re-create the check constraint
if ($xmldb_field->getEnum()) {
/// Drop the current enum
$results = array_merge($results, $this->getDropEnumSQL($xmldb_table, $xmldb_field));
/// Change field name (over a clone to avoid some potential problems later)
$new_xmldb_field = clone($xmldb_field);
$new_xmldb_field->setName($newname);
/// Recreate the enum
$results = array_merge($results, $this->getCreateEnumSQL($xmldb_table, $new_xmldb_field));
}
return $results;
}
/**
* Returns the code (array of statements) needed to execute extra statements on table drop
*/
function getDropTableExtraSQL ($xmldb_table) {
$xmldb_field = new XMLDBField('id'); // Fields having sequences should be exclusively, id.
return $this->getDropSequenceSQL($xmldb_table, $xmldb_field, false);
}
/**
* Returns the code (array of statements) needed to execute extra statements on table rename
*/
function getRenameTableExtraSQL ($xmldb_table, $newname) {
$results = array();
$xmldb_field = new XMLDBField('id'); // Fields having sequences should be exclusively, id.
$oldseqname = $this->getSequenceFromDB($xmldb_table);
$newseqname = $this->getNameForObject($newname, $xmldb_field->getName(), 'seq');
/// Rename de sequence
$results[] = 'RENAME ' . $oldseqname . ' TO ' . $newseqname;
$oldtriggername = $this->getTriggerFromDB($xmldb_table);
$newtriggername = $this->getNameForObject($newname, $xmldb_field->getName(), 'trg');
/// Drop old trigger
$results[] = "DROP TRIGGER " . $oldtriggername;
$newt = new XMLDBTable($newname); /// Temp table for trigger code generation
/// Create new trigger
$results = array_merge($results, $this->getCreateTriggerSQL($newt, $xmldb_field));
/// Rename all the check constraints in the table
$oldtablename = $this->getTableName($xmldb_table);
$newtablename = $this->getTableName($newt);
$oldconstraintprefix = $this->getNameForObject($xmldb_table->getName(), '');
$newconstraintprefix = $this->getNameForObject($newt->getName(), '', '');
if ($constraints = $this->getCheckConstraintsFromDB($xmldb_table)) {
foreach ($constraints as $constraint) {
/// Drop the old constraint
$results[] = 'ALTER TABLE ' . $newtablename . ' DROP CONSTRAINT ' . $constraint->name;
/// Calculate the new constraint name
$newconstraintname = str_replace($oldconstraintprefix, $newconstraintprefix, $constraint->name);
/// Add the new constraint
$results[] = 'ALTER TABLE ' . $newtablename . ' ADD CONSTRAINT ' . $newconstraintname .
' CHECK (' . $constraint->description . ')';
}
}
return $results;
}
/**
* Given one XMLDBTable and one XMLDBField, return the SQL statements needded to alter the field in the table
* Oracle has some severe limits:
* - clob and blob fields doesn't allow type to be specified
* - error is dropped if the null/not null clause is specified and hasn't changed
* - changes in precision/decimals of numeric fields drop an ORA-1440 error
*/
function getAlterFieldSQL($xmldb_table, $xmldb_field) {
global $db;
$results = array(); /// To store all the needed SQL commands
/// Get the quoted name of the table and field
$tablename = $this->getTableName($xmldb_table);
$fieldname = $this->getEncQuoted($xmldb_field->getName());
/// Take a look to field metadata
$meta = array_change_key_case($db->MetaColumns($tablename));
$metac = $meta[$fieldname];
$oldtype = strtolower($metac->type);
$oldmetatype = column_type($xmldb_table->getName(), $fieldname);
$oldlength = $metac->max_length;
/// To calculate the oldlength if the field is numeric, we need to perform one extra query
/// because ADOdb has one bug here. http://phplens.com/lens/lensforum/msgs.php?id=15883
if ($oldmetatype == 'N') {
$uppertablename = strtoupper($tablename);
$upperfieldname = strtoupper($fieldname);
if ($col = get_record_sql("SELECT cname, precision
FROM col
WHERE tname = '$uppertablename'
AND cname = '$upperfieldname'")) {
$oldlength = $col->precision;
}
}
$olddecimals = empty($metac->scale) ? null : $metac->scale;
$oldnotnull = empty($metac->not_null) ? false : $metac->not_null;
$olddefault = empty($metac->default_value) || strtoupper($metac->default_value) == 'NULL' ? null : $metac->default_value;
$typechanged = true; //By default, assume that the column type has changed
$precisionchanged = true; //By default, assume that the column precision has changed
$decimalchanged = true; //By default, assume that the column decimal has changed
$defaultchanged = true; //By default, assume that the column default has changed
$notnullchanged = true; //By default, assume that the column notnull has changed
$from_temp_fields = false; //By default don't assume we are going to use temporal fields
/// Detect if we are changing the type of the column
if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER && substr($oldmetatype, 0, 1) == 'I') ||
($xmldb_field->getType() == XMLDB_TYPE_NUMBER && $oldmetatype == 'N') ||
($xmldb_field->getType() == XMLDB_TYPE_FLOAT && $oldmetatype == 'F') ||
($xmldb_field->getType() == XMLDB_TYPE_CHAR && substr($oldmetatype, 0, 1) == 'C') ||
($xmldb_field->getType() == XMLDB_TYPE_TEXT && substr($oldmetatype, 0, 1) == 'X') ||
($xmldb_field->getType() == XMLDB_TYPE_BINARY && $oldmetatype == 'B')) {
$typechanged = false;
}
/// Detect if precision has changed
if (($xmldb_field->getType() == XMLDB_TYPE_TEXT) ||
($xmldb_field->getType() == XMLDB_TYPE_BINARY) ||
($oldlength == -1) ||
($xmldb_field->getLength() == $oldlength)) {
$precisionchanged = false;
}
/// Detect if decimal has changed
if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER) ||
($xmldb_field->getType() == XMLDB_TYPE_CHAR) ||
($xmldb_field->getType() == XMLDB_TYPE_TEXT) ||
($xmldb_field->getType() == XMLDB_TYPE_BINARY) ||
(!$xmldb_field->getDecimals()) ||
(!$olddecimals) ||
($xmldb_field->getDecimals() == $olddecimals)) {
$decimalchanged = false;
}
/// Detect if we are changing the default
if (($xmldb_field->getDefault() === null && $olddefault === null) ||
($xmldb_field->getDefault() === $olddefault) || //Check both equality and
("'" . $xmldb_field->getDefault() . "'" === $olddefault)) { //Equality with quotes because ADOdb returns the default with quotes
$defaultchanged = false;
}
/// Detect if we are changing the nullability
if (($xmldb_field->getNotnull() === $oldnotnull)) {
$notnullchanged = false;
}
/// If type has changed or precision or decimal has changed and we are in one numeric field
/// - create one temp column with the new specs
/// - fill the new column with the values from the old one
/// - drop the old column
/// - rename the temp column to the original name
if (($typechanged) || (($oldmetatype == 'N' || $oldmetatype == 'I') && ($precisionchanged || $decimalchanged))) {
$tempcolname = $xmldb_field->getName() . '_alter_column_tmp';
/// Prevent temp field to have both NULL/NOT NULL and DEFAULT constraints
$this->alter_column_skip_notnull = true;
$this->alter_column_skip_default = true;
$xmldb_field->setName($tempcolname);
/// Create the temporal column
$results = array_merge($results, $this->getAddFieldSQL($xmldb_table, $xmldb_field));
/// Copy contents from original col to the temporal one
$results[] = 'UPDATE ' . $tablename . ' SET ' . $tempcolname . ' = ' . $fieldname;
/// Drop the old column
$xmldb_field->setName($fieldname); //Set back the original field name
$results = array_merge($results, $this->getDropFieldSQL($xmldb_table, $xmldb_field));
/// Rename the temp column to the original one
$results[] = 'ALTER TABLE ' . $tablename . ' RENAME COLUMN ' . $tempcolname . ' TO ' . $fieldname;
/// Mark we have performed one change based in temp fields
$from_temp_fields = true;
/// Re-enable the notnull and default sections so the general AlterFieldSQL can use it
$this->alter_column_skip_notnull = false;
$this->alter_column_skip_default = false;
/// Dissable the type section because we have done it with the temp field
$this->alter_column_skip_type = true;
/// If new field is nullable, nullability hasn't changed
if (!$xmldb_field->getNotnull()) {
$notnullchanged = false;
}
/// If new field hasn't default, default hasn't changed
if ($xmldb_field->getDefault() === null) {
$defaultchanged = false;
}
}
/// If type and precision and decimals hasn't changed, prevent the type clause
if (!$typechanged && !$precisionchanged && !$decimalchanged) {
$this->alter_column_skip_type = true;
}
/// If NULL/NOT NULL hasn't changed
/// prevent null clause to be specified
if (!$notnullchanged) {
$this->alter_column_skip_notnull = true; /// Initially, prevent the notnull clause
/// But, if we have used the temp field and the new field is not null, then enforce the not null clause
if ($from_temp_fields && $xmldb_field->getNotnull()) {
$this->alter_column_skip_notnull = false;
}
}
/// If default hasn't changed
/// prevent default clause to be specified
if (!$defaultchanged) {
$this->alter_column_skip_default = true; /// Initially, prevent the default clause
/// But, if we have used the temp field and the new field has default clause, then enforce the default clause
if ($from_temp_fields && $default_clause = $this->getDefaultClause($xmldb_field)) {
$this->alter_column_skip_default = false;
}
}
/// If arriving here, something is not being skiped (type, notnull, default), calculate the standar AlterFieldSQL
if (!$this->alter_column_skip_type || !$this->alter_column_skip_notnull || !$this->alter_column_skip_default) {
$results = array_merge($results, parent::getAlterFieldSQL($xmldb_table, $xmldb_field));
return $results;
}
/// Finally return results
return $results;
}
/**
* Given one XMLDBTable and one XMLDBField, return the SQL statements needded to create its enum
* (usually invoked from getModifyEnumSQL()
*/
function getCreateEnumSQL($xmldb_table, $xmldb_field) {
/// All we have to do is to create the check constraint
return array('ALTER TABLE ' . $this->getTableName($xmldb_table) .
' ADD ' . $this->getEnumExtraSQL($xmldb_table, $xmldb_field));
}
/**
* Given one XMLDBTable and one XMLDBField, return the SQL statements needded to drop its enum
* (usually invoked from getModifyEnumSQL()
*/
function getDropEnumSQL($xmldb_table, $xmldb_field) {
/// Let's introspect to know the real name of the check constraint
if ($check_constraints = $this->getCheckConstraintsFromDB($xmldb_table, $xmldb_field)) {
$check_constraint = array_shift($check_constraints); /// Get the 1st (should be only one)
$constraint_name = strtolower($check_constraint->name); /// Extract the REAL name
/// All we have to do is to drop the check constraint
return array('ALTER TABLE ' . $this->getTableName($xmldb_table) .
' DROP CONSTRAINT ' . $constraint_name);
} else { /// Constraint not found. Nothing to do
return array();
}
}
/**
* Given one XMLDBTable and one XMLDBField, return the SQL statements needded to create its default
* (usually invoked from getModifyDefaultSQL()
*/
function getCreateDefaultSQL($xmldb_table, $xmldb_field) {
/// Just a wrapper over the getAlterFieldSQL() function for Oracle that
/// is capable of handling defaults
return $this->getAlterFieldSQL($xmldb_table, $xmldb_field);
}
/**
* Given one XMLDBTable and one XMLDBField, return the SQL statements needded to drop its default
* (usually invoked from getModifyDefaultSQL()
*/
function getDropDefaultSQL($xmldb_table, $xmldb_field) {
/// Just a wrapper over the getAlterFieldSQL() function for Oracle that
/// is capable of handling defaults
return $this->getAlterFieldSQL($xmldb_table, $xmldb_field);
}
/**
* Given one XMLDBTable returns one array with all the check constrainsts
* in the table (fetched from DB)
* Optionally the function allows one xmldb_field to be specified in
* order to return only the check constraints belonging to one field.
* Each element contains the name of the constraint and its description
* If no check constraints are found, returns an empty array
*/
function getCheckConstraintsFromDB($xmldb_table, $xmldb_field = null) {
$results = array();
$tablename = strtoupper($this->getTableName($xmldb_table));
if ($constraints = get_records_sql("SELECT lower(c.constraint_name) AS name, c.search_condition AS description
FROM user_constraints c
WHERE c.table_name = '{$tablename}'
AND c.constraint_type = 'C'
AND c.constraint_name not like 'SYS%'")) {
foreach ($constraints as $constraint) {
$results[$constraint->name] = $constraint;
}
}
/// Filter by the required field if specified
if ($xmldb_field) {
$filtered_results = array();
$filter = $xmldb_field->getName();
/// Lets clean a bit each constraint description, looking for the filtered field
foreach ($results as $key => $result) {
/// description starts by "$filter IN" assume it's a constraint beloging to the field
if (preg_match("/^{$filter} IN/i", $result->description)) {
$filtered_results[$key] = $result;
}
}
/// Assign filtered results to the final results array
$results = $filtered_results;
}
return $results;
}
/**
* Given one XMLDBTable returns one string with the sequence of the table
* in the table (fetched from DB)
* The sequence name for oracle is calculated by looking the corresponding
* trigger and retrieving the sequence name from it (because sequences are
* independent elements)
* If no sequence is found, returns false
*/
function getSequenceFromDB($xmldb_table) {
$tablename = strtoupper($this->getTableName($xmldb_table));
$prefixupper = strtoupper($this->prefix);
$sequencename = false;
if ($trigger = get_record_sql("SELECT trigger_name, trigger_body
FROM user_triggers
WHERE table_name = '{$tablename}'
AND trigger_name LIKE '{$prefixupper}%_ID%_TRG'")) {
/// If trigger found, regexp it looking for the sequence name
preg_match('/.*SELECT (.*)\.nextval/i', $trigger->trigger_body, $matches);
if (isset($matches[1])) {
$sequencename = $matches[1];
}
}
return $sequencename;
}
/**
* Given one XMLDBTable returns one string with the trigger
* in the table (fetched from DB)
* If no trigger is found, returns false
*/
function getTriggerFromDB($xmldb_table) {
$tablename = strtoupper($this->getTableName($xmldb_table));
$prefixupper = strtoupper($this->prefix);
$triggername = false;
if ($trigger = get_record_sql("SELECT trigger_name, trigger_body
FROM user_triggers
WHERE table_name = '{$tablename}'
AND trigger_name LIKE '{$prefixupper}%_ID%_TRG'")) {
$triggername = $trigger->trigger_name;
}
return $triggername;
}
/**
* Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg)
* return if such name is currently in use (true) or no (false)
* (invoked from getNameForObject()
*/
function isNameInUse($object_name, $type, $table_name) {
switch($type) {
case 'ix':
case 'uix':
case 'seq':
case 'trg':
if ($check = get_records_sql("SELECT object_name
FROM user_objects
WHERE lower(object_name) = '" . strtolower($object_name) . "'")) {
return true;
}
break;
case 'pk':
case 'uk':
case 'fk':
case 'ck':
if ($check = get_records_sql("SELECT constraint_name
FROM user_constraints
WHERE lower(constraint_name) = '" . strtolower($object_name) . "'")) {
return true;
}
break;
}
return false; //No name in use found
}
/**
* Returns an array of reserved words (lowercase) for this DB
*/
function getReservedWords() {
/// This file contains the reserved words for Oracle databases
/// from http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a96540/ap_keywd.htm
$reserved_words = array (
'access', 'add', 'all', 'alter', 'and', 'any',
'as', 'asc', 'audit', 'between', 'by', 'char',
'check', 'cluster', 'column', 'comment',
'compress', 'connect', 'create', 'current',
'date', 'decimal', 'default', 'delete', 'desc',
'distinct', 'drop', 'else', 'exclusive', 'exists',
'file', 'float', 'for', 'from', 'grant', 'group',
'having', 'identified', 'immediate', 'in',
'increment', 'index', 'initial', 'insert',
'integer', 'intersect', 'into', 'is', 'level',
'like', 'lock', 'long', 'maxextents', 'minus',
'mlslabel', 'mode', 'modify', 'noaudit',
'nocompress', 'not', 'nowait', 'null', 'number',
'of', 'offline', 'on', 'online', 'option', 'or',
'order', 'pctfree', 'prior', 'privileges',
'public', 'raw', 'rename', 'resource', 'revoke',
'row', 'rowid', 'rownum', 'rows', 'select',
'session', 'set', 'share', 'size', 'smallint',
'start', 'successful', 'synonym', 'sysdate',
'table', 'then', 'to', 'trigger', 'uid', 'union',
'unique', 'update', 'user', 'validate', 'values',
'varchar', 'varchar2', 'view', 'whenever',
'where', 'with'
);
return $reserved_words;
}
}
?>
| bobpuffer/1.9.12-LAE1.3 | lib/xmldb/classes/generators/oci8po/oci8po.class.php | PHP | gpl-2.0 | 29,382 |
<?php
class BWGViewGalleries_bwg {
////////////////////////////////////////////////////////////////////////////////////////
// Events //
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// Constants //
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// Variables //
////////////////////////////////////////////////////////////////////////////////////////
private $model;
////////////////////////////////////////////////////////////////////////////////////////
// Constructor & Destructor //
////////////////////////////////////////////////////////////////////////////////////////
public function __construct($model) {
$this->model = $model;
}
////////////////////////////////////////////////////////////////////////////////////////
// Public Methods //
////////////////////////////////////////////////////////////////////////////////////////
public function display() {
global $WD_BWG_UPLOAD_DIR;
$rows_data = $this->model->get_rows_data();
$page_nav = $this->model->page_nav();
$search_value = ((isset($_POST['search_value'])) ? esc_html(stripslashes($_POST['search_value'])) : '');
$search_select_value = ((isset($_POST['search_select_value'])) ? (int) $_POST['search_select_value'] : 0);
$asc_or_desc = ((isset($_POST['asc_or_desc'])) ? esc_html(stripslashes($_POST['asc_or_desc'])) : 'asc');
$order_by = (isset($_POST['order_by']) ? esc_html(stripslashes($_POST['order_by'])) : 'order');
$order_class = 'manage-column column-title sorted ' . $asc_or_desc;
$ids_string = '';
?>
<div style="clear: both; float: left; width: 95%;">
<div style="float:left; font-size: 14px; font-weight: bold;">
This section allows you to create, edit and delete galleries.
<a style="color: blue; text-decoration: none;" target="_blank" href="http://web-dorado.com/wordpress-gallery-guide-step-2.html">Read More in User Manual</a>
</div>
<div style="float: right; text-align: right;">
<a style="text-decoration: none;" target="_blank" href="http://web-dorado.com/products/wordpress-photo-gallery-plugin.html">
<img width="215" border="0" alt="web-dorado.com" src="<?php echo WD_BWG_URL . '/images/logo.png'; ?>" />
</a>
</div>
</div>
<form class="wrap" id="galleries_form" method="post" action="admin.php?page=galleries_bwg" style="float: left; width: 95%;">
<span class="gallery-icon"></span>
<h2>
Galleries
<a href="" class="add-new-h2" onclick="spider_set_input_value('task', 'add');
spider_form_submit(event, 'galleries_form')">Add new</a>
</h2>
<div id="draganddrop" class="updated" style="display:none;"><strong><p>Changes made in this table should be saved.</p></strong></div>
<div class="buttons_div">
<span class="button-secondary non_selectable" onclick="spider_check_all_items()">
<input type="checkbox" id="check_all_items" name="check_all_items" onclick="spider_check_all_items_checkbox()" style="margin: 0; vertical-align: middle;" />
<span style="vertical-align: middle;">Select All</span>
</span>
<input id="show_hide_weights" class="button-secondary" type="button" onclick="spider_show_hide_weights();return false;" value="Hide order column" />
<input class="button-secondary" type="submit" onclick="spider_set_input_value('task', 'save_order')" value="Save Order" />
<input class="button-secondary" type="submit" onclick="spider_set_input_value('task', 'publish_all')" value="Publish" />
<input class="button-secondary" type="submit" onclick="spider_set_input_value('task', 'unpublish_all')" value="Unpublish" />
<input class="button-secondary" type="submit" onclick="if (confirm('Do you want to delete selected items?')) {
spider_set_input_value('task', 'delete_all');
} else {
return false;
}" value="Delete" />
</div>
<div class="tablenav top">
<?php
WDWLibrary::search('Name', $search_value, 'galleries_form');
WDWLibrary::html_page_nav($page_nav['total'], $page_nav['limit'], 'galleries_form');
?>
</div>
<table class="wp-list-table widefat fixed pages">
<thead>
<th class="table_small_col"></th>
<th class="manage-column column-cb check-column table_small_col"><input id="check_all" type="checkbox" onclick="spider_check_all(this)" style="margin:0;" /></th>
<th class="table_small_col <?php if ($order_by == 'id') {echo $order_class;} ?>">
<a onclick="spider_set_input_value('task', '');
spider_set_input_value('order_by', 'id');
spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'id') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>');
spider_form_submit(event, 'galleries_form')" href="">
<span>ID</span><span class="sorting-indicator"></span>
</a>
</th>
<th class="table_extra_large_col">Thumbnail</th>
<th class="<?php if ($order_by == 'name') {echo $order_class;} ?>">
<a onclick="spider_set_input_value('task', '');
spider_set_input_value('order_by', 'name');
spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'name') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>');
spider_form_submit(event, 'galleries_form')" href="">
<span>Name</span><span class="sorting-indicator"></span>
</a>
</th>
<th class="<?php if ($order_by == 'slug') {echo $order_class;} ?>">
<a onclick="spider_set_input_value('task', '');
spider_set_input_value('order_by', 'slug');
spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'slug') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>');
spider_form_submit(event, 'galleries_form')" href="">
<span>Slug</span><span class="sorting-indicator"></span>
</a>
</th>
<th class="<?php if ($order_by == 'display_name') {echo $order_class;} ?>">
<a onclick="spider_set_input_value('task', '');
spider_set_input_value('order_by', 'display_name');
spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'display_name') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>');
spider_form_submit(event, 'galleries_form')" href="">
<span>Author</span><span class="sorting-indicator"></span>
</a>
</th>
<th id="th_order" class="table_medium_col <?php if ($order_by == 'order') {echo $order_class;} ?>">
<a onclick="spider_set_input_value('task', '');
spider_set_input_value('order_by', 'order');
spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'order') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>');
spider_form_submit(event, 'galleries_form')" href="">
<span>Order</span><span class="sorting-indicator"></span>
</a>
</th>
<th class="table_big_col <?php if ($order_by == 'published') {echo $order_class;} ?>">
<a onclick="spider_set_input_value('task', '');
spider_set_input_value('order_by', 'published');
spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'published') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>');
spider_form_submit(event, 'galleries_form')" href="">
<span>Published</span><span class="sorting-indicator"></span>
</a>
</th>
<th class="table_big_col">Edit</th>
<th class="table_big_col">Delete</th>
</thead>
<tbody id="tbody_arr">
<?php
if ($rows_data) {
foreach ($rows_data as $row_data) {
$alternate = (!isset($alternate) || $alternate == 'class="alternate"') ? '' : 'class="alternate"';
$published_image = (($row_data->published) ? 'publish' : 'unpublish');
$published = (($row_data->published) ? 'unpublish' : 'publish');
if ($row_data->preview_image == '') {
$preview_image = WD_BWG_URL . '/images/no-image.png';
}
else {
$preview_image = site_url() . '/' . $WD_BWG_UPLOAD_DIR . $row_data->preview_image;
}
?>
<tr id="tr_<?php echo $row_data->id; ?>" <?php echo $alternate; ?>>
<td class="connectedSortable table_small_col"><div title="Drag to re-order"class="handle" style="margin:5px auto 0 auto;"></div></td>
<td class="table_small_col check-column"><input id="check_<?php echo $row_data->id; ?>" name="check_<?php echo $row_data->id; ?>" onclick="spider_check_all(this)" type="checkbox" /></td>
<td class="table_small_col"><?php echo $row_data->id; ?></td>
<td class="table_extra_large_col">
<img title="<?php echo $row_data->name; ?>" style="border: 1px solid #CCCCCC; max-width:60px; max-height:60px;" src="<?php echo $preview_image . '?date=' . date('Y-m-y H:i:s'); ?>">
</td>
<td><a onclick="spider_set_input_value('task', 'edit');
spider_set_input_value('page_number', '1');
spider_set_input_value('search_value', '');
spider_set_input_value('search_or_not', '');
spider_set_input_value('asc_or_desc', 'asc');
spider_set_input_value('order_by', 'order');
spider_set_input_value('current_id', '<?php echo $row_data->id; ?>');
spider_form_submit(event, 'galleries_form')" href="" title="Edit"><?php echo $row_data->name; ?></a></td>
<td><?php echo $row_data->slug; ?></td>
<td><?php echo get_userdata($row_data->author)->display_name; ?></td>
<td class="spider_order table_medium_col"><input id="order_input_<?php echo $row_data->id; ?>" name="order_input_<?php echo $row_data->id; ?>" type="text" size="1" value="<?php echo $row_data->order; ?>" /></td>
<td class="table_big_col"><a onclick="spider_set_input_value('task', '<?php echo $published; ?>');spider_set_input_value('current_id', '<?php echo $row_data->id; ?>');spider_form_submit(event, 'galleries_form')" href=""><img src="<?php echo WD_BWG_URL . '/images/' . $published_image . '.png'; ?>"></img></a></td>
<td class="table_big_col"><a onclick="spider_set_input_value('task', 'edit');
spider_set_input_value('page_number', '1');
spider_set_input_value('search_value', '');
spider_set_input_value('search_or_not', '');
spider_set_input_value('asc_or_desc', 'asc');
spider_set_input_value('order_by', 'order');
spider_set_input_value('current_id', '<?php echo $row_data->id; ?>');
spider_form_submit(event, 'galleries_form')" href="">Edit</a></td>
<td class="table_big_col"><a onclick="spider_set_input_value('task', 'delete');
spider_set_input_value('current_id', '<?php echo $row_data->id; ?>');
spider_form_submit(event, 'galleries_form')" href="">Delete</a></td>
</tr>
<?php
$ids_string .= $row_data->id . ',';
}
}
?>
</tbody>
</table>
<input id="task" name="task" type="hidden" value="" />
<input id="current_id" name="current_id" type="hidden" value="" />
<input id="ids_string" name="ids_string" type="hidden" value="<?php echo $ids_string; ?>" />
<input id="asc_or_desc" name="asc_or_desc" type="hidden" value="asc" />
<input id="order_by" name="order_by" type="hidden" value="<?php echo $order_by; ?>" />
<script>
window.onload = spider_show_hide_weights;
</script>
</form>
<?php
}
public function edit($id) {
global $WD_BWG_UPLOAD_DIR;
$row = $this->model->get_row_data($id);
$option_row = $this->model->get_option_row_data();
$page_title = (($id != 0) ? 'Edit gallery ' . $row->name : 'Create new gallery');
?>
<div style="clear: both; float: left; width: 95%;">
<div id="message_div" class="updated" style="display: none;"></div>
<div style="float:left; font-size: 14px; font-weight: bold;">
This section allows you to add/edit gallery.
<a style="color: blue; text-decoration: none;" target="_blank" href="http://web-dorado.com/wordpress-gallery-guide-step-2.html">Read More in User Manual</a>
</div>
<div style="float: right; text-align: right;">
<a style="text-decoration: none;" target="_blank" href="http://web-dorado.com/products/wordpress-photo-gallery-plugin.html">
<img width="215" border="0" alt="web-dorado.com" src="<?php echo WD_BWG_URL . '/images/logo.png'; ?>" />
</a>
</div>
</div>
<script>
function spider_set_href(a, number, type) {
var image_url = document.getElementById("image_url_" + number).value;
var thumb_url = document.getElementById("thumb_url_" + number).value;
a.href='<?php echo add_query_arg(array('action' => 'editThumb', 'width' => '800', 'height' => '500'), admin_url('admin-ajax.php')); ?>&type=' + type + '&image_id=' + number + '&image_url=' + image_url + '&thumb_url=' + thumb_url + '&TB_iframe=1';
}
function bwg_add_preview_image(files) {
document.getElementById("preview_image").value = files[0]['thumb_url'];
document.getElementById("button_preview_image").style.display = "none";
document.getElementById("delete_preview_image").style.display = "inline-block";
if (document.getElementById("img_preview_image")) {
document.getElementById("img_preview_image").src = files[0]['reliative_url'];
document.getElementById("img_preview_image").style.display = "inline-block";
}
}
var j_int = 0;
var bwg_j = 'pr_' + j_int;
function bwg_add_image(files) {
var tbody = document.getElementById('tbody_arr');
for (var i in files) {
var is_video = files[i]['filetype'] == 'YOUTUBE' || files[i]['filetype'] == 'VIMEO';
var tr = document.createElement('tr');
tr.setAttribute('id', "tr_" + bwg_j);
if (tbody.firstChild) {
tbody.insertBefore(tr, tbody.firstChild);
}
else {
tbody.appendChild(tr);
}
// Handle TD.
var td_handle = document.createElement('td');
td_handle.setAttribute('class', "connectedSortable table_small_col");
td_handle.setAttribute('title', "Drag to re-order");
tr.appendChild(td_handle);
var div_handle = document.createElement('div');
div_handle.setAttribute('class', "handle connectedSortable");
div_handle.setAttribute('style', "margin: 5px auto 0px;");
td_handle.appendChild(div_handle);
// Checkbox TD.
var td_checkbox = document.createElement('td');
td_checkbox.setAttribute('class', "table_small_col check-column");
td_checkbox.setAttribute('onclick', "spider_check_all(this)");
tr.appendChild(td_checkbox);
var input_checkbox = document.createElement('input');
input_checkbox.setAttribute('id', "check_" + bwg_j);
input_checkbox.setAttribute('name', "check_" + bwg_j);
input_checkbox.setAttribute('type', "checkbox");
td_checkbox.appendChild(input_checkbox);
// Numbering TD.
var td_numbering = document.createElement('td');
td_numbering.setAttribute('class', "table_small_col");
td_numbering.innerHTML = "";
tr.appendChild(td_numbering);
// Thumb TD.
var td_thumb = document.createElement('td');
td_thumb.setAttribute('class', "table_extra_large_col");
tr.appendChild(td_thumb);
var a_thumb = document.createElement('a');
a_thumb.setAttribute('class', "thickbox thickbox-preview");
a_thumb.setAttribute('href', "<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'display'/*thumb_display*/, 'width' => '650', 'height' => '500'), admin_url('admin-ajax.php')); ?>&image_id=" + bwg_j + "&TB_iframe=1");
a_thumb.setAttribute('title', files[i]['name']);
td_thumb.appendChild(a_thumb);
var img_thumb = document.createElement('img');
img_thumb.setAttribute('id', "image_thumb_" + bwg_j);
img_thumb.setAttribute('class', "thumb");
img_thumb.setAttribute('src', files[i]['thumb']);
a_thumb.appendChild(img_thumb);
// Filename TD.
var td_filename = document.createElement('td');
td_filename.setAttribute('class', "table_extra_large_col");
tr.appendChild(td_filename);
var div_filename = document.createElement('div');
div_filename.setAttribute('class', "filename");
div_filename.setAttribute('id', "filename_" + bwg_j);
td_filename.appendChild(div_filename);
var strong_filename = document.createElement('strong');
div_filename.appendChild(strong_filename);
var a_filename = document.createElement('a');
a_filename.setAttribute('href', "<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'display', 'width' => '800', 'height' => '500'), admin_url('admin-ajax.php')); ?>&image_id=" + bwg_j + "&TB_iframe=1");
a_filename.setAttribute('class', "spider_word_wrap thickbox thickbox-preview");
a_filename.setAttribute('title', files[i]['filename']);
a_filename.innerHTML = files[i]['filename'];
strong_filename.appendChild(a_filename);
var div_date_modified = document.createElement('div');
div_date_modified.setAttribute('class', "fileDescription");
div_date_modified.setAttribute('title', "Date modified");
div_date_modified.setAttribute('id', "date_modified_" + bwg_j);
div_date_modified.innerHTML = files[i]['date_modified'];
td_filename.appendChild(div_date_modified);
var div_fileresolution = document.createElement('div');
div_fileresolution.setAttribute('class', "fileDescription");
div_fileresolution.setAttribute('title', "Image Resolution");
div_fileresolution.setAttribute('id', "fileresolution" + bwg_j);
div_fileresolution.innerHTML = files[i]['resolution'];
td_filename.appendChild(div_fileresolution);
var div_filesize = document.createElement('div');
div_filesize.setAttribute('class', "fileDescription");
div_filesize.setAttribute('title', (!is_video) ? "Image size" : "Duration");
div_filesize.setAttribute('id', "filesize" + bwg_j);
div_filesize.innerHTML = files[i]['size'];
td_filename.appendChild(div_filesize);
var div_filetype = document.createElement('div');
div_filetype.setAttribute('class', "fileDescription");
div_filetype.setAttribute('title', "Type");
div_filetype.setAttribute('id', "filetype" + bwg_j);
div_filetype.innerHTML = files[i]['filetype'];
td_filename.appendChild(div_filetype);
if (!is_video) {
var div_edit = document.createElement('div');
td_filename.appendChild(div_edit);
var span_edit_crop = document.createElement('span');
span_edit_crop.setAttribute('class', "edit_thumb");
div_edit.appendChild(span_edit_crop);
var a_crop = document.createElement('a');
a_crop.setAttribute('class', "thickbox thickbox-preview");
a_crop.setAttribute('onclick', "spider_set_href(this, '" + bwg_j + "', 'crop');");
a_crop.innerHTML = "Crop";
span_edit_crop.appendChild(a_crop);
div_edit.innerHTML += " | ";
var span_edit_rotate = document.createElement('span');
span_edit_rotate.setAttribute('class', "edit_thumb");
div_edit.appendChild(span_edit_rotate);
var a_rotate = document.createElement('a');
a_rotate.setAttribute('class', "thickbox thickbox-preview");
a_rotate.setAttribute('onclick', "spider_set_href(this, '" + bwg_j + "', 'rotate');");
a_rotate.innerHTML = "Rotate";
span_edit_rotate.appendChild(a_rotate);
div_edit.innerHTML += " | "
var span_edit_recover = document.createElement('span');
span_edit_recover.setAttribute('class', "edit_thumb");
div_edit.appendChild(span_edit_recover);
var a_recover = document.createElement('a');
a_recover.setAttribute('onclick', 'if (confirm("Do you want to reset the image?")) { spider_set_input_value("ajax_task", "recover"); spider_set_input_value("image_current_id", "' + bwg_j + '"); spider_ajax_save("galleries_form");} return false;');
a_recover.innerHTML = "Reset";
span_edit_recover.appendChild(a_recover);
}
var input_image_url = document.createElement('input');
input_image_url.setAttribute('id', "image_url_" + bwg_j);
input_image_url.setAttribute('name', "image_url_" + bwg_j);
input_image_url.setAttribute('type', "hidden");
input_image_url.setAttribute('value', files[i]['url']);
td_filename.appendChild(input_image_url);
var input_thumb_url = document.createElement('input');
input_thumb_url.setAttribute('id', "thumb_url_" + bwg_j);
input_thumb_url.setAttribute('name', "thumb_url_" + bwg_j);
input_thumb_url.setAttribute('type', "hidden");
input_thumb_url.setAttribute('value', files[i]['thumb_url']);
td_filename.appendChild(input_thumb_url);
var input_filename = document.createElement('input');
input_filename.setAttribute('id', "input_filename_" + bwg_j);
input_filename.setAttribute('name', "input_filename_" + bwg_j);
input_filename.setAttribute('type', "hidden");
input_filename.setAttribute('value', files[i]['filename']);
td_filename.appendChild(input_filename);
var input_date_modified = document.createElement('input');
input_date_modified.setAttribute('id', "input_date_modified_" + bwg_j);
input_date_modified.setAttribute('name', "input_date_modified_" + bwg_j);
input_date_modified.setAttribute('type', "hidden");
input_date_modified.setAttribute('value', files[i]['date_modified']);
td_filename.appendChild(input_date_modified);
var input_resolution = document.createElement('input');
input_resolution.setAttribute('id', "input_resolution_" + bwg_j);
input_resolution.setAttribute('name', "input_resolution_" + bwg_j);
input_resolution.setAttribute('type', "hidden");
input_resolution.setAttribute('value', files[i]['resolution']);
td_filename.appendChild(input_resolution);
var input_size = document.createElement('input');
input_size.setAttribute('id', "input_size_" + bwg_j);
input_size.setAttribute('name', "input_size_" + bwg_j);
input_size.setAttribute('type', "hidden");
input_size.setAttribute('value', files[i]['size']);
td_filename.appendChild(input_size);
var input_filetype = document.createElement('input');
input_filetype.setAttribute('id', "input_filetype_" + bwg_j);
input_filetype.setAttribute('name', "input_filetype_" + bwg_j);
input_filetype.setAttribute('type', "hidden");
input_filetype.setAttribute('value', files[i]['filetype']);
td_filename.appendChild(input_filetype);
// Alt/Title TD.
var td_alt = document.createElement('td');
td_alt.setAttribute('class', "table_extra_large_col");
tr.appendChild(td_alt);
var input_alt = document.createElement('input');
input_alt.setAttribute('id', "image_alt_text_" + bwg_j);
input_alt.setAttribute('name', "image_alt_text_" + bwg_j);
input_alt.setAttribute('type', "text");
input_alt.setAttribute('size', "24");
if (is_video) {
input_alt.setAttribute('value', files[i]['name']);
}
else {
input_alt.setAttribute('value', files[i]['filename']);
}
td_alt.appendChild(input_alt);
<?php if ($option_row->thumb_click_action != 'open_lightbox') { ?>
//Redirect url
input_alt = document.createElement('input');
input_alt.setAttribute('id', "redirect_url_" + bwg_j);
input_alt.setAttribute('name', "redirect_url_" + bwg_j);
input_alt.setAttribute('type', "text");
input_alt.setAttribute('size', "24");
td_alt.appendChild(input_alt);
<?php } ?>
// Description TD.
var td_desc = document.createElement('td');
td_desc.setAttribute('class', "table_extra_large_col");
tr.appendChild(td_desc);
var textarea_desc = document.createElement('textarea');
textarea_desc.setAttribute('id', "image_description_" + bwg_j);
textarea_desc.setAttribute('name', "image_description_" + bwg_j);
textarea_desc.setAttribute('rows', "2");
textarea_desc.setAttribute('cols', "20");
textarea_desc.setAttribute('style', "resize:vertical;");
if (is_video) {
textarea_desc.innerHTML = files[i]['description'];
}
td_desc.appendChild(textarea_desc);
// Tag TD.
var td_tag = document.createElement('td');
td_tag.setAttribute('class', "table_extra_large_col");
tr.appendChild(td_tag);
var a_tag = document.createElement('a');
a_tag.setAttribute('class', "button button-small button-primary thickbox thickbox-preview");
a_tag.setAttribute('href', "<?php echo add_query_arg(array('action' => 'addTags', 'width' => '650', 'height' => '500'), admin_url('admin-ajax.php')); ?>&image_id=" + bwg_j + "&TB_iframe=1");
a_tag.innerHTML = 'Add tag';
td_tag.appendChild(a_tag);
var div_tag = document.createElement('div');
div_tag.setAttribute('class', "tags_div");
div_tag.setAttribute('id', "tags_div_" + bwg_j);
td_tag.appendChild(div_tag);
var hidden_tag = document.createElement('input');
hidden_tag.setAttribute('type', "hidden");
hidden_tag.setAttribute('id', "tags_" + bwg_j);
hidden_tag.setAttribute('name', "tags_" + bwg_j);
hidden_tag.setAttribute('value', "");
td_tag.appendChild(hidden_tag);
// Order TD.
var td_order = document.createElement('td');
td_order.setAttribute('class', "spider_order table_medium_col");
td_order.setAttribute('style', "display: none;");
tr.appendChild(td_order);
var input_order = document.createElement('input');
input_order.setAttribute('id', "order_input_" + bwg_j);
input_order.setAttribute('name', "order_input_" + bwg_j);
input_order.setAttribute('type', "text");
input_order.setAttribute('value', 0 - j_int);
input_order.setAttribute('size', "1");
td_order.appendChild(input_order);
// Publish TD.
var td_publish = document.createElement('td');
td_publish.setAttribute('class', "table_big_col");
tr.appendChild(td_publish);
var a_publish = document.createElement('a');
a_publish.setAttribute('onclick', "spider_set_input_value('ajax_task', 'image_unpublish');spider_set_input_value('image_current_id', '" + bwg_j + "');spider_ajax_save('galleries_form');");
td_publish.appendChild(a_publish);
var img_publish = document.createElement('img');
img_publish.setAttribute('src', "<?php echo WD_BWG_URL . '/images/publish.png'; ?>");
a_publish.appendChild(img_publish);
// Delete TD.
var td_delete = document.createElement('td');
td_delete.setAttribute('class', "table_big_col");
tr.appendChild(td_delete);
var a_delete = document.createElement('a');
a_delete.setAttribute('onclick', "spider_set_input_value('ajax_task', 'image_delete');spider_set_input_value('image_current_id', '" + bwg_j + "');spider_ajax_save('galleries_form');");
a_delete.innerHTML = 'Delete';
td_delete.appendChild(a_delete);
document.getElementById("ids_string").value += bwg_j + ',';
j_int++;
bwg_j = 'pr_' + j_int;
}
jQuery("#show_hide_weights").val("Hide order column");
spider_show_hide_weights();
}
</script>
<form class="wrap" method="post" id="galleries_form" action="admin.php?page=galleries_bwg" style="float: left; width: 95%;">
<span class="gallery-icon"></span>
<h2><?php echo $page_title; ?></h2>
<div style="float:right;">
<input class="button-secondary" type="button" onclick="if (spider_check_required('name', 'Name')) {return false;};
spider_set_input_value('page_number', '1');
spider_set_input_value('ajax_task', 'ajax_save');
spider_ajax_save('galleries_form');
spider_set_input_value('task', 'save')" value="Save" />
<input class="button-secondary" type="button" onclick="if (spider_check_required('name', 'Name')) {return false;};
spider_set_input_value('ajax_task', 'ajax_apply');
spider_ajax_save('galleries_form')" value="Apply" />
<input class="button-secondary" type="submit" onclick="spider_set_input_value('page_number', '1');
spider_set_input_value('task', 'cancel')" value="Cancel" />
</div>
<table style="clear:both;">
<tbody>
<tr>
<td class="spider_label"><label for="name">Name: <span style="color:#FF0000;">*</span> </label></td>
<td><input type="text" id="name" name="name" value="<?php echo $row->name; ?>" size="39" /></td>
</tr>
<tr>
<td class="spider_label"><label for="slug">Slug: </label></td>
<td><input type="text" id="slug" name="slug" value="<?php echo $row->slug; ?>" size="39" /></td>
</tr>
<tr>
<td class="spider_label"><label for="description">Description: </label></td>
<td>
<div style="width:500px;">
<?php
if (user_can_richedit()) {
wp_editor($row->description, 'description', array('teeny' => FALSE, 'textarea_name' => 'description', 'media_buttons' => FALSE, 'textarea_rows' => 5));
}
else {
?>
<textarea cols="36" rows="5" id="description" name="description" style="resize:vertical">
<?php echo $row->description; ?>
</textarea>
<?php
}
?>
</div>
</td>
</tr>
<tr>
<td class="spider_label"><label>Author: </label></td>
<td><?php echo get_userdata($row->author)->display_name; ?></td>
</tr>
<tr>
<td class="spider_label"><label for="published1">Published: </label></td>
<td>
<input type="radio" class="inputbox" id="published0" name="published" <?php echo (($row->published) ? '' : 'checked="checked"'); ?> value="0" >
<label for="published0">No</label>
<input type="radio" class="inputbox" id="published1" name="published" <?php echo (($row->published) ? 'checked="checked"' : ''); ?> value="1" >
<label for="published1">Yes</label>
</td>
</tr>
<tr>
<td class="spider_label"><label for="url">Preview image: </label></td>
<td>
<a href="<?php echo add_query_arg(array('action' => 'addImages', 'width' => '700', 'height' => '550', 'extensions' => 'jpg,jpeg,png,gif', 'callback' => 'bwg_add_preview_image', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>"
id="button_preview_image"
class="button-primary thickbox thickbox-preview"
title="Add Preview Image"
onclick="return false;"
style="margin-bottom:5px; display:none;">
Add Preview Image
</a>
<input type="hidden" id="preview_image" name="preview_image" value="<?php echo $row->preview_image; ?>" style="display:inline-block;"/>
<img id="img_preview_image"
style="max-height:90px; max-width:120px; vertical-align:middle;"
src="<?php echo site_url() . '/' . $WD_BWG_UPLOAD_DIR . $row->preview_image; ?>">
<span id="delete_preview_image" class="spider_delete_img"
onclick="spider_remove_url('button_preview_image', 'preview_image', 'delete_preview_image', 'img_preview_image')"></span>
</td>
</tr>
<tr>
<td colspan=2>
<?php
echo $this->image_display($id);
?>
</td>
</tr>
</tbody>
</table>
<input id="task" name="task" type="hidden" value="" />
<input id="current_id" name="current_id" type="hidden" value="<?php echo $row->id; ?>" />
<script>
<?php
if ($row->preview_image == '') {
?>
spider_remove_url('button_preview_image', 'preview_image', 'delete_preview_image', 'img_preview_image');
<?php
}
?>
</script>
<div id="opacity_div" style="display: none; background-color: rgba(0, 0, 0, 0.2); position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99998;"></div>
<div id="loading_div" style="display:none; text-align: center; position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99999;">
<img src="<?php echo WD_BWG_URL . '/images/ajax_loader.png'; ?>" class="spider_ajax_loading" style="margin-top: 200px; width:50px;">
</div>
</form>
<?php
}
public function image_display($id) {
global $WD_BWG_UPLOAD_DIR;
$rows_data = $this->model->get_image_rows_data($id);
$page_nav = $this->model->image_page_nav($id);
$option_row = $this->model->get_option_row_data();
$search_value = ((isset($_POST['search_value'])) ? esc_html(stripslashes($_POST['search_value'])) : '');
$asc_or_desc = ((isset($_POST['asc_or_desc'])) ? esc_html(stripslashes($_POST['asc_or_desc'])) : 'asc');
$image_order_by = (isset($_POST['image_order_by']) ? esc_html(stripslashes($_POST['image_order_by'])) : 'order');
$order_class = 'manage-column column-title sorted ' . $asc_or_desc;
$page_number = (isset($_POST['page_number']) ? esc_html(stripslashes($_POST['page_number'])) : 1);
$ids_string = '';
?>
<div id="draganddrop" class="updated" style="display:none;"><strong><p>Changes made in this table should be saved.</p></strong></div>
<div class="buttons_div_left">
<a href="<?php echo add_query_arg(array('action' => 'addImages', 'width' => '700', 'height' => '550', 'extensions' => 'jpg,jpeg,png,gif', 'callback' => 'bwg_add_image', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>" class="button-primary thickbox thickbox-preview" id="content-add_media" title="Add Images" onclick="return false;" style="margin-bottom:5px;">
Add Images
</a>
<input id="show_add_video" class="button-primary" type="button" onclick="jQuery('.opacity_add_video').show(); return false;" value="Add Video" />
</div>
<div class="buttons_div_right">
<span class="button-secondary non_selectable" onclick="spider_check_all_items()">
<input type="checkbox" id="check_all_items" name="check_all_items" onclick="spider_check_all_items_checkbox()" style="margin: 0; vertical-align: middle;" />
<span style="vertical-align: middle;">Select All</span>
</span>
<input id="show_hide_weights" class="button-secondary" type="button" onclick="spider_show_hide_weights();return false;" value="Hide order column" />
<input class="button-primary" type="submit" onclick="spider_set_input_value('ajax_task', 'image_set_watermark');
spider_ajax_save('galleries_form');
return false;" value="Set Watermark" />
<input class="button-secondary" type="submit" onclick="jQuery('.opacity_resize_image').show(); return false;" value="Resize" />
<input class="button-secondary" type="submit" onclick="spider_set_input_value('ajax_task', 'image_recover_all');
spider_ajax_save('galleries_form');
return false;" value="Reset" />
<a onclick="return bwg_check_checkboxes();" href="<?php echo add_query_arg(array('action' => 'addTags', 'width' => '650', 'height' => '500'), admin_url('admin-ajax.php')); ?>&TB_iframe=1" class="button-primary thickbox thickbox-preview">Add tag</a>
<input class="button-secondary" type="submit" onclick="spider_set_input_value('ajax_task', 'image_publish_all');
spider_ajax_save('galleries_form');
return false;" value="Publish" />
<input class="button-secondary" type="submit" onclick="spider_set_input_value('ajax_task', 'image_unpublish_all');
spider_ajax_save('galleries_form');
return false;" value="Unpublish" />
<input class="button-secondary" type="submit" onclick="if (confirm('Do you want to delete selected items?')) {
spider_set_input_value('ajax_task', 'image_delete_all');
spider_ajax_save('galleries_form');
return false;
} else {
return false;
}" value="Delete" />
</div>
<div id="opacity_add_video" class="opacity_resize_image opacity_add_video bwg_opacity_video" onclick="jQuery('.opacity_add_video').hide();jQuery('.opacity_resize_image').hide();"></div>
<div id="add_video" class="opacity_add_video bwg_add_video">
<input type="text" id="video_url" name="video_url" value="" />
<input class="button-primary" type="button" onclick="if (bwg_get_video_info('video_url')) {jQuery('.opacity_add_video').hide();} return false;" value="Add to gallery" />
<input class="button-secondary" type="button" onclick="jQuery('.opacity_add_video').hide(); return false;" value="Cancel" />
<div class="spider_description">Enter YouTube or Vimeo link here.</div>
</div>
<div id="" class="opacity_resize_image bwg_resize_image">
Resize images to:
<input type="text" name="image_width" id="image_width" value="1600" /> x
<input type="text" name="image_height" id="image_height" value="1200" /> px
<input class="button-primary" type="button" onclick="spider_set_input_value('ajax_task', 'image_resize');
spider_ajax_save('galleries_form');
jQuery('.opacity_resize_image').hide();
return false;" value="Resize" />
<input class="button-secondary" type="button" onclick="jQuery('.opacity_resize_image').hide(); return false;" value="Cancel" />
<div class="spider_description">The maximum size of resized image.</div>
</div>
<div class="tablenav top">
<?php
WDWLibrary::ajax_search('Filename', $search_value, 'galleries_form');
WDWLibrary::ajax_html_page_nav($page_nav['total'], $page_nav['limit'], 'galleries_form');
?>
</div>
<table id="images_table" class="wp-list-table widefat fixed pages">
<thead>
<th class="check-column table_small_col"></th>
<th class="manage-column column-cb check-column table_small_col"><input id="check_all" type="checkbox" onclick="spider_check_all(this)" style="margin:0;" /></th>
<th class="table_small_col">#</th>
<th class="table_extra_large_col">Thumbnail</th>
<th class="table_extra_large_col <?php if ($image_order_by == 'filename') {echo $order_class;} ?>">
<a onclick="spider_set_input_value('task', '');
spider_set_input_value('image_order_by', 'filename');
spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'filename') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>');
spider_ajax_save('galleries_form');">
<span>Filename</span><span class="sorting-indicator"></span>
</a>
</th>
<th class="table_extra_large_col <?php if ($image_order_by == 'alt') {echo $order_class;} ?>">
<a onclick="spider_set_input_value('task', '');
spider_set_input_value('image_order_by', 'alt');
spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'alt') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>');
spider_ajax_save('galleries_form');">
<span>Alt/Title<?php if ($option_row->thumb_click_action != 'open_lightbox') { ?><br />Redirect URL<?php } ?></span><span class="sorting-indicator"></span>
</a>
</th>
<th class="table_extra_large_col <?php if ($image_order_by == 'description') {echo $order_class;} ?>">
<a onclick="spider_set_input_value('task', '');
spider_set_input_value('image_order_by', 'description');
spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'description') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>');
spider_ajax_save('galleries_form');">
<span>Description</span><span class="sorting-indicator"></span>
</a>
</th>
<th class="table_extra_large_col">Tags</th>
<th id="th_order" class="table_medium_col <?php if ($image_order_by == 'order') {echo $order_class;} ?>">
<a onclick="spider_set_input_value('task', '');
spider_set_input_value('image_order_by', 'order');
spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'order') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>');
spider_ajax_save('galleries_form');">
<span>Order</span><span class="sorting-indicator"></span>
</a>
</th>
<th class="table_big_col <?php if ($image_order_by == 'published') {echo $order_class;} ?>">
<a onclick="spider_set_input_value('task', '');
spider_set_input_value('image_order_by', 'published');
spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'published') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>');
spider_ajax_save('galleries_form');">
<span>Published</span><span class="sorting-indicator"></span>
</a>
</th>
<th class="table_big_col">Delete</th>
</thead>
<tbody id="tbody_arr">
<?php
$i = ($page_number - 1) * 20;
if ($rows_data) {
foreach ($rows_data as $row_data) {
$is_video = $row_data->filetype == 'YOUTUBE' || $row_data->filetype == 'VIMEO';
$alternate = (!isset($alternate) || $alternate == 'class="alternate"') ? '' : 'class="alternate"';
$rows_tag_data = $this->model->get_tag_rows_data($row_data->id);
$published_image = (($row_data->published) ? 'publish' : 'unpublish');
$published = (($row_data->published) ? 'unpublish' : 'publish');
?>
<tr id="tr_<?php echo $row_data->id; ?>" <?php echo $alternate; ?>>
<td class="connectedSortable table_small_col"><div title="Drag to re-order" class="handle" style="margin:5px auto 0 auto;"></div></td>
<td class="table_small_col check-column"><input id="check_<?php echo $row_data->id; ?>" name="check_<?php echo $row_data->id; ?>" onclick="spider_check_all(this)" type="checkbox" /></td>
<td class="table_small_col"><?php echo ++$i; ?></td>
<td class="table_extra_large_col">
<a class="thickbox thickbox-preview" title="<?php echo $row_data->alt; ?>" href="<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'display'/*thumb_display*/, 'image_id' => $row_data->id, 'width' => '800', 'height' => '500', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>">
<img id="image_thumb_<?php echo $row_data->id; ?>" class="thumb" src="<?php echo (!$is_video ? site_url() . '/' . $WD_BWG_UPLOAD_DIR : "") . $row_data->thumb_url . '?date=' . date('Y-m-y H:i:s'); ?>">
</a>
</td>
<td class="table_extra_large_col">
<div class="filename" id="filename_<?php echo $row_data->id; ?>">
<strong><a title="<?php echo $row_data->alt; ?>" class="spider_word_wrap thickbox thickbox-preview" href="<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'display', 'image_id' => $row_data->id, 'width' => '800', 'height' => '500', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>"><?php echo $row_data->filename; ?></a></strong>
</div>
<div class="fileDescription" title="Date modified" id="date_modified_<?php echo $row_data->id; ?>"><?php echo date("d F Y, H:i", strtotime($row_data->date)); ?></div>
<div class="fileDescription" title="Image Resolution" id="fileresolution_<?php echo $row_data->id; ?>"><?php echo $row_data->resolution; ?></div>
<div class="fileDescription" title="<?php echo (!$is_video ? "Image size" : "Duration")?>" id="filesize_<?php echo $row_data->id; ?>"><?php echo $row_data->size; ?></div>
<div class="fileDescription" title="Type" id="filetype_<?php echo $row_data->id; ?>"><?php echo $row_data->filetype; ?></div>
<?php if(!$is_video) {?>
<div>
<span class="edit_thumb"><a class="thickbox thickbox-preview" href="<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'crop', 'image_id' => $row_data->id, 'TB_iframe' => '1', 'width' => '800', 'height' => '500'), admin_url('admin-ajax.php')); ?>">Crop</a></span> |
<span class="edit_thumb"><a class="thickbox thickbox-preview" href="<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'rotate', 'image_id' => $row_data->id, 'width' => '800', 'height' => '500', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>">Rotate</a></span> |
<span class="edit_thumb"><a onclick="if (confirm('Do you want to reset the image?')) {
spider_set_input_value('ajax_task', 'recover');
spider_set_input_value('image_current_id', '<?php echo $row_data->id; ?>');
spider_ajax_save('galleries_form');
}
return false;">Reset</a></span>
</div>
<?php } ?>
<input type="hidden" id="image_url_<?php echo $row_data->id; ?>" name="image_url_<?php echo $row_data->id; ?>" value="<?php echo $row_data->image_url; ?>" />
<input type="hidden" id="thumb_url_<?php echo $row_data->id; ?>" name="thumb_url_<?php echo $row_data->id; ?>" value="<?php echo $row_data->thumb_url; ?>" />
<input type="hidden" id="input_filename_<?php echo $row_data->id; ?>" name="input_filename_<?php echo $row_data->id; ?>" value="<?php echo $row_data->filename; ?>" />
<input type="hidden" id="input_date_modified_<?php echo $row_data->id; ?>" name="input_date_modified_<?php echo $row_data->id; ?>" value="<?php echo $row_data->date; ?>" />
<input type="hidden" id="input_resolution_<?php echo $row_data->id; ?>" name="input_resolution_<?php echo $row_data->id; ?>" value="<?php echo $row_data->resolution; ?>" />
<input type="hidden" id="input_size_<?php echo $row_data->id; ?>" name="input_size_<?php echo $row_data->id; ?>" value="<?php echo $row_data->size; ?>" />
<input type="hidden" id="input_filetype_<?php echo $row_data->id; ?>" name="input_filetype_<?php echo $row_data->id; ?>" value="<?php echo $row_data->filetype; ?>" />
</td>
<td class="table_extra_large_col">
<input size="24" type="text" id="image_alt_text_<?php echo $row_data->id; ?>" name="image_alt_text_<?php echo $row_data->id; ?>" value="<?php echo $row_data->alt; ?>" />
<?php if ($option_row->thumb_click_action != 'open_lightbox') { ?>
<input size="24" type="text" id="redirect_url_<?php echo $row_data->id; ?>" name="redirect_url_<?php echo $row_data->id; ?>" value="<?php echo $row_data->redirect_url; ?>" />
<?php } ?>
</td>
<td class="table_extra_large_col">
<textarea cols="20" rows="2" id="image_description_<?php echo $row_data->id; ?>" name="image_description_<?php echo $row_data->id; ?>" style="resize:vertical;"><?php echo $row_data->description; ?></textarea>
</td>
<td class="table_extra_large_col">
<a href="<?php echo add_query_arg(array('action' => 'addTags', 'image_id' => $row_data->id, 'width' => '650', 'height' => '500', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>" class="button button-small button-primary thickbox thickbox-preview">Add tag</a>
<div class="tags_div" id="tags_div_<?php echo $row_data->id; ?>">
<?php
$tags_id_string = '';
if ($rows_tag_data) {
foreach($rows_tag_data as $row_tag_data) {
?>
<div class="tag_div" id="<?php echo $row_data->id; ?>_tag_<?php echo $row_tag_data->term_id; ?>">
<span class="tag_name"><?php echo $row_tag_data->name; ?></span>
<span style="float:right;" class="spider_delete_img_small" onclick="bwg_remove_tag('<?php echo $row_tag_data->term_id; ?>', '<?php echo $row_data->id; ?>')" />
</div>
<?php
$tags_id_string .= $row_tag_data->term_id . ',';
}
}
?>
</div>
<input type="hidden" value="<?php echo $tags_id_string; ?>" id="tags_<?php echo $row_data->id; ?>" name="tags_<?php echo $row_data->id; ?>"/>
</td>
<td class="spider_order table_medium_col"><input id="order_input_<?php echo $row_data->id; ?>" name="order_input_<?php echo $row_data->id; ?>" type="text" size="1" value="<?php echo $row_data->order; ?>" /></td>
<td class="table_big_col"><a onclick="spider_set_input_value('ajax_task', 'image_<?php echo $published; ?>');
spider_set_input_value('image_current_id', '<?php echo $row_data->id; ?>');
spider_ajax_save('galleries_form');"><img src="<?php echo WD_BWG_URL . '/images/' . $published_image . '.png'; ?>"></img></a></td>
<td class="table_big_col"><a onclick="spider_set_input_value('ajax_task', 'image_delete');
spider_set_input_value('image_current_id', '<?php echo $row_data->id; ?>');
spider_ajax_save('galleries_form');">Delete</a></td>
</tr>
<?php
$ids_string .= $row_data->id . ',';
}
}
?>
<input id="ids_string" name="ids_string" type="hidden" value="<?php echo $ids_string; ?>" />
<input id="asc_or_desc" name="asc_or_desc" type="hidden" value="asc" />
<input id="image_order_by" name="image_order_by" type="hidden" value="<?php echo $image_order_by; ?>" />
<input id="ajax_task" name="ajax_task" type="hidden" value="" />
<input id="image_current_id" name="image_current_id" type="hidden" value="" />
<input id="added_tags_select_all" name="added_tags_select_all" type="hidden" value="" />
</tbody>
</table>
<script>
window.onload = spider_show_hide_weights;
</script>
<?php
}
////////////////////////////////////////////////////////////////////////////////////////
// Getters & Setters //
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// Private Methods //
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// Listeners //
////////////////////////////////////////////////////////////////////////////////////////
} | duynguyenhai/wordpress | wp-content/plugins/photo-gallery/admin/views/BWGViewGalleries_bwg.php | PHP | gpl-2.0 | 57,953 |
package visitors;
/**
* Created by stratosphr on 20/11/15.
*/
public interface IVisitedSort extends IVisited {
Object accept(ISortVisitor visitor);
}
| stratosphr/Logic | src/visitors/IVisitedSort.java | Java | gpl-2.0 | 159 |
/*
* aTunes
* Copyright (C) Alex Aranda, Sylvain Gaudard and contributors
*
* See http://www.atunes.org/wiki/index.php?title=Contributing for information about contributors
*
* http://www.atunes.org
* http://sourceforge.net/projects/atunes
*
* 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.
*/
package net.sourceforge.atunes.kernel.modules.navigator;
import java.awt.Component;
import java.util.List;
import javax.swing.Action;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import net.sourceforge.atunes.kernel.actions.CustomAbstractAction;
import net.sourceforge.atunes.model.IAudioObject;
import net.sourceforge.atunes.model.IPlayListHandler;
import net.sourceforge.atunes.model.ITreeNode;
/**
* Enables or disables navigator actions given selection
*
* @author alex
*
*/
public class NavigatorActionsStateController {
private IPlayListHandler playListHandler;
/**
* @param playListHandler
*/
public void setPlayListHandler(final IPlayListHandler playListHandler) {
this.playListHandler = playListHandler;
}
/**
* Enables or disables tree popup actions
*
* @param rootSelected
* @param components
* @param nodes
*/
void updateTreePopupMenuWithTreeSelection(final boolean rootSelected,
final Component[] components, final List<ITreeNode> nodes) {
for (Component c : components) {
updateMenuComponent(rootSelected, nodes, c);
}
}
/**
* Enables or disables table popup actions
*
* @param rootSelected
* @param components
* @param selection
*/
void updateTablePopupMenuWithTableSelection(final boolean rootSelected,
final Component[] components, final List<IAudioObject> selection) {
for (Component c : components) {
updateTableMenuComponent(rootSelected, selection, c);
}
}
/**
* @param rootSelected
* @param selection
* @param c
*/
private void updateMenuComponent(final boolean rootSelected,
final List<ITreeNode> selection, final Component c) {
if (c != null) {
if (c instanceof JMenu) {
for (int i = 0; i < ((JMenu) c).getItemCount(); i++) {
updateMenuComponent(rootSelected, selection,
((JMenu) c).getItem(i));
}
} else if (c instanceof JMenuItem) {
updateMenuItem(rootSelected, selection, (JMenuItem) c);
}
}
}
/**
* @param rootSelected
* @param selection
* @param c
*/
private void updateTableMenuComponent(final boolean rootSelected,
final List<IAudioObject> selection, final Component c) {
if (c != null) {
if (c instanceof JMenu) {
for (int i = 0; i < ((JMenu) c).getItemCount(); i++) {
updateTableMenuComponent(rootSelected, selection,
((JMenu) c).getItem(i));
}
} else if (c instanceof JMenuItem) {
updateTableMenuItem(rootSelected, selection, (JMenuItem) c);
}
}
}
/**
* @param rootSelected
* @param selection
* @param menuItem
*/
private void updateMenuItem(final boolean rootSelected,
final List<ITreeNode> selection, final JMenuItem menuItem) {
Action a = menuItem.getAction();
if (a instanceof CustomAbstractAction) {
CustomAbstractAction customAction = (CustomAbstractAction) a;
if (!customAction.isEnabledForPlayList(this.playListHandler
.getVisiblePlayList())) {
customAction.setEnabled(false);
} else {
customAction.setEnabled(customAction
.isEnabledForNavigationTreeSelection(rootSelected,
selection));
}
}
}
/**
* @param rootSelected
* @param selection
* @param menuItem
*/
private void updateTableMenuItem(final boolean rootSelected,
final List<IAudioObject> selection, final JMenuItem menuItem) {
Action a = menuItem.getAction();
if (a instanceof CustomAbstractAction) {
CustomAbstractAction customAction = (CustomAbstractAction) a;
if (!customAction.isEnabledForPlayList(this.playListHandler
.getVisiblePlayList())) {
customAction.setEnabled(false);
} else {
customAction.setEnabled(customAction
.isEnabledForNavigationTableSelection(selection));
}
}
}
}
| PDavid/aTunes | aTunes/src/main/java/net/sourceforge/atunes/kernel/modules/navigator/NavigatorActionsStateController.java | Java | gpl-2.0 | 4,445 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.mum.ea.mb;
import edu.mum.ea.ejb.ProjectEJB;
import edu.mum.ea.ejb.ReleaseBacklogEJB;
import edu.mum.ea.ejb.SprintEJB;
import edu.mum.ea.ejb.TaskEJB;
import edu.mum.ea.entity.Project;
import edu.mum.ea.entity.ReleaseBacklog;
import edu.mum.ea.entity.Sprint;
import edu.mum.ea.entity.Task;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
/**
*
* @author Syed
*/
@ManagedBean
@RequestScoped
public class SprintMB {
private Sprint sprint;
@EJB
private SprintEJB sprintEJB;
@EJB
private ProjectEJB projectEJB;
@EJB
private ReleaseBacklogEJB releaseBacklogEJB;
@EJB
private TaskEJB taskEJB;
@ManagedProperty(value = "#{sessionMB}")
private SessionMB sessionMB;
private List<Task> taskList = new ArrayList<Task>();
private List<ReleaseBacklog> releaseBacklogList = new ArrayList<ReleaseBacklog>();
private long relBacklogId;
private List<String> selectedTasks = new ArrayList<String>();
private List<Sprint> sprintList;
/**
* Creates a new instance of ProjectMB
*/
public SprintMB() {
sprint = new Sprint();
sprintList = new ArrayList<Sprint>();
}
@PostConstruct
public void init() {
//Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
//Project project = projectEJB.find(sessionMB.getUserSelectedProject().getId());
releaseBacklogList = releaseBacklogEJB.findAllRelBakByProject(sessionMB.getUserSelectedProject().getId());//project.getReleaseBacklogList();
}
public SessionMB getSessionMB() {
return sessionMB;
}
public void setSessionMB(SessionMB sessionMB) {
this.sessionMB = sessionMB;
}
public Sprint getSprint() {
return sprint;
}
public void setSprint(Sprint sprint) {
this.sprint = sprint;
}
public List<Sprint> getSprintList() {
sprintList = sprintEJB.findAllSprintByProject(sessionMB.getUserSelectedProject().getId());//sprintEJB.findAll();
return sprintList;
}
public void setSprintList(List<Sprint> sprintList) {
this.sprintList = sprintList;
}
public List<ReleaseBacklog> getReleaseBacklogList() {
return releaseBacklogList;
}
public void setReleaseBacklogList(List<ReleaseBacklog> releaseBacklogList) {
this.releaseBacklogList = releaseBacklogList;
}
public long getRelBacklogId() {
return relBacklogId;
}
public void setRelBacklogId(long relBacklogId) {
this.relBacklogId = relBacklogId;
}
public List<Task> getTaskList() {
return taskList;
}
public void setTaskList(List<Task> taskList) {
this.taskList = taskList;
}
public List<String> getSelectedTasks() {
return selectedTasks;
}
public void setSelectedTasks(List<String> selectedTasks) {
this.selectedTasks = selectedTasks;
}
public String createSprint() {
sprint.setReleaseBacklog(releaseBacklogEJB.find(getRelBacklogId()));
sprintEJB.save(sprint);
return "sprint-list";
}
public String gotoUpdatePage(Long id){
sprint = sprintEJB.find(id);
try {
setRelBacklogId(sprint.getReleaseBacklog().getId());
} catch(Exception e) {
//System.out.println("-----" + e.getMessage());
}
return "sprint-update";
}
public String updateSprint(){
try {
sprint.setReleaseBacklog(releaseBacklogEJB.find(getRelBacklogId()));
} catch (Exception e) {
//System.out.println("-----" + e.getMessage());
}
sprintEJB.edit(sprint);
return "sprint-list";
}
public String deleteSprint(Long sprintId){
sprintEJB.delete(sprintId);
return "sprint-list";
}
public String sprintDetail(Long id) {
sprint = sprintEJB.find(id);
taskList = taskEJB.findAll();
for (Task t : sprint.getTasks()) {
selectedTasks.add(t.getId().toString());
}
return "sprint-view";
}
public String addTaskToSprint() {
long sprintId = sprint.getId();
sprint = sprintEJB.find(sprintId);
taskList = sprint.getTasks();
int size = taskList.size();
for (int i = 0; i < size; i++) {
taskList.remove(taskList.get(i));
size--;
--i;
}
for (String taskId : selectedTasks) {
if (!taskList.contains(taskEJB.find(Long.parseLong(taskId)))) {
sprint.getTasks().add(taskEJB.find(Long.parseLong(taskId)));
}
}
sprintEJB.edit(sprint);
return "/sprint/sprint-list";
}
}
| ruzdi/ProjectManagement | ProjectManagement-war/src/java/edu/mum/ea/mb/SprintMB.java | Java | gpl-2.0 | 5,482 |
/* $Id$ */
/*
* Copyright (C) 2013 Teluu Inc. (http://www.teluu.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
*/
#include <pjsua2/account.hpp>
#include <pjsua2/endpoint.hpp>
#include <pjsua2/presence.hpp>
#include <pj/ctype.h>
#include "util.hpp"
using namespace pj;
using namespace std;
#define THIS_FILE "account.cpp"
///////////////////////////////////////////////////////////////////////////////
void RtcpFbCap::fromPj(const pjmedia_rtcp_fb_cap &prm)
{
this->codecId = pj2Str(prm.codec_id);
this->type = prm.type;
this->typeName = pj2Str(prm.type_name);
this->param = pj2Str(prm.param);
}
pjmedia_rtcp_fb_cap RtcpFbCap::toPj() const
{
pjmedia_rtcp_fb_cap cap;
pj_bzero(&cap, sizeof(cap));
cap.codec_id = str2Pj(this->codecId);
cap.type = this->type;
cap.type_name = str2Pj(this->typeName);
cap.param = str2Pj(this->param);
return cap;
}
///////////////////////////////////////////////////////////////////////////////
RtcpFbConfig::RtcpFbConfig()
{
pjmedia_rtcp_fb_setting setting;
pjmedia_rtcp_fb_setting_default(&setting);
fromPj(setting);
}
void RtcpFbConfig::fromPj(const pjmedia_rtcp_fb_setting &prm)
{
this->dontUseAvpf = PJ2BOOL(prm.dont_use_avpf);
this->caps.clear();
for (unsigned i = 0; i < prm.cap_count; ++i) {
RtcpFbCap cap;
cap.fromPj(prm.caps[i]);
this->caps.push_back(cap);
}
}
pjmedia_rtcp_fb_setting RtcpFbConfig::toPj() const
{
pjmedia_rtcp_fb_setting setting;
pj_bzero(&setting, sizeof(setting));
setting.dont_use_avpf = this->dontUseAvpf;
setting.cap_count = this->caps.size();
for (unsigned i = 0; i < setting.cap_count; ++i) {
setting.caps[i] = this->caps[i].toPj();
}
return setting;
}
void RtcpFbConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error)
{
ContainerNode this_node = node.readContainer("RtcpFbConfig");
NODE_READ_BOOL (this_node, dontUseAvpf);
ContainerNode cap_node = this_node.readArray("caps");
this->caps.clear();
while (cap_node.hasUnread()) {
RtcpFbCap cap;
NODE_READ_STRING (cap_node, cap.codecId);
NODE_READ_NUM_T (cap_node, pjmedia_rtcp_fb_type, cap.type);
NODE_READ_STRING (cap_node, cap.typeName);
NODE_READ_STRING (cap_node, cap.param);
this->caps.push_back(cap);
}
}
void RtcpFbConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error)
{
ContainerNode this_node = node.writeNewContainer("RtcpFbConfig");
NODE_WRITE_BOOL (this_node, dontUseAvpf);
ContainerNode cap_node = this_node.writeNewArray("caps");
for (unsigned i=0; i<this->caps.size(); ++i) {
NODE_WRITE_STRING (cap_node, this->caps[i].codecId);
NODE_WRITE_NUM_T (cap_node, pjmedia_rtcp_fb_type,
this->caps[i].type);
NODE_WRITE_STRING (cap_node, this->caps[i].typeName);
NODE_WRITE_STRING (cap_node, this->caps[i].param);
}
}
///////////////////////////////////////////////////////////////////////////////
void SrtpCrypto::fromPj(const pjmedia_srtp_crypto &prm)
{
this->key = pj2Str(prm.key);
this->name = pj2Str(prm.name);
this->flags = prm.flags;
}
pjmedia_srtp_crypto SrtpCrypto::toPj() const
{
pjmedia_srtp_crypto crypto;
crypto.key = str2Pj(this->key);
crypto.name = str2Pj(this->name);
crypto.flags = this->flags;
return crypto;
}
///////////////////////////////////////////////////////////////////////////////
SrtpOpt::SrtpOpt()
{
pjsua_srtp_opt opt;
pjsua_srtp_opt_default(&opt);
fromPj(opt);
}
void SrtpOpt::fromPj(const pjsua_srtp_opt &prm)
{
this->cryptos.clear();
for (unsigned i = 0; i < prm.crypto_count; ++i) {
SrtpCrypto crypto;
crypto.fromPj(prm.crypto[i]);
this->cryptos.push_back(crypto);
}
this->keyings.clear();
for (unsigned i = 0; i < prm.keying_count; ++i) {
this->keyings.push_back(prm.keying[i]);
}
}
pjsua_srtp_opt SrtpOpt::toPj() const
{
pjsua_srtp_opt opt;
pj_bzero(&opt, sizeof(opt));
opt.crypto_count = this->cryptos.size();
for (unsigned i = 0; i < opt.crypto_count; ++i) {
opt.crypto[i] = this->cryptos[i].toPj();
}
opt.keying_count = this->keyings.size();
for (unsigned i = 0; i < opt.keying_count; ++i) {
opt.keying[i] = (pjmedia_srtp_keying_method)this->keyings[i];
}
return opt;
}
void SrtpOpt::readObject(const ContainerNode &node) PJSUA2_THROW(Error)
{
ContainerNode this_node = node.readContainer("SrtpOpt");
ContainerNode crypto_node = this_node.readArray("cryptos");
this->cryptos.clear();
while (crypto_node.hasUnread()) {
SrtpCrypto crypto;
NODE_READ_STRING (crypto_node, crypto.key);
NODE_READ_STRING (crypto_node, crypto.name);
NODE_READ_UNSIGNED (crypto_node, crypto.flags);
this->cryptos.push_back(crypto);
}
ContainerNode keying_node = this_node.readArray("keyings");
this->keyings.clear();
while (keying_node.hasUnread()) {
unsigned keying;
NODE_READ_UNSIGNED (keying_node, keying);
this->keyings.push_back(keying);
}
}
void SrtpOpt::writeObject(ContainerNode &node) const PJSUA2_THROW(Error)
{
ContainerNode this_node = node.writeNewContainer("SrtpOpt");
ContainerNode crypto_node = this_node.writeNewArray("cryptos");
for (unsigned i=0; i<this->cryptos.size(); ++i) {
NODE_WRITE_STRING (crypto_node, this->cryptos[i].key);
NODE_WRITE_STRING (crypto_node, this->cryptos[i].name);
NODE_WRITE_UNSIGNED (crypto_node, this->cryptos[i].flags);
}
ContainerNode keying_node = this_node.writeNewArray("keyings");
for (unsigned i=0; i<this->keyings.size(); ++i) {
NODE_WRITE_UNSIGNED (keying_node, this->keyings[i]);
}
}
///////////////////////////////////////////////////////////////////////////////
void AccountRegConfig::readObject(const ContainerNode &node)
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.readContainer("AccountRegConfig");
NODE_READ_STRING (this_node, registrarUri);
NODE_READ_BOOL (this_node, registerOnAdd);
NODE_READ_UNSIGNED (this_node, timeoutSec);
NODE_READ_UNSIGNED (this_node, retryIntervalSec);
NODE_READ_UNSIGNED (this_node, firstRetryIntervalSec);
NODE_READ_UNSIGNED (this_node, randomRetryIntervalSec);
NODE_READ_UNSIGNED (this_node, delayBeforeRefreshSec);
NODE_READ_BOOL (this_node, dropCallsOnFail);
NODE_READ_UNSIGNED (this_node, unregWaitMsec);
NODE_READ_UNSIGNED (this_node, proxyUse);
NODE_READ_STRING (this_node, contactParams);
readSipHeaders(this_node, "headers", headers);
}
void AccountRegConfig::writeObject(ContainerNode &node) const
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.writeNewContainer("AccountRegConfig");
NODE_WRITE_STRING (this_node, registrarUri);
NODE_WRITE_BOOL (this_node, registerOnAdd);
NODE_WRITE_UNSIGNED (this_node, timeoutSec);
NODE_WRITE_UNSIGNED (this_node, retryIntervalSec);
NODE_WRITE_UNSIGNED (this_node, firstRetryIntervalSec);
NODE_WRITE_UNSIGNED (this_node, randomRetryIntervalSec);
NODE_WRITE_UNSIGNED (this_node, delayBeforeRefreshSec);
NODE_WRITE_BOOL (this_node, dropCallsOnFail);
NODE_WRITE_UNSIGNED (this_node, unregWaitMsec);
NODE_WRITE_UNSIGNED (this_node, proxyUse);
NODE_WRITE_STRING (this_node, contactParams);
writeSipHeaders(this_node, "headers", headers);
}
///////////////////////////////////////////////////////////////////////////////
void AccountSipConfig::readObject(const ContainerNode &node)
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.readContainer("AccountSipConfig");
NODE_READ_STRINGV (this_node, proxies);
NODE_READ_STRING (this_node, contactForced);
NODE_READ_STRING (this_node, contactParams);
NODE_READ_STRING (this_node, contactUriParams);
NODE_READ_BOOL (this_node, authInitialEmpty);
NODE_READ_STRING (this_node, authInitialAlgorithm);
NODE_READ_INT (this_node, transportId);
ContainerNode creds_node = this_node.readArray("authCreds");
authCreds.resize(0);
while (creds_node.hasUnread()) {
AuthCredInfo cred;
cred.readObject(creds_node);
authCreds.push_back(cred);
}
}
void AccountSipConfig::writeObject(ContainerNode &node) const
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.writeNewContainer("AccountSipConfig");
NODE_WRITE_STRINGV (this_node, proxies);
NODE_WRITE_STRING (this_node, contactForced);
NODE_WRITE_STRING (this_node, contactParams);
NODE_WRITE_STRING (this_node, contactUriParams);
NODE_WRITE_BOOL (this_node, authInitialEmpty);
NODE_WRITE_STRING (this_node, authInitialAlgorithm);
NODE_WRITE_INT (this_node, transportId);
ContainerNode creds_node = this_node.writeNewArray("authCreds");
for (unsigned i=0; i<authCreds.size(); ++i) {
authCreds[i].writeObject(creds_node);
}
}
///////////////////////////////////////////////////////////////////////////////
void AccountCallConfig::readObject(const ContainerNode &node)
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.readContainer("AccountCallConfig");
NODE_READ_NUM_T ( this_node, pjsua_call_hold_type, holdType);
NODE_READ_NUM_T ( this_node, pjsua_100rel_use, prackUse);
NODE_READ_NUM_T ( this_node, pjsua_sip_timer_use, timerUse);
NODE_READ_UNSIGNED( this_node, timerMinSESec);
NODE_READ_UNSIGNED( this_node, timerSessExpiresSec);
}
void AccountCallConfig::writeObject(ContainerNode &node) const
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.writeNewContainer("AccountCallConfig");
NODE_WRITE_NUM_T ( this_node, pjsua_call_hold_type, holdType);
NODE_WRITE_NUM_T ( this_node, pjsua_100rel_use, prackUse);
NODE_WRITE_NUM_T ( this_node, pjsua_sip_timer_use, timerUse);
NODE_WRITE_UNSIGNED( this_node, timerMinSESec);
NODE_WRITE_UNSIGNED( this_node, timerSessExpiresSec);
}
///////////////////////////////////////////////////////////////////////////////
void AccountPresConfig::readObject(const ContainerNode &node)
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.readContainer("AccountPresConfig");
NODE_READ_BOOL ( this_node, publishEnabled);
NODE_READ_BOOL ( this_node, publishQueue);
NODE_READ_UNSIGNED( this_node, publishShutdownWaitMsec);
NODE_READ_STRING ( this_node, pidfTupleId);
readSipHeaders(this_node, "headers", headers);
}
void AccountPresConfig::writeObject(ContainerNode &node) const
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.writeNewContainer("AccountPresConfig");
NODE_WRITE_BOOL ( this_node, publishEnabled);
NODE_WRITE_BOOL ( this_node, publishQueue);
NODE_WRITE_UNSIGNED( this_node, publishShutdownWaitMsec);
NODE_WRITE_STRING ( this_node, pidfTupleId);
writeSipHeaders(this_node, "headers", headers);
}
///////////////////////////////////////////////////////////////////////////////
void AccountMwiConfig::readObject(const ContainerNode &node)
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.readContainer("AccountMwiConfig");
NODE_READ_BOOL ( this_node, enabled);
NODE_READ_UNSIGNED( this_node, expirationSec);
}
void AccountMwiConfig::writeObject(ContainerNode &node) const
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.writeNewContainer("AccountMwiConfig");
NODE_WRITE_BOOL ( this_node, enabled);
NODE_WRITE_UNSIGNED( this_node, expirationSec);
}
///////////////////////////////////////////////////////////////////////////////
void AccountNatConfig::readObject(const ContainerNode &node)
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.readContainer("AccountNatConfig");
NODE_READ_NUM_T ( this_node, pjsua_stun_use, sipStunUse);
NODE_READ_NUM_T ( this_node, pjsua_stun_use, mediaStunUse);
NODE_READ_NUM_T ( this_node, pjsua_nat64_opt, nat64Opt);
NODE_READ_BOOL ( this_node, iceEnabled);
NODE_READ_INT ( this_node, iceMaxHostCands);
NODE_READ_BOOL ( this_node, iceAggressiveNomination);
NODE_READ_UNSIGNED( this_node, iceNominatedCheckDelayMsec);
NODE_READ_INT ( this_node, iceWaitNominationTimeoutMsec);
NODE_READ_BOOL ( this_node, iceNoRtcp);
NODE_READ_BOOL ( this_node, iceAlwaysUpdate);
NODE_READ_BOOL ( this_node, turnEnabled);
NODE_READ_STRING ( this_node, turnServer);
NODE_READ_NUM_T ( this_node, pj_turn_tp_type, turnConnType);
NODE_READ_STRING ( this_node, turnUserName);
NODE_READ_INT ( this_node, turnPasswordType);
NODE_READ_STRING ( this_node, turnPassword);
NODE_READ_INT ( this_node, contactRewriteUse);
NODE_READ_INT ( this_node, contactRewriteMethod);
NODE_READ_INT ( this_node, viaRewriteUse);
NODE_READ_INT ( this_node, sdpNatRewriteUse);
NODE_READ_INT ( this_node, sipOutboundUse);
NODE_READ_STRING ( this_node, sipOutboundInstanceId);
NODE_READ_STRING ( this_node, sipOutboundRegId);
NODE_READ_UNSIGNED( this_node, udpKaIntervalSec);
NODE_READ_STRING ( this_node, udpKaData);
NODE_READ_INT ( this_node, contactUseSrcPort);
}
void AccountNatConfig::writeObject(ContainerNode &node) const
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.writeNewContainer("AccountNatConfig");
NODE_WRITE_NUM_T ( this_node, pjsua_stun_use, sipStunUse);
NODE_WRITE_NUM_T ( this_node, pjsua_stun_use, mediaStunUse);
NODE_WRITE_NUM_T ( this_node, pjsua_nat64_opt, nat64Opt);
NODE_WRITE_BOOL ( this_node, iceEnabled);
NODE_WRITE_INT ( this_node, iceMaxHostCands);
NODE_WRITE_BOOL ( this_node, iceAggressiveNomination);
NODE_WRITE_UNSIGNED( this_node, iceNominatedCheckDelayMsec);
NODE_WRITE_INT ( this_node, iceWaitNominationTimeoutMsec);
NODE_WRITE_BOOL ( this_node, iceNoRtcp);
NODE_WRITE_BOOL ( this_node, iceAlwaysUpdate);
NODE_WRITE_BOOL ( this_node, turnEnabled);
NODE_WRITE_STRING ( this_node, turnServer);
NODE_WRITE_NUM_T ( this_node, pj_turn_tp_type, turnConnType);
NODE_WRITE_STRING ( this_node, turnUserName);
NODE_WRITE_INT ( this_node, turnPasswordType);
NODE_WRITE_STRING ( this_node, turnPassword);
NODE_WRITE_INT ( this_node, contactRewriteUse);
NODE_WRITE_INT ( this_node, contactRewriteMethod);
NODE_WRITE_INT ( this_node, viaRewriteUse);
NODE_WRITE_INT ( this_node, sdpNatRewriteUse);
NODE_WRITE_INT ( this_node, sipOutboundUse);
NODE_WRITE_STRING ( this_node, sipOutboundInstanceId);
NODE_WRITE_STRING ( this_node, sipOutboundRegId);
NODE_WRITE_UNSIGNED( this_node, udpKaIntervalSec);
NODE_WRITE_STRING ( this_node, udpKaData);
NODE_WRITE_INT ( this_node, contactUseSrcPort);
}
///////////////////////////////////////////////////////////////////////////////
void AccountMediaConfig::readObject(const ContainerNode &node)
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.readContainer("AccountMediaConfig");
NODE_READ_BOOL ( this_node, lockCodecEnabled);
NODE_READ_BOOL ( this_node, streamKaEnabled);
NODE_READ_NUM_T ( this_node, pjmedia_srtp_use, srtpUse);
NODE_READ_INT ( this_node, srtpSecureSignaling);
NODE_READ_OBJ ( this_node, srtpOpt);
NODE_READ_NUM_T ( this_node, pjsua_ipv6_use, ipv6Use);
NODE_READ_OBJ ( this_node, transportConfig);
NODE_READ_BOOL ( this_node, rtcpMuxEnabled);
}
void AccountMediaConfig::writeObject(ContainerNode &node) const
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.writeNewContainer("AccountMediaConfig");
NODE_WRITE_BOOL ( this_node, lockCodecEnabled);
NODE_WRITE_BOOL ( this_node, streamKaEnabled);
NODE_WRITE_NUM_T ( this_node, pjmedia_srtp_use, srtpUse);
NODE_WRITE_INT ( this_node, srtpSecureSignaling);
NODE_WRITE_OBJ ( this_node, srtpOpt);
NODE_WRITE_NUM_T ( this_node, pjsua_ipv6_use, ipv6Use);
NODE_WRITE_OBJ ( this_node, transportConfig);
NODE_WRITE_BOOL ( this_node, rtcpMuxEnabled);
}
///////////////////////////////////////////////////////////////////////////////
void AccountVideoConfig::readObject(const ContainerNode &node)
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.readContainer("AccountVideoConfig");
NODE_READ_BOOL ( this_node, autoShowIncoming);
NODE_READ_BOOL ( this_node, autoTransmitOutgoing);
NODE_READ_UNSIGNED( this_node, windowFlags);
NODE_READ_NUM_T ( this_node, pjmedia_vid_dev_index,
defaultCaptureDevice);
NODE_READ_NUM_T ( this_node, pjmedia_vid_dev_index,
defaultRenderDevice);
NODE_READ_NUM_T ( this_node, pjmedia_vid_stream_rc_method,
rateControlMethod);
NODE_READ_UNSIGNED( this_node, rateControlBandwidth);
NODE_READ_UNSIGNED( this_node, startKeyframeCount);
NODE_READ_UNSIGNED( this_node, startKeyframeInterval);
}
void AccountVideoConfig::writeObject(ContainerNode &node) const
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.writeNewContainer("AccountVideoConfig");
NODE_WRITE_BOOL ( this_node, autoShowIncoming);
NODE_WRITE_BOOL ( this_node, autoTransmitOutgoing);
NODE_WRITE_UNSIGNED( this_node, windowFlags);
NODE_WRITE_NUM_T ( this_node, pjmedia_vid_dev_index,
defaultCaptureDevice);
NODE_WRITE_NUM_T ( this_node, pjmedia_vid_dev_index,
defaultRenderDevice);
NODE_WRITE_NUM_T ( this_node, pjmedia_vid_stream_rc_method,
rateControlMethod);
NODE_WRITE_UNSIGNED( this_node, rateControlBandwidth);
NODE_WRITE_UNSIGNED( this_node, startKeyframeCount);
NODE_WRITE_UNSIGNED( this_node, startKeyframeInterval);
}
///////////////////////////////////////////////////////////////////////////////
void AccountIpChangeConfig::readObject(const ContainerNode &node)
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.readContainer("AccountIpChangeConfig");
NODE_READ_BOOL ( this_node, shutdownTp);
NODE_READ_BOOL ( this_node, hangupCalls);
NODE_READ_UNSIGNED( this_node, reinviteFlags);
}
void AccountIpChangeConfig::writeObject(ContainerNode &node) const
PJSUA2_THROW(Error)
{
ContainerNode this_node = node.writeNewContainer("AccountIpChangeConfig");
NODE_WRITE_BOOL ( this_node, shutdownTp);
NODE_WRITE_BOOL ( this_node, hangupCalls);
NODE_WRITE_UNSIGNED( this_node, reinviteFlags);
}
///////////////////////////////////////////////////////////////////////////////
AccountConfig::AccountConfig()
{
pjsua_acc_config acc_cfg;
pjsua_acc_config_default(&acc_cfg);
pjsua_media_config med_cfg;
pjsua_media_config_default(&med_cfg);
fromPj(acc_cfg, &med_cfg);
}
/* Convert to pjsip. */
void AccountConfig::toPj(pjsua_acc_config &ret) const
{
unsigned i;
pjsua_acc_config_default(&ret);
// Global
ret.priority = priority;
ret.id = str2Pj(idUri);
// AccountRegConfig
ret.reg_uri = str2Pj(regConfig.registrarUri);
ret.register_on_acc_add = regConfig.registerOnAdd;
ret.reg_timeout = regConfig.timeoutSec;
ret.reg_retry_interval = regConfig.retryIntervalSec;
ret.reg_first_retry_interval= regConfig.firstRetryIntervalSec;
ret.reg_retry_random_interval= regConfig.randomRetryIntervalSec;
ret.reg_delay_before_refresh= regConfig.delayBeforeRefreshSec;
ret.drop_calls_on_reg_fail = regConfig.dropCallsOnFail;
ret.unreg_timeout = regConfig.unregWaitMsec;
ret.reg_use_proxy = regConfig.proxyUse;
ret.reg_contact_params = str2Pj(regConfig.contactParams);
for (i=0; i<regConfig.headers.size(); ++i) {
pj_list_push_back(&ret.reg_hdr_list, ®Config.headers[i].toPj());
}
// AccountSipConfig
ret.cred_count = 0;
if (sipConfig.authCreds.size() > PJ_ARRAY_SIZE(ret.cred_info))
PJSUA2_RAISE_ERROR(PJ_ETOOMANY);
for (i=0; i<sipConfig.authCreds.size(); ++i) {
const AuthCredInfo &src = sipConfig.authCreds[i];
pjsip_cred_info *dst = &ret.cred_info[i];
dst->realm = str2Pj(src.realm);
dst->scheme = str2Pj(src.scheme);
dst->username = str2Pj(src.username);
dst->data_type = src.dataType;
dst->data = str2Pj(src.data);
dst->ext.aka.k = str2Pj(src.akaK);
dst->ext.aka.op = str2Pj(src.akaOp);
dst->ext.aka.amf= str2Pj(src.akaAmf);
ret.cred_count++;
}
ret.proxy_cnt = 0;
if (sipConfig.proxies.size() > PJ_ARRAY_SIZE(ret.proxy))
PJSUA2_RAISE_ERROR(PJ_ETOOMANY);
for (i=0; i<sipConfig.proxies.size(); ++i) {
ret.proxy[ret.proxy_cnt++] = str2Pj(sipConfig.proxies[i]);
}
ret.force_contact = str2Pj(sipConfig.contactForced);
ret.contact_params = str2Pj(sipConfig.contactParams);
ret.contact_uri_params = str2Pj(sipConfig.contactUriParams);
ret.auth_pref.initial_auth = sipConfig.authInitialEmpty;
ret.auth_pref.algorithm = str2Pj(sipConfig.authInitialAlgorithm);
ret.transport_id = sipConfig.transportId;
// AccountCallConfig
ret.call_hold_type = callConfig.holdType;
ret.require_100rel = callConfig.prackUse;
ret.use_timer = callConfig.timerUse;
ret.timer_setting.min_se = callConfig.timerMinSESec;
ret.timer_setting.sess_expires = callConfig.timerSessExpiresSec;
// AccountPresConfig
for (i=0; i<presConfig.headers.size(); ++i) {
pj_list_push_back(&ret.sub_hdr_list, &presConfig.headers[i].toPj());
}
ret.publish_enabled = presConfig.publishEnabled;
ret.publish_opt.queue_request= presConfig.publishQueue;
ret.unpublish_max_wait_time_msec = presConfig.publishShutdownWaitMsec;
ret.pidf_tuple_id = str2Pj(presConfig.pidfTupleId);
// AccountMwiConfig
ret.mwi_enabled = mwiConfig.enabled;
ret.mwi_expires = mwiConfig.expirationSec;
// AccountNatConfig
ret.sip_stun_use = natConfig.sipStunUse;
ret.media_stun_use = natConfig.mediaStunUse;
ret.nat64_opt = natConfig.nat64Opt;
ret.ice_cfg_use = PJSUA_ICE_CONFIG_USE_CUSTOM;
ret.ice_cfg.enable_ice = natConfig.iceEnabled;
ret.ice_cfg.ice_max_host_cands = natConfig.iceMaxHostCands;
ret.ice_cfg.ice_opt.aggressive = natConfig.iceAggressiveNomination;
ret.ice_cfg.ice_opt.nominated_check_delay =
natConfig.iceNominatedCheckDelayMsec;
ret.ice_cfg.ice_opt.controlled_agent_want_nom_timeout =
natConfig.iceWaitNominationTimeoutMsec;
ret.ice_cfg.ice_no_rtcp = natConfig.iceNoRtcp;
ret.ice_cfg.ice_always_update = natConfig.iceAlwaysUpdate;
ret.turn_cfg_use = PJSUA_TURN_CONFIG_USE_CUSTOM;
ret.turn_cfg.enable_turn = natConfig.turnEnabled;
ret.turn_cfg.turn_server = str2Pj(natConfig.turnServer);
ret.turn_cfg.turn_conn_type = natConfig.turnConnType;
ret.turn_cfg.turn_auth_cred.type = PJ_STUN_AUTH_CRED_STATIC;
ret.turn_cfg.turn_auth_cred.data.static_cred.username =
str2Pj(natConfig.turnUserName);
ret.turn_cfg.turn_auth_cred.data.static_cred.data_type =
(pj_stun_passwd_type)natConfig.turnPasswordType;
ret.turn_cfg.turn_auth_cred.data.static_cred.data =
str2Pj(natConfig.turnPassword);
ret.turn_cfg.turn_auth_cred.data.static_cred.realm = pj_str((char*)"");
ret.turn_cfg.turn_auth_cred.data.static_cred.nonce = pj_str((char*)"");
ret.allow_contact_rewrite = natConfig.contactRewriteUse;
ret.contact_rewrite_method = natConfig.contactRewriteMethod;
ret.contact_use_src_port = natConfig.contactUseSrcPort;
ret.allow_via_rewrite = natConfig.viaRewriteUse;
ret.allow_sdp_nat_rewrite = natConfig.sdpNatRewriteUse;
ret.use_rfc5626 = natConfig.sipOutboundUse;
ret.rfc5626_instance_id = str2Pj(natConfig.sipOutboundInstanceId);
ret.rfc5626_reg_id = str2Pj(natConfig.sipOutboundRegId);
ret.ka_interval = natConfig.udpKaIntervalSec;
ret.ka_data = str2Pj(natConfig.udpKaData);
// AccountMediaConfig
ret.rtp_cfg = mediaConfig.transportConfig.toPj();
ret.lock_codec = mediaConfig.lockCodecEnabled;
#if defined(PJMEDIA_STREAM_ENABLE_KA) && (PJMEDIA_STREAM_ENABLE_KA != 0)
ret.use_stream_ka = mediaConfig.streamKaEnabled;
#endif
ret.use_srtp = mediaConfig.srtpUse;
ret.srtp_secure_signaling = mediaConfig.srtpSecureSignaling;
ret.srtp_opt = mediaConfig.srtpOpt.toPj();
ret.ipv6_media_use = mediaConfig.ipv6Use;
ret.enable_rtcp_mux = mediaConfig.rtcpMuxEnabled;
ret.rtcp_fb_cfg = mediaConfig.rtcpFbConfig.toPj();
// AccountVideoConfig
ret.vid_in_auto_show = videoConfig.autoShowIncoming;
ret.vid_out_auto_transmit = videoConfig.autoTransmitOutgoing;
ret.vid_wnd_flags = videoConfig.windowFlags;
ret.vid_cap_dev = videoConfig.defaultCaptureDevice;
ret.vid_rend_dev = videoConfig.defaultRenderDevice;
ret.vid_stream_rc_cfg.method= videoConfig.rateControlMethod;
ret.vid_stream_rc_cfg.bandwidth = videoConfig.rateControlBandwidth;
ret.vid_stream_sk_cfg.count = videoConfig.startKeyframeCount;
ret.vid_stream_sk_cfg.interval = videoConfig.startKeyframeInterval;
// AccountIpChangeConfig
ret.ip_change_cfg.shutdown_tp = ipChangeConfig.shutdownTp;
ret.ip_change_cfg.hangup_calls = ipChangeConfig.hangupCalls;
ret.ip_change_cfg.reinvite_flags = ipChangeConfig.reinviteFlags;
}
/* Initialize from pjsip. */
void AccountConfig::fromPj(const pjsua_acc_config &prm,
const pjsua_media_config *mcfg)
{
const pjsip_hdr *hdr;
unsigned i;
// Global
priority = prm.priority;
idUri = pj2Str(prm.id);
// AccountRegConfig
regConfig.registrarUri = pj2Str(prm.reg_uri);
regConfig.registerOnAdd = (prm.register_on_acc_add != 0);
regConfig.timeoutSec = prm.reg_timeout;
regConfig.retryIntervalSec = prm.reg_retry_interval;
regConfig.firstRetryIntervalSec = prm.reg_first_retry_interval;
regConfig.randomRetryIntervalSec = prm.reg_retry_random_interval;
regConfig.delayBeforeRefreshSec = prm.reg_delay_before_refresh;
regConfig.dropCallsOnFail = PJ2BOOL(prm.drop_calls_on_reg_fail);
regConfig.unregWaitMsec = prm.unreg_timeout;
regConfig.proxyUse = prm.reg_use_proxy;
regConfig.contactParams = pj2Str(prm.reg_contact_params);
regConfig.headers.clear();
hdr = prm.reg_hdr_list.next;
while (hdr != &prm.reg_hdr_list) {
SipHeader new_hdr;
new_hdr.fromPj(hdr);
regConfig.headers.push_back(new_hdr);
hdr = hdr->next;
}
// AccountSipConfig
sipConfig.authCreds.clear();
for (i=0; i<prm.cred_count; ++i) {
AuthCredInfo cred;
const pjsip_cred_info &src = prm.cred_info[i];
cred.realm = pj2Str(src.realm);
cred.scheme = pj2Str(src.scheme);
cred.username = pj2Str(src.username);
cred.dataType = src.data_type;
cred.data = pj2Str(src.data);
cred.akaK = pj2Str(src.ext.aka.k);
cred.akaOp = pj2Str(src.ext.aka.op);
cred.akaAmf = pj2Str(src.ext.aka.amf);
sipConfig.authCreds.push_back(cred);
}
sipConfig.proxies.clear();
for (i=0; i<prm.proxy_cnt; ++i) {
sipConfig.proxies.push_back(pj2Str(prm.proxy[i]));
}
sipConfig.contactForced = pj2Str(prm.force_contact);
sipConfig.contactParams = pj2Str(prm.contact_params);
sipConfig.contactUriParams = pj2Str(prm.contact_uri_params);
sipConfig.authInitialEmpty = PJ2BOOL(prm.auth_pref.initial_auth);
sipConfig.authInitialAlgorithm = pj2Str(prm.auth_pref.algorithm);
sipConfig.transportId = prm.transport_id;
// AccountCallConfig
callConfig.holdType = prm.call_hold_type;
callConfig.prackUse = prm.require_100rel;
callConfig.timerUse = prm.use_timer;
callConfig.timerMinSESec = prm.timer_setting.min_se;
callConfig.timerSessExpiresSec = prm.timer_setting.sess_expires;
// AccountPresConfig
presConfig.headers.clear();
hdr = prm.sub_hdr_list.next;
while (hdr != &prm.sub_hdr_list) {
SipHeader new_hdr;
new_hdr.fromPj(hdr);
presConfig.headers.push_back(new_hdr);
hdr = hdr->next;
}
presConfig.publishEnabled = PJ2BOOL(prm.publish_enabled);
presConfig.publishQueue = PJ2BOOL(prm.publish_opt.queue_request);
presConfig.publishShutdownWaitMsec = prm.unpublish_max_wait_time_msec;
presConfig.pidfTupleId = pj2Str(prm.pidf_tuple_id);
// AccountMwiConfig
mwiConfig.enabled = PJ2BOOL(prm.mwi_enabled);
mwiConfig.expirationSec = prm.mwi_expires;
// AccountNatConfig
natConfig.sipStunUse = prm.sip_stun_use;
natConfig.mediaStunUse = prm.media_stun_use;
natConfig.nat64Opt = prm.nat64_opt;
if (prm.ice_cfg_use == PJSUA_ICE_CONFIG_USE_CUSTOM) {
natConfig.iceEnabled = PJ2BOOL(prm.ice_cfg.enable_ice);
natConfig.iceMaxHostCands = prm.ice_cfg.ice_max_host_cands;
natConfig.iceAggressiveNomination =
PJ2BOOL(prm.ice_cfg.ice_opt.aggressive);
natConfig.iceNominatedCheckDelayMsec =
prm.ice_cfg.ice_opt.nominated_check_delay;
natConfig.iceWaitNominationTimeoutMsec =
prm.ice_cfg.ice_opt.controlled_agent_want_nom_timeout;
natConfig.iceNoRtcp = PJ2BOOL(prm.ice_cfg.ice_no_rtcp);
natConfig.iceAlwaysUpdate = PJ2BOOL(prm.ice_cfg.ice_always_update);
} else {
pjsua_media_config default_mcfg;
if (!mcfg) {
pjsua_media_config_default(&default_mcfg);
mcfg = &default_mcfg;
}
natConfig.iceEnabled = PJ2BOOL(mcfg->enable_ice);
natConfig.iceMaxHostCands= mcfg->ice_max_host_cands;
natConfig.iceAggressiveNomination = PJ2BOOL(mcfg->ice_opt.aggressive);
natConfig.iceNominatedCheckDelayMsec =
mcfg->ice_opt.nominated_check_delay;
natConfig.iceWaitNominationTimeoutMsec =
mcfg->ice_opt.controlled_agent_want_nom_timeout;
natConfig.iceNoRtcp = PJ2BOOL(mcfg->ice_no_rtcp);
natConfig.iceAlwaysUpdate = PJ2BOOL(mcfg->ice_always_update);
}
if (prm.turn_cfg_use == PJSUA_TURN_CONFIG_USE_CUSTOM) {
natConfig.turnEnabled = PJ2BOOL(prm.turn_cfg.enable_turn);
natConfig.turnServer = pj2Str(prm.turn_cfg.turn_server);
natConfig.turnConnType = prm.turn_cfg.turn_conn_type;
natConfig.turnUserName =
pj2Str(prm.turn_cfg.turn_auth_cred.data.static_cred.username);
natConfig.turnPasswordType =
prm.turn_cfg.turn_auth_cred.data.static_cred.data_type;
natConfig.turnPassword =
pj2Str(prm.turn_cfg.turn_auth_cred.data.static_cred.data);
} else {
pjsua_media_config default_mcfg;
if (!mcfg) {
pjsua_media_config_default(&default_mcfg);
mcfg = &default_mcfg;
}
natConfig.turnEnabled = PJ2BOOL(mcfg->enable_turn);
natConfig.turnServer = pj2Str(mcfg->turn_server);
natConfig.turnConnType = mcfg->turn_conn_type;
natConfig.turnUserName =
pj2Str(mcfg->turn_auth_cred.data.static_cred.username);
natConfig.turnPasswordType =
mcfg->turn_auth_cred.data.static_cred.data_type;
natConfig.turnPassword =
pj2Str(mcfg->turn_auth_cred.data.static_cred.data);
}
natConfig.contactRewriteUse = prm.allow_contact_rewrite;
natConfig.contactRewriteMethod = prm.contact_rewrite_method;
natConfig.contactUseSrcPort = prm.contact_use_src_port;
natConfig.viaRewriteUse = prm.allow_via_rewrite;
natConfig.sdpNatRewriteUse = prm.allow_sdp_nat_rewrite;
natConfig.sipOutboundUse = prm.use_rfc5626;
natConfig.sipOutboundInstanceId = pj2Str(prm.rfc5626_instance_id);
natConfig.sipOutboundRegId = pj2Str(prm.rfc5626_reg_id);
natConfig.udpKaIntervalSec = prm.ka_interval;
natConfig.udpKaData = pj2Str(prm.ka_data);
// AccountMediaConfig
mediaConfig.transportConfig.fromPj(prm.rtp_cfg);
mediaConfig.lockCodecEnabled= PJ2BOOL(prm.lock_codec);
#if defined(PJMEDIA_STREAM_ENABLE_KA) && (PJMEDIA_STREAM_ENABLE_KA != 0)
mediaConfig.streamKaEnabled = PJ2BOOL(prm.use_stream_ka);
#else
mediaConfig.streamKaEnabled = false;
#endif
mediaConfig.srtpUse = prm.use_srtp;
mediaConfig.srtpSecureSignaling = prm.srtp_secure_signaling;
mediaConfig.srtpOpt.fromPj(prm.srtp_opt);
mediaConfig.ipv6Use = prm.ipv6_media_use;
mediaConfig.rtcpMuxEnabled = PJ2BOOL(prm.enable_rtcp_mux);
mediaConfig.rtcpFbConfig.fromPj(prm.rtcp_fb_cfg);
// AccountVideoConfig
videoConfig.autoShowIncoming = PJ2BOOL(prm.vid_in_auto_show);
videoConfig.autoTransmitOutgoing = PJ2BOOL(prm.vid_out_auto_transmit);
videoConfig.windowFlags = prm.vid_wnd_flags;
videoConfig.defaultCaptureDevice = prm.vid_cap_dev;
videoConfig.defaultRenderDevice = prm.vid_rend_dev;
videoConfig.rateControlMethod = prm.vid_stream_rc_cfg.method;
videoConfig.rateControlBandwidth = prm.vid_stream_rc_cfg.bandwidth;
videoConfig.startKeyframeCount = prm.vid_stream_sk_cfg.count;
videoConfig.startKeyframeInterval = prm.vid_stream_sk_cfg.interval;
// AccountIpChangeConfig
ipChangeConfig.shutdownTp = PJ2BOOL(prm.ip_change_cfg.shutdown_tp);
ipChangeConfig.hangupCalls = PJ2BOOL(prm.ip_change_cfg.hangup_calls);
ipChangeConfig.reinviteFlags = prm.ip_change_cfg.reinvite_flags;
}
void AccountConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error)
{
ContainerNode this_node = node.readContainer("AccountConfig");
NODE_READ_INT ( this_node, priority);
NODE_READ_STRING ( this_node, idUri);
NODE_READ_OBJ ( this_node, regConfig);
NODE_READ_OBJ ( this_node, sipConfig);
NODE_READ_OBJ ( this_node, callConfig);
NODE_READ_OBJ ( this_node, presConfig);
NODE_READ_OBJ ( this_node, mwiConfig);
NODE_READ_OBJ ( this_node, natConfig);
NODE_READ_OBJ ( this_node, mediaConfig);
NODE_READ_OBJ ( this_node, videoConfig);
}
void AccountConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error)
{
ContainerNode this_node = node.writeNewContainer("AccountConfig");
NODE_WRITE_INT ( this_node, priority);
NODE_WRITE_STRING ( this_node, idUri);
NODE_WRITE_OBJ ( this_node, regConfig);
NODE_WRITE_OBJ ( this_node, sipConfig);
NODE_WRITE_OBJ ( this_node, callConfig);
NODE_WRITE_OBJ ( this_node, presConfig);
NODE_WRITE_OBJ ( this_node, mwiConfig);
NODE_WRITE_OBJ ( this_node, natConfig);
NODE_WRITE_OBJ ( this_node, mediaConfig);
NODE_WRITE_OBJ ( this_node, videoConfig);
}
///////////////////////////////////////////////////////////////////////////////
void AccountInfo::fromPj(const pjsua_acc_info &pai)
{
id = pai.id;
isDefault = pai.is_default != 0;
uri = pj2Str(pai.acc_uri);
regIsConfigured = pai.has_registration != 0;
regIsActive = pai.has_registration && pai.expires > 0 &&
(pai.status / 100 == 2);
regExpiresSec = pai.expires;
regStatus = pai.status;
regStatusText = pj2Str(pai.status_text);
regLastErr = pai.reg_last_err;
onlineStatus = pai.online_status != 0;
onlineStatusText = pj2Str(pai.online_status_text);
}
///////////////////////////////////////////////////////////////////////////////
Account::Account()
: id(PJSUA_INVALID_ID)
{
}
Account::~Account()
{
/* If this instance is deleted, also delete the corresponding account in
* PJSUA library.
*/
shutdown();
}
void Account::create(const AccountConfig &acc_cfg,
bool make_default) PJSUA2_THROW(Error)
{
pjsua_acc_config pj_acc_cfg;
acc_cfg.toPj(pj_acc_cfg);
pj_acc_cfg.user_data = (void*)this;
PJSUA2_CHECK_EXPR( pjsua_acc_add(&pj_acc_cfg, make_default, &id) );
}
void Account::shutdown()
{
if (isValid() && pjsua_get_state() < PJSUA_STATE_CLOSING) {
// Cleanup buddies in the buddy list
while(buddyList.size() > 0) {
Buddy *b = buddyList[0];
delete b; /* this will remove itself from the list */
}
// This caused error message of "Error: cannot find Account.."
// when Endpoint::on_reg_started() is called for unregistration.
//pjsua_acc_set_user_data(id, NULL);
pjsua_acc_del(id);
}
}
void Account::modify(const AccountConfig &acc_cfg) PJSUA2_THROW(Error)
{
pjsua_acc_config pj_acc_cfg;
acc_cfg.toPj(pj_acc_cfg);
pj_acc_cfg.user_data = (void*)this;
PJSUA2_CHECK_EXPR( pjsua_acc_modify(id, &pj_acc_cfg) );
}
bool Account::isValid() const
{
return pjsua_acc_is_valid(id) != 0;
}
void Account::setDefault() PJSUA2_THROW(Error)
{
PJSUA2_CHECK_EXPR( pjsua_acc_set_default(id) );
}
bool Account::isDefault() const
{
return pjsua_acc_get_default() == id;
}
int Account::getId() const
{
return id;
}
Account *Account::lookup(int acc_id)
{
return (Account*)pjsua_acc_get_user_data(acc_id);
}
AccountInfo Account::getInfo() const PJSUA2_THROW(Error)
{
pjsua_acc_info pj_ai;
AccountInfo ai;
PJSUA2_CHECK_EXPR( pjsua_acc_get_info(id, &pj_ai) );
ai.fromPj(pj_ai);
return ai;
}
void Account::setRegistration(bool renew) PJSUA2_THROW(Error)
{
PJSUA2_CHECK_EXPR( pjsua_acc_set_registration(id, renew) );
}
void
Account::setOnlineStatus(const PresenceStatus &pres_st) PJSUA2_THROW(Error)
{
pjrpid_element pj_rpid;
pj_bzero(&pj_rpid, sizeof(pj_rpid));
pj_rpid.type = PJRPID_ELEMENT_TYPE_PERSON;
pj_rpid.activity = pres_st.activity;
pj_rpid.id = str2Pj(pres_st.rpidId);
pj_rpid.note = str2Pj(pres_st.note);
PJSUA2_CHECK_EXPR( pjsua_acc_set_online_status2(
id, pres_st.status == PJSUA_BUDDY_STATUS_ONLINE,
&pj_rpid) );
}
void Account::setTransport(TransportId tp_id) PJSUA2_THROW(Error)
{
PJSUA2_CHECK_EXPR( pjsua_acc_set_transport(id, tp_id) );
}
void Account::presNotify(const PresNotifyParam &prm) PJSUA2_THROW(Error)
{
pj_str_t pj_state_str = str2Pj(prm.stateStr);
pj_str_t pj_reason = str2Pj(prm.reason);
pjsua_msg_data msg_data;
prm.txOption.toPj(msg_data);
PJSUA2_CHECK_EXPR( pjsua_pres_notify(id, (pjsua_srv_pres*)prm.srvPres,
prm.state, &pj_state_str,
&pj_reason, prm.withBody,
&msg_data) );
}
const BuddyVector& Account::enumBuddies() const PJSUA2_THROW(Error)
{
return buddyList;
}
BuddyVector2 Account::enumBuddies2() const PJSUA2_THROW(Error)
{
BuddyVector2 bv2;
pjsua_buddy_id ids[PJSUA_MAX_BUDDIES];
unsigned i, count = PJSUA_MAX_BUDDIES;
PJSUA2_CHECK_EXPR( pjsua_enum_buddies(ids, &count) );
for (i = 0; i < count; ++i) {
bv2.push_back(Buddy(ids[i]));
}
return bv2;
}
Buddy* Account::findBuddy(string uri, FindBuddyMatch *buddy_match) const
PJSUA2_THROW(Error)
{
if (!buddy_match) {
static FindBuddyMatch def_bm;
buddy_match = &def_bm;
}
for (unsigned i = 0; i < buddyList.size(); i++) {
if (buddy_match->match(uri, *buddyList[i]))
return buddyList[i];
}
PJSUA2_RAISE_ERROR(PJ_ENOTFOUND);
}
Buddy Account::findBuddy2(string uri) const PJSUA2_THROW(Error)
{
pj_str_t pj_uri;
pjsua_buddy_id bud_id;
pj_strset2(&pj_uri, (char*)uri.c_str());
bud_id = pjsua_buddy_find(&pj_uri);
if (id == PJSUA_INVALID_ID) {
PJSUA2_RAISE_ERROR(PJ_ENOTFOUND);
}
Buddy buddy(bud_id);
return buddy;
}
void Account::addBuddy(Buddy *buddy)
{
pj_assert(buddy);
buddyList.push_back(buddy);
}
void Account::removeBuddy(Buddy *buddy)
{
pj_assert(buddy);
BuddyVector::iterator it;
for (it = buddyList.begin(); it != buddyList.end(); it++) {
if (*it == buddy) {
buddyList.erase(it);
return;
}
}
pj_assert(!"Bug! Buddy to be removed is not in the buddy list!");
}
| ismangil/pjproject | pjsip/src/pjsua2/account.cpp | C++ | gpl-2.0 | 39,647 |
/**
* card_view = new BaristaCardView({el: $("target_selector",
url:"",
title:"",
subtitle:"",
fg_color: "#1b9e77",
image:"",
span_class: "col-lg-12"});
*
* A Backbone View that displays a card of information wrapped in link
* The view is meant to be a top level entry point to other pages
* basic use:
card_view = new BaristaCardView();
* optional arguments:
* @param {string} url the link to navigate to if the card is clicked, defaults to ""
* @param {string} title the title of the card. defaults to "title"
* @param {string} subtitle the subtitle of the card. defaults to "subtitle"
* @param {string} image the link to an image to show as the cards main content. defaults to ""
* @param {string} fg_color the hex color code to use as the foreground color of the view, defaults to
* #1b9e77
* @param {string} span_class a bootstrap span class to size the width of the view, defaults to
* "col-lg-12"
*/
Barista.Views.BaristaCardView = Backbone.View.extend({
/**
* give the view a name to be used throughout the View's functions when it needs to know what its class
* name is
* @type {String}
*/
name: "BaristaCardView",
/**
* supply a base model for the view
* Overide this if you need to use it for dynamic content
* @type {Backbone}
*/
model: new Backbone.Model(),
/**
* overide the view's default initialize method in order to catch options and render a custom template
*/
initialize: function(){
// set up color options. default if not specified
this.fg_color = (this.options.fg_color !== undefined) ? this.options.fg_color : "#1b9e77";
// set up the span size
this.span_class = (this.options.span_class !== undefined) ? this.options.span_class : "col-lg-12";
// set up the url
this.url = (this.options.url !== undefined) ? this.options.url : "";
// set up the title
this.title = (this.options.title !== undefined) ? this.options.title : "Title";
// set up the subtitle
this.subtitle = (this.options.subtitle !== undefined) ? this.options.subtitle : "subtitle";
// set up the image
this.image = (this.options.image !== undefined) ? this.options.image : "";
// bind render to model changes
this.listenTo(this.model,'change', this.update);
// compile the default template for the view
this.compile_template();
},
/**
* use Handlebars to compile the template for the view
*/
compile_template: function(){
var self = this;
this.div_string = 'barista_view' + new Date().getTime();;
this.$el.append(BaristaTemplates.CMapCard({div_string: this.div_string,
span_class: this.span_class,
url: this.url,
title: this.title,
subtitle: this.subtitle,
image: this.image,
fg_color: this.fg_color}));
}
});
| cmap/barista | source/views/BaristaCardView.js | JavaScript | gpl-2.0 | 2,907 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ludum2D.Tiles;
using Ludum2D.World;
using Microsoft.Xna.Framework;
namespace Ludum2D.Core {
public class LudumCore {
private static LudumCore instance;
public static LudumCore Instance {
get {
if (instance == null) {
instance = new LudumCore();
}
return instance;
}
}
private LudumCore() {
}
public bool Initialized { get; private set; }
/// <summary>
/// Initialize the cores of the engine
/// </summary>
public void Initialize() {
}
/// <summary>
/// Sets the size of a tile
/// </summary>
/// <param name="sq">Width and height of a tile; Must be x^2</param>
public void SetTileSize(int sq) {
if (!Initialized) {
throw new Exception("The tile size cannot be modified once the the LudumCore has been initialized");
}
Tile.Width = sq;
}
}
} | oxysoft/Ludum2D | Ludum2D/Core/LudumCore.cs | C# | gpl-2.0 | 943 |
<?php
/* core/themes/classy/templates/navigation/menu-local-task.html.twig */
class __TwigTemplate_0969a23526138fcc37f60cc805db1d447beeec2f58012651e0e2200d57c77ec5 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$tags = array();
$filters = array();
$functions = array();
try {
$this->env->getExtension('sandbox')->checkSecurity(
array(),
array(),
array()
);
} catch (Twig_Sandbox_SecurityError $e) {
$e->setTemplateFile($this->getTemplateName());
if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
$e->setTemplateLine($tags[$e->getTagName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
$e->setTemplateLine($filters[$e->getFilterName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
$e->setTemplateLine($functions[$e->getFunctionName()]);
}
throw $e;
}
// line 17
echo "<li";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["attributes"]) ? $context["attributes"] : null), "addClass", array(0 => (((isset($context["is_active"]) ? $context["is_active"] : null)) ? ("is-active") : (""))), "method"), "html", null, true));
echo ">";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["link"]) ? $context["link"] : null), "html", null, true));
echo "</li>
";
}
public function getTemplateName()
{
return "core/themes/classy/templates/navigation/menu-local-task.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 43 => 17,);
}
}
/* {#*/
/* /***/
/* * @file*/
/* * Theme override for a local task link.*/
/* **/
/* * Available variables:*/
/* * - attributes: HTML attributes for the wrapper element.*/
/* * - is_active: Whether the task item is an active tab.*/
/* * - link: A rendered link element.*/
/* **/
/* * Note: This template renders the content for each task item in*/
/* * menu-local-tasks.html.twig.*/
/* **/
/* * @see template_preprocess_menu_local_task()*/
/* *//* */
/* #}*/
/* <li{{ attributes.addClass(is_active ? 'is-active') }}>{{ link }}</li>*/
/* */
| padmanabhan-developer/EstarProd | sites/default/files/php/twig/075870e6_menu-local-task.html.twig_09bb732346e5d24c980d871bac93beeabc98bdcdafc22eac5ff5f4c40f13cf6a/6ea817bad80d90d325204bb326b2453055a5d09f565dc9938936aba350e2c955.php | PHP | gpl-2.0 | 2,927 |
package mrdev023.opengl;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.*;
import java.awt.*;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import mrdev023.exception.*;
public class Display {
private static DisplayMode displayMode;
private static String TITLE = "";
private static long window;
private static boolean hasResized = false;
public static void create(String title,int width,int height){
if ( !glfwInit() )
throw new IllegalStateException("Unable to initialize GLFW");
TITLE = title;
displayMode = new DisplayMode(width,height);
window = glfwCreateWindow(displayMode.getWidth(),displayMode.getHeight(), TITLE, NULL, NULL);
}
public static void create(String title,int width,int height,int major,int minor){
if ( !glfwInit() )
throw new IllegalStateException("Unable to initialize GLFW");
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major); // Nous voulons OpenGL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
TITLE = title;
displayMode = new DisplayMode(width,height);
window = glfwCreateWindow(displayMode.getWidth(),displayMode.getHeight(), TITLE, NULL, NULL);
}
public static void setMouseGrabbed(boolean a){
if(a){
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
}else{
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
}
public static void setVSync(boolean a) throws DisplayException{
if(a)glfwSwapInterval(1);
else glfwSwapInterval(0);
}
public static void create(String title,int width,int height,int major,int minor,int sample){
if ( !glfwInit() )
throw new IllegalStateException("Unable to initialize GLFW");
glfwWindowHint(GLFW_SAMPLES, sample); // antialiasing 4x
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major); // Nous voulons OpenGL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
TITLE = title;
displayMode = new DisplayMode(width,height);
window = glfwCreateWindow(displayMode.getWidth(),displayMode.getHeight(), TITLE, NULL, NULL);
}
public static void setSample(int sample){
glfwWindowHint(GLFW_SAMPLES, sample);
}
public static void setResizable(boolean a){
if(a)glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
else glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
}
public static void setTitle(String title){
TITLE = title;
glfwSetWindowTitle(window, TITLE);
}
public static String getTitle(){
return TITLE;
}
public static boolean wasResized(){
IntBuffer w = BufferUtils.createIntBuffer(1);
IntBuffer h = BufferUtils.createIntBuffer(1);
glfwGetWindowSize(window, w, h);
int width = w.get(0);
int height = h.get(0);
if(Display.getDisplayMode().getWidth() != width || Display.getDisplayMode().getHeight() != height || hasResized){
setDisplayMode(new DisplayMode(width, height));
hasResized = false;
return true;
}else{
return false;
}
}
public static void printMonitorsInfo(){
PointerBuffer monitors = glfwGetMonitors();
GLFWVidMode m;
if(monitors == null){
System.out.println("No monitor detected !");
return;
}
for(int i = 0;i < monitors.capacity();i++){
m = glfwGetVideoMode(monitors.get(i));
System.out.println(glfwGetMonitorName(monitors.get(i)) + "(" + i + ") : " + m.width() + "x" + m.height() + ":" + m.refreshRate() + "Hz");
}
}
public static boolean isCloseRequested(){
return glfwWindowShouldClose(window);
}
public static void createContext(){
glfwMakeContextCurrent(window);
GL.createCapabilities();
}
public static void updateEvent(){
glfwPollEvents();
}
public static void updateFrame(){
glfwSwapBuffers(window);
}
public static DisplayMode getDisplayMode() {
return displayMode;
}
public static void setDisplayMode(DisplayMode displayMode) {
if(Display.displayMode == null || displayMode == null)return;
Display.displayMode.setDisplayMode(displayMode);
hasResized = true;
}
public static void destroy(){
glfwDestroyWindow(window);
glfwTerminate();
}
public static long getWindow() {
return window;
}
}
| mrdev023/Modern-Game-Engine | src/mrdev023/opengl/Display.java | Java | gpl-2.0 | 4,476 |
/*
#Date of creation : 9 Jan 2016.
#Aim of program : To print power set of a set of characters.
#Coded by : Rishikesh Agrawani.
*/
package main
import "fmt"
func main() {
var n, r, i, j uint
fmt.Print("Enter the number of binary variables(for which you want the binary combinations): ")
fmt.Scanf("%d", &n)
fmt.Print("\nEnter ", n, " binary variables name( name should be only 1 character long) separated by space: ")
a := make([]string, n)
r = 1
for i = 0; i < n; i++ {
fmt.Scanf("%s", &a[i])
r *= 2
}
fmt.Println("\nColumns => ", n, "\nRows => ", r)
for i = 0; i < r; i++ {
for j = 0; j < n; j++ {
if (i>>j)&1 == 1 {
fmt.Print(a[j], " ")
} else {
fmt.Print("- ")
}
}
fmt.Println()
}
}
/*1st RUN:
Enter the number of binary variables(for which you want the binary combinations): 4
Enter 4 binary variables name( name should be only 1 character long) separated by space: a b c d
Columns => 4
Rows => 16
- - - -
a - - -
- b - -
a b - -
- - c -
a - c -
- b c -
a b c -
- - - d
a - - d
- b - d
a b - d
- - c d
a - c d
- b c d
a b c d
*/
/*2nd RUN:
Enter the number of binary variables(for which you want the binary combinations):
Enter 5 binary variables name( name should be only 1 character long) separated by space:
Columns => 5
Rows => 32
- - - - -
p - - - -
- q - - -
p q - - -
- - r - -
p - r - -
- q r - -
p q r - -
- - - s -
p - - s -
- q - s -
p q - s -
- - r s -
p - r s -
- q r s -
p q r s -
- - - - t
p - - - t
- q - - t
p q - - t
- - r - t
p - r - t
- q r - t
p q r - t
- - - s t
p - - s t
- q - s t
p q - s t
- - r s t
p - r s t
- q r s t
p q r s t
*/
| hygull/go | sources/hck-ds-examples/power_set_for_set_of_characters.go | GO | gpl-2.0 | 1,645 |
/*
* UriMapFeature.hpp
*
* Copyright (c) 2010 Paul Giblock <pgib/at/users.sourceforge.net>
*
* This file is part of Unison - http://unison.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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef UNISON_LV2_URI_MAP_FEATURE_H
#define UNISON_LV2_URI_MAP_FEATURE_H
#include "Feature.hpp"
#include <lv2/uri-map.lv2/uri-map.h>
namespace Lv2 {
namespace Internal {
class UriMap;
class UriMapFeature : public Feature
{
public:
UriMapFeature (UriMap* uriMap);
LV2_Feature* lv2Feature ();
void initialize (LV2_Feature*, const Lv2Plugin&) const {};
void cleanup (LV2_Feature*) const {};
private:
static uint32_t uriToId (LV2_URI_Map_Callback_Data cbData, const char* map, const char* uri);
LV2_Feature m_feature;
LV2_URI_Map_Feature m_data;
UriMap* m_uriMap;
};
} // Internal
} // Lv2
#endif
// vim: tw=90 ts=8 sw=2 sts=2 et sta noai
| pgiblock/unison | extensions/lv2/UriMapFeature.hpp | C++ | gpl-2.0 | 1,593 |
<div class="wide form">
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl($this->route),
'method'=>'get',
)); ?>
<div class="row">
<?php echo $form->label($model,'id'); ?>
<?php echo $form->textField($model,'id',array('size'=>20,'maxlength'=>20)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'executed_at'); ?>
<?php echo $form->textField($model,'executed_at'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'class'); ?>
<?php echo $form->textField($model,'class',array('size'=>8,'maxlength'=>8)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'amount'); ?>
<?php echo $form->textField($model,'amount',array('size'=>20,'maxlength'=>20)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'charge_account'); ?>
<?php echo $form->textField($model,'charge_account',array('size'=>10,'maxlength'=>10)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'deposit_account'); ?>
<?php echo $form->textField($model,'deposit_account',array('size'=>10,'maxlength'=>10)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'charge_user'); ?>
<?php echo $form->textField($model,'charge_user',array('size'=>10,'maxlength'=>10)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'deposit_user'); ?>
<?php echo $form->textField($model,'deposit_user',array('size'=>10,'maxlength'=>10)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'subject'); ?>
<?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>255)); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Search'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- search-form --> | mianfiga/monedademos | protected/views/pending/_search.php | PHP | gpl-2.0 | 1,754 |
import tkinter
FRAME_BORDER = 5
class PageView(object):
__root = None
bd = None
def __init__(self, root=None, main_frame=None):
param = self.params()
if root is None:
# standalone
self.__root = tkinter.Tk()
self.__root.title(param['title'])
self.__root.geometry('%sx%s+%s+%s' % (param['w'],
param['h'],
param['x'],
param['y']
))
else:
# inside
self.__root = root
self.bd = param['bd']
if main_frame is None:
# standalone
main_f = tkinter.Frame(master=self.__root, bg='black', bd=self.bd)
main_f.pack(fill='both', expand=True)
else:
# inside
main_f = main_frame
self.make_widgets(main_f)
@property
def root(self):
return self.__root
def close(self):
self.__root.destroy()
self.__root.quit()
# Override
def make_widgets(self, main_frame):
pass
# Override
def params(self):
param = {
'x': 0,
'y': 0,
'w': 500,
'h': 500,
'title': '% Type Prog Title Here %',
}
return param
def mk_scrollable_area(obj, obj_frame, sbars):
obj.grid(row=0, column=0, sticky='NSWE')
if 'y' in sbars:
y_scrollbar = tkinter.ttk.Scrollbar(obj_frame)
y_scrollbar.grid(row=0, column=1, sticky='NS')
y_scrollbar['command'] = obj.yview
obj['yscrollcommand'] = y_scrollbar.set
if 'x' in sbars:
x_scrollbar = tkinter.ttk.Scrollbar(obj_frame, orient='horizontal')
x_scrollbar.grid(row=1, column=0, sticky='WE')
x_scrollbar['command'] = obj.xview
obj['xscrollcommand'] = x_scrollbar.set
obj_frame.columnconfigure(1, 'minsize')
obj_frame.columnconfigure(0, weight=1)
obj_frame.rowconfigure(1, 'minsize')
obj_frame.rowconfigure(0, weight=1)
def mk_listbox(frame, side='top', sbars='y', sel_mode=tkinter.EXTENDED):
BORDER = 0
COLOR = 'grey'
listbox_frame = tkinter.Frame(frame, bg=COLOR, bd=BORDER)
listbox_frame.pack(side=side, fill='both', expand=True)
listbox = tkinter.Listbox(listbox_frame, selectmode=sel_mode)
mk_scrollable_area(listbox, listbox_frame, sbars)
return listbox
def mk_treeview(frame, side='top', sbars='y'):
BORDER = 0
COLOR = 'grey'
treeview_frame = tkinter.Frame(frame, bg=COLOR, bd=BORDER)
treeview_frame.pack(side=side, fill='both', expand=True)
treeview = tkinter.ttk.Treeview(treeview_frame)
mk_scrollable_area(treeview, treeview_frame, sbars)
return treeview
| sora7/listparse | src/listparse/ui/common.py | Python | gpl-2.0 | 2,865 |
// Copyright (C) 2012 Markus Fischer
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// Contact: info@doctor-doc.com
package ch.dbs.actions.bestellung;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.lang.StringEscapeUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import util.CodeUrl;
import util.Http;
import ch.dbs.form.JournalDetails;
import enums.Connect;
/**
* This class reads answers from the normal EZB UI searched with the parameter
* xmloutput=1 to get XML.
*/
public class EZBXML {
private static final Logger LOG = LoggerFactory.getLogger(EZBXML.class);
public List<JournalDetails> searchByTitle(final String jtitle, final String bibid) {
final Http http = new Http();
final CodeUrl coder = new CodeUrl();
final StringBuffer link = new StringBuffer(
"http://ezb.uni-regensburg.de/ezeit/searchres.phtml?xmloutput=1&colors=7&lang=de&jq_type1=KT&jq_bool2=AND&jq_not2=+&jq_type2=KS&jq_term2=&jq_bool3=AND&jq_not3=+&jq_type3=PU&jq_term3=&offset=-1&hits_per_page=30&search_journal=Suche+starten&Notations%5B%5D=all&selected_colors%5B%5D=1&selected_colors%5B%5D=2&selected_colors%5B%5D=4&bibid=");
link.append(bibid);
link.append("&jq_term1=");
link.append(coder.encode(jtitle, "ISO-8859-1"));
String content = http.getContent(link.toString(), Connect.TIMEOUT_2.getValue(), Connect.TRIES_2.getValue(),
null);
// if we have > 30 hits, try a more concise search using: &jq_type1=KS (title starts with) instead of &jq_type1=KT (words in title)
if (content != null && content.contains("<search_count>")) {
final int x = Integer.parseInt(content.substring(content.indexOf("<search_count>") + 14,
content.indexOf("</search_count>")));
if (x > 30) {
final StringBuffer link2 = new StringBuffer(
"http://ezb.uni-regensburg.de/ezeit/searchres.phtml?xmloutput=1&colors=7&lang=de&jq_type1=KS&jq_bool2=AND&jq_not2=+&jq_type2=KS&jq_term2=&jq_bool3=AND&jq_not3=+&jq_type3=PU&jq_term3=&offset=-1&hits_per_page=30&search_journal=Suche+starten&Notations%5B%5D=all&selected_colors%5B%5D=1&selected_colors%5B%5D=2&selected_colors%5B%5D=4&bibid=");
link2.append(bibid);
link2.append("&jq_term1=");
link2.append(coder.encode(jtitle, "ISO-8859-1"));
content = http.getContent(link2.toString(), Connect.TIMEOUT_2.getValue(), Connect.TRIES_2.getValue(),
null);
}
}
final List<String> jourids = getJourids(content);
return searchByJourids(jourids, bibid);
}
public List<JournalDetails> searchByIssn(final String issn, final String bibid) {
final Http http = new Http();
final StringBuffer link = new StringBuffer(
"http://ezb.uni-regensburg.de/ezeit/searchres.phtml?xmloutput=1&colors=5&lang=de&jq_type1=KT&jq_term1=&jq_bool2=AND&jq_not2=+&jq_type2=KS&jq_term2=&jq_bool3=AND&jq_not3=+&jq_type3=PU&jq_term3=&jq_bool4=AND&jq_not4=+&jq_type4=IS&offset=-1&hits_per_page=50&search_journal=Suche+starten&Notations%5B%5D=all&selected_colors%5B%5D=1&selected_colors%5B%5D=2&selected_colors%5B%5D=4&bibid=");
link.append(bibid);
link.append("&jq_term4=");
link.append(issn);
final String content = http.getContent(link.toString(), Connect.TIMEOUT_2.getValue(),
Connect.TRIES_2.getValue(), null);
final List<String> jourids = getJourids(content);
return searchByJourids(jourids, bibid);
}
public List<JournalDetails> searchByJourids(final List<String> jourids, final String bibid) {
final List<JournalDetails> list = new ArrayList<JournalDetails>();
final Http http = new Http();
final StringBuffer link = new StringBuffer(
"http://rzblx1.uni-regensburg.de/ezeit/detail.phtml?xmloutput=1&colors=7&lang=de&bibid=");
link.append(bibid);
link.append("&jour_id=");
final StringBuffer infoLink = new StringBuffer(
"http://ezb.uni-regensburg.de/ezeit/detail.phtml?colors=7&lang=de&bibid=");
infoLink.append(bibid);
infoLink.append("&jour_id=");
try {
for (final String jourid : jourids) {
final JournalDetails jd = new JournalDetails();
final String content = http.getContent(link.toString() + jourid, Connect.TIMEOUT_1.getValue(),
Connect.TRIES_1.getValue(), null);
if (content != null) {
final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
final DocumentBuilder builder = domFactory.newDocumentBuilder();
final Document doc = builder.parse(new InputSource(new StringReader(content)));
final XPathFactory factory = XPathFactory.newInstance();
final XPath xpath = factory.newXPath();
final XPathExpression exprJournal = xpath.compile("//journal");
final XPathExpression exprPissns = xpath.compile("//journal/detail/P_ISSNs");
final XPathExpression exprEissns = xpath.compile("//journal/detail/E_ISSNs");
final NodeList resultJournal = (NodeList) exprJournal.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < resultJournal.getLength(); i++) {
final Node firstResultNode = resultJournal.item(i);
final Element journal = (Element) firstResultNode;
// Title
String title = getValue(journal.getElementsByTagName("title"));
if (title != null) {
title = Jsoup.clean(title, Whitelist.none());
title = Jsoup.parse(title).text();
}
jd.setZeitschriftentitel(title);
// P-ISSNs
final NodeList resultPissns = (NodeList) exprPissns.evaluate(doc, XPathConstants.NODESET);
// get first pissn
for (int z = 0; z < resultPissns.getLength(); z++) {
final Node firstPissnsNode = resultPissns.item(i);
final Element pissnElement = (Element) firstPissnsNode;
final String pissn = getValue(pissnElement.getElementsByTagName("P_ISSN"));
jd.setIssn(pissn);
}
// try to get Eissn if we have no Pissn
if (jd.getIssn() == null) {
// E-ISSNs
final NodeList resultEissns = (NodeList) exprEissns.evaluate(doc, XPathConstants.NODESET);
// get first eissn
for (int z = 0; z < resultEissns.getLength(); z++) {
final Node firstEissnsNode = resultEissns.item(i);
final Element eissnElement = (Element) firstEissnsNode;
final String eissn = getValue(eissnElement.getElementsByTagName("E_ISSN"));
jd.setIssn(eissn);
}
}
// add info link
jd.setLink(infoLink.toString() + jourid);
list.add(jd);
}
}
}
} catch (final XPathExpressionException e) {
LOG.error(e.toString());
} catch (final SAXParseException e) {
LOG.error(e.toString());
} catch (final SAXException e) {
LOG.error(e.toString());
} catch (final IOException e) {
LOG.error(e.toString());
} catch (final ParserConfigurationException e) {
LOG.error(e.toString());
} catch (final Exception e) {
LOG.error(e.toString());
}
return list;
}
private List<String> getJourids(final String content) {
final List<String> result = new ArrayList<String>();
try {
if (content != null) {
final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
final DocumentBuilder builder = domFactory.newDocumentBuilder();
final Document doc = builder.parse(new InputSource(new StringReader(content)));
final XPathFactory factory = XPathFactory.newInstance();
final XPath xpath = factory.newXPath();
final XPathExpression exprJournals = xpath.compile("//journals/journal");
final NodeList journals = (NodeList) exprJournals.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < journals.getLength(); i++) {
final Node firstResultNode = journals.item(i);
final Element journal = (Element) firstResultNode;
final String id = journal.getAttribute("jourid");
if (id != null) {
result.add(id);
}
}
}
} catch (final XPathExpressionException e) {
LOG.error(e.toString());
} catch (final SAXParseException e) {
LOG.error(e.toString());
} catch (final SAXException e) {
LOG.error(e.toString());
} catch (final IOException e) {
LOG.error(e.toString());
} catch (final ParserConfigurationException e) {
LOG.error(e.toString());
} catch (final Exception e) {
LOG.error(e.toString());
}
return result;
}
private String getValue(final NodeList list) {
String result = null;
final Element listElement = (Element) list.item(0);
if (listElement != null) {
final NodeList textList = listElement.getChildNodes();
if (textList.getLength() > 0) {
result = StringEscapeUtils.unescapeXml(textList.item(0).getNodeValue());
}
}
return result;
}
}
| gbv/doctor-doc | source/ch/dbs/actions/bestellung/EZBXML.java | Java | gpl-2.0 | 11,803 |
import os, socket, sys, urllib
from wx.lib.embeddedimage import PyEmbeddedImage
ldc_name = "Live Debian Creator"
ldc_cli_version = "1.4.0"
ldc_gui_version = "1.11.0"
if (sys.platform == "win32"):
slash = "\\"
if os.path.isfile(sys.path[0]): #fix for compiled binaries
homepath = os.path.dirname(sys.path[0]) + slash
else:
homepath = sys.path[0] + slash
else:
slash = "/"
#socket.setdefaulttimeout(10)
def defineBrowserAgent(uiname, uiversion):
class AppURLopener(urllib.FancyURLopener):
version = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
#version = uiname + " " + uiversion + " / " + sys.platform
urllib._urlopener = AppURLopener()
bookico = PyEmbeddedImage(
"iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAABPZJ"
"REFUWIWtl09sFFUcxz/iYN+YTZyNxewiTWiV6FZQtqhkN3pgGw6UW6unJVxEDtaThJMc9WLg"
"oj1hwJhANURqQkw9NGwTla0c6JqArELSMVCzi63uKJX5UR7Bw8x0Z2d3yxJ5yctM3vu93/f7"
"+ztv4CGPqamp9A/nL2Q6lTceBqht26pw7kL+7K+10S/tJ9OpBBPASCdnH/k/wFNTU+nzc/+M"
"2v925a2N21Sq1yKJg/wxV7XWyIHBnYPjD53A9PS0mrv+e/6yw6gT60+72iK7AVJJSBoCBihD"
"AVC6WK7O3bx3+thFyY30ycSH7+w5FNXXcQgymUzaei49+vHMX/kq/SqpYGiDRbYHlBFoigMu"
"gklxHsZ1NlG4yygvKiruWauV3vsS2L59e+qZVwfHqsnB3G8LkI2ZHHzdImGBaZi+BgVaqIhi"
"sqo4uQBlrQDPI2jx5gMQUFu39A3veW3ru9leMmO19aQ2JDm8C5SCuDJBgUJRM6DkKE5WFYUF"
"cLSAxgOnNeiqBHZt6z2wO2UdSvXGrfimFNYrIzhHbca/LlOcTzL0coJsj8IRKC4pJhfAXvKB"
"dKBFQu+AdjsnsG/AOpzc+RZWKkc8FgcFGDYApas1SgtAUjxXJOK+a1XUgRHrzc4JlMslqB5C"
"ZYbg+Sws2rAYByPlSQcntNQtNSLaNGCoxv07HRJAQ63ioM6MI2fGPdt6DngKDbVK1kS9IKBV"
"PQmN6P4qBNAgGlw/jqJp9vKKBtVILrA4nA+GegAPBCT8Z0P6RF0dvAfgwdRRIu2rYfU+sLKr"
"mtcCq3UIPGyABmupzIBRoOIkuXzF7oyACq2KDne5FmQC2fC+UyWtZxmIlchtseg1sti2yzf2"
"z8n8559kdmzbYW/evLnalgAGmLr+Lp00aw3WYomUUaDfKpNJphmIDWEZXvd1N9m80HNj+Fs5"
"Pvx0TY0AE6sQUGB45SOA0m0kwyWnHfLdh8nGd5NJDGMqEwyXoi5QXJrAltmVsNxabq2mrWVi"
"qHoitkpCBJwKp6uTVDbaVGKziK5wWWaQoAOGu2IbO5pGkLfuKocD5WrJwVRQXirjXC+DAdY6"
"1ZSYCng8cnxNk8K1fukF/eA+FqAFpIaiMT0VXgIr5fcohUfosca23EzgTh3cDep5taFdcCN1"
"bviAMTB98OZqakfAH65vx4rqKBlNm2+8grUeWGCrGW5S9yWwti7ofW5Ucx9rIBK6bIRB2lVN"
"Y29tQcBonG4Ta6k/NSBeDkSH2Sp0GoiUYYsQ+AB+0rTt4hov/lpQ0lrKDT/F66y3IjLN9rmh"
"VQVo1b4StHgkWhAIEjioKBFfx91GFzR5wJ5HRINpem3YQfzyklAihgCjxDT1SvLvLLLkR0rA"
"jdzOmjxwotbVf656+/20YmS9wrIfvSdO8p53A0UAM0RihVqIjNSB/WXRIFpwXVhebgxCkwdu"
"/33b/kXY94VD/KWPjvY9lduVvaWxCVzYYipxW1eKFhwRajcdat9RemP+vd2jbx6cCIt19Gf0"
"6fETw28fKR6jf9Ci24LuuFeuMWC2IIlLXxVl70+5ZDckuxWuFuIxqIjgTDOjzvV9UC7OTbbS"
"3fGvmW3bauyzE/nCFXe4dIMsy45tVX889oT+83RXV5d5bf21MXIyZD3re2WGgnyfOFK9VG0J"
"/MAEOhmnTp1KXF28mlsXWzezf+/+1legyPgPTicVRBS2XfsAAAAASUVORK5CYII=")
getbookicoIcon = bookico.GetIcon | godaigroup/livedebiancreator | prefs.py | Python | gpl-2.0 | 2,733 |
<?php
namespace Connections_Directory\Content_Blocks\Entry\Related;
use Connections_Directory\Content_Blocks\Entry\Related;
/**
* Class Last_Name
*
* @package Connections_Directory\Content_Blocks\Entry
*/
class Last_Name extends Related {
/**
* @since 9.8
* @var string
*/
const ID = 'entry-related-last_name';
/**
* @since 9.7
* @var array
*/
private $properties = array(
'relation' => 'last_name',
);
/**
* Related constructor.
*
* @since 9.8
*
* @param $id
*/
public function __construct( $id ) {
$atts = array(
'context' => 'single',
'name' => __( 'Related Entries by Last Name', 'connections' ),
'permission_callback' => '__return_true',
'heading' => __( 'Related by Last Name', 'connections' ),
'script_handle' => 'Connections_Directory/Block/Carousel/Script',
'style_handle' => 'Connections_Directory/Block/Carousel/Style',
);
parent::__construct( $id, $atts );
$this->setProperties( $this->properties );
$this->hooks();
}
/**
* Add hooks.
*
* @since 9.8
*/
private function hooks() {
// Add the last name to the Content Block heading.
add_filter(
'Connections_Directory/Entry/Related/Query_Parameters',
function( $queryParameters ) {
if ( is_array( $queryParameters ) && array_key_exists( 'last_name', $queryParameters ) ) {
$this->set(
'heading',
/* translators: A surname, family name, or last name. */
sprintf( __( 'Related by Last Name - %s', 'connections' ), $queryParameters['last_name'] )
);
}
return $queryParameters;
}
);
}
}
| Connections-Business-Directory/Connections | includes/Content_Blocks/Entry/Related/Last_Name.php | PHP | gpl-2.0 | 1,642 |
<?php $st_buttons_p = ot_get_option('st_buttons_p'); ?>
<?php $sidebar_checkbox = get_post_meta($post->ID, 'sidebar_checkbox', true);?>
<?php $full_width = get_post_meta($post->ID, 'portfolio_options_full', true);?>
<?php $details = get_post_meta($post->ID, 'portfolio_options_repeatable', true); if($details){$details = array_filter($details);};?>
<?php $terms = get_the_terms($post->ID, 'portfolio_tags' ); ?>
<?php $share = get_post_meta($post->ID, 'portfolio_options_share', true);?>
<?php get_header(); ?>
<?php //get_template_part('includes/title-breadcrumb' ) ?>
<div id="main" class="inner-page <?php if ($sidebar_checkbox){?>left-sidebar-template<?php }?>">
<div class="container">
<div class="row">
<div class="<?php if ($full_width){?>col-md-12<?php }else{?>col-md-9<?php }?> page-content">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php get_template_part('includes/single-portfolio-post' );?>
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.', GETTEXT_DOMAIN) ?></p>
<?php endif; ?>
</div>
<?php if (!$full_width){?>
<div class="col-md-3">
<?php if ( is_active_sidebar(4)||!empty($details) || $terms || !$share ){?>
<div class="sidebar">
<?php if ( !empty($details) || $terms || !$share ){?>
<div class="widget portfolio-info-widget">
<ul>
<?php if($details){ ?>
<?php $separator = "%%";
$output = '';
foreach ($details as $item) {
if($item){
list($item_text1, $item_text2) = explode($separator, trim($item));
$output .= '<li><strong>' . $item_text1 . ':</strong> ' . do_shortcode($item_text2) . '</li>';
}
}
echo $output;?>
<?php } ?>
<?php if($terms){?>
<li class="tags">
<?php if($terms) : foreach ($terms as $term) { ?>
<?php echo '<a title="'.$term->name.'" href="'.get_term_link($term->slug, 'portfolio_tags').'">'.$term->name.'</a>'?>
<?php } endif;?>
<div class="clearfix"></div>
</li>
<?php }?>
<?php if(!$share&&$st_buttons_p){?>
<li class="st-share-portfolio"><strong><?php _e( 'Share', GETTEXT_DOMAIN);?>:</strong>
<?php echo $st_buttons_p;?>
</li>
<?php }?>
</ul>
</div>
<?php }?>
<?php if ( !function_exists( 'dynamic_sidebar' ) || !dynamic_sidebar('Portfolio Post Sidebar') ) ?>
</div>
<?php } ?>
</div>
<?php }?>
</div>
</div>
</div>
<?php get_footer(); ?> | ronykader06/Badsha | wp-content/themes/dokan.me/single-portfolio.php | PHP | gpl-2.0 | 2,901 |
<?php
/**
* template_lite upper modifier plugin
*
* Type: modifier
* Name: upper
* Purpose: Wrapper for the PHP 'strtoupper' function
*/
function tpl_modifier_upper($string) {
return strtoupper($string);
}
?> | dreikanter/motoko | mtk/lib/template_lite/plugins/modifier.upper.php | PHP | gpl-2.0 | 235 |
# encoding: utf-8
# module PyKDE4.kdeui
# from /usr/lib/python3/dist-packages/PyKDE4/kdeui.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import PyKDE4.kdecore as __PyKDE4_kdecore
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtGui as __PyQt4_QtGui
import PyQt4.QtSvg as __PyQt4_QtSvg
class KPassivePopupMessageHandler(__PyQt4_QtCore.QObject, __PyKDE4_kdecore.KMessageHandler):
# no doc
def message(self, *args, **kwargs): # real signature unknown
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
| ProfessorX/Config | .PyCharm30/system/python_stubs/-1247971765/PyKDE4/kdeui/KPassivePopupMessageHandler.py | Python | gpl-2.0 | 584 |
/*
* Copyright (C) 2005-2014 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <ace/Message_Block.h>
#include <ace/OS_NS_string.h>
#include <ace/OS_NS_unistd.h>
#include <ace/os_include/arpa/os_inet.h>
#include <ace/os_include/netinet/os_tcp.h>
#include <ace/os_include/sys/os_types.h>
#include <ace/os_include/sys/os_socket.h>
#include <ace/OS_NS_string.h>
#include <ace/Reactor.h>
#include <ace/Auto_Ptr.h>
#include "WorldSocket.h"
#include "Common.h"
#include "Player.h"
#include "Util.h"
#include "World.h"
#include "WorldPacket.h"
#include "SharedDefines.h"
#include "ByteBuffer.h"
#include "Opcodes.h"
#include "DatabaseEnv.h"
#include "BigNumber.h"
#include "SHA1.h"
#include "WorldSession.h"
#include "WorldSocketMgr.h"
#include "Log.h"
#include "PacketLog.h"
#include "ScriptMgr.h"
#include "AccountMgr.h"
#if defined(__GNUC__)
#pragma pack(1)
#else
#pragma pack(push, 1)
#endif
struct ServerPktHeader
{
ServerPktHeader(uint32 size, uint32 cmd, AuthCrypt* _authCrypt) : size(size)
{
if (_authCrypt->IsInitialized())
{
uint32 data = (size << 13) | cmd & MAX_OPCODE;
memcpy(&header[0], &data, 4);
_authCrypt->EncryptSend((uint8*)&header[0], getHeaderLength());
}
else
{
// Dynamic header size is not needed anymore, we are using not encrypted part for only the first few packets
memcpy(&header[0], &size, 2);
memcpy(&header[2], &cmd, 2);
}
}
uint8 getHeaderLength()
{
return 4;
}
const uint32 size;
uint8 header[4];
};
struct AuthClientPktHeader
{
uint16 size;
uint32 cmd;
};
struct WorldClientPktHeader
{
uint16 size;
uint16 cmd;
};
#if defined(__GNUC__)
#pragma pack()
#else
#pragma pack(pop)
#endif
WorldSocket::WorldSocket (void): WorldHandler(),
m_LastPingTime(ACE_Time_Value::zero), m_OverSpeedPings(0), m_Session(0),
m_RecvWPct(0), m_RecvPct(), m_Header(sizeof(AuthClientPktHeader)),
m_WorldHeader(sizeof(WorldClientPktHeader)), m_OutBuffer(0),
m_OutBufferSize(65536), m_OutActive(false),
m_Seed(static_cast<uint32> (rand32()))
{
reference_counting_policy().value (ACE_Event_Handler::Reference_Counting_Policy::ENABLED);
msg_queue()->high_water_mark(8 * 1024 * 1024);
msg_queue()->low_water_mark(8 * 1024 * 1024);
}
WorldSocket::~WorldSocket (void)
{
delete m_RecvWPct;
if (m_OutBuffer)
m_OutBuffer->release();
closing_ = true;
peer().close();
}
bool WorldSocket::IsClosed (void) const
{
return closing_;
}
void WorldSocket::CloseSocket (void)
{
{
ACE_GUARD (LockType, Guard, m_OutBufferLock);
if (closing_)
return;
closing_ = true;
peer().close_writer();
}
{
ACE_GUARD (LockType, Guard, m_SessionLock);
m_Session = NULL;
}
}
const std::string& WorldSocket::GetRemoteAddress (void) const
{
return m_Address;
}
int WorldSocket::SendPacket(WorldPacket const& pct)
{
ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, -1);
if (closing_)
return -1;
// Dump outgoing packet
if (sPacketLog->CanLogPacket())
sPacketLog->LogPacket(pct, SERVER_TO_CLIENT);
WorldPacket const* pkt = &pct;
// Empty buffer used in case packet should be compressed
// Disable compression for now :)
/* WorldPacket buff;
if (m_Session && pkt->size() > 0x400)
{
buff.Compress(m_Session->GetCompressionStream(), pkt);
pkt = &buff;
}*/
uint16 opcodeNumber = serveurOpcodeTable[pkt->GetOpcode()]->OpcodeNumber;
if (m_Session)
TC_LOG_TRACE("network.opcode", "S->C: %s %s", m_Session->GetPlayerInfo().c_str(), GetOpcodeNameForLogging(pkt->GetOpcode(), true).c_str());
sScriptMgr->OnPacketSend(this, *pkt);
ServerPktHeader header(!m_Crypt.IsInitialized() ? pkt->size() + 2 : pct.size(), opcodeNumber, &m_Crypt);
if (m_OutBuffer->space() >= pkt->size() + header.getHeaderLength() && msg_queue()->is_empty())
{
// Put the packet on the buffer.
if (m_OutBuffer->copy((char*) header.header, header.getHeaderLength()) == -1)
ACE_ASSERT (false);
if (!pkt->empty())
if (m_OutBuffer->copy((char*) pkt->contents(), pkt->size()) == -1)
ACE_ASSERT (false);
}
else
{
// Enqueue the packet.
ACE_Message_Block* mb;
ACE_NEW_RETURN(mb, ACE_Message_Block(pkt->size() + header.getHeaderLength()), -1);
mb->copy((char*) header.header, header.getHeaderLength());
if (!pkt->empty())
mb->copy((const char*)pkt->contents(), pkt->size());
if (msg_queue()->enqueue_tail(mb, (ACE_Time_Value*)&ACE_Time_Value::zero) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::SendPacket enqueue_tail failed");
mb->release();
return -1;
}
}
return 0;
}
long WorldSocket::AddReference (void)
{
return static_cast<long> (add_reference());
}
long WorldSocket::RemoveReference (void)
{
return static_cast<long> (remove_reference());
}
int WorldSocket::open (void *a)
{
ACE_UNUSED_ARG (a);
// Prevent double call to this func.
if (m_OutBuffer)
return -1;
// This will also prevent the socket from being Updated
// while we are initializing it.
m_OutActive = true;
// Hook for the manager.
if (sWorldSocketMgr->OnSocketOpen(this) == -1)
return -1;
// Allocate the buffer.
ACE_NEW_RETURN (m_OutBuffer, ACE_Message_Block (m_OutBufferSize), -1);
// Store peer address.
ACE_INET_Addr remote_addr;
if (peer().get_remote_addr(remote_addr) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::open: peer().get_remote_addr errno = %s", ACE_OS::strerror (errno));
return -1;
}
m_Address = remote_addr.get_host_addr();
// not an opcode. this packet sends raw string WORLD OF WARCRAFT CONNECTION - SERVER TO CLIENT"
// because of our implementation, bytes "WO" become the opcode
WorldPacket packet(MSG_VERIFY_CONNECTIVITY);
packet << std::string("RLD OF WARCRAFT CONNECTION - SERVER TO CLIENT");
if (SendPacket(packet) == -1)
return -1;
// Register with ACE Reactor
if (reactor()->register_handler(this, ACE_Event_Handler::READ_MASK | ACE_Event_Handler::WRITE_MASK) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::open: unable to register client handler errno = %s", ACE_OS::strerror (errno));
return -1;
}
// reactor takes care of the socket from now on
remove_reference();
return 0;
}
int WorldSocket::close (u_long)
{
shutdown();
closing_ = true;
remove_reference();
return 0;
}
int WorldSocket::handle_input (ACE_HANDLE)
{
if (closing_)
return -1;
switch (handle_input_missing_data())
{
case -1 :
{
if ((errno == EWOULDBLOCK) ||
(errno == EAGAIN))
{
return Update(); // interesting line, isn't it ?
}
TC_LOG_DEBUG("network", "WorldSocket::handle_input: Peer error closing connection errno = %s", ACE_OS::strerror (errno));
errno = ECONNRESET;
return -1;
}
case 0:
{
TC_LOG_DEBUG("network", "WorldSocket::handle_input: Peer has closed connection");
errno = ECONNRESET;
return -1;
}
case 1:
return 1;
default:
return Update(); // another interesting line ;)
}
ACE_NOTREACHED(return -1);
}
int WorldSocket::handle_output (ACE_HANDLE)
{
ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, -1);
if (closing_)
return -1;
size_t send_len = m_OutBuffer->length();
if (send_len == 0)
return handle_output_queue(Guard);
#ifdef MSG_NOSIGNAL
ssize_t n = peer().send (m_OutBuffer->rd_ptr(), send_len, MSG_NOSIGNAL);
#else
ssize_t n = peer().send (m_OutBuffer->rd_ptr(), send_len);
#endif // MSG_NOSIGNAL
if (n == 0)
return -1;
else if (n == -1)
{
if (errno == EWOULDBLOCK || errno == EAGAIN)
return schedule_wakeup_output (Guard);
return -1;
}
else if (n < (ssize_t)send_len) //now n > 0
{
m_OutBuffer->rd_ptr (static_cast<size_t> (n));
// move the data to the base of the buffer
m_OutBuffer->crunch();
return schedule_wakeup_output (Guard);
}
else //now n == send_len
{
m_OutBuffer->reset();
return handle_output_queue (Guard);
}
ACE_NOTREACHED (return 0);
}
int WorldSocket::handle_output_queue (GuardType& g)
{
if (msg_queue()->is_empty())
return cancel_wakeup_output(g);
ACE_Message_Block* mblk;
if (msg_queue()->dequeue_head(mblk, (ACE_Time_Value*)&ACE_Time_Value::zero) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::handle_output_queue dequeue_head");
return -1;
}
const size_t send_len = mblk->length();
#ifdef MSG_NOSIGNAL
ssize_t n = peer().send(mblk->rd_ptr(), send_len, MSG_NOSIGNAL);
#else
ssize_t n = peer().send(mblk->rd_ptr(), send_len);
#endif // MSG_NOSIGNAL
if (n == 0)
{
mblk->release();
return -1;
}
else if (n == -1)
{
if (errno == EWOULDBLOCK || errno == EAGAIN)
{
msg_queue()->enqueue_head(mblk, (ACE_Time_Value*) &ACE_Time_Value::zero);
return schedule_wakeup_output (g);
}
mblk->release();
return -1;
}
else if (n < (ssize_t)send_len) //now n > 0
{
mblk->rd_ptr(static_cast<size_t> (n));
if (msg_queue()->enqueue_head(mblk, (ACE_Time_Value*) &ACE_Time_Value::zero) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::handle_output_queue enqueue_head");
mblk->release();
return -1;
}
return schedule_wakeup_output (g);
}
else //now n == send_len
{
mblk->release();
return msg_queue()->is_empty() ? cancel_wakeup_output(g) : ACE_Event_Handler::WRITE_MASK;
}
ACE_NOTREACHED(return -1);
}
int WorldSocket::handle_close (ACE_HANDLE h, ACE_Reactor_Mask)
{
// Critical section
{
ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, -1);
closing_ = true;
if (h == ACE_INVALID_HANDLE)
peer().close_writer();
}
// Critical section
{
ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1);
m_Session = NULL;
}
reactor()->remove_handler(this, ACE_Event_Handler::DONT_CALL | ACE_Event_Handler::ALL_EVENTS_MASK);
return 0;
}
int WorldSocket::Update (void)
{
if (closing_)
return -1;
if (m_OutActive)
return 0;
{
ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, 0);
if (m_OutBuffer->length() == 0 && msg_queue()->is_empty())
return 0;
}
int ret;
do
ret = handle_output(get_handle());
while (ret > 0);
return ret;
}
int WorldSocket::handle_input_header (void)
{
ACE_ASSERT(m_RecvWPct == NULL);
if (m_Crypt.IsInitialized())
{
ACE_ASSERT(m_WorldHeader.length() == sizeof(WorldClientPktHeader));
uint8* uintHeader = (uint8*)m_WorldHeader.rd_ptr();
m_Crypt.DecryptRecv(uintHeader, sizeof(WorldClientPktHeader));
WorldClientPktHeader& header = *(WorldClientPktHeader*)uintHeader;
uint32 value = *(uint32*)uintHeader;
header.cmd = value & 0x1FFF;
header.size = ((value & ~(uint32)0x1FFF) >> 13);
if (header.size > 10236)
{
Player* _player = m_Session ? m_Session->GetPlayer() : NULL;
TC_LOG_ERROR("network", "WorldSocket::handle_input_header(): client (account: %u, char [GUID: %u, name: %s]) sent malformed packet (size: %d, cmd: %d)",
m_Session ? m_Session->GetAccountId() : 0,
_player ? _player->GetGUIDLow() : 0,
_player ? _player->GetName().c_str() : "<none>",
header.size, header.cmd);
errno = EINVAL;
return -1;
}
uint16 opcodeNumber = PacketFilter::DropHighBytes(header.cmd);
ACE_NEW_RETURN(m_RecvWPct, WorldPacket(clientOpcodeTable.GetOpcodeByNumber(opcodeNumber), header.size), -1);
m_RecvWPct->SetReceivedOpcode(opcodeNumber);
if (header.size > 0)
{
m_RecvWPct->resize(header.size);
m_RecvPct.base ((char*) m_RecvWPct->contents(), m_RecvWPct->size());
}
else
ACE_ASSERT(m_RecvPct.space() == 0);
}
else
{
ACE_ASSERT(m_Header.length() == sizeof(AuthClientPktHeader));
uint8* uintHeader = (uint8*)m_Header.rd_ptr();
AuthClientPktHeader& header = *((AuthClientPktHeader*)uintHeader);
if ((header.size < 4) || (header.size > 10240))
{
Player* _player = m_Session ? m_Session->GetPlayer() : NULL;
TC_LOG_ERROR("network", "WorldSocket::handle_input_header(): client (account: %u, char [GUID: %u, name: %s]) sent malformed packet (size: %d, cmd: %d)",
m_Session ? m_Session->GetAccountId() : 0,
_player ? _player->GetGUIDLow() : 0,
_player ? _player->GetName().c_str() : "<none>",
header.size, header.cmd);
errno = EINVAL;
return -1;
}
header.size -= 4;
uint16 opcodeNumber = PacketFilter::DropHighBytes(header.cmd);
ACE_NEW_RETURN(m_RecvWPct, WorldPacket(clientOpcodeTable.GetOpcodeByNumber(opcodeNumber), header.size), -1);
m_RecvWPct->SetReceivedOpcode(opcodeNumber);
if (header.size > 0)
{
m_RecvWPct->resize(header.size);
m_RecvPct.base ((char*) m_RecvWPct->contents(), m_RecvWPct->size());
}
else
ACE_ASSERT(m_RecvPct.space() == 0);
}
return 0;
}
int WorldSocket::handle_input_payload (void)
{
// set errno properly here on error !!!
// now have a header and payload
if (m_Crypt.IsInitialized())
{
ACE_ASSERT (m_RecvPct.space() == 0);
ACE_ASSERT (m_WorldHeader.space() == 0);
ACE_ASSERT (m_RecvWPct != NULL);
const int ret = ProcessIncoming (m_RecvWPct);
m_RecvPct.base (NULL, 0);
m_RecvPct.reset();
m_RecvWPct = NULL;
m_WorldHeader.reset();
if (ret == -1)
errno = EINVAL;
return ret;
}
else
{
ACE_ASSERT(m_RecvPct.space() == 0);
ACE_ASSERT(m_Header.space() == 0);
ACE_ASSERT(m_RecvWPct != NULL);
const int ret = ProcessIncoming(m_RecvWPct);
m_RecvPct.base(NULL, 0);
m_RecvPct.reset();
m_RecvWPct = NULL;
m_Header.reset();
if (ret == -1)
errno = EINVAL;
return ret;
}
}
int WorldSocket::handle_input_missing_data (void)
{
char buf [4096];
ACE_Data_Block db (sizeof (buf),
ACE_Message_Block::MB_DATA,
buf,
0,
0,
ACE_Message_Block::DONT_DELETE,
0);
ACE_Message_Block message_block(&db,
ACE_Message_Block::DONT_DELETE,
0);
const size_t recv_size = message_block.space();
const ssize_t n = peer().recv (message_block.wr_ptr(),
recv_size);
if (n <= 0)
return int(n);
message_block.wr_ptr (n);
while (message_block.length() > 0)
{
if (m_Crypt.IsInitialized())
{
if (m_WorldHeader.space() > 0)
{
//need to receive the header
const size_t to_header = (message_block.length() > m_WorldHeader.space() ? m_WorldHeader.space() : message_block.length());
m_WorldHeader.copy (message_block.rd_ptr(), to_header);
message_block.rd_ptr (to_header);
if (m_WorldHeader.space() > 0)
{
// Couldn't receive the whole header this time.
ACE_ASSERT (message_block.length() == 0);
errno = EWOULDBLOCK;
return -1;
}
// We just received nice new header
if (handle_input_header() == -1)
{
ACE_ASSERT ((errno != EWOULDBLOCK) && (errno != EAGAIN));
return -1;
}
}
}
else
{
if (m_Header.space() > 0)
{
//need to receive the header
const size_t to_header = (message_block.length() > m_Header.space() ? m_Header.space() : message_block.length());
m_Header.copy (message_block.rd_ptr(), to_header);
message_block.rd_ptr (to_header);
if (m_Header.space() > 0)
{
// Couldn't receive the whole header this time.
ACE_ASSERT (message_block.length() == 0);
errno = EWOULDBLOCK;
return -1;
}
// We just received nice new header
if (handle_input_header() == -1)
{
ACE_ASSERT ((errno != EWOULDBLOCK) && (errno != EAGAIN));
return -1;
}
}
}
// Its possible on some error situations that this happens
// for example on closing when epoll receives more chunked data and stuff
// hope this is not hack, as proper m_RecvWPct is asserted around
if (!m_RecvWPct)
{
TC_LOG_ERROR("network", "Forcing close on input m_RecvWPct = NULL");
errno = EINVAL;
return -1;
}
// We have full read header, now check the data payload
if (m_RecvPct.space() > 0)
{
//need more data in the payload
const size_t to_data = (message_block.length() > m_RecvPct.space() ? m_RecvPct.space() : message_block.length());
m_RecvPct.copy (message_block.rd_ptr(), to_data);
message_block.rd_ptr (to_data);
if (m_RecvPct.space() > 0)
{
// Couldn't receive the whole data this time.
ACE_ASSERT (message_block.length() == 0);
errno = EWOULDBLOCK;
return -1;
}
}
//just received fresh new payload
if (handle_input_payload() == -1)
{
ACE_ASSERT ((errno != EWOULDBLOCK) && (errno != EAGAIN));
return -1;
}
}
return size_t(n) == recv_size ? 1 : 2;
}
int WorldSocket::cancel_wakeup_output (GuardType& g)
{
if (!m_OutActive)
return 0;
m_OutActive = false;
g.release();
if (reactor()->cancel_wakeup
(this, ACE_Event_Handler::WRITE_MASK) == -1)
{
// would be good to store errno from reactor with errno guard
TC_LOG_ERROR("network", "WorldSocket::cancel_wakeup_output");
return -1;
}
return 0;
}
int WorldSocket::schedule_wakeup_output (GuardType& g)
{
if (m_OutActive)
return 0;
m_OutActive = true;
g.release();
if (reactor()->schedule_wakeup
(this, ACE_Event_Handler::WRITE_MASK) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::schedule_wakeup_output");
return -1;
}
return 0;
}
int WorldSocket::ProcessIncoming(WorldPacket* new_pct)
{
ACE_ASSERT (new_pct);
// manage memory ;)
ACE_Auto_Ptr<WorldPacket> aptr(new_pct);
Opcodes opcode = new_pct->GetOpcode();
if (closing_)
return -1;
// Dump received packet.
if (sPacketLog->CanLogPacket())
sPacketLog->LogPacket(*new_pct, CLIENT_TO_SERVER);
std::string opcodeName = GetOpcodeNameForLogging(opcode, false);
if (m_Session)
TC_LOG_TRACE("network.opcode", "C->S: %s %s", m_Session->GetPlayerInfo().c_str(), opcodeName.c_str());
try
{
switch (opcode)
{
case CMSG_PING:
return HandlePing(*new_pct);
case CMSG_AUTH_SESSION:
if (m_Session)
{
TC_LOG_ERROR("network", "WorldSocket::ProcessIncoming: received duplicate CMSG_AUTH_SESSION from %s", m_Session->GetPlayerInfo().c_str());
return -1;
}
sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct));
return HandleAuthSession(*new_pct);
//case CMSG_KEEP_ALIVE:
// sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct));
// return 0;
case CMSG_LOG_DISCONNECT:
new_pct->rfinish(); // contains uint32 disconnectReason;
sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct));
return 0;
// not an opcode, client sends string "WORLD OF WARCRAFT CONNECTION - CLIENT TO SERVER" without opcode
// first 4 bytes become the opcode (2 dropped)
case MSG_VERIFY_CONNECTIVITY:
{
sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct));
std::string str;
*new_pct >> str;
if (str != "D OF WARCRAFT CONNECTION - CLIENT TO SERVER")
return -1;
return HandleSendAuthSession();
}
/*case CMSG_ENABLE_NAGLE:
{
TC_LOG_DEBUG("network", "%s", opcodeName.c_str());
sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct));
return m_Session ? m_Session->HandleEnableNagleAlgorithm() : -1;
}*/
default:
{
ACE_GUARD_RETURN(LockType, Guard, m_SessionLock, -1);
if (!m_Session)
{
TC_LOG_ERROR("network.opcode", "ProcessIncoming: Client not authed opcode = %u", uint32(opcode));
return -1;
}
// prevent invalid memory access/crash with custom opcodes
if (opcode >= NUM_OPCODES)
return 0;
OpcodeHandler const* handler = clientOpcodeTable[opcode];
if (!handler || handler->Status == STATUS_UNHANDLED)
{
TC_LOG_ERROR("network.opcode", "No defined handler for opcode %s sent by %s", GetOpcodeNameForLogging(new_pct->GetOpcode(), false, new_pct->GetReceivedOpcode()).c_str(), m_Session->GetPlayerInfo().c_str());
return 0;
}
// Our Idle timer will reset on any non PING opcodes.
// Catches people idling on the login screen and any lingering ingame connections.
m_Session->ResetTimeOutTime();
// OK, give the packet to WorldSession
aptr.release();
// WARNING here we call it with locks held.
// Its possible to cause deadlock if QueuePacket calls back
m_Session->QueuePacket(new_pct);
return 0;
}
}
}
catch (ByteBufferException &)
{
TC_LOG_ERROR("network", "WorldSocket::ProcessIncoming ByteBufferException occured while parsing an instant handled packet %s from client %s, accountid=%i. Disconnected client.",
opcodeName.c_str(), GetRemoteAddress().c_str(), m_Session ? int32(m_Session->GetAccountId()) : -1);
new_pct->hexlike();
return -1;
}
ACE_NOTREACHED (return 0);
}
int WorldSocket::HandleSendAuthSession()
{
WorldPacket packet(SMSG_AUTH_CHALLENGE, 37);
packet << uint16(0);
for (int i = 0; i < 8; i++)
packet << uint32(0);
packet << uint8(1);
packet << uint32(m_Seed);
return SendPacket(packet);
}
int WorldSocket::HandleAuthSession(WorldPacket& recvPacket)
{
uint8 digest[20];
uint32 clientSeed;
uint8 security;
uint16 clientBuild;
uint32 id;
uint32 addonSize;
LocaleConstant locale;
std::string account;
SHA1Hash sha;
BigNumber k;
WorldPacket addonsData;
recvPacket.read_skip<uint32>();
recvPacket.read_skip<uint32>();
recvPacket >> digest[18];
recvPacket >> digest[14];
recvPacket >> digest[3];
recvPacket >> digest[4];
recvPacket >> digest[0];
recvPacket.read_skip<uint32>();
recvPacket >> digest[11];
recvPacket >> clientSeed;
recvPacket >> digest[19];
recvPacket.read_skip<uint8>();
recvPacket.read_skip<uint8>();
recvPacket >> digest[2];
recvPacket >> digest[9];
recvPacket >> digest[12];
recvPacket.read_skip<uint64>();
recvPacket.read_skip<uint32>();
recvPacket >> digest[16];
recvPacket >> digest[5];
recvPacket >> digest[6];
recvPacket >> digest[8];
recvPacket >> clientBuild;
recvPacket >> digest[17];
recvPacket >> digest[7];
recvPacket >> digest[13];
recvPacket >> digest[15];
recvPacket >> digest[1];
recvPacket >> digest[10];
recvPacket >> addonSize;
addonsData.resize(addonSize);
recvPacket.read((uint8*)addonsData.contents(), addonSize);
recvPacket.ReadBit();
uint32 accountNameLength = recvPacket.ReadBits(11);
account = recvPacket.ReadString(accountNameLength);
if (sWorld->IsClosed())
{
SendAuthResponseError(AUTH_REJECT);
TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: World closed, denying client (%s).", GetRemoteAddress().c_str());
return -1;
}
// Get the account information from the realmd database
// 0 1 2 3 4 5 6 7 8
// SELECT id, sessionkey, last_ip, locked, expansion, mutetime, locale, recruiter, os FROM account WHERE username = ?
PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_INFO_BY_NAME);
stmt->setString(0, account);
PreparedQueryResult result = LoginDatabase.Query(stmt);
// Stop if the account is not found
if (!result)
{
SendAuthResponseError(AUTH_UNKNOWN_ACCOUNT);
TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Sent Auth Response (unknown account).");
return -1;
}
Field* fields = result->Fetch();
uint8 expansion = fields[4].GetUInt8();
uint32 world_expansion = sWorld->getIntConfig(CONFIG_EXPANSION);
if (expansion > world_expansion)
expansion = world_expansion;
///- Re-check ip locking (same check as in realmd).
if (fields[3].GetUInt8() == 1) // if ip is locked
{
if (strcmp (fields[2].GetCString(), GetRemoteAddress().c_str()))
{
SendAuthResponseError(AUTH_FAILED);
TC_LOG_DEBUG("network", "WorldSocket::HandleAuthSession: Sent Auth Response (Account IP differs).");
return -1;
}
}
id = fields[0].GetUInt32();
k.SetHexStr(fields[1].GetCString());
int64 mutetime = fields[5].GetInt64();
//! Negative mutetime indicates amount of seconds to be muted effective on next login - which is now.
if (mutetime < 0)
{
mutetime = time(NULL) + llabs(mutetime);
PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_MUTE_TIME_LOGIN);
stmt->setInt64(0, mutetime);
stmt->setUInt32(1, id);
LoginDatabase.Execute(stmt);
}
locale = LocaleConstant (fields[6].GetUInt8());
if (locale >= TOTAL_LOCALES)
locale = LOCALE_enUS;
uint32 recruiter = fields[7].GetUInt32();
std::string os = fields[8].GetString();
// Must be done before WorldSession is created
if (sWorld->getBoolConfig(CONFIG_WARDEN_ENABLED) && os != "Win" && os != "OSX")
{
SendAuthResponseError(AUTH_REJECT);
TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Client %s attempted to log in using invalid client OS (%s).", GetRemoteAddress().c_str(), os.c_str());
return -1;
}
// Checks gmlevel per Realm
stmt = LoginDatabase.GetPreparedStatement(LOGIN_GET_GMLEVEL_BY_REALMID);
stmt->setUInt32(0, id);
stmt->setInt32(1, int32(realmID));
result = LoginDatabase.Query(stmt);
if (!result)
security = 0;
else
{
fields = result->Fetch();
security = fields[0].GetUInt8();
}
// Re-check account ban (same check as in realmd)
stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_BANS);
stmt->setUInt32(0, id);
stmt->setString(1, GetRemoteAddress());
PreparedQueryResult banresult = LoginDatabase.Query(stmt);
if (banresult) // if account banned
{
SendAuthResponseError(AUTH_BANNED);
TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Sent Auth Response (Account banned).");
return -1;
}
// Check locked state for serveur
AccountTypes allowedAccountType = sWorld->GetPlayerSecurityLimit();
TC_LOG_DEBUG("network", "Allowed Level: %u Player Level %u", allowedAccountType, AccountTypes(security));
if (allowedAccountType > SEC_PLAYER && AccountTypes(security) < allowedAccountType)
{
SendAuthResponseError(AUTH_UNAVAILABLE);
TC_LOG_INFO("network", "WorldSocket::HandleAuthSession: User tries to login but his security level is not enough");
return -1;
}
// Check that Key and account name are the same on client and serveur
uint32 t = 0;
uint32 seed = m_Seed;
sha.UpdateData(account);
sha.UpdateData((uint8*)&t, 4);
sha.UpdateData((uint8*)&clientSeed, 4);
sha.UpdateData((uint8*)&seed, 4);
sha.UpdateBigNumbers(&k, NULL);
sha.Finalize();
std::string address = GetRemoteAddress();
if (memcmp(sha.GetDigest(), digest, 20))
{
SendAuthResponseError(AUTH_FAILED);
TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Authentication failed for account: %u ('%s') address: %s", id, account.c_str(), address.c_str());
return -1;
}
TC_LOG_DEBUG("network", "WorldSocket::HandleAuthSession: Client '%s' authenticated successfully from %s.",
account.c_str(),
address.c_str());
// Check if this user is by any chance a recruiter
stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_RECRUITER);
stmt->setUInt32(0, id);
result = LoginDatabase.Query(stmt);
bool isRecruiter = false;
if (result)
isRecruiter = true;
// Update the last_ip in the database
stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_LAST_IP);
stmt->setString(0, address);
stmt->setString(1, account);
LoginDatabase.Execute(stmt);
// NOTE ATM the socket is single-threaded, have this in mind ...
ACE_NEW_RETURN(m_Session, WorldSession(id, this, AccountTypes(security), expansion, mutetime, locale, recruiter, isRecruiter), -1);
m_Crypt.Init(&k);
m_Session->LoadGlobalAccountData();
m_Session->LoadTutorialsData();
m_Session->ReadAddonsInfo(addonsData);
m_Session->LoadPermissions();
// Initialize Warden system only if it is enabled by config
if (sWorld->getBoolConfig(CONFIG_WARDEN_ENABLED))
m_Session->InitWarden(&k, os);
// Sleep this Network thread for
uint32 sleepTime = sWorld->getIntConfig(CONFIG_SESSION_ADD_DELAY);
ACE_OS::sleep(ACE_Time_Value(0, sleepTime));
sWorld->AddSession(m_Session);
return 0;
}
int WorldSocket::HandlePing (WorldPacket& recvPacket)
{
uint32 ping;
uint32 latency;
// Get the ping packet content
recvPacket >> latency;
recvPacket >> ping;
if (m_LastPingTime == ACE_Time_Value::zero)
m_LastPingTime = ACE_OS::gettimeofday(); // for 1st ping
else
{
ACE_Time_Value cur_time = ACE_OS::gettimeofday();
ACE_Time_Value diff_time (cur_time);
diff_time -= m_LastPingTime;
m_LastPingTime = cur_time;
if (diff_time < ACE_Time_Value (27))
{
++m_OverSpeedPings;
uint32 max_count = sWorld->getIntConfig (CONFIG_MAX_OVERSPEED_PINGS);
if (max_count && m_OverSpeedPings > max_count)
{
ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1);
if (m_Session && !m_Session->HasPermission(rbac::RBAC_PERM_SKIP_CHECK_OVERSPEED_PING))
{
TC_LOG_ERROR("network", "WorldSocket::HandlePing: %s kicked for over-speed pings (address: %s)",
m_Session->GetPlayerInfo().c_str(), GetRemoteAddress().c_str());
return -1;
}
}
}
else
m_OverSpeedPings = 0;
}
// critical section
{
ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1);
if (m_Session)
{
m_Session->SetLatency (latency);
m_Session->ResetClientTimeDelay();
}
else
{
TC_LOG_ERROR("network", "WorldSocket::HandlePing: peer sent CMSG_PING, "
"but is not authenticated or got recently kicked, "
" address = %s",
GetRemoteAddress().c_str());
return -1;
}
}
WorldPacket packet(SMSG_PONG, 4);
packet << ping;
return SendPacket(packet);
}
void WorldSocket::SendAuthResponseError(uint8 code)
{
WorldPacket packet(SMSG_AUTH_RESPONSE, 1);
packet.WriteBit(0); // has account info
packet.WriteBit(0); // has queue info
packet << uint8(code);
SendPacket(packet);
}
| MistyWorld/MistyWorld_6xx | src/serveur/jeu/Server/WorldSocket.cpp | C++ | gpl-2.0 | 34,533 |
<?php
/**
* The admin-specific functionality of the plugin.
*
* @link kjhuer.com
* @since 1.0.0
*
* @package Za_Collect
* @subpackage Za_Collect/admin
*/
/**
* The admin-specific functionality of the plugin.
*
* Defines the plugin name, version, and two examples hooks for how to
* enqueue the admin-specific stylesheet and JavaScript.
*
* @package Za_Collect
* @subpackage Za_Collect/admin
* @author Kevin J Huer <kjhuer@gmail.com>
*/
class Za_Collect_Admin {
/**
* The ID of this plugin.
*
* @since 1.0.0
* @access private
* @var string $plugin_name The ID of this plugin.
*/
private $plugin_name;
/**
* The version of this plugin.
*
* @since 1.0.0
* @access private
* @var string $version The current version of this plugin.
*/
private $version;
/**
* Initialize the class and set its properties.
*
* @since 1.0.0
* @param string $plugin_name The name of this plugin.
* @param string $version The version of this plugin.
*/
public function __construct( $plugin_name, $version ) {
$this->plugin_name = $plugin_name;
$this->version = $version;
}
/**
* Register the stylesheets for the admin area.
*
* @since 1.0.0
*/
public function enqueue_styles() {
wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/za-collect-admin.css', array(), $this->version, 'all' );
}
/**
* Register the JavaScript for the admin area.
*
* @since 1.0.0
*/
public function enqueue_scripts() {
wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/za-collect-admin.js', array( 'jquery' ), $this->version, false );
}
/**
* Add options page for zaCollect
*
* @since 1.0.0
*/
public function add_plugin_admin_menu(){
add_options_page('zaCollect','zaCollect','manage_options',$this->plugin_name,array($this,'display_plugin_setup_page'));
}
public function add_action_links( $links ) {
/*
* Documentation : https://codex.wordpress.org/Plugin_API/Filter_Reference/plugin_action_links_(plugin_file_name)
*/
$settings_link = array(
'<a href="' . admin_url( 'options-general.php?page=' . $this->plugin_name ) . '">' . __('Settings', $this->plugin_name) . '</a>',
);
return array_merge( $settings_link, $links );
}
/**
* Render the settings page for this plugin.
*
* @since 1.0.0
*/
public function display_plugin_setup_page() {
include_once( 'partials/za-collect-admin-display.php' );
}
public function options_update() {
register_setting($this->plugin_name, $this->plugin_name, array($this, 'validate'));
}
public function validate( $input ){
$valid = array();
$valid['referral_id'] = (isset($input['referral_id']) && !empty($input['referral_id']) && preg_match( '/^[0-9]{18}$/', $input['referral_id'] ) ) ? sanitize_text_field($input['referral_id']) : '';
if ( empty($valid['referral_id']) && !empty($input['referral_id']) ) {
add_settings_error(
'referral_id', // Setting title
'referral_id_texterror', // Error ID
'Please enter a valid referral ID (18 numbers, no spaces or extra characters)', // Error message
'error' // Type of message
);
}
$valid['buy_button_text'] =(isset($input['buy_button_text']) && !empty($input['buy_button_text'])) ? sanitize_text_field($input['buy_button_text']) : '';
$valid['accent_color'] = (isset($input['accent_color']) && !empty($input['accent_color'])) ? sanitize_text_field($input['accent_color']) : '';
if ( !empty($valid['accent_color']) && !preg_match( '/^#[a-f0-9]{6}$/i', $valid['accent_color'] ) ) { // if user insert a HEX color with #
add_settings_error(
'accent_color', // Setting title
'accent_color_texterror', // Error ID
'Please enter a valid hex value color for accent color', // Error message
'error' // Type of message
);
}
$valid['accent_text_color'] = (isset($input['accent_text_color']) && !empty($input['accent_text_color'])) ? sanitize_text_field($input['accent_text_color']) : '';
if ( !empty($valid['accent_text_color']) && !preg_match( '/^#[a-f0-9]{6}$/i', $valid['accent_text_color'] ) ) { // if user insert a HEX color with #
add_settings_error(
'accent_text_color', // Setting title
'accent_text_color_texterror', // Error ID
'Please enter a valid hex value color for accent text color', // Error message
'error' // Type of message
);
}
$valid['new_window'] = (isset($input['new_window']) && !empty($input['new_window'])) ? 1 : 0;
return $valid;
}
}
| kjameshuer/za-collect | admin/class-za-collect-admin.php | PHP | gpl-2.0 | 5,664 |
#!/usr/bin/python
#CHANGE ONLY, IF YOU KNOW, WHAT YOU DO!
#OPKMANAGER WILL CRASH IF YOUR OUTPUT IS INVALID!
import subprocess
import argparse
import time
import calendar
import string
import sys
class RegisterAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
print "Official Repository" # Name
print "web" # Type (maybe web for web, or anything else for usb)
print "http://www.gcw-zero.com/files/upload/opk/" #URL
print "official.py --update" #Call for updating the list
print "O" #letter to show
class UpdateAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
process = subprocess.Popen('wget --timeout='+str(values[0])+' -qO- http://ziz.gp2x.de/gcw-repos/count.php',stdout=subprocess.PIPE,shell=True)
process = subprocess.Popen('wget --timeout='+str(values[0])+' -qO- http://www.gcw-zero.com/downloads',stdout=subprocess.PIPE,shell=True)
#process = subprocess.Popen('wget --timeout='+str(values[0])+' -qO- http://ziz.gp2x.de/temp/test.htm',stdout=subprocess.PIPE,shell=True)
#process = subprocess.Popen('cat downloads',stdout=subprocess.PIPE,shell=True)
output = process.stdout.read().split('<div class="downloads_overview">')
for output_part in output:
part = output_part.split('\n')
line_number = 0;
not_found = 1;
while (line_number < len(part)):
if (part[line_number].strip().startswith('<span class="downloads_title">')):
not_found = 0;
break;
line_number += 1;
if not_found:
continue;
program_name_description = part[line_number];
name = program_name_description.split('>')[1].split('<')[0];
if (name == ""):
continue
line_number = 0;
not_found = 1;
while (line_number < len(part)):
if (part[line_number].strip().startswith('<a class="downloads_link"')):
not_found = 0;
break;
line_number += 1;
if not_found:
continue;
filename = part[line_number].split('href="file.php?file=')[1].split('">')[0];
print "["+name+"]"
description = program_name_description.split('>')[3];
print "description: "+description
print "filename: " + filename
l = len(part)
found_version = 0
found_image = 0
found_long = 0;
for i in range(0,l-1):
if string.find(part[i],'Publication Date') != -1:
version = part[i+1]
version = version.split('>')[1]
version = version.split('<')[0]
t = time.strptime(version,"%A, %d %b %Y")
print "version: " + str(calendar.timegm(t)) #NEEDED!
found_version = 1
if string.find(part[i],'<div class="downloads_preview"') != -1:
image = part[i];
image = image.split("background-image: url('")[1].split("');")[0];
print "image_url: http://www.gcw-zero.com/" + image
if string.find(part[i],'<p class="more fade">') != -1:
long_description = part[i];
long_description = long_description.split('<p class="more fade">')[1].split("</p>")[0];
long_description = long_description.replace('<br /> ','\\n')
long_description = long_description.split('>')
sys.stdout.write("long_description: ")
for long_description_part in long_description:
sys.stdout.write(long_description_part.split('<')[0])
sys.stdout.write('\n')
found_long = 1
if (found_version and found_image and found_long):
break
print ""
def main():
parser = argparse.ArgumentParser(description="Ziz's Repository script")
parser.add_argument('--register', nargs=0, action=RegisterAction)
parser.add_argument('--update', nargs=1, action=UpdateAction)
args = parser.parse_args()
if __name__ == "__main__":
main()
| theZiz/OPKManager | repositories/official.py | Python | gpl-2.0 | 3,617 |
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log: CMAny.hpp,v $
* Revision 1.2 2001/05/11 13:27:14 tng
* Copyright update.
*
* Revision 1.1 2001/02/27 14:48:46 tng
* Schema: Add CMAny and ContentLeafNameTypeVector, by Pei Yong Zhang
*
*/
#if !defined(CMANY_HPP)
#define CMANY_HPP
#include <util/XercesDefs.hpp>
#include <validators/common/CMNode.hpp>
class CMStateSet;
class CMAny : public CMNode
{
public :
// -----------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------
CMAny
(
const ContentSpecNode::NodeTypes type
, const unsigned int URI
, const unsigned int position
);
~CMAny();
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
unsigned int getURI() const;
unsigned int getPosition() const;
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
void setPosition(const unsigned int newPosition);
// -----------------------------------------------------------------------
// Implementation of the public CMNode virtual interface
// -----------------------------------------------------------------------
bool isNullable() const;
protected :
// -----------------------------------------------------------------------
// Implementation of the protected CMNode virtual interface
// -----------------------------------------------------------------------
void calcFirstPos(CMStateSet& toSet) const;
void calcLastPos(CMStateSet& toSet) const;
private :
// -----------------------------------------------------------------------
// Private data members
//
// fURI;
// URI of the any content model. This value is set if the type is
// of the following:
// XMLContentSpec.CONTENTSPECNODE_ANY,
// XMLContentSpec.CONTENTSPECNODE_ANY_OTHER.
//
// fPosition
// Part of the algorithm to convert a regex directly to a DFA
// numbers each leaf sequentially. If its -1, that means its an
// epsilon node. Zero and greater are non-epsilon positions.
// -----------------------------------------------------------------------
unsigned int fURI;
unsigned int fPosition;
};
#endif
| stippi/Clockwerk | include/xerces/validators/common/CMAny.hpp | C++ | gpl-2.0 | 5,208 |
<?php // $Id: report.php,v 1.29 2008/11/30 21:33:58 skodak Exp $
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
$courses = get_courses('all','c.shortname','c.id,c.shortname,c.fullname');
$courseoptions = array();
foreach ($courses as $c) {
$context = get_context_instance(CONTEXT_COURSE, $c->id);
if (has_capability('coursereport/stats:view', $context)) {
$courseoptions[$c->id] = $c->shortname;
}
}
$reportoptions = stats_get_report_options($course->id, $mode);
$timeoptions = report_stats_timeoptions($mode);
if (empty($timeoptions)) {
print_error('nostatstodisplay', '', $CFG->wwwroot.'/course/view.php?id='.$course->id);
}
$table->width = 'auto';
if ($mode == STATS_MODE_DETAILED) {
$param = stats_get_parameters($time,null,$course->id,$mode); // we only care about the table and the time string (if we have time)
//TODO: lceanup this ugly mess
$sql = 'SELECT DISTINCT s.userid, u.firstname, u.lastname, u.idnumber
FROM {stats_user_'.$param->table.'} s
JOIN {user} u ON u.id = s.userid
WHERE courseid = '.$course->id
. ((!empty($param->stattype)) ? ' AND stattype = \''.$param->stattype.'\'' : '')
. ((!empty($time)) ? ' AND timeend >= '.$param->timeafter : '')
.' ORDER BY u.lastname, u.firstname ASC';
if (!$us = $DB->get_records_sql($sql, $param->params)) {
print_error('nousers');
}
foreach ($us as $u) {
$users[$u->userid] = fullname($u, true);
}
$table->align = array('left','left','left','left','left','left','left','left');
$table->data[] = array(get_string('course'),choose_from_menu($courseoptions,'course',$course->id,'','','',true),
get_string('users'),choose_from_menu($users,'userid',$userid,'','','',true),
get_string('statsreporttype'),choose_from_menu($reportoptions,'report',($report == 5) ? $report.$roleid : $report,'','','',true),
get_string('statstimeperiod'),choose_from_menu($timeoptions,'time',$time,'','','',true),
'<input type="submit" value="'.get_string('view').'" />') ;
} else if ($mode == STATS_MODE_RANKED) {
$table->align = array('left','left','left','left','left','left');
$table->data[] = array(get_string('statsreporttype'),choose_from_menu($reportoptions,'report',($report == 5) ? $report.$roleid : $report,'','','',true),
get_string('statstimeperiod'),choose_from_menu($timeoptions,'time',$time,'','','',true),
'<input type="submit" value="'.get_string('view').'" />') ;
} else if ($mode == STATS_MODE_GENERAL) {
$table->align = array('left','left','left','left','left','left','left');
$table->data[] = array(get_string('course'),choose_from_menu($courseoptions,'course',$course->id,'','','',true),
get_string('statsreporttype'),choose_from_menu($reportoptions,'report',($report == 5) ? $report.$roleid : $report,'','','',true),
get_string('statstimeperiod'),choose_from_menu($timeoptions,'time',$time,'','','',true),
'<input type="submit" value="'.get_string('view').'" />') ;
}
echo '<form action="index.php" method="post">'."\n"
.'<div>'."\n"
.'<input type="hidden" name="mode" value="'.$mode.'" />'."\n";
print_table($table);
echo '</div>';
echo '</form>';
if (!empty($report) && !empty($time)) {
if ($report == STATS_REPORT_LOGINS && $course->id != SITEID) {
print_error('reportnotavailable');
}
$param = stats_get_parameters($time,$report,$course->id,$mode);
if ($mode == STATS_MODE_DETAILED) {
$param->table = 'user_'.$param->table;
}
if (!empty($param->sql)) {
$sql = $param->sql;
} else {
//TODO: lceanup this ugly mess
$sql = 'SELECT '.((empty($param->fieldscomplete)) ? 'id,roleid,timeend,' : '').$param->fields
.' FROM {stats_'.$param->table.'} WHERE '
.(($course->id == SITEID) ? '' : ' courseid = '.$course->id.' AND ')
.((!empty($userid)) ? ' userid = '.$userid.' AND ' : '')
.((!empty($roleid)) ? ' roleid = '.$roleid.' AND ' : '')
. ((!empty($param->stattype)) ? ' stattype = \''.$param->stattype.'\' AND ' : '')
.' timeend >= '.$param->timeafter
.' '.$param->extras
.' ORDER BY timeend DESC';
}
$stats = $DB->get_records_sql($sql, $params);
if (empty($stats)) {
notify(get_string('statsnodata'));
} else {
$stats = stats_fix_zeros($stats,$param->timeafter,$param->table,(!empty($param->line2)));
print_heading(format_string($course->shortname).' - '.get_string('statsreport'.$report)
.((!empty($user)) ? ' '.get_string('statsreportforuser').' ' .fullname($user,true) : '')
.((!empty($roleid)) ? ' '.$DB->get_field('role','name', array('id'=>$roleid)) : ''));
if (empty($CFG->gdversion)) {
echo "(".get_string("gdneed").")";
} else {
if ($mode == STATS_MODE_DETAILED) {
echo '<div class="graph"><img src="'.$CFG->wwwroot.'/course/report/stats/graph.php?mode='.$mode.'&course='.$course->id.'&time='.$time.'&report='.$report.'&userid='.$userid.'" alt="'.get_string('statisticsgraph').'" /></div';
} else {
echo '<div class="graph"><img src="'.$CFG->wwwroot.'/course/report/stats/graph.php?mode='.$mode.'&course='.$course->id.'&time='.$time.'&report='.$report.'&roleid='.$roleid.'" alt="'.get_string('statisticsgraph').'" /></div>';
}
}
$table = new StdClass;
$table->align = array('left','center','center','center');
$param->table = str_replace('user_','',$param->table);
switch ($param->table) {
case 'daily' : $period = get_string('day'); break;
case 'weekly' : $period = get_string('week'); break;
case 'monthly': $period = get_string('month', 'form'); break;
default : $period = '';
}
$table->head = array(get_string('periodending','moodle',$period));
if (empty($param->crosstab)) {
$table->head[] = $param->line1;
if (!empty($param->line2)) {
$table->head[] = $param->line2;
}
}
if (empty($param->crosstab)) {
foreach ($stats as $stat) {
$a = array(userdate($stat->timeend-(60*60*24),get_string('strftimedate'),$CFG->timezone),$stat->line1);
if (isset($stat->line2)) {
$a[] = $stat->line2;
}
if (empty($CFG->loglifetime) || ($stat->timeend-(60*60*24)) >= (time()-60*60*24*$CFG->loglifetime)) {
if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE, $course->id))) {
$a[] = '<a href="'.$CFG->wwwroot.'/course/report/log/index.php?id='.
$course->id.'&chooselog=1&showusers=1&showcourses=1&user='
.$userid.'&date='.usergetmidnight($stat->timeend-(60*60*24)).'">'
.get_string('course').' ' .get_string('logs').'</a> ';
} else {
$a[] = '';
}
}
$table->data[] = $a;
}
} else {
$data = array();
$roles = array();
$times = array();
$missedlines = array();
$rolenames = get_all_roles();
foreach ($rolenames as $r) {
$rolenames[$r->id] = $r->name;
}
$rolenames = role_fix_names($rolenames, get_context_instance(CONTEXT_COURSE, $course->id));
foreach ($stats as $stat) {
if (!empty($stat->zerofixed)) {
$missedlines[] = $stat->timeend;
}
$data[$stat->timeend][$stat->roleid] = $stat->line1;
if ($stat->roleid != 0) {
if (!array_key_exists($stat->roleid,$roles)) {
$roles[$stat->roleid] = $rolenames[$stat->roleid];
}
} else {
if (!array_key_exists($stat->roleid,$roles)) {
$roles[$stat->roleid] = get_string('all');
}
}
if (!array_key_exists($stat->timeend,$times)) {
$times[$stat->timeend] = userdate($stat->timeend,get_string('strftimedate'),$CFG->timezone);
}
}
foreach ($data as $time => $rolesdata) {
if (in_array($time,$missedlines)) {
$rolesdata = array();
foreach ($roles as $roleid => $guff) {
$rolesdata[$roleid] = 0;
}
}
else {
foreach (array_keys($roles) as $r) {
if (!array_key_exists($r, $rolesdata)) {
$rolesdata[$r] = 0;
}
}
}
krsort($rolesdata);
$row = array_merge(array($times[$time]),$rolesdata);
if (empty($CFG->loglifetime) || ($stat->timeend-(60*60*24)) >= (time()-60*60*24*$CFG->loglifetime)) {
if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE, $course->id))) {
$row[] = '<a href="'.$CFG->wwwroot.'/course/report/log/index.php?id='
.$course->id.'&chooselog=1&showusers=1&showcourses=1&user='.$userid
.'&date='.usergetmidnight($time-(60*60*24)).'">'
.get_string('course').' ' .get_string('logs').'</a> ';
} else {
$row[] = '';
}
}
$table->data[] = $row;
}
krsort($roles);
$table->head = array_merge($table->head,$roles);
}
$table->head[] = get_string('logs');
if (!empty($lastrecord)) {
$lastrecord[] = $lastlink;
$table->data[] = $lastrecord;
}
print_table($table);
}
}
?>
| nicolasconnault/moodle2.0 | course/report/stats/report.php | PHP | gpl-2.0 | 11,351 |
module Actions
module Pulp3
module Repository
class CreatePublication < Pulp3::AbstractAsyncTask
middleware.use Actions::Middleware::ExecuteIfContentsChanged
def plan(repository, smart_proxy, options)
sequence do
action = plan_self(:repository_id => repository.id, :smart_proxy_id => smart_proxy.id, :contents_changed => options[:contents_changed], :options => options)
plan_action(SavePublication, repository, action.output, :contents_changed => options[:contents_changed])
end
end
def invoke_external_task
repository = ::Katello::Repository.find(input[:repository_id])
smart_proxy = ::SmartProxy.find(input[:smart_proxy_id])
if repository.publication_href.nil? || input[:options][:force]
output[:response] = repository.backend_service(smart_proxy).create_publication
else
[]
end
end
end
end
end
end
| ares/katello | app/lib/actions/pulp3/repository/create_publication.rb | Ruby | gpl-2.0 | 984 |
'use strict';
app.controller('orderController', ['$scope', '$rootScope', 'toastrService', 'orderService',
function ($scope, $rootScope, toastrService, orderService) {
$scope.paging = 1;
$scope.disabledMore = false;
$scope.data = [];
$scope.getOrders = function () {
orderService.get($scope.paging).then(function (data) {
if (data.length > 0) {
$scope.data.push.apply($scope.data, data);
} else {
$scope.disabledMore = true;
}
});
}
$scope.more = function () {
$scope.paging++;
$scope.getOrders();
};
$scope.refresh = function () {
$scope.paging = 1;
$scope.data = [];
$scope.getOrders();
};
$scope.getOrders();
$scope.openOrder = function (item, $index) {
$scope.order = item;
$scope.order.$index = $index;
$('#modal-order').modal({
backdrop: true
});
};
}
]); | ozalvarez/elcubo9 | elcubo9.admin/app/controllers/orderController.js | JavaScript | gpl-2.0 | 1,103 |
#!/usr/bin/env python
####################################
#
# --- TEXTPATGEN TEMPLATE ---
#
# Users can change the output by editing
# this file directly.
#
####################################
import sys
sys.stdout.write('####################################\n')
sys.stdout.write('#\n')
sys.stdout.write('# -- TEXTPATGEN GENERATED FILE --\n')
sys.stdout.write('#\n')
sys.stdout.write('# -- Created from a Python script.\n')
sys.stdout.write('#\n')
sys.stdout.write("####################################\n")
num=0
for length in range(0, 16):
for width in range(0, 15):
sys.stdout.write('X-%04X ' % num)
num=num+1
width=width+1
length=length+1
sys.stdout.write('X-%04X\n' % num)
num=num+1
sys.stdout.write('# -- End of file.\n');
sys.stdout.flush()
| kevinleake01/textpatgen | 12-workspace-py/tpl-py-0001.py | Python | gpl-2.0 | 774 |
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<title><?php
/*
* Print the <title> tag based on what is being viewed.
*/
global $page, $paged;
wp_title( '|', true, 'right' );
// Add the blog name.
bloginfo( 'name' );
// Add the blog description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
echo " | $site_description";
// Add a page number if necessary:
if ( $paged >= 2 || $page >= 2 )
echo ' | ' . sprintf( __( 'Page %s', 'twentyten' ), max( $paged, $page ) );
?></title>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" />
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo('template_url'); ?>/css/skin.css" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<?php
/* We add some JavaScript to pages with the comment form
* to support sites with threaded comments (when in use).
*/
if ( is_singular() && get_option( 'thread_comments' ) )
wp_enqueue_script( 'comment-reply' );
/* Always have wp_head() just before the closing </head>
* tag of your theme, or you will break many plugins, which
* generally use this hook to add elements to <head> such
* as styles, scripts, and meta tags.
*/
wp_head();
?>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/javascript/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/javascript/jquery.jcarousel.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#mycarousel').jcarousel({
scroll:3,
auto:5,
wrap:"both"
});
});
</script>
</head>
<a name="menu"></a>
<body <?php body_class(); ?>>
<div class="centralizarCorpo content">
<div class="header">
<div class='img_header_detalhe img_header_detalhe_size'>
<div class="img_header_logo_jzconsultoria img_header_logo_jzconsultoria_size"></div>
<div class="img_header_consultoria_treinamento img_header_consultoria_treinamento_size"></div>
</div>
<div class="img_header_menu img_header_menu_size"></div>
<div class="img_header_line img_header_line_size"></div>
<div class="menu">
<a class="bt_empresa" href="#empresa"><div class="img_header_bt1 img_header_bt1_size"></div></a>
<a class="bt_consultoria" href="#consultoria"><div class="img_header_bt2 img_header_bt2_size"></div></a>
<a class="bt_treinamentos" href="#treinamento"><div class="img_header_bt3 img_header_bt3_size"></div></a>
<a class="bt_clientes" href="#clientes"><div class="img_header_bt4 img_header_bt4_size"></div></a>
<a class="bt_contato" href="#contato"><div class="img_header_bt5 img_header_bt5_size"></div></a>
</div>
</div> | fearzendron/jzconsultoria | wp-content/themes/jzconsultoria/header-home.php | PHP | gpl-2.0 | 2,963 |
from .. import config
from .. import fixtures
from ..assertions import eq_
from ..assertions import in_
from ..schema import Column
from ..schema import Table
from ... import bindparam
from ... import case
from ... import Computed
from ... import exists
from ... import false
from ... import func
from ... import Integer
from ... import literal
from ... import literal_column
from ... import null
from ... import select
from ... import String
from ... import testing
from ... import text
from ... import true
from ... import tuple_
from ... import union
from ... import util
class CollateTest(fixtures.TablesTest):
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String(100)),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.some_table.insert(),
[
{"id": 1, "data": "collate data1"},
{"id": 2, "data": "collate data2"},
],
)
def _assert_result(self, select, result):
eq_(config.db.execute(select).fetchall(), result)
@testing.requires.order_by_collation
def test_collate_order_by(self):
collation = testing.requires.get_order_by_collation(testing.config)
self._assert_result(
select([self.tables.some_table]).order_by(
self.tables.some_table.c.data.collate(collation).asc()
),
[(1, "collate data1"), (2, "collate data2")],
)
class OrderByLabelTest(fixtures.TablesTest):
"""Test the dialect sends appropriate ORDER BY expressions when
labels are used.
This essentially exercises the "supports_simple_order_by_label"
setting.
"""
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
Column("x", Integer),
Column("y", Integer),
Column("q", String(50)),
Column("p", String(50)),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.some_table.insert(),
[
{"id": 1, "x": 1, "y": 2, "q": "q1", "p": "p3"},
{"id": 2, "x": 2, "y": 3, "q": "q2", "p": "p2"},
{"id": 3, "x": 3, "y": 4, "q": "q3", "p": "p1"},
],
)
def _assert_result(self, select, result):
eq_(config.db.execute(select).fetchall(), result)
def test_plain(self):
table = self.tables.some_table
lx = table.c.x.label("lx")
self._assert_result(select([lx]).order_by(lx), [(1,), (2,), (3,)])
def test_composed_int(self):
table = self.tables.some_table
lx = (table.c.x + table.c.y).label("lx")
self._assert_result(select([lx]).order_by(lx), [(3,), (5,), (7,)])
def test_composed_multiple(self):
table = self.tables.some_table
lx = (table.c.x + table.c.y).label("lx")
ly = (func.lower(table.c.q) + table.c.p).label("ly")
self._assert_result(
select([lx, ly]).order_by(lx, ly.desc()),
[(3, util.u("q1p3")), (5, util.u("q2p2")), (7, util.u("q3p1"))],
)
def test_plain_desc(self):
table = self.tables.some_table
lx = table.c.x.label("lx")
self._assert_result(
select([lx]).order_by(lx.desc()), [(3,), (2,), (1,)]
)
def test_composed_int_desc(self):
table = self.tables.some_table
lx = (table.c.x + table.c.y).label("lx")
self._assert_result(
select([lx]).order_by(lx.desc()), [(7,), (5,), (3,)]
)
@testing.requires.group_by_complex_expression
def test_group_by_composed(self):
table = self.tables.some_table
expr = (table.c.x + table.c.y).label("lx")
stmt = (
select([func.count(table.c.id), expr])
.group_by(expr)
.order_by(expr)
)
self._assert_result(stmt, [(1, 3), (1, 5), (1, 7)])
class LimitOffsetTest(fixtures.TablesTest):
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
Column("x", Integer),
Column("y", Integer),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.some_table.insert(),
[
{"id": 1, "x": 1, "y": 2},
{"id": 2, "x": 2, "y": 3},
{"id": 3, "x": 3, "y": 4},
{"id": 4, "x": 4, "y": 5},
],
)
def _assert_result(self, select, result, params=()):
eq_(config.db.execute(select, params).fetchall(), result)
def test_simple_limit(self):
table = self.tables.some_table
self._assert_result(
select([table]).order_by(table.c.id).limit(2),
[(1, 1, 2), (2, 2, 3)],
)
@testing.requires.offset
def test_simple_offset(self):
table = self.tables.some_table
self._assert_result(
select([table]).order_by(table.c.id).offset(2),
[(3, 3, 4), (4, 4, 5)],
)
@testing.requires.offset
def test_simple_limit_offset(self):
table = self.tables.some_table
self._assert_result(
select([table]).order_by(table.c.id).limit(2).offset(1),
[(2, 2, 3), (3, 3, 4)],
)
@testing.requires.offset
def test_limit_offset_nobinds(self):
"""test that 'literal binds' mode works - no bound params."""
table = self.tables.some_table
stmt = select([table]).order_by(table.c.id).limit(2).offset(1)
sql = stmt.compile(
dialect=config.db.dialect, compile_kwargs={"literal_binds": True}
)
sql = str(sql)
self._assert_result(sql, [(2, 2, 3), (3, 3, 4)])
@testing.requires.bound_limit_offset
def test_bound_limit(self):
table = self.tables.some_table
self._assert_result(
select([table]).order_by(table.c.id).limit(bindparam("l")),
[(1, 1, 2), (2, 2, 3)],
params={"l": 2},
)
@testing.requires.bound_limit_offset
def test_bound_offset(self):
table = self.tables.some_table
self._assert_result(
select([table]).order_by(table.c.id).offset(bindparam("o")),
[(3, 3, 4), (4, 4, 5)],
params={"o": 2},
)
@testing.requires.bound_limit_offset
def test_bound_limit_offset(self):
table = self.tables.some_table
self._assert_result(
select([table])
.order_by(table.c.id)
.limit(bindparam("l"))
.offset(bindparam("o")),
[(2, 2, 3), (3, 3, 4)],
params={"l": 2, "o": 1},
)
class CompoundSelectTest(fixtures.TablesTest):
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
Column("x", Integer),
Column("y", Integer),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.some_table.insert(),
[
{"id": 1, "x": 1, "y": 2},
{"id": 2, "x": 2, "y": 3},
{"id": 3, "x": 3, "y": 4},
{"id": 4, "x": 4, "y": 5},
],
)
def _assert_result(self, select, result, params=()):
eq_(config.db.execute(select, params).fetchall(), result)
def test_plain_union(self):
table = self.tables.some_table
s1 = select([table]).where(table.c.id == 2)
s2 = select([table]).where(table.c.id == 3)
u1 = union(s1, s2)
self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)])
def test_select_from_plain_union(self):
table = self.tables.some_table
s1 = select([table]).where(table.c.id == 2)
s2 = select([table]).where(table.c.id == 3)
u1 = union(s1, s2).alias().select()
self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)])
@testing.requires.order_by_col_from_union
@testing.requires.parens_in_union_contained_select_w_limit_offset
def test_limit_offset_selectable_in_unions(self):
table = self.tables.some_table
s1 = (
select([table])
.where(table.c.id == 2)
.limit(1)
.order_by(table.c.id)
)
s2 = (
select([table])
.where(table.c.id == 3)
.limit(1)
.order_by(table.c.id)
)
u1 = union(s1, s2).limit(2)
self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)])
@testing.requires.parens_in_union_contained_select_wo_limit_offset
def test_order_by_selectable_in_unions(self):
table = self.tables.some_table
s1 = select([table]).where(table.c.id == 2).order_by(table.c.id)
s2 = select([table]).where(table.c.id == 3).order_by(table.c.id)
u1 = union(s1, s2).limit(2)
self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)])
def test_distinct_selectable_in_unions(self):
table = self.tables.some_table
s1 = select([table]).where(table.c.id == 2).distinct()
s2 = select([table]).where(table.c.id == 3).distinct()
u1 = union(s1, s2).limit(2)
self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)])
@testing.requires.parens_in_union_contained_select_w_limit_offset
def test_limit_offset_in_unions_from_alias(self):
table = self.tables.some_table
s1 = (
select([table])
.where(table.c.id == 2)
.limit(1)
.order_by(table.c.id)
)
s2 = (
select([table])
.where(table.c.id == 3)
.limit(1)
.order_by(table.c.id)
)
# this necessarily has double parens
u1 = union(s1, s2).alias()
self._assert_result(
u1.select().limit(2).order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)]
)
def test_limit_offset_aliased_selectable_in_unions(self):
table = self.tables.some_table
s1 = (
select([table])
.where(table.c.id == 2)
.limit(1)
.order_by(table.c.id)
.alias()
.select()
)
s2 = (
select([table])
.where(table.c.id == 3)
.limit(1)
.order_by(table.c.id)
.alias()
.select()
)
u1 = union(s1, s2).limit(2)
self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)])
class ExpandingBoundInTest(fixtures.TablesTest):
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
Column("x", Integer),
Column("y", Integer),
Column("z", String(50)),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.some_table.insert(),
[
{"id": 1, "x": 1, "y": 2, "z": "z1"},
{"id": 2, "x": 2, "y": 3, "z": "z2"},
{"id": 3, "x": 3, "y": 4, "z": "z3"},
{"id": 4, "x": 4, "y": 5, "z": "z4"},
],
)
def _assert_result(self, select, result, params=()):
eq_(config.db.execute(select, params).fetchall(), result)
def test_multiple_empty_sets(self):
# test that any anonymous aliasing used by the dialect
# is fine with duplicates
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(table.c.x.in_(bindparam("q", expanding=True)))
.where(table.c.y.in_(bindparam("p", expanding=True)))
.order_by(table.c.id)
)
self._assert_result(stmt, [], params={"q": [], "p": []})
@testing.requires.tuple_in
def test_empty_heterogeneous_tuples(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(
tuple_(table.c.x, table.c.z).in_(
bindparam("q", expanding=True)
)
)
.order_by(table.c.id)
)
self._assert_result(stmt, [], params={"q": []})
@testing.requires.tuple_in
def test_empty_homogeneous_tuples(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(
tuple_(table.c.x, table.c.y).in_(
bindparam("q", expanding=True)
)
)
.order_by(table.c.id)
)
self._assert_result(stmt, [], params={"q": []})
def test_bound_in_scalar(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(table.c.x.in_(bindparam("q", expanding=True)))
.order_by(table.c.id)
)
self._assert_result(stmt, [(2,), (3,), (4,)], params={"q": [2, 3, 4]})
@testing.requires.tuple_in
def test_bound_in_two_tuple(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(
tuple_(table.c.x, table.c.y).in_(
bindparam("q", expanding=True)
)
)
.order_by(table.c.id)
)
self._assert_result(
stmt, [(2,), (3,), (4,)], params={"q": [(2, 3), (3, 4), (4, 5)]}
)
@testing.requires.tuple_in
def test_bound_in_heterogeneous_two_tuple(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(
tuple_(table.c.x, table.c.z).in_(
bindparam("q", expanding=True)
)
)
.order_by(table.c.id)
)
self._assert_result(
stmt,
[(2,), (3,), (4,)],
params={"q": [(2, "z2"), (3, "z3"), (4, "z4")]},
)
def test_empty_set_against_integer(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(table.c.x.in_(bindparam("q", expanding=True)))
.order_by(table.c.id)
)
self._assert_result(stmt, [], params={"q": []})
def test_empty_set_against_integer_negation(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(table.c.x.notin_(bindparam("q", expanding=True)))
.order_by(table.c.id)
)
self._assert_result(stmt, [(1,), (2,), (3,), (4,)], params={"q": []})
def test_empty_set_against_string(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(table.c.z.in_(bindparam("q", expanding=True)))
.order_by(table.c.id)
)
self._assert_result(stmt, [], params={"q": []})
def test_empty_set_against_string_negation(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(table.c.z.notin_(bindparam("q", expanding=True)))
.order_by(table.c.id)
)
self._assert_result(stmt, [(1,), (2,), (3,), (4,)], params={"q": []})
def test_null_in_empty_set_is_false(self):
stmt = select(
[
case(
[
(
null().in_(
bindparam("foo", value=(), expanding=True)
),
true(),
)
],
else_=false(),
)
]
)
in_(config.db.execute(stmt).fetchone()[0], (False, 0))
class LikeFunctionsTest(fixtures.TablesTest):
__backend__ = True
run_inserts = "once"
run_deletes = None
@classmethod
def define_tables(cls, metadata):
Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String(50)),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.some_table.insert(),
[
{"id": 1, "data": "abcdefg"},
{"id": 2, "data": "ab/cdefg"},
{"id": 3, "data": "ab%cdefg"},
{"id": 4, "data": "ab_cdefg"},
{"id": 5, "data": "abcde/fg"},
{"id": 6, "data": "abcde%fg"},
{"id": 7, "data": "ab#cdefg"},
{"id": 8, "data": "ab9cdefg"},
{"id": 9, "data": "abcde#fg"},
{"id": 10, "data": "abcd9fg"},
],
)
def _test(self, expr, expected):
some_table = self.tables.some_table
with config.db.connect() as conn:
rows = {
value
for value, in conn.execute(
select([some_table.c.id]).where(expr)
)
}
eq_(rows, expected)
def test_startswith_unescaped(self):
col = self.tables.some_table.c.data
self._test(col.startswith("ab%c"), {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
def test_startswith_autoescape(self):
col = self.tables.some_table.c.data
self._test(col.startswith("ab%c", autoescape=True), {3})
def test_startswith_sqlexpr(self):
col = self.tables.some_table.c.data
self._test(
col.startswith(literal_column("'ab%c'")),
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
)
def test_startswith_escape(self):
col = self.tables.some_table.c.data
self._test(col.startswith("ab##c", escape="#"), {7})
def test_startswith_autoescape_escape(self):
col = self.tables.some_table.c.data
self._test(col.startswith("ab%c", autoescape=True, escape="#"), {3})
self._test(col.startswith("ab#c", autoescape=True, escape="#"), {7})
def test_endswith_unescaped(self):
col = self.tables.some_table.c.data
self._test(col.endswith("e%fg"), {1, 2, 3, 4, 5, 6, 7, 8, 9})
def test_endswith_sqlexpr(self):
col = self.tables.some_table.c.data
self._test(
col.endswith(literal_column("'e%fg'")), {1, 2, 3, 4, 5, 6, 7, 8, 9}
)
def test_endswith_autoescape(self):
col = self.tables.some_table.c.data
self._test(col.endswith("e%fg", autoescape=True), {6})
def test_endswith_escape(self):
col = self.tables.some_table.c.data
self._test(col.endswith("e##fg", escape="#"), {9})
def test_endswith_autoescape_escape(self):
col = self.tables.some_table.c.data
self._test(col.endswith("e%fg", autoescape=True, escape="#"), {6})
self._test(col.endswith("e#fg", autoescape=True, escape="#"), {9})
def test_contains_unescaped(self):
col = self.tables.some_table.c.data
self._test(col.contains("b%cde"), {1, 2, 3, 4, 5, 6, 7, 8, 9})
def test_contains_autoescape(self):
col = self.tables.some_table.c.data
self._test(col.contains("b%cde", autoescape=True), {3})
def test_contains_escape(self):
col = self.tables.some_table.c.data
self._test(col.contains("b##cde", escape="#"), {7})
def test_contains_autoescape_escape(self):
col = self.tables.some_table.c.data
self._test(col.contains("b%cd", autoescape=True, escape="#"), {3})
self._test(col.contains("b#cd", autoescape=True, escape="#"), {7})
class ComputedColumnTest(fixtures.TablesTest):
__backend__ = True
__requires__ = ("computed_columns",)
@classmethod
def define_tables(cls, metadata):
Table(
"square",
metadata,
Column("id", Integer, primary_key=True),
Column("side", Integer),
Column("area", Integer, Computed("side * side")),
Column("perimeter", Integer, Computed("4 * side")),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.square.insert(),
[{"id": 1, "side": 10}, {"id": 10, "side": 42}],
)
def test_select_all(self):
with config.db.connect() as conn:
res = conn.execute(
select([text("*")])
.select_from(self.tables.square)
.order_by(self.tables.square.c.id)
).fetchall()
eq_(res, [(1, 10, 100, 40), (10, 42, 1764, 168)])
def test_select_columns(self):
with config.db.connect() as conn:
res = conn.execute(
select(
[self.tables.square.c.area, self.tables.square.c.perimeter]
)
.select_from(self.tables.square)
.order_by(self.tables.square.c.id)
).fetchall()
eq_(res, [(100, 40), (1764, 168)])
class ExistsTest(fixtures.TablesTest):
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"stuff",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String(50)),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.stuff.insert(),
[
{"id": 1, "data": "some data"},
{"id": 2, "data": "some data"},
{"id": 3, "data": "some data"},
{"id": 4, "data": "some other data"},
],
)
def test_select_exists(self, connection):
stuff = self.tables.stuff
eq_(
connection.execute(
select([literal(1)]).where(
exists().where(stuff.c.data == "some data")
)
).fetchall(),
[(1,)],
)
def test_select_exists_false(self, connection):
stuff = self.tables.stuff
eq_(
connection.execute(
select([literal(1)]).where(
exists().where(stuff.c.data == "no data")
)
).fetchall(),
[],
)
class IsOrIsNotDistinctFromTest(fixtures.TablesTest):
__backend__ = True
__requires__ = ("supports_is_distinct_from",)
@classmethod
def define_tables(cls, metadata):
Table(
"is_distinct_test",
metadata,
Column("id", Integer, primary_key=True),
Column("col_a", Integer, nullable=True),
Column("col_b", Integer, nullable=True),
)
@testing.combinations(
("both_int_different", 0, 1, 1),
("both_int_same", 1, 1, 0),
("one_null_first", None, 1, 1),
("one_null_second", 0, None, 1),
("both_null", None, None, 0),
id_="iaaa",
argnames="col_a_value, col_b_value, expected_row_count_for_is",
)
def test_is_or_isnot_distinct_from(
self, col_a_value, col_b_value, expected_row_count_for_is, connection
):
tbl = self.tables.is_distinct_test
connection.execute(
tbl.insert(),
[{"id": 1, "col_a": col_a_value, "col_b": col_b_value}],
)
result = connection.execute(
tbl.select(tbl.c.col_a.is_distinct_from(tbl.c.col_b))
).fetchall()
eq_(
len(result),
expected_row_count_for_is,
)
expected_row_count_for_isnot = (
1 if expected_row_count_for_is == 0 else 0
)
result = connection.execute(
tbl.select(tbl.c.col_a.isnot_distinct_from(tbl.c.col_b))
).fetchall()
eq_(
len(result),
expected_row_count_for_isnot,
)
| gltn/stdm | stdm/third_party/sqlalchemy/testing/suite/test_select.py | Python | gpl-2.0 | 24,377 |
<?php
/**
* @Project NUKEVIET 4.x
* @Author VINADES.,JSC (contact@vinades.vn)
* @Copyright (C) 2014 VINADES.,JSC. All rights reserved
* @License GNU/GPL version 2 or any later version
* @Createdate 9/9/2010, 6:38
*/
if (! defined('NV_IS_FILE_WEBTOOLS')) {
die('Stop!!!');
}
$contents = 'Error Access!!!';
$checksess = $nv_Request->get_title('checksess', 'get', '');
if ($checksess == md5($global_config['sitekey'] . session_id()) and file_exists(NV_ROOTDIR . '/install/update_data.php')) {
$contents = '';
$list_file_docs = nv_scandir(NV_ROOTDIR . '/install', '/^update_docs_([a-z]{2})\.html$/');
// Xoa cac file docs
foreach ($list_file_docs as $docsfile) {
$check_del = nv_deletefile(NV_ROOTDIR . '/install/' . $docsfile);
if ($check_del[0] == 0) {
$contents .= $check_del[1] . ' ' . $lang_module['update_manual_delete'];
}
}
// Xoa file du lieu nang cap
$check_delete_file = nv_deletefile(NV_ROOTDIR . '/install/update_data.php');
if ($check_delete_file[0] == 0) {
$contents .= $check_delete_file[1] . ' ' . $lang_module['update_manual_delete'];
}
// Xoa thu muc file thay doi
if (file_exists(NV_ROOTDIR . '/install/update')) {
$check_delete_dir = nv_deletefile(NV_ROOTDIR . '/install/update', true);
if ($check_delete_dir[0] == 0) {
$contents .= $check_delete_dir[1] . ' ' . $lang_module['update_manual_delete'];
}
}
// Xoa file log
$list_file_logs = nv_scandir(NV_ROOTDIR . '/' . NV_DATADIR, '/^config_update_NVUD([A-Z0-9]+)\.php$/');
foreach ($list_file_logs as $logsfile) {
$check_del = nv_deletefile(NV_ROOTDIR . '/' . NV_DATADIR . '/' . $logsfile);
if ($check_del[0] == 0) {
$contents .= $check_del[1] . ' ' . $lang_module['update_manual_delete'];
}
}
clearstatcache();
}
if ($contents == '') {
$contents = 'OK';
}
include NV_ROOTDIR . '/includes/header.php';
echo $contents;
include NV_ROOTDIR . '/includes/footer.php';
| nukeplus/nuke | admin/webtools/deleteupdate.php | PHP | gpl-2.0 | 2,041 |
<?php
/**
* Project: Securimage: A PHP class for creating and managing form CAPTCHA images<br />
* File: securimage_show_example2.php<br />
*
* Copyright (c) 2011, Drew Phillips
* 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.
*
* 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 HOLDER 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.
*
* Any modifications to the library should be indicated clearly in the source code
* to inform users that the changes are not a part of the original software.<br /><br />
*
* If you found this script useful, please take a quick moment to rate it.<br />
* http://www.hotscripts.com/rate/49400.html Thanks.
*
* @link http://www.phpcaptcha.org Securimage PHP CAPTCHA
* @link http://www.phpcaptcha.org/latest.zip Download Latest Version
* @link http://www.phpcaptcha.org/Securimage_Docs/ Online Documentation
* @copyright 2011 Drew Phillips
* @author Drew Phillips <drew@drew-phillips.com>
* @version 3.0 (October 2011)
* @package Securimage
*
*/
require_once dirname(__FILE__) . '/securimage.php';
$img = new Securimage();
//Change some settings
$img->image_width = 280;
$img->image_height = 100;
$img->perturbation = 0.9; // high level of distortion
$img->code_length = rand(5,6); // random code length
$img->image_bg_color = new Securimage_Color("#ffffff");
$img->num_lines = 12;
$img->noise_level = 5;
$img->text_color = new Securimage_Color("#000000");
$img->noise_color = $img->text_color;
$img->line_color = new Securimage_Color("#cccccc");
$img->show(); | scorpioinfotech/mariasplace2 | wp-content/plugins/qa/securimage/securimage_show_example2.php | PHP | gpl-2.0 | 2,746 |
# encoding: utf-8
#
# Copyright 2017 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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.
#
# Cerebrum 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 Cerebrum; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
""" An abstract event that can be stored in the database. """
from __future__ import absolute_import
import datetime
import itertools
import mx.DateTime
import pytz
import cereconf
class _VerbSingleton(type):
""" A metaclass that makes each EventType verb a singleton. """
verbs = {}
def __call__(cls, verb, *args):
if verb not in cls.verbs:
cls.verbs[verb] = super(_VerbSingleton, cls).__call__(verb, *args)
return cls.verbs[verb]
def get_verb(cls, verb):
return cls.verbs.get(verb)
class EventType(_VerbSingleton('EventTypeSingleton', (object,), {})):
"""Holds an event type."""
__slots__ = ['verb', 'description', ]
def __init__(self, verb, description):
""" Initialize EventType.
:verb: Scim verb
:description: HR description text
"""
self.verb = verb
self.description = description
def __repr__(self):
return '<{0.__class__.__name__!s} {0.verb}>'.format(self)
def __eq__(self, other):
"""Equality."""
return isinstance(other, EventType) and other.verb == self.verb
def __hash__(self):
"""Hash."""
return hash(self.verb)
# Define event types:
ADD = EventType('add', 'Add an object to subject')
CREATE = EventType('create', 'Create a new subject')
ACTIVATE = EventType('activate', 'Subject has no longer quarantines in system')
MODIFY = EventType('modify', 'Attributes has changed')
DEACTIVATE = EventType('deactivate', 'Quarantine is activated')
DELETE = EventType('delete', 'Subject is deleted')
REMOVE = EventType('remove', 'Remove an object from subject')
PASSWORD = EventType('password', 'Subject has changed password')
JOIN = EventType('join', 'Join two objects')
class EntityRef(object):
""" Representation of a single entity.
The entity_id can be used internally to identify which object we reference
The entity_type and ident is used to generate a reference to the object
that other systems can use.
"""
__slots__ = ['ident', 'entity_type', 'entity_id', ]
def __init__(self, entity_id, entity_type, ident):
self.entity_id = int(entity_id)
self.entity_type = entity_type
self.ident = ident
def __repr__(self):
return ("<{0.__class__.__name__}"
" id={0.entity_id!r}"
" type={0.entity_type!r}"
" ident={0.ident!r}>").format(self)
def __eq__(self, other):
return (isinstance(other, EntityRef) and
self.entity_id == other.entity_id)
def to_dict(self):
return {
'ident': self.ident,
'entity_id': self.entity_id,
'entity_type': self.entity_type, }
class DateTimeDescriptor(object):
""" Datetime descriptor that handles timezones.
When setting the datetime, this method will try to localize it with the
default_timezone in the following ways:
- mx.DateTime.DateTimeType: Naive datetime, assume in default_timezone
- datetime.datetime: Assume in default_timezone if naive
- integer: Assume timestamp in UTC
The returned object will always be a localized datetime.datetime
"""
default_timezone = pytz.timezone(cereconf.TIMEZONE)
def __init__(self, slot):
""" Creates a new datetime descriptor.
:param str slot:
The attribute name where the actual value is stored.
"""
self.slot = slot
def __repr__(self):
return '{0.__class__.__name__}({0.slot!r})'.format(self)
def __get__(self, obj, cls=None):
if not obj:
return self
return getattr(obj, self.slot, None)
def __set__(self, obj, value):
if value is None:
self.__delete__(obj)
return
if isinstance(value, (int, long, )):
# UTC timestamp
value = pytz.utc.localize(
datetime.datetime.fromtimestamp(value))
elif isinstance(value, mx.DateTime.DateTimeType):
# Naive datetime in default_timezone
value = self.default_timezone.localize(value.pydatetime())
elif isinstance(value, datetime.datetime):
if value.tzinfo is None:
value = self.default_timezone.localize(value)
else:
raise TypeError('Invalid datetime {0} ({1})'.format(type(value),
repr(value)))
setattr(obj, self.slot, value)
def __delete__(self, obj):
if hasattr(obj, self.slot):
delattr(obj, self.slot)
class Event(object):
""" Event abstraction.
Contains all the neccessary data to serialize an event.
"""
DEFAULT_TIMEZONE = 'Europe/Oslo'
__slots__ = ['event_type', 'subject', 'objects', 'context', 'attributes',
'_timestamp', '_scheduled', ]
timestamp = DateTimeDescriptor('_timestamp')
scheduled = DateTimeDescriptor('_scheduled')
def __init__(self, event_type,
subject=None,
objects=None,
context=None,
attributes=None,
timestamp=None,
scheduled=None):
"""
:param EventType event: the type of event
:param EntityRef subject: reference to the affected entity
:param list objects: sequence of other affected objects (EntityRef)
:param list context: sequence of affected systems (str)
:param list attributes: sequence of affected attributes (str)
:param datetime timestamp: when the event originated
:param datetime schedule: when the event should be issued
"""
self.event_type = event_type
self.subject = subject
self.timestamp = timestamp
self.scheduled = scheduled
self.objects = set(objects or [])
self.context = set(context or [])
self.attributes = set(attributes or [])
def __repr__(self):
return ('<{0.__class__.__name__}'
' event={0.event_type!r}'
' subject={0.subject!r}>').format(self)
def mergeable(self, other):
"""Can this event be merged with other."""
if self.scheduled is not None:
return False
if self.subject != other.subject:
return False
if self.event_type == CREATE:
return other.event_type not in (DEACTIVATE, REMOVE)
if self.event_type == DELETE:
return other.event_type in (REMOVE, DEACTIVATE, ADD, ACTIVATE,
MODIFY, PASSWORD)
if (self.event_type == other.event_type and
self.event_type in (ADD, REMOVE, ACTIVATE, DEACTIVATE)):
return True
if self.context != other.context:
return False
return True
def merge(self, other):
"""Merge messages."""
def ret_self():
self.objects.update(other.objects)
return [self]
if not self.mergeable(other):
return [self, other]
if self.event_type == CREATE:
if other.event_type == DELETE:
return []
if other.event_type == ADD:
self.context.update(other.context)
return ret_self()
if other.event_type == ACTIVATE:
return ret_self() # TODO: if quarantine is an attr, delete it
if other.event_type == MODIFY:
self.attributes.update(other.attributes)
return ret_self()
if other.event_type == PASSWORD:
self.attributes.add('password')
return ret_self()
elif self.event_type == DELETE:
return ret_self()
elif other.event_type == DELETE:
return [other]
elif (ACTIVATE == self.event_type and
DEACTIVATE == other.event_type and
self.context == other.context):
return []
elif (ADD == self.event_type and
REMOVE == other.event_type and
self.context == other.context):
return []
elif self.event_type == other.event_type:
if self.event_type in (ADD, REMOVE, ACTIVATE, DEACTIVATE):
self.context.update(other.context)
return ret_self()
if self.context != other.context:
return [self, other]
self.attributes.update(other.attributes)
return ret_self()
return [self, other]
def merge_events(events):
"""Merge events with similarities.
As long as subject is the same:
* create + add/activate/modify/password = create with attributes merged
* create + deactivate/remove is untouched
* create + delete should be removed
* delete + remove/deactivate/add/activate/modify/password = delete
* x + x = x
* activate + deactivate = noop (careful with aud)
Sort into canonical order:
#. create
#. delete
#. add
#. activate
#. modify
#. password
#. deactivate
#. remove
"""
order = (CREATE, DELETE, ADD, ACTIVATE, MODIFY, PASSWORD, DEACTIVATE,
REMOVE, JOIN)
ps = [[] for x in order]
for pl in events:
pltype = pl.event_type
idx = order.index(pltype)
ps[idx].append(pl)
result = {}
for idx, tp, pl in zip(range(len(order)), order, ps):
for p in pl:
if p.subject not in result:
result[p.subject] = [p]
else:
result[p.subject].append(p)
def merge_list(finished, merged, current, rest):
while rest or merged:
if rest:
new = current.merge(rest[0])
if not new:
rest.pop(0)
merged.extend(rest)
rest = merged
if not rest:
return finished
merged = []
current = rest.pop(0)
elif len(new) == 1:
if new[0] is not current:
merged.extend(rest)
rest = merged
current = rest.pop(0)
merged = []
else:
rest.pop(0)
else:
merged.append(rest.pop(0))
else: # merged is not empty
finished.append(current)
rest = merged
merged = []
current = rest.pop(0)
finished.append(current)
return finished
for sub, lst in result.items():
result[sub] = merge_list([], [], lst[0], lst[1:])
return list(itertools.chain(*result.values()))
| unioslo/cerebrum | Cerebrum/modules/event_publisher/event.py | Python | gpl-2.0 | 11,579 |
# -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
| shahabsaf1/Python | plugins/reminders.py | Python | gpl-2.0 | 2,643 |
/*
* Flocking Debugging Unit Generators
* http://github.com/colinbdclark/flocking
*
* Copyright 2011-2014, Colin Clark
* Dual licensed under the MIT and GPL Version 2 licenses.
*/
/*global require*/
/*jshint white: false, newcap: true, regexp: true, browser: true,
forin: false, nomen: true, bitwise: false, maxerr: 100,
indent: 4, plusplus: false, curly: true, eqeqeq: true,
freeze: true, latedef: true, noarg: true, nonew: true, quotmark: double, undef: true,
unused: true, strict: true, asi: false, boss: false, evil: false, expr: false,
funcscope: false*/
var fluid = fluid || require("infusion"),
flock = fluid.registerNamespace("flock");
(function () {
"use strict";
// TODO: Unit tests.
flock.ugen.print = function (input, output, options) {
var that = flock.ugen(input, output, options);
that.gen = function (numSamps) {
var inputs = that.inputs,
out = that.output,
m = that.model,
label = m.label,
chan = inputs.channel,
// Basic multichannel support. This should be inproved
// by factoring the multichannel input code out of flock.ugen.out.
source = chan ? inputs.source.output[chan.output[0]] : inputs.source.output,
trig = inputs.trigger.output[0],
freq = inputs.freq.output[0],
i,
j,
val;
if (trig > 0.0 && m.prevTrig <= 0.0) {
fluid.log(fluid.logLevel.IMPORTANT, label + source);
}
if (m.freq !== freq) {
m.sampInterval = Math.round(m.sampleRate / freq);
m.freq = freq;
m.counter = m.sampInterval;
}
for (i = 0, j = 0 ; i < numSamps; i++, j += m.strides.source) {
if (m.counter >= m.sampInterval) {
fluid.log(fluid.logLevel.IMPORTANT, label + source[j]);
m.counter = 0;
}
m.counter++;
out[i] = val = source[i];
}
m.value = m.unscaledValue = val;
};
that.init = function () {
var o = that.options;
that.model.label = o.label ? o.label + ": " : "";
that.onInputChanged();
};
that.init();
return that;
};
flock.ugenDefaults("flock.ugen.print", {
rate: "audio",
inputs: {
source: null,
trigger: 0.0,
freq: 1.0
},
ugenOptions: {
model: {
unscaledValue: 0.0,
value: 0.0,
counter: 0
},
strideInputs: ["source"]
}
});
}());
| mcanthony/Flocking | src/ugens/debugging.js | JavaScript | gpl-2.0 | 2,806 |
/*
This file is part of the KDE project
* Copyright (C) 2009 Pierre Stirnweiss <pstirnweiss@googlemail.com>
* Copyright (C) 2011 Boudewijn Rempt <boud@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 "TextPasteCommand.h"
#include <KoTextEditor.h>
#include <KoTextDocument.h>
#include <KoTextPaste.h>
#include <KoChangeTracker.h>
#include <KoShapeController.h>
#include <klocale.h>
#include <kdebug.h>
#include <kaction.h>
#include <QTextDocument>
#include <QApplication>
#include <QMimeData>
#include "ChangeTrackedDeleteCommand.h"
#include "DeleteCommand.h"
#include "KoDocumentRdfBase.h"
#ifdef SHOULD_BUILD_RDF
#include <Soprano/Soprano>
#else
namespace Soprano
{
class Model
{
};
}
#endif
TextPasteCommand::TextPasteCommand(const QMimeData *mimeData,
QTextDocument *document,
KoShapeController *shapeController,
KoCanvasBase *canvas, KUndo2Command *parent, bool pasteAsText)
: KUndo2Command (parent),
m_mimeData(mimeData),
m_document(document),
m_rdf(0),
m_shapeController(shapeController),
m_canvas(canvas),
m_pasteAsText(pasteAsText),
m_first(true)
{
m_rdf = qobject_cast<KoDocumentRdfBase*>(shapeController->resourceManager()->resource(KoText::DocumentRdf).value<QObject*>());
if (m_pasteAsText)
setText(i18nc("(qtundo-format)", "Paste As Text"));
else
setText(i18nc("(qtundo-format)", "Paste"));
}
void TextPasteCommand::undo()
{
KUndo2Command::undo();
}
void TextPasteCommand::redo()
{
if (m_document.isNull()) return;
KoTextDocument textDocument(m_document);
KoTextEditor *editor = textDocument.textEditor();
if (!m_first) {
KUndo2Command::redo();
} else {
editor->beginEditBlock(); //this is needed so Qt does not merge successive paste actions together
m_first = false;
if (editor->hasSelection()) { //TODO
editor->addCommand(new DeleteCommand(DeleteCommand::NextChar, m_document.data(), m_shapeController, this));
}
// check for mime type
if (m_mimeData->hasFormat(KoOdf::mimeType(KoOdf::Text))
|| m_mimeData->hasFormat(KoOdf::mimeType(KoOdf::OpenOfficeClipboard)) ) {
KoOdf::DocumentType odfType = KoOdf::Text;
if (!m_mimeData->hasFormat(KoOdf::mimeType(odfType))) {
odfType = KoOdf::OpenOfficeClipboard;
}
if (m_pasteAsText) {
editor->insertText(m_mimeData->text());
} else {
QSharedPointer<Soprano::Model> rdfModel;
#ifdef SHOULD_BUILD_RDF
if(!m_rdf) {
rdfModel = QSharedPointer<Soprano::Model>(Soprano::createModel());
} else {
rdfModel = m_rdf->model();
}
#endif
KoTextPaste paste(editor, m_shapeController, rdfModel, m_canvas, this);
paste.paste(odfType, m_mimeData);
#ifdef SHOULD_BUILD_RDF
if (m_rdf) {
m_rdf->updateInlineRdfStatements(editor->document());
}
#endif
}
} else if (!m_pasteAsText && m_mimeData->hasHtml()) {
editor->insertHtml(m_mimeData->html());
} else if (m_pasteAsText || m_mimeData->hasText()) {
editor->insertText(m_mimeData->text());
}
editor->endEditBlock(); //see above beginEditBlock
}
}
| yxl/emscripten-calligra-mobile | libs/kotext/commands/TextPasteCommand.cpp | C++ | gpl-2.0 | 4,258 |
// External imports
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import javax.imageio.ImageIO;
import javax.swing.*;
// Local imports
import org.j3d.renderer.aviatrix3d.texture.TextureCreateUtils;
/**
* Example application that demonstrates how to use the loader interface
* to load a file into the scene graph.
* <p>
*
* @author Justin Couch
* @version $Revision: 1.1 $
*/
public class NormalMapDemo extends JFrame
implements ActionListener
{
private JFileChooser openDialog;
/** Renderer for the basic image */
private ImageIcon srcIcon;
private JLabel srcLabel;
/** Renderer for the normal map version */
private ImageIcon mapIcon;
private JLabel mapLabel;
/** Utility for munging textures to power of 2 size */
private TextureCreateUtils textureUtils;
public NormalMapDemo()
{
super("Normal map conversion demo");
setSize(1280, 1024);
setLocation(0, 0);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textureUtils = new TextureCreateUtils();
JPanel p1 = new JPanel(new BorderLayout());
srcIcon = new ImageIcon();
srcLabel = new JLabel();
srcLabel.setVerticalTextPosition(SwingConstants.BOTTOM);
srcLabel.setText("Source Image");
mapIcon = new ImageIcon();
mapLabel = new JLabel();
mapLabel.setVerticalTextPosition(SwingConstants.BOTTOM);
mapLabel.setText("NormalMap Image");
JButton b = new JButton("Open A file");
b.addActionListener(this);
p1.add(b, BorderLayout.SOUTH);
p1.add(srcLabel, BorderLayout.WEST);
p1.add(mapLabel, BorderLayout.EAST);
getContentPane().add(p1);
}
//---------------------------------------------------------------
// Methods defined by WindowListener
//---------------------------------------------------------------
/**
* Process the action event from the open button
*/
public void actionPerformed(ActionEvent evt)
{
if(openDialog == null)
openDialog = new JFileChooser();
int ret_val = openDialog.showOpenDialog(this);
if(ret_val != JFileChooser.APPROVE_OPTION)
return;
File file = openDialog.getSelectedFile();
try
{
System.out.println("Loading external file: " + file);
FileInputStream is = new FileInputStream(file);
BufferedInputStream stream = new BufferedInputStream(is);
BufferedImage img = ImageIO.read(stream);
if(img == null)
{
System.out.println("Image load barfed");
return;
}
srcIcon.setImage(img);
srcLabel.setIcon(srcIcon);
BufferedImage map_img = textureUtils.createNormalMap(img, null);
mapIcon.setImage(map_img);
mapLabel.setIcon(mapIcon);
}
catch(IOException ioe)
{
System.out.println("crashed " + ioe.getMessage());
ioe.printStackTrace();
}
}
//---------------------------------------------------------------
// Local methods
//---------------------------------------------------------------
public static void main(String[] args)
{
NormalMapDemo demo = new NormalMapDemo();
demo.setVisible(true);
}
}
| Norkart/NK-VirtualGlobe | aviatrix3d/examples/texture/NormalMapDemo.java | Java | gpl-2.0 | 3,599 |
<?php
/**
* Created by PhpStorm.
* User: Anh Tuan
* Date: 4/22/14
* Time: 12:26 AM
*/
//////////////////////////////////////////////////////////////////
// Dropcap shortcode
//////////////////////////////////////////////////////////////////
add_shortcode( 'dropcap', 'shortcode_dropcap' );
function shortcode_dropcap( $atts, $content = null ) {
extract( shortcode_atts( array(
'text' => '',
'el_class' => ''
), $atts ) );
return '<span class="dropcap '.$el_class.'">' . $content . '</span>';
} | yogaValdlabs/shopingchart | wp-content/themes/aloxo/inc/shortcodes/dropcap/dropcap.php | PHP | gpl-2.0 | 515 |
/*
* $RCSfile: OrCRIF.java,v $
*
* Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
*
* Use is subject to license terms.
*
* $Revision: 1.1 $
* $Date: 2005/02/11 04:56:38 $
* $State: Exp $
*/
package com.sun.media.jai.opimage;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.RenderContext;
import java.awt.image.renderable.ParameterBlock;
import java.awt.image.renderable.RenderableImage;
import javax.media.jai.CRIFImpl;
import javax.media.jai.ImageLayout;
import java.util.Map;
/**
* A <code>CRIF</code> supporting the "Or" operation in the
* rendered and renderable image layers.
*
* @since EA2
* @see javax.media.jai.operator.OrDescriptor
* @see OrOpImage
*
*/
public class OrCRIF extends CRIFImpl {
/** Constructor. */
public OrCRIF() {
super("or");
}
/**
* Creates a new instance of <code>OrOpImage</code> in the
* rendered layer. This method satisifies the implementation of RIF.
*
* @param paramBlock The two source images to be "Ored" together.
* @param renderHints Optionally contains destination image layout.
*/
public RenderedImage create(ParameterBlock paramBlock,
RenderingHints renderHints) {
// Get ImageLayout from renderHints if any.
ImageLayout layout = RIFUtil.getImageLayoutHint(renderHints);
return new OrOpImage(paramBlock.getRenderedSource(0),
paramBlock.getRenderedSource(1),
renderHints,
layout);
}
}
| RoProducts/rastertheque | JAILibrary/src/com/sun/media/jai/opimage/OrCRIF.java | Java | gpl-2.0 | 1,740 |
<?php
/**
Admin Page Framework v3.5.6 by Michael Uno
Generated by PHP Class Files Script Generator <https://github.com/michaeluno/PHP-Class-Files-Script-Generator>
<http://en.michaeluno.jp/admin-page-framework>
Copyright (c) 2013-2015, Michael Uno; Licensed under MIT <http://opensource.org/licenses/MIT>
*/
abstract class SeamlessDonationsAdminPageFramework_TaxonomyField_View extends SeamlessDonationsAdminPageFramework_TaxonomyField_Model {
public function _replyToPrintFieldsWOTableRows($oTerm) {
echo $this->_getFieldsOutput(isset($oTerm->term_id) ? $oTerm->term_id : null, false);
}
public function _replyToPrintFieldsWithTableRows($oTerm) {
echo $this->_getFieldsOutput(isset($oTerm->term_id) ? $oTerm->term_id : null, true);
}
private function _getFieldsOutput($iTermID, $bRenderTableRow) {
$_aOutput = array();
$_aOutput[] = wp_nonce_field($this->oProp->sClassHash, $this->oProp->sClassHash, true, false);
$this->_setOptionArray($iTermID, $this->oProp->sOptionKey);
$this->oForm->format();
$_oFieldsTable = new SeamlessDonationsAdminPageFramework_FormTable($this->oProp->aFieldTypeDefinitions, $this->_getFieldErrors(), $this->oMsg);
$_aOutput[] = $bRenderTableRow ? $_oFieldsTable->getFieldRows($this->oForm->aFields['_default'], array($this, '_replyToGetFieldOutput')) : $_oFieldsTable->getFields($this->oForm->aFields['_default'], array($this, '_replyToGetFieldOutput'));
$_sOutput = $this->oUtil->addAndApplyFilters($this, 'content_' . $this->oProp->sClassName, implode(PHP_EOL, $_aOutput));
$this->oUtil->addAndDoActions($this, 'do_' . $this->oProp->sClassName, $this);
return $_sOutput;
}
public function _replyToPrintColumnCell($vValue, $sColumnSlug, $sTermID) {
$_sCellHTML = '';
if (isset($_GET['taxonomy']) && $_GET['taxonomy']) {
$_sCellHTML = $this->oUtil->addAndApplyFilter($this, "cell_{$_GET['taxonomy']}", $vValue, $sColumnSlug, $sTermID);
}
$_sCellHTML = $this->oUtil->addAndApplyFilter($this, "cell_{$this->oProp->sClassName}", $_sCellHTML, $sColumnSlug, $sTermID);
$_sCellHTML = $this->oUtil->addAndApplyFilter($this, "cell_{$this->oProp->sClassName}_{$sColumnSlug}", $_sCellHTML, $sTermID);
echo $_sCellHTML;
}
} | johnmanlove/NoOn1 | wp-content/plugins/seamless-donations/library/apf/factory/AdminPageFramework_TaxonomyField/AdminPageFramework_TaxonomyField_View.php | PHP | gpl-2.0 | 2,360 |
<?php
/**
* Created by PhpStorm.
* User: udit
* Date: 12/9/14
* Time: 10:43 AM
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'WM_Revision' ) ) {
/**
* Class WM_Revision
*
* Handles all the functionality to track custom fields
*
* @since 0.4
*/
class WM_Revision {
/**
* @since 0.4
*/
function __construct() {
/**
* This hook filters the number of revisions to keep for a specific post.
*/
add_filter( 'wp_revisions_to_keep', array( $this, 'filter_revisions_to_keep' ), 999, 2 );
/**
* This hooks gets fired once a revision is stored in WP_Post table in DB.
*
* This gives us $revision_id. So we can make use of that and store our stuff into post meta for that particular revision.
* E.g., Taxonomy diff, meta diff., featured image diff, etc.
*
*/
add_action( '_wp_put_post_revision', array( $this, 'post_revision_process' ), 10, 1 );
/**
* Filter whether the post has changed since the last revision.
*
* By default a revision is saved only if one of the revisioned fields has changed.
* This filter can override that so a revision is saved even if nothing has changed.
*
* We will take care of our own fields and pass on the flag.
*/
add_filter( 'wp_save_post_revision_post_has_changed', array( $this, 'check_for_changes' ), 10, 3 );
/**
* We may have to call this dynamically within a for loop. depending upon how many custom fields that we are supporting.
*/
foreach ( array_keys( $this->get_custom_revision_fields() ) as $field ) {
add_filter( '_wp_post_revision_field_'.$field, array( $this, 'revision_field_content' ), 10, 4 );
}
/**
* This adds custom diff ui for custom revision fields
*/
add_filter( 'wp_get_revision_ui_diff', array( $this, 'revision_ui_diff' ), 10, 3 );
}
/**
* @param $num
* @param $post
*
* @return int
* @since 0.1
*/
function filter_revisions_to_keep( $num, $post ) {
// Check individual Post Limit
$revision_limit = get_post_meta( $post->ID, WM_Admin::$wm_revision_limit_meta_key, true );
if ( '' !== $revision_limit ) {
if ( ! is_numeric( $revision_limit ) ) {
$num = - 1;
} else {
$num = intval( $revision_limit );
}
} else {
$post_type = get_post_type( $post );
$revision_limit = get_option( WM_Settings::$revision_limit_key . $post_type, false );
if ( '' === $revision_limit || ! is_numeric( $revision_limit ) ) {
$num = - 1;
} else {
$num = intval( $revision_limit );
}
}
return $num;
}
/**
* @return array $revision_fields
* @since 0.5
*/
function get_custom_revision_fields() {
$revision_fields = array(
'post_author' => array(
'label' => __( 'Post Author', WM_TEXT_DOMAIN ),
'meta_key' => '_wm_post_author',
'meta_value' => function( $post ) {
$author = new WP_User( $post->post_author );
return $author->display_name . ' (' . $post->post_author . ')';
},
),
'post_status' => array(
'label' => __( 'Post Status', WM_TEXT_DOMAIN ),
'meta_key' => '_wm_post_status',
'meta_value' => function( $post ) {
$post_status = get_post_status_object( $post->post_status );
return $post_status->label;
},
),
'post_date' => array(
'label' => __( 'Post Date', WM_TEXT_DOMAIN ),
'meta_key' => '_wm_post_date',
'meta_value' => function( $post ) {
$datef = 'M j, Y @ H:i';
return date_i18n( $datef, strtotime( $post->post_date ) );
},
),
);
return $revision_fields;
}
/**
* @param $revision_id
* @since 0.4
*/
function post_revision_process( $revision_id ) {
$revision = get_post( $revision_id );
$post = get_post( $revision->post_parent );
foreach ( $this->get_custom_revision_fields() as $field => $fieldmeta ) {
update_post_meta( $post->ID, $fieldmeta['meta_key'] . '_' . $revision_id , call_user_func( $fieldmeta['meta_value'], $post ) );
}
}
/**
* @param $post_has_changed
* @param $last_revision
* @param $post
*
* @return mixed
* @since 0.4
*/
function check_for_changes( $post_has_changed, $last_revision, $post ) {
foreach ( $this->get_custom_revision_fields() as $field => $fieldmeta ) {
$post_value = normalize_whitespace( call_user_func( $fieldmeta['meta_value'], $post ) );
$revision_value = normalize_whitespace( apply_filters( "_wp_post_revision_field_$field", $last_revision->$field, $field, $last_revision, 'from' ) );
if ( $post_value != $revision_value ) {
$post_has_changed = true;
break;
}
}
return $post_has_changed;
}
/**
* Contextually filter a post revision field.
*
* The dynamic portion of the hook name, $field, corresponds to each of the post
* fields of the revision object being iterated over in a foreach statement.
*
* @param string $value The current revision field to compare to or from.
* @param string $field The current revision field.
* @param WP_Post $post The revision post object to compare to or from.
* @param string $context The context of whether the current revision is the old or the new one. Values are 'to' or 'from'.
*
* @return string $value
* @since 0.4
*/
function revision_field_content( $value, $field, $post, $context ) {
$revision_fields = $this->get_custom_revision_fields();
if ( array_key_exists( $field, $revision_fields ) ) {
$value = get_post_meta( $post->post_parent, $revision_fields[ $field ]['meta_key'] . '_' . $post->ID, true );
}
return $value;
}
/**
* Filter the fields displayed in the post revision diff UI.
*
* @since 4.1.0
*
* @param array $return Revision UI fields. Each item is an array of id, name and diff.
* @param WP_Post $compare_from The revision post to compare from.
* @param WP_Post $compare_to The revision post to compare to.
*
* @return array $return
* @since 0.5
*/
function revision_ui_diff( $return, $compare_from, $compare_to ) {
foreach ( $this->get_custom_revision_fields() as $field => $fieldmeta ) {
/**
* Contextually filter a post revision field.
*
* The dynamic portion of the hook name, `$field`, corresponds to each of the post
* fields of the revision object being iterated over in a foreach statement.
*
* @since 3.6.0
*
* @param string $compare_from->$field The current revision field to compare to or from.
* @param string $field The current revision field.
* @param WP_Post $compare_from The revision post object to compare to or from.
* @param string null The context of whether the current revision is the old
* or the new one. Values are 'to' or 'from'.
*/
$content_from = $compare_from ? apply_filters( "_wp_post_revision_field_$field", $compare_from->$field, $field, $compare_from, 'from' ) : '';
/** This filter is documented in wp-admin/includes/revision.php */
$content_to = apply_filters( "_wp_post_revision_field_$field", $compare_to->$field, $field, $compare_to, 'to' );
$args = array(
'show_split_view' => true,
);
/**
* Filter revisions text diff options.
*
* Filter the options passed to {@see wp_text_diff()} when viewing a post revision.
*
* @since 4.1.0
*
* @param array $args {
* Associative array of options to pass to {@see wp_text_diff()}.
*
* @type bool $show_split_view True for split view (two columns), false for
* un-split view (single column). Default true.
* }
* @param string $field The current revision field.
* @param WP_Post $compare_from The revision post to compare from.
* @param WP_Post $compare_to The revision post to compare to.
*/
$args = apply_filters( 'revision_text_diff_options', $args, $field, $compare_from, $compare_to );
$diff = wp_text_diff( $content_from, $content_to, $args );
if ( $diff ) {
$return[] = array(
'id' => $field,
'name' => $fieldmeta['label'],
'diff' => $diff,
);
}
}
return $return;
}
}
}
| desaiuditd/watchman | revision/class-wm-revision.php | PHP | gpl-2.0 | 8,344 |
<?php
/**
* The main template file.
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package morrisseys_catering
*/
get_header(); ?>
<?php if ( have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
/* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'content', get_post_format() );
?>
<?php endwhile; ?>
<?php morrisseys_catering_content_nav( 'nav-below' ); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
<div id="food-content">
<h1>image</h1>
<div id="inner-box">
<p>Fresh. Local. Family Owned.</p>
<a class="button" href="#">
<h1>Icon menu </h1>
<p>Browse Menus</p>
</a>
</div>
</div>
<div class="wrapper">
<blockquote id="feedback">
<p> Thank you for providing us each delicious food and service for the St. Mary's
50th Anniversary Celebration! The food was excellent and you are all the best to work with! We are grateful for you, thank you.<br>
<span>-Siobhan </span>
</p>
<div class="splitter">
</div>
<br>
<br>
<p>Many thanks for your kindness during such a sad time for us - you were so helpful. Everyone enjoyed your wonderful food at the church reception. <br> <span>-Mrs. Showalter</span></p>
</blockquote>
<div id="contact-info">
<div id="contact-box">
<img src="wp-content/themes/morrisseys_catering/images/icon_phone.png" alt="phone.icon"> <p> (804) 592-2188</p>
</div>
<br>
<br>
<div class="address-info">
<p> 8901 Three Chopt Road, Suite A, Richmond, Va 23229 </p>
<p> Located in the Westbury Pharmacy Center</p>
</div> <!--address-info -->
</div> <!-- contact-info" -->
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
| nickdtaylor1993/morrisseys_catering | wp-content/themes/morrisseys_catering/index.php | PHP | gpl-2.0 | 2,289 |
<?php
/* --------------------------------------------------------------
$Id: customer_memo.php 10395 2016-11-07 13:18:38Z GTB $
modified eCommerce Shopsoftware
http://www.modified-shop.org
Copyright (c) 2009 - 2013 [www.modified-shop.org]
--------------------------------------------------------------
Released under the GNU General Public License
--------------------------------------------------------------
Third Party contribution:
(c) 2003 XT-Commerce
(c) 2003 nextcommerce (customer_memo.php,v 1.6 2003/08/18); www.nextcommerce.org
--------------------------------------------------------------*/
defined( '_VALID_XTC' ) or die( 'Direct Access to this location is not allowed.' );
?>
<td class="dataTableConfig col-left" style="vertical-align:top;"><?php echo ENTRY_MEMO; ?></td>
<td class="dataTableConfig col-single-right">
<?php
$memo_query = xtc_db_query("SELECT *
FROM " . TABLE_CUSTOMERS_MEMO . "
WHERE customers_id = '" . (int)$_GET['cID'] . "'
ORDER BY memo_date DESC");
if (xtc_db_num_rows($memo_query) > 0) {
while ($memo_values = xtc_db_fetch_array($memo_query)) {
$poster_query = xtc_db_query("SELECT customers_firstname, customers_lastname FROM " . TABLE_CUSTOMERS . " WHERE customers_id = '" . $memo_values['poster_id'] . "'");
$poster_values = xtc_db_fetch_array($poster_query);
?>
<div style="margin:2px; padding:2px; border: 1px solid; border-color: #cccccc;">
<table style="width:100%">
<tr>
<td class="main" style="width:120px; border:none; padding:2px;"><strong><?php echo TEXT_DATE; ?></strong>:</td>
<td class="main" style="border:none; padding:2px;"><?php echo xtc_date_short($memo_values['memo_date']); ?></td>
</tr>
<tr>
<td class="main" style="border:none; padding:2px;"><strong><?php echo TEXT_TITLE; ?></strong>:</td>
<td class="main" style="border:none; padding:2px;"><?php echo $memo_values['memo_title']; ?></td>
</tr>
<tr>
<td class="main" style="border:none; padding:2px;"><strong><?php echo TEXT_POSTER; ?></strong>:</td>
<td class="main" style="border:none; padding:2px;"><?php echo $poster_values['customers_lastname'] . ' ' . $poster_values['customers_firstname']; ?></td>
</tr>
<tr>
<td class="main" style="border:none; padding:2px; vertical-align:top;"><strong><?php echo ENTRY_MEMO; ?></strong>:</td>
<td class="main" style="border:none; padding:2px;"><?php echo $memo_values['memo_text']; ?></td>
</tr>
<tr>
<td class="txta-r" colspan="2" style="border:none; padding:2px;"><a style="text-decoration:none;" href="<?php echo xtc_href_link(basename($PHP_SELF), 'cID=' . (int)$_GET['cID'] . '&action=edit&special=remove_memo&mID=' . $memo_values['memo_id']); ?>" class="button" onclick="return confirmLink('<?php echo DELETE_ENTRY; ?>', '', this)"><?php echo BUTTON_DELETE; ?></a></td>
</tr>
</table>
</div>
<?php
}
echo '<br/>';
}
?>
<div style="margin:2px; padding:2px; border: 1px solid; border-color: #cccccc;">
<table style="width:100%">
<tr>
<td class="main" style="width:80px; border:none; padding:2px;"><strong><?php echo TEXT_TITLE; ?></strong>:</td>
<td class="main" style="border:none; padding:2px;"><?php echo xtc_draw_input_field('memo_title', ((isset($cInfo->memo_title)) ? $cInfo->memo_title : ''), 'style="width:100%; max-width:676px;"'); ?></td>
</tr>
<tr>
<td class="main" style="border:none; padding:2px; vertical-align:top;"><strong><?php echo ENTRY_MEMO; ?></strong>:</td>
<td class="main" style="border:none; padding:2px;"><?php echo xtc_draw_textarea_field('memo_text', 'soft', '80', '8', ((isset($cInfo->memo_text)) ? $cInfo->memo_text : ''), 'style="width:99%; max-width:676px;"'); ?></td>
</tr>
<tr>
<td class="txta-r" colspan="2" style="border:none; padding:2px;"><input type="submit" class="button" value="<?php echo BUTTON_INSERT; ?>"></td>
</tr>
</table>
</div>
</td> | dsiekiera/modified-bs4 | admin/includes/modules/customer_memo.php | PHP | gpl-2.0 | 4,322 |
/*
neutrino bouquet editor - channel selection
Copyright (C) 2001 Steffen Hehn 'McClean'
Copyright (C) 2017 Sven Hoefer
License: GPL
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/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <unistd.h>
#include <global.h>
#include <neutrino.h>
#include <driver/fontrenderer.h>
#include <driver/screen_max.h>
#include <gui/widget/icons.h>
#include <zapit/getservices.h>
#include <zapit/zapit.h>
#include "bouqueteditor_chanselect.h"
extern CBouquetManager *g_bouquetManager;
CBEChannelSelectWidget::CBEChannelSelectWidget(const std::string & Caption, CZapitBouquet* Bouquet, CZapitClient::channelsMode Mode)
{
caption = Caption;
bouquet = Bouquet;
mode = Mode;
selected = 0;
liststart = 0;
channellist_sort_mode = SORT_ALPHA;
bouquetChannels = NULL;
int iw, ih;
action_icon_width = 0;
frameBuffer->getIconSize(NEUTRINO_ICON_BUTTON_DUMMY_SMALL, &action_icon_width, &ih);
status_icon_width = 0;
frameBuffer->getIconSize(NEUTRINO_ICON_MARKER_SCRAMBLED, &iw, &ih);
status_icon_width = std::max(status_icon_width, iw);
frameBuffer->getIconSize(NEUTRINO_ICON_MARKER_STREAMING, &iw, &ih);
status_icon_width = std::max(status_icon_width, iw);
}
CBEChannelSelectWidget::~CBEChannelSelectWidget()
{
}
void CBEChannelSelectWidget::paintItem(int pos)
{
int ypos = y + header_height + pos*item_height;
unsigned int current = liststart + pos;
bool i_selected = current == selected;
int i_radius = RADIUS_NONE;
fb_pixel_t color;
fb_pixel_t bgcolor;
getItemColors(color, bgcolor, i_selected);
if (i_selected)
{
if (current < Channels.size() || Channels.empty())
paintDetails(pos, current);
i_radius = RADIUS_LARGE;
}
else
{
if (current < Channels.size() && (Channels[current]->flags & CZapitChannel::NOT_PRESENT))
color = COL_MENUCONTENTINACTIVE_TEXT;
}
if (i_radius)
frameBuffer->paintBoxRel(x, ypos, width - SCROLLBAR_WIDTH, item_height, COL_MENUCONTENT_PLUS_0);
frameBuffer->paintBoxRel(x, ypos, width - SCROLLBAR_WIDTH, item_height, bgcolor, i_radius);
if (current < Channels.size())
{
if (isChannelInBouquet(current))
frameBuffer->paintIcon(NEUTRINO_ICON_BUTTON_GREEN, x + OFFSET_INNER_MID, ypos, item_height);
else
frameBuffer->paintIcon(NEUTRINO_ICON_BUTTON_DUMMY_SMALL, x + OFFSET_INNER_MID, ypos, item_height);
int text_offset = 2*OFFSET_INNER_MID + action_icon_width;
item_font->RenderString(x + text_offset, ypos + item_height, width - text_offset - SCROLLBAR_WIDTH - 2*OFFSET_INNER_MID - status_icon_width, Channels[current]->getName(), color);
if (Channels[current]->scrambled)
frameBuffer->paintIcon(NEUTRINO_ICON_MARKER_SCRAMBLED, x + width - SCROLLBAR_WIDTH - OFFSET_INNER_MID - status_icon_width, ypos, item_height);
else if (!Channels[current]->getUrl().empty())
frameBuffer->paintIcon(NEUTRINO_ICON_MARKER_STREAMING, x + width - SCROLLBAR_WIDTH - OFFSET_INNER_MID - status_icon_width, ypos, item_height);
}
frameBuffer->blit();
}
void CBEChannelSelectWidget::paintItems()
{
liststart = (selected/items_count)*items_count;
for(unsigned int count = 0; count < items_count; count++)
paintItem(count);
int total_pages;
int current_page;
getScrollBarData(&total_pages, ¤t_page, Channels.size(), items_count, selected);
paintScrollBar(x + width - SCROLLBAR_WIDTH, y + header_height, SCROLLBAR_WIDTH, body_height, total_pages, current_page);
}
void CBEChannelSelectWidget::paintHead()
{
CBEGlobals::paintHead(caption + (mode == CZapitClient::MODE_TV ? " - TV" : " - Radio"),
mode == CZapitClient::MODE_TV ? NEUTRINO_ICON_VIDEO : NEUTRINO_ICON_AUDIO);
}
struct button_label CBEChannelSelectButtons[] =
{
{ NEUTRINO_ICON_BUTTON_RED, LOCALE_CHANNELLIST_FOOT_SORT_ALPHA },
{ NEUTRINO_ICON_BUTTON_OKAY, LOCALE_BOUQUETEDITOR_SWITCH },
{ NEUTRINO_ICON_BUTTON_HOME, LOCALE_BOUQUETEDITOR_RETURN }
};
void CBEChannelSelectWidget::paintFoot()
{
switch (channellist_sort_mode)
{
case SORT_FREQ:
{
CBEChannelSelectButtons[0].locale = LOCALE_CHANNELLIST_FOOT_SORT_FREQ;
break;
}
case SORT_SAT:
{
CBEChannelSelectButtons[0].locale = LOCALE_CHANNELLIST_FOOT_SORT_SAT;
break;
}
case SORT_CH_NUMBER:
{
CBEChannelSelectButtons[0].locale = LOCALE_CHANNELLIST_FOOT_SORT_CHNUM;
break;
}
case SORT_ALPHA:
default:
{
CBEChannelSelectButtons[0].locale = LOCALE_CHANNELLIST_FOOT_SORT_ALPHA;
break;
}
}
const short numbuttons = sizeof(CBEChannelSelectButtons)/sizeof(CBEChannelSelectButtons[0]);
CBEGlobals::paintFoot(numbuttons, CBEChannelSelectButtons);
}
std::string CBEChannelSelectWidget::getInfoText(int index)
{
std::string res = "";
if (Channels.empty())
return res;
std::string satname = CServiceManager::getInstance()->GetSatelliteName(Channels[index]->getSatellitePosition());
if (IS_WEBCHAN(Channels[index]->getChannelID()))
satname = "Web-Channel"; // TODO split into WebTV/WebRadio
transponder t;
CServiceManager::getInstance()->GetTransponder(Channels[index]->getTransponderId(), t);
std::string desc = t.description();
if (Channels[index]->pname)
{
if (desc.empty())
desc = std::string(Channels[index]->pname);
else
desc += " (" + std::string(Channels[index]->pname) + ")";
}
if (!Channels[index]->getDesc().empty())
desc += "\n" + Channels[index]->getDesc();
res = satname + " - " + desc;
return res;
}
void CBEChannelSelectWidget::updateSelection(unsigned int newpos)
{
if (newpos == selected || newpos == (unsigned int)-1)
return;
unsigned int prev_selected = selected;
selected = newpos;
unsigned int oldliststart = liststart;
liststart = (selected/items_count)*items_count;
if (oldliststart != liststart)
{
paintItems();
}
else
{
paintItem(prev_selected - liststart);
paintItem(selected - liststart);
}
}
int CBEChannelSelectWidget::exec(CMenuTarget* parent, const std::string & /*actionKey*/)
{
neutrino_msg_t msg;
neutrino_msg_data_t data;
int res = menu_return::RETURN_REPAINT;
selected = 0;
if (parent)
parent->hide();
bouquetChannels = mode == CZapitClient::MODE_TV ? &(bouquet->tvChannels) : &(bouquet->radioChannels);
Channels.clear();
if (mode == CZapitClient::MODE_RADIO)
CServiceManager::getInstance()->GetAllRadioChannels(Channels);
else
CServiceManager::getInstance()->GetAllTvChannels(Channels);
sort(Channels.begin(), Channels.end(), CmpChannelByChName());
paintHead();
paintBody();
paintFoot();
paintItems();
uint64_t timeoutEnd = CRCInput::calcTimeoutEnd(*timeout_ptr);
channelChanged = false;
bool loop = true;
while (loop)
{
g_RCInput->getMsgAbsoluteTimeout(&msg, &data, &timeoutEnd);
if (msg <= CRCInput::RC_MaxRC)
timeoutEnd = CRCInput::calcTimeoutEnd(*timeout_ptr);
if ((msg == CRCInput::RC_timeout) || (msg == CRCInput::RC_home))
{
loop = false;
}
else if (msg == CRCInput::RC_up || msg == (neutrino_msg_t)g_settings.key_pageup ||
msg == CRCInput::RC_down || msg == (neutrino_msg_t)g_settings.key_pagedown)
{
int new_selected = UpDownKey(Channels, msg, items_count, selected);
updateSelection(new_selected);
}
else if (msg == (neutrino_msg_t) g_settings.key_list_start || msg == (neutrino_msg_t) g_settings.key_list_end)
{
if (!Channels.empty())
{
int new_selected = msg == (neutrino_msg_t) g_settings.key_list_start ? 0 : Channels.size() - 1;
updateSelection(new_selected);
}
}
else if (msg == CRCInput::RC_ok || msg == CRCInput::RC_green)
{
if (selected < Channels.size())
selectChannel();
}
else if (msg == CRCInput::RC_red)
{
if (selected < Channels.size())
sortChannels();
}
else if (CNeutrinoApp::getInstance()->listModeKey(msg))
{
// do nothing
}
else
{
CNeutrinoApp::getInstance()->handleMsg(msg, data);
}
}
hide();
return res;
}
void CBEChannelSelectWidget::sortChannels()
{
channellist_sort_mode++;
if (channellist_sort_mode >= SORT_END)
channellist_sort_mode = SORT_ALPHA;
switch (channellist_sort_mode)
{
case SORT_FREQ:
{
sort(Channels.begin(), Channels.end(), CmpChannelByFreq());
break;
}
case SORT_SAT:
{
sort(Channels.begin(), Channels.end(), CmpChannelBySat());
break;
}
case SORT_CH_NUMBER:
{
sort(Channels.begin(), Channels.end(), CmpChannelByChNum());
break;
}
case SORT_ALPHA:
default:
{
sort(Channels.begin(), Channels.end(), CmpChannelByChName());
break;
}
}
paintFoot();
paintItems();
}
void CBEChannelSelectWidget::selectChannel()
{
channelChanged = true;
if (isChannelInBouquet(selected))
bouquet->removeService(Channels[selected]);
else
bouquet->addService(Channels[selected]);
bouquetChannels = mode == CZapitClient::MODE_TV ? &(bouquet->tvChannels) : &(bouquet->radioChannels);
paintItem(selected - liststart);
g_RCInput->postMsg(CRCInput::RC_down, 0);
}
bool CBEChannelSelectWidget::isChannelInBouquet(int index)
{
for (unsigned int i=0; i< bouquetChannels->size(); i++)
{
if ((*bouquetChannels)[i]->getChannelID() == Channels[index]->getChannelID())
return true;
}
return false;
}
bool CBEChannelSelectWidget::hasChanged()
{
return channelChanged;
}
| TangoCash/neutrino-mp-cst-next | src/gui/bedit/bouqueteditor_chanselect.cpp | C++ | gpl-2.0 | 9,692 |
vti_encoding:SR|utf8-nl
vti_timelastmodified:TR|08 Nov 2012 23:29:31 -0000
vti_extenderversion:SR|5.0.2.6790
vti_lineageid:SR|{44761BDF-1053-4E8B-8B42-2966A30F18D2}
vti_cacheddtm:TX|08 Nov 2012 23:29:31 -0000
vti_filesize:IR|2149
vti_backlinkinfo:VX|
| JustinTBayer/chapter-manager | _vti_cnf/changelog.php | PHP | gpl-2.0 | 258 |
package org.janelia.alignment.match;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* List of {@link CanvasMatches} with associated tileIds mapped for fast lookup.
*
* @author Eric Trautman
*/
public class TileIdsWithMatches {
private final Set<String> tileIds;
private final List<CanvasMatches> canvasMatchesList;
public TileIdsWithMatches() {
this.canvasMatchesList = new ArrayList<>();
this.tileIds = new HashSet<>();
}
/**
*
* @param canvasMatchesList list of matches for section (could include tiles not in stack).
* @param stackTileIds set of tile ids in stack.
* To be kept, match pair must have both tiles in stack.
*/
public void addMatches(final List<CanvasMatches> canvasMatchesList,
final Set<String> stackTileIds) {
for (final CanvasMatches canvasMatches : canvasMatchesList) {
final String pId = canvasMatches.getpId();
final String qId = canvasMatches.getqId();
if (stackTileIds.contains(pId) && stackTileIds.contains(qId)) {
this.canvasMatchesList.add(canvasMatches);
this.tileIds.add(pId);
this.tileIds.add(qId);
}
}
}
public boolean contains(final String tileId) {
return tileIds.contains(tileId);
}
public List<CanvasMatches> getCanvasMatchesList() {
return canvasMatchesList;
}
}
| saalfeldlab/render | render-app/src/main/java/org/janelia/alignment/match/TileIdsWithMatches.java | Java | gpl-2.0 | 1,543 |
/* Pin Tool for
* calculation of the Stack Reuse Distance Histogram
*
* (C) 2015, Josef Weidendorfer / LRR-TUM
* GPLv2+ (see COPYING)
*/
#include "pin.H"
#include <stdio.h>
#include <cassert>
#include <cstring>
#include <cmath>
#include <unistd.h>
#include "dist.cpp"
// Consistency checks?
#define DEBUG 0
// 2: Huge amount of debug output, 1: checks, 0: silent
#define VERBOSE 0
// uses INS_IsStackRead/Write: misleading with -fomit-frame-pointer
#define IGNORE_STACK 1
// collect addresses in chunk buffer before? (always worse)
#define MERGE_CHUNK 0
#define CHUNKSIZE 4096
// must be a power-of-two
#define MEMBLOCKLEN 64
unsigned long stackAccesses;
unsigned long ignoredReads, ignoredWrites;
/* ===================================================================== */
/* Command line options */
/* ===================================================================== */
KNOB<int> KnobMinDist(KNOB_MODE_WRITEONCE, "pintool",
"m", "4096", "minimum bucket distance");
KNOB<int> KnobDoubleSteps(KNOB_MODE_WRITEONCE, "pintool",
"s", "1", "number of buckets for doubling distance");
KNOB<bool> KnobPIDPrefix(KNOB_MODE_WRITEONCE, "pintool",
"p", "0", "prepend output by --PID--");
/* ===================================================================== */
/* Handle Memory block access (aligned at multiple of MEMBLOCKLEN) */
/* ===================================================================== */
#if MERGE_CHUNK
void accessMerging(Addr a)
{
static Addr mergeBuffer[CHUNKSIZE];
static int ptr = 0;
if (ptr < CHUNKSIZE) {
mergeBuffer[ptr++] = a;
return;
}
sort(mergeBuffer,mergeBuffer+CHUNKSIZE);
for(ptr=0; ptr<CHUNKSIZE; ptr++) {
RD_accessBlock(mergeBuffer[ptr]);
}
ptr = 0;
}
#define RD_accessBlock accessMerging
#endif
/* ===================================================================== */
/* Direct Callbacks */
/* ===================================================================== */
void memAccess(ADDRINT addr, UINT32 size)
{
Addr a1 = (void*) (addr & ~(MEMBLOCKLEN-1));
Addr a2 = (void*) ((addr+size-1) & ~(MEMBLOCKLEN-1));
if (a1 == a2) {
if (VERBOSE >1)
fprintf(stderr," => %p\n", a1);
RD_accessBlock(a1);
}
else {
if (VERBOSE >1)
fprintf(stderr," => CROSS %p/%p\n", a1, a2);
RD_accessBlock(a1);
RD_accessBlock(a2);
}
}
VOID memRead(THREADID t, ADDRINT addr, UINT32 size)
{
if (t > 0) {
// we are NOT thread-safe, ignore access
ignoredReads++;
return;
}
if (VERBOSE >1)
fprintf(stderr,"R %p/%d", (void*)addr, size);
memAccess(addr, size);
}
VOID memWrite(THREADID t, ADDRINT addr, UINT32 size)
{
if (t > 0) {
// we are NOT thread-safe, ignore access
ignoredWrites++;
return;
}
if (VERBOSE >1)
fprintf(stderr,"W %p/%d", (void*)addr, size);
memAccess(addr, size);
}
VOID stackAccess()
{
stackAccesses++;
}
/* ===================================================================== */
/* Instrumentation */
/* ===================================================================== */
VOID Instruction(INS ins, VOID* v)
{
if (IGNORE_STACK && (INS_IsStackRead(ins) || INS_IsStackWrite(ins))) {
INS_InsertPredicatedCall( ins, IPOINT_BEFORE, (AFUNPTR)stackAccess,
IARG_END);
return;
}
UINT32 memOperands = INS_MemoryOperandCount(ins);
for (UINT32 memOp = 0; memOp < memOperands; memOp++) {
if (INS_MemoryOperandIsRead(ins, memOp))
INS_InsertPredicatedCall( ins, IPOINT_BEFORE, (AFUNPTR)memRead,
IARG_THREAD_ID,
IARG_MEMORYOP_EA, memOp,
IARG_UINT32, INS_MemoryOperandSize(ins, memOp),
IARG_END);
if (INS_MemoryOperandIsWritten(ins, memOp))
INS_InsertPredicatedCall( ins, IPOINT_BEFORE, (AFUNPTR)memWrite,
IARG_THREAD_ID,
IARG_MEMORYOP_EA, memOp,
IARG_UINT32, INS_MemoryOperandSize(ins, memOp),
IARG_END);
}
}
/* ===================================================================== */
/* Callbacks from Pin */
/* ===================================================================== */
VOID ThreadStart(THREADID t, CONTEXT *ctxt, INT32 flags, VOID *v)
{
fprintf(stderr, "Thread %d started\n", t);
}
/* ===================================================================== */
/* Output results at exit */
/* ===================================================================== */
VOID Exit(INT32 code, VOID *v)
{
char pStr[20];
if (KnobPIDPrefix.Value())
sprintf(pStr, "--%5d-- ", getpid());
else
pStr[0] = 0;
RD_printHistogram(stderr, pStr, MEMBLOCKLEN);
fprintf(stderr,
"%s ignored stack accesses: %lu\n",
pStr, stackAccesses);
fprintf(stderr,
"%s ignored accesses by thread != 0: %lu reads, %lu writes\n",
pStr, ignoredReads, ignoredWrites);
}
/* ===================================================================== */
/* Usage/Main Function of the Pin Tool */
/* ===================================================================== */
INT32 Usage()
{
PIN_ERROR( "PinDist: Get the Stack Reuse Distance Histogram\n"
+ KNOB_BASE::StringKnobSummary() + "\n");
return -1;
}
int main (int argc, char *argv[])
{
if (PIN_Init(argc, argv)) return Usage();
// add buckets [0-1023], [1K - 2K-1], ... [1G - ]
double d = KnobMinDist.Value();
int s = KnobDoubleSteps.Value();
double f = pow(2, 1.0/s);
RD_init((int)(d / MEMBLOCKLEN));
for(d*=f; d< 1024*1024*1024; d*=f)
RD_addBucket((int)(d / MEMBLOCKLEN));
stackAccesses = 0;
PIN_InitSymbols();
INS_AddInstrumentFunction(Instruction, 0);
PIN_AddFiniFunction(Exit, 0);
PIN_AddThreadStartFunction(ThreadStart, 0);
PIN_StartProgram();
return 0;
}
| lrr-tum/reuse | pindist/pindist.cpp | C++ | gpl-2.0 | 5,945 |
import { createSelector } from '@automattic/state-utils';
import { filter, orderBy } from 'lodash';
import 'calypso/state/comments/init';
function filterCommentsByStatus( comments, status ) {
return 'all' === status
? filter(
comments,
( comment ) => 'approved' === comment.status || 'unapproved' === comment.status
)
: filter( comments, ( comment ) => status === comment.status );
}
/**
* Returns list of loaded comments for a given site, filtered by status
*
* @param {object} state Redux state
* @param {number} siteId Site for whose comments to find
* @param {string} [status] Status to filter comments
* @param {string} [order=asc] Order in which to sort filtered comments
* @returns {Array<object>} Available comments for site, filtered by status
*/
export const getSiteComments = createSelector(
( state, siteId, status, order = 'asc' ) => {
const comments = state.comments.items ?? {};
const parsedComments = Object.keys( comments )
.filter( ( key ) => parseInt( key.split( '-', 1 ), 10 ) === siteId )
.reduce( ( list, key ) => [ ...list, ...comments[ key ] ], [] );
return status
? orderBy( filterCommentsByStatus( parsedComments, status ), 'date', order )
: orderBy( parsedComments, 'date', order );
},
( state ) => [ state.comments.items ]
);
| Automattic/wp-calypso | client/state/comments/selectors/get-site-comments.js | JavaScript | gpl-2.0 | 1,304 |
(function(customer_id) {
tinymce.create('tinymce.plugins.ItStream_AttachToPost', {
customer_id: customer_id,
init : function(editor, plugin_url) {
editor.addButton('player_scheduling', {
title : 'Embed ItStream Player',
cmd : 'itm_scheduling',
image : plugin_url + '/scheduling.gif'
});
// Register a new TinyMCE command
editor.addCommand('itm_scheduling', this.render_attach_to_post_interface, {
editor: editor,
plugin: editor.plugins.ItStream_AttachToPost
});
},
createControl : function(n, cm) {
return null;
},
getInfo : function() {
return {
longname : 'ItStream Scheduling Button',
author : 'It-Marketing',
authorurl : 'http://www.itmarketingsrl.it/',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/example',
version : "0.1"
};
},
wm_close_event: function() {
// Restore scrolling for the main content window when the attach to post interface is closed
jQuery('html,body').css('overflow', 'auto');
tinyMCE.activeEditor.selection.select(tinyMCE.activeEditor.dom.select('p')[0]);
tinyMCE.activeEditor.selection.collapse(0);
},
render_attach_to_post_interface: function() {
var attach_to_post_url = itstream_ajax.attach_to_post;
if (typeof(customer_id) != 'undefined') {
attach_to_post_url += "?id=" + itstream_ajax.customer_id;
}
var win = window;
while (win.parent != null && win.parent != win) {
win = win.parent;
}
win = jQuery(win);
var winWidth = win.width();
var winHeight = win.height();
var popupWidth = 680;
var popupHeight = 560;
var minWidth = 320;
var minHeight = 200;
var maxWidth = winWidth - (winWidth * 0.05);
var maxHeight = winHeight - (winHeight * 0.05);
if (maxWidth < minWidth) { maxWidth = winWidth - 10; }
if (maxHeight < minHeight) { maxHeight = winHeight - 10; }
if (popupWidth > maxWidth) { popupWidth = maxWidth; }
if (popupHeight > maxHeight) { popupHeight = maxHeight; }
// Open a window
this.editor.windowManager.open({
url: attach_to_post_url,
id: 'its_attach_to_post_dialog',
width: popupWidth,
height: popupHeight,
title: 'ItStream - Embed Player',
inline: 1
/*buttons: [{
text: 'Close',
onclick: 'close'
}]*/
});
// Ensure that the window cannot be scrolled - XXX actually allow scrolling in the main window and disable it for the inner-windows/frames/elements as to create a single scrollbar
jQuery('html,body').css('overflow', 'hidden');
jQuery('#its_attach_to_post_dialog_ifr').css('overflow-y', 'auto');
jQuery('#its_attach_to_post_dialog_ifr').css('overflow-x', 'hidden');
}
});
// Register plugin
tinymce.PluginManager.add( 'itstream', tinymce.plugins.ItStream_AttachToPost );
})(itstream_ajax.customer_id); | wp-plugins/itstream | admin/assets/js/editor.js | JavaScript | gpl-2.0 | 3,621 |
<?php
/**
* ExtendedEditBar extension for BlueSpice
*
* Provides additional buttons to the wiki edit field.
*
* 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.
*
* This file is part of BlueSpice for MediaWiki
* For further information visit http://www.blue-spice.org
*
* @author Markus Glaser <glaser@hallowelt.biz>
* @author MediaWiki Extension
* @version 2.22.0 stable
* @package BlueSpice_Extensions
* @subpackage ExtendedEditBar
* @copyright Copyright (C) 2010 Hallo Welt! - Medienwerkstatt GmbH, All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License v2 or later
* @filesource
*/
/* Changelog
* v1.20.0
*
* v1.0.0
* - raised to stable
* v0.1
* - initial release
*/
/**
* Base class for ExtendedEditBar extension
* @package BlueSpice_Extensions
* @subpackage ExtendedEditBar
*/
class ExtendedEditBar extends BsExtensionMW {
/**
* Constructor of ExtendedEditBar class
*/
public function __construct() {
wfProfileIn( 'BS::'.__METHOD__ );
// Base settings
$this->mExtensionFile = __FILE__;
$this->mExtensionType = EXTTYPE::OTHER; //SPECIALPAGE/OTHER/VARIABLE/PARSERHOOK
$this->mInfo = array(
EXTINFO::NAME => 'ExtendedEditBar',
EXTINFO::DESCRIPTION => wfMessage( 'bs-extendededitbar-desc' )->escaped(),
EXTINFO::AUTHOR => 'MediaWiki Extension, packaging by Markus Glaser',
EXTINFO::VERSION => 'default',
EXTINFO::STATUS => 'default',
EXTINFO::PACKAGE => 'default',
EXTINFO::URL => 'http://www.blue-spice.org',
EXTINFO::DEPS => array( 'bluespice' => '2.22.0' )
);
$this->mExtensionKey = 'MW::ExtendedEditBar';
wfProfileOut('BS::'.__METHOD__ );
}
/**
* Initialization of ExtendedEditBar extension
*/
protected function initExt() {
wfProfileIn( 'BS::'.__METHOD__ );
$this->setHook('EditPageBeforeEditToolbar');
wfProfileOut( 'BS::'.__METHOD__ );
}
/**
*
* @global type $wgStylePath
* @global type $wgContLang
* @global type $wgLang
* @global OutputPage $wgOut
* @global type $wgUseTeX
* @global type $wgEnableUploads
* @global type $wgForeignFileRepos
* @param string $toolbar
* @return boolean
*/
public function onEditPageBeforeEditToolbar( &$toolbar ) {
$this->getOutput()->addModuleStyles( 'ext.bluespice.extendeditbar.styles' );
$this->getOutput()->addModules( 'ext.bluespice.extendeditbar' );
//This is copy-code from EditPage::getEditToolbar(). Sad but neccesary
//until we suppot WikiEditor and this get's obsolete.
global $wgContLang, $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
$imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
$sNs = $this->getLanguage()->getNsText( NS_IMAGE );
$sCaption = wfMessage( 'bs-extendededitbar-gallerysamplecaption' )->plain();
$sPicture = wfMessage( 'bs-extendededitbar-gallerysamplepicture' )->plain();
$sGallery = "{$sNs}:{$sPicture}.jpg|{$sCaption}\n{$sNs}:{$sPicture}.jpg|{$sCaption}";
$sHeader = wfMessage( 'bs-extendededitbar-tablesampleheader' )->plain();
$sRow = wfMessage( 'bs-extendededitbar-tablesamplerow' )->plain();
$sCell = wfMessage( 'bs-extendededitbar-tablesamplecell' )->plain();
$sTable = "! {$sHeader} 1\n! {$sHeader} 2\n! {$sHeader} 3\n|-\n| {$sRow} 1, ".
"{$sCell} 1\n| {$sRow} 1, {$sCell} 2\n| {$sRow} 1, {$sCell} 3\n|-\n|".
" {$sRow} 2, {$sCell} 1\n| {$sRow} 2, {$sCell} 2\n| {$sRow} 2, {$sCell} 3";
$aMWButtonCfgs = array(
'mw-editbutton-bold' => array(
'open' => '\'\'\'',
'close' => '\'\'\'',
'sample' => wfMessage( 'bold_sample' )->text(),
'tip' => wfMessage( 'bold_tip' )->text(),
'key' => 'B'
),
'mw-editbutton-italic' => array(
'open' => '\'\'',
'close' => '\'\'',
'sample' => wfMessage( 'italic_sample' )->text(),
'tip' => wfMessage( 'italic_tip' )->text(),
'key' => 'I'
),
'mw-editbutton-link' => array(
'open' => '[[',
'close' => ']]',
'sample' => wfMessage( 'link_sample' )->text(),
'tip' => wfMessage( 'link_tip' )->text(),
'key' => 'L'
),
'mw-editbutton-extlink' => array(
'open' => '[',
'close' => ']',
'sample' => wfMessage( 'extlink_sample' )->text(),
'tip' => wfMessage( 'extlink_tip' )->text(),
'key' => 'X'
),
'mw-editbutton-headline' => array(
'open' => "\n== ",
'close' => " ==\n",
'sample' => wfMessage( 'headline_sample' )->text(),
'tip' => wfMessage( 'headline_tip' )->text(),
'key' => 'H'
),
'mw-editbutton-image' => $imagesAvailable ? array(
'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
'close' => ']]',
'sample' => wfMessage( 'image_sample' )->text(),
'tip' => wfMessage( 'image_tip' )->text(),
'key' => 'D',
) : false,
'mw-editbutton-media' => $imagesAvailable ? array(
'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
'close' => ']]',
'sample' => wfMessage( 'media_sample' )->text(),
'tip' => wfMessage( 'media_tip' )->text(),
'key' => 'M'
) : false,
'mw-editbutton-math' => $wgUseTeX ? array(
'open' => "<math>",
'close' => "</math>",
'sample' => wfMessage( 'math_sample' )->text(),
'tip' => wfMessage( 'math_tip' )->text(),
'key' => 'C'
) : false,
'mw-editbutton-signature' => array(
'open' => '--~~~~',
'close' => '',
'sample' => '',
'tip' => wfMessage( 'sig_tip' )->text(),
'key' => 'Y'
),
);
$aBSButtonCfgs = array(
'bs-editbutton-redirect' => array(
'tip' => wfMessage('bs-extendededitbar-redirecttip')->plain(),
'open' => "#REDIRECT [[",
'close' => "]]",
'sample' => wfMessage('bs-extendededitbar-redirectsample')->plain()
),
'bs-editbutton-strike' => array(
'tip' => wfMessage('bs-extendededitbar-striketip')->plain(),
'open' => "<s>",
'close' => "</s>",
'sample' => wfMessage('bs-extendededitbar-strikesample')->plain()
),
'bs-editbutton-linebreak' => array(
'tip' => wfMessage('bs-extendededitbar-entertip')->plain(),
'open' => "<br />\n",
'close' => "",
'sample' => ''
),
'bs-editbutton-sup' => array(
'tip' => wfMessage('bs-extendededitbar-uppertip')->plain(),
'open' => "<sup>",
'close' => "</sup>",
'sample' => wfMessage('bs-extendededitbar-uppersample')->plain()
),
'bs-editbutton-sub' => array(
'tip' => wfMessage('bs-extendededitbar-lowertip')->plain(),
'open' => "<sub>",
'close' => "</sub>",
'sample' => wfMessage('bs-extendededitbar-lowersample')->plain()
),
'bs-editbutton-small' => array(
'tip' => wfMessage('bs-extendededitbar-smalltip')->plain(),
'open' => "<small>",
'close' => "</small>",
'sample' => wfMessage('bs-extendededitbar-smallsample')->plain()
),
'bs-editbutton-comment' => array(
'tip' => wfMessage('bs-extendededitbar-commenttip')->plain(),
'open' => "<!-- ",
'close' => " -->",
'sample' => wfMessage('bs-extendededitbar-commentsample')->plain()
),
'bs-editbutton-gallery' => array(
'tip' => wfMessage('bs-extendededitbar-gallerytip')->plain(),
'open' => "\n<gallery>\n",
'close' => "\n</gallery>",
'sample' => $sGallery
),
'bs-editbutton-blockquote' => array(
'tip' => wfMessage('bs-extendededitbar-quotetip')->plain(),
'open' => "\n<blockquote>\n",
'close' => "\n</blockquote>",
'sample' => wfMessage('bs-extendededitbar-quotesample')->plain()
),
'bs-editbutton-table' => array(
'tip' => wfMessage('bs-extendededitbar-tabletip')->plain(),
'open' => "{| class=\"wikitable\"\n|-\n",
'close' => "\n|}",
'sample' => $sTable
),
);
$aButtonCfgs = $aMWButtonCfgs + $aBSButtonCfgs;
$aRows = array(
array('editing' => array(), 'dialogs' => array(), 'table' => array( 10 => 'bs-editbutton-table' )), //this is reserverd for BlueSpice dialogs
array(
'formatting' => array(
10 => 'mw-editbutton-bold',
20 => 'mw-editbutton-italic',
30 => 'bs-editbutton-strike',
40 => 'mw-editbutton-headline',
50 => 'bs-editbutton-linebreak',
),
'content' => array(
//10 => 'mw-editbutton-link',
//20 => 'mw-editbutton-extlink',
30 => 'mw-editbutton-strike',
//40 => 'mw-editbutton-image',
//50 => 'mw-editbutton-media',
60 => 'bs-editbutton-gallery',
),
'misc' => array(
10 => 'mw-editbutton-signature',
20 => 'bs-editbutton-redirect',
30 => 'bs-editbutton-comment',
)
)
);
wfRunHooks( 'BSExtendedEditBarBeforeEditToolbar', array( &$aRows, &$aButtonCfgs ));
$aContent = array();
foreach( $aRows as $aRow ) {
$sRow = Html::openElement( 'div', array( 'class' => 'row' ) );
foreach( $aRow as $sGroupId => $aButtons ) {
$sGroup = Html::openElement( 'div', array( 'class' => 'group' ) );
ksort( $aButtons );
foreach ( $aButtons as $iButtonSort => $sButtonId ) {
if( !isset( $aButtonCfgs[$sButtonId] ) ) continue;
$aButtonCfg = $aButtonCfgs[$sButtonId];
if( !is_array( $aButtonCfg ) ) continue;
$aDefaultAttributes = array(
'href' => '#',
'class' => 'bs-button-32 mw-toolbar-editbutton'
);
$aAttributes = array(
'title' => $aButtonCfg['tip'],
'id' => $sButtonId
) + $aDefaultAttributes;
if( isset( $aButtonCfg['open'] ) ) $aAttributes['data-open'] = $aButtonCfg['open'];
if( isset( $aButtonCfg['close'] ) ) $aAttributes['data-close'] = $aButtonCfg['close'];
if( isset( $aButtonCfg['sample'] ) ) $aAttributes['data-sample'] = $aButtonCfg['sample'];
$sButton = Html::element(
'a',
$aAttributes,
$aButtonCfg['tip']
);
$sGroup .= $sButton;
}
$sGroup .= Html::closeElement('div');
$sRow.= $sGroup;
}
$sRow.= Html::closeElement('div');
$aContent[] = $sRow;
}
//We have to keep the old toolbar (the one with ugly icons) because
//some extensions (i.e. MsUpload) rely on it to add elements to the DOM.
//Unfortunately VisualEditor wil set it to visible when toggled.
//Therefore we move it out of sight using CSS positioning. Some buttons
//May be not visible though.
//TODO: Take contents of div#toolbar as base
$toolbar .= Html::rawElement(
'div',
array( 'id' => 'bs-extendededitbar' ),
implode( '', $aContent)
);
return true;
}
} | scolladogsp/wiki | extensions/BlueSpiceExtensions/ExtendedEditBar/ExtendedEditBar.class.php | PHP | gpl-2.0 | 11,037 |
package org.wordpress.android.ui.notifications;
import com.android.volley.VolleyError;
import org.wordpress.android.models.Note;
import java.util.List;
public class NotificationEvents {
public static class NotificationsChanged {
final public boolean hasUnseenNotes;
public NotificationsChanged() {
this.hasUnseenNotes = false;
}
public NotificationsChanged(boolean hasUnseenNotes) {
this.hasUnseenNotes = hasUnseenNotes;
}
}
public static class NoteModerationFailed {}
public static class NoteModerationStatusChanged {
final boolean isModerating;
final String noteId;
public NoteModerationStatusChanged(String noteId, boolean isModerating) {
this.noteId = noteId;
this.isModerating = isModerating;
}
}
public static class NoteLikeStatusChanged {
final String noteId;
public NoteLikeStatusChanged(String noteId) {
this.noteId = noteId;
}
}
public static class NoteVisibilityChanged {
final boolean isHidden;
final String noteId;
public NoteVisibilityChanged(String noteId, boolean isHidden) {
this.noteId = noteId;
this.isHidden = isHidden;
}
}
public static class NotificationsSettingsStatusChanged {
final String mMessage;
public NotificationsSettingsStatusChanged(String message) {
mMessage = message;
}
public String getMessage() {
return mMessage;
}
}
public static class NotificationsUnseenStatus {
final public boolean hasUnseenNotes;
public NotificationsUnseenStatus(boolean hasUnseenNotes) {
this.hasUnseenNotes = hasUnseenNotes;
}
}
public static class NotificationsRefreshCompleted {
final List<Note> notes;
public NotificationsRefreshCompleted(List<Note> notes) {
this.notes = notes;
}
}
public static class NotificationsRefreshError {
VolleyError error;
public NotificationsRefreshError(VolleyError error) {
this.error = error;
}
public NotificationsRefreshError() {
}
}
}
| mzorz/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/notifications/NotificationEvents.java | Java | gpl-2.0 | 2,258 |
<?php
/**
* @ignore
*/
function mysql_table_exists($database, $tableName) {
global $tc_db;
$tables = array();
$tablesResults = $tc_db->GetAll("SHOW TABLES FROM `$database`;");
foreach ($tablesResults AS $row) $tables[] = $row[0];
return(in_array($tableName, $tables));
}
function pgsql_table_exists($database, $tableName) {
global $tc_db;
$tables = array();
$tablesResults = $tc_db->GetAll(" select table_name from information_schema.tables where table_schema='public' and table_type='BASE TABLE'");
foreach ($tablesResults AS $row) $tables[] = $row[0];
return(in_array($tableName, $tables));
}
function sqlite_table_exists($database, $tableName) {
global $tc_db;
$tables = array();
$tablesResults = $tc_db->GetAll("SELECT name FROM sqlite_master WHERE type = 'table'" );
foreach ($tablesResults AS $row) $tables[] = $row[0];
return(in_array($tableName, $tables));
}
function CreateSalt() {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$salt = '';
for ($i = 0; $i < 3; ++$i) {
$salt .= $chars[mt_rand(0, strlen($chars) - 1)];
}
return $salt;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pl" lang="pl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Kusaba B Installation</title>
<style type="text/css">
body { font-family: sans-serif; font-size: 75%; background: #ffe }
a { text-decoration: none; color: #550 }
h1,h2 { margin: 0px; background: #fca }
h1 { font-size: 150% }
h2 { font-size: 100%; margin-top: 1em }
.hl { font-style: italic }
.plus { float: right; font-size: 8px; font-weight: normal; padding: 1px 4px 2px 4px; margin: 0px 0px; background: #eb9; color: #000; border: 1px solid #da8; cursor: hand; cursor: pointer }
.plus:hover { background: #da8; border: 1px solid #c97 }
ul { list-style: none; padding-left: 0px; margin: 0px }
li { margin: 0px }
li:hover { background: #fec; }
li a { display: block; width: 100%; }
</style>
<link rel="shortcut icon" href="/favicon.ico" />
</head>
<body>
<div style="text-align:center;"><h1>Kusaba B Installation</h1></div>
<?php
echo '<h2>Checking configuration file...</h2>';
if (file_exists('../config.php')) {
require '../config.php';
require KU_ROOTDIR . 'inc/functions.php';
if (KU_RANDOMSEED!="ENTER RANDOM LETTERS/NUMBERS HERE"&&KU_RANDOMSEED!="") {
echo 'Configuration appears correct.';
echo '<h2>Checking database...</h2>';
$reqiredtables = array("ads","announcements","banlist","bannedhashes","blotter","boards","board_filetypes","embeds","events","filetypes","front","loginattempts","modlog","module_settings","posts","reports","sections","staff","watchedthreads","wordfilter");
foreach ($reqiredtables as $tablename) {
if (KU_DBTYPE == 'mysql' || KU_DBTYPE == 'mysqli') {
if (!mysql_table_exists(KU_DBDATABASE,KU_DBPREFIX.$tablename)) {
die("Couldn't find the table <strong>".KU_DBPREFIX.$tablename."</strong> in the database. Please <a href=\"install-mysql.php\"><strong><u>insert the mySQL dump</u></strong></a>.");
}
}
if (KU_DBTYPE == 'postgres7' || KU_DBTYPE == 'postgres8' || KU_DBTYPE == 'postgres') {
if (!pgsql_table_exists(KU_DBDATABASE,KU_DBPREFIX.$tablename)) {
die("Couldn't find the table <strong>".KU_DBPREFIX.$tablename."</strong> in the database. Please <a href=\"install-pgsql.php\"><strong><u>insert the PostgreSQL dump</u></strong></a>.");
}
}
if (KU_DBTYPE == 'sqlite') {
if (!sqlite_table_exists(KU_DBDATABASE,KU_DBPREFIX.$tablename)) {
die("Couldn't find the table <strong>".KU_DBPREFIX.$tablename."</strong> in the database. Please <a href=\"install-sqlite.php\"><strong><u>insert the SQLite dump</u></strong></a>.");
}
}
}
echo 'Database appears correct.';
echo '<h2>Inserting default administrator account...</h2>';
$result_exists = $tc_db->GetOne("SELECT COUNT(*) FROM `".KU_DBPREFIX."staff` WHERE `username` = 'admin'");
if ($result_exists==0) {
$salt = CreateSalt();
$result = $tc_db->Execute("INSERT INTO `".KU_DBPREFIX."staff` ( `username` , `salt`, `password` , `type` , `addedon` ) VALUES ( 'admin' , '".$salt."', '".md5("admin".$salt)."' , '1' , '".time()."' )");
echo 'Account inserted.';
$result = true;
} else {
echo 'There is already an administrator account inserted.';
$result = true;
}
if ($result) {
require_once KU_ROOTDIR . 'inc/classes/menu.class.php';
$menu_class = new Menu();
$menu_class->Generate();
echo '<h2>Done!</h2>Installation has finished! The default administrator account is <strong>admin</strong> with the password of <strong>admin</strong>.<br /><br />Delete this and the install-mysql.php file from the server, then <a href="manage.php">add some boards</a>!';
echo '<br /><br /><br /><h1><font color="red">DELETE THIS AND install-mysql.php RIGHT NOW!</font></h1>';
} else {
echo 'Error inserting SQL. Please add <strong>$tc_db->debug = true;</strong> just before ?> in config.php to turn on debugging, and check the error message.';
}
} else {
echo 'Please enter a random string into the <strong>KU_RANDOMSEED</strong> value.';
}
} else {
echo 'Unable to locate config.php';
}
?>
</body>
</html>
| 314parley/Kusaba-B | INSTALL/install.php | PHP | gpl-2.0 | 5,390 |
<?php
/**
* @file
* Teamwork15 sub theme template functions
*
*/
/**
* Implements hook_preprocess_maintenance_page().
*/
function teamwork_15_subtheme_preprocess_maintenance_page(&$variables) {
backdrop_add_css(backdrop_get_path('theme', 'bartik') . '/css/maintenance-page.css');
}
/**
* Implements hook_preprocess_layout().
*/
function teamwork_15_subtheme_preprocess_layout(&$variables) {
if ($variables['content']['header']) {
$variables['content']['header'] = '<div class="l-header-inner">' . $variables['content']['header'] . '</div>';
}
if (theme_get_setting('teamwork_15_subtheme_cdn') > 0)
{
backdrop_add_css('http://cdnjs.cloudflare.com/ajax/libs/pure/0.6.0/pure-min.css', array('type' => 'external', 'every_page' => TRUE, 'group' => CSS_DEFAULT));
}
$var1 = theme_get_setting('teamwork_15_subtheme_juiced_main_background');
$var2 = theme_get_setting('teamwork_15_subtheme_juiced_big_statement_background');
$var3 = theme_get_setting('teamwork_15_subtheme_juiced_main_background_blurred');
$var4 = theme_get_setting('teamwork_15_subtheme_juiced_big_statement_background_blurred');
if ($var1 && $var3 > 0)
{
backdrop_add_css("@media screen and (min-width: 769px) { .juiced-main::before { content: ' '; width: 100%; height: 100%; display: block; position: absolute; z-index: -100; -webkit-filter: blur(20px); -moz-filter: blur(20px); -o-filter: blur(20px); -ms-filter: blur(20px); filter: blur(20px); opacity: 0.4; background: url($var1) no-repeat; background-size: cover; background-position: center; } }", array('type' => 'inline'));
}
if ($var1 && $var3 == 0)
{
backdrop_add_css("@media screen and (min-width: 769px) { .juiced-main { background: url($var1) no-repeat; background-size: cover; background-position: center; } }", array('type' => 'inline'));
}
if ($var2 && $var4 > 0)
{
backdrop_add_css("@media screen and (min-width: 769px) { .l-big-statement::before { content: ' '; width: 100%; height: 100%; display: block; position: absolute; z-index: -100; -webkit-filter: blur(20px); -moz-filter: blur(20px); -o-filter: blur(20px); -ms-filter: blur(20px); filter: blur(20px); opacity: 0.4; background: url($var2) no-repeat fixed; background-size: cover; background-position: center; } }", array('type' => 'inline'));
}
if ($var2 && $var4 == 0)
{
backdrop_add_css("@media screen and (min-width: 769px) { .l-big-statement { background: url($var2) no-repeat fixed; background-size: cover; background-position: center; } }", array('type' => 'inline'));
}
$var5 = theme_get_setting('teamwork_15_subtheme_body_main_background');
$var6 = theme_get_setting('teamwork_15_subtheme_footer_main_background');
$var7 = theme_get_setting('teamwork_15_subtheme_body_main_background_blurred');
$var8 = theme_get_setting('teamwork_15_subtheme_footer_main_background_blurred');
if ($var5 && $var7 > 0)
{
backdrop_add_css("@media screen and (min-width: 769px) { .layout::before { content: ' '; width: 100%; height: 100%; display: block; position: absolute; z-index: -100; -webkit-filter: blur(20px); -moz-filter: blur(20px); -o-filter: blur(20px); -ms-filter: blur(20px); filter: blur(20px); opacity: 0.4; background: url($var5) no-repeat; background-size: cover; background-position: center; } }", array('type' => 'inline'));
}
if ($var5 && $var7 == 0)
{
backdrop_add_css("@media screen and (min-width: 769px) { .layout { background: url($var5) no-repeat; background-size: cover; background-position: center; } }", array('type' => 'inline'));
}
if ($var6 && $var8 > 0)
{
backdrop_add_css("@media screen and (min-width: 769px) { footer.l-footer::before { content: ' '; width: 100%; height: 100%; display: block; position: absolute; z-index: -100; -webkit-filter: blur(20px); -moz-filter: blur(20px); -o-filter: blur(20px); -ms-filter: blur(20px); filter: blur(20px); opacity: 0.4; background: url($var6) no-repeat fixed; background-size: cover; background-position: center; } footer.l-footer { background: transparent; } }", array('type' => 'inline'));
}
if ($var6 && $var8 == 0)
{
backdrop_add_css("@media screen and (min-width: 769px) { footer.l-footer { background: url($var6) no-repeat fixed; background-size: cover; background-position: center; } }", array('type' => 'inline'));
}
if (theme_get_setting('teamwork_15_subtheme_script1') > 0)
{
backdrop_add_js("https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js", array('type' => 'external', 'scope' => 'footer', 'every_page' => TRUE, 'preprocess' => TRUE));
}
if (theme_get_setting('teamwork_15_subtheme_script2') > 0)
{
backdrop_add_js("https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js", array('type' => 'external', 'scope' => 'footer', 'every_page' => TRUE, 'preprocess' => TRUE));
}
if (theme_get_setting('teamwork_15_subtheme_script3') > 0)
{
backdrop_add_js("https://cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", array('type' => 'external', 'scope' => 'footer', 'every_page' => TRUE, 'preprocess' => TRUE));
}
if (theme_get_setting('teamwork_15_subtheme_script4') > 0)
{
backdrop_add_js("https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.4/hammer.min.js", array('type' => 'external', 'scope' => 'footer', 'every_page' => TRUE, 'preprocess' => TRUE));
}
backdrop_add_js("themes/teamwork_15_subtheme/js/scripts.js", array('type' => 'file', 'scope' => 'footer', 'every_page' => TRUE, 'preprocess' => TRUE));
backdrop_add_js("document.write('<script src=\"http://' + (location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1\"></' + 'script>')", array('type' => 'inline', 'scope' => 'footer', 'weight' => 9999));
}
/**
* Implements theme_field__field_type().
*/
function teamwork_15_subtheme_field__taxonomy_term_reference($variables) {
$output = '';
// Render the label, if it's not hidden.
if (!$variables['label_hidden']) {
$output .= '<h3 class="field-label">' . $variables['label'] . ': </h3>';
}
// Render the items.
$output .= ($variables['element']['#label_display'] == 'inline') ? '<ul class="links inline">' : '<ul class="links">';
foreach ($variables['items'] as $delta => $item) {
$item_attributes = (isset($variables['item_attributes'][$delta])) ? backdrop_attributes($variables['item_attributes'][$delta]) : '';
$output .= '<li class="taxonomy-term-reference-' . $delta . '"' . $item_attributes . '>' . backdrop_render($item) . '</li>';
}
$output .= '</ul>';
// Render the surrounding DIV with appropriate classes and attributes.
if (!in_array('clearfix', $variables['classes'])) {
$variables['classes'][] = 'clearfix';
}
$output = '<div class="' . implode(' ', $variables['classes']) . '"' . backdrop_attributes($variables['attributes']) . '>' . $output . '</div>';
return $output;
}
/**
* Implements theme_preprocess_image_style().
*/
function teamwork_15_subtheme_preprocess_image_style(&$vars) {
$vars['attributes']['class'][] = 'pure-img';
}
function teamwork_15_subtheme_button(&$vars) {
$classes = array('button-success', 'pure-button-primary', 'button-xlarge', 'pure-button');
if (!isset($vars['#attributes']['class'])) {
$vars['#attributes'] = array('class' => $classes);
}
else {
$vars['#attributes']['class'] = array_merge($vars['#attributes']['class'], $classes);
}
if (!isset($vars['element']['#attributes']['class'])) {
$vars['element']['#attributes'] = array('class' => $classes);
}
else {
$vars['element']['#attributes']['class'] = array_merge($vars['element']['#attributes']['class'], $classes);
}
return theme_button($vars);
}
function teamwork_15_subtheme_css_alter(&$css) {
$css_to_remove = array();
if (theme_get_setting('teamwork_15_subtheme_cdn') > 0)
{
$css_to_remove[] = backdrop_get_path('theme','teamwork_15') . '/css/pure.min.css';
}
if (theme_get_setting('teamwork_15_subtheme_sass') > 0)
{
$css_to_remove[] = backdrop_get_path('theme','teamwork_15') . '/css/style.css';
$css_to_remove[] = backdrop_get_path('theme','teamwork_15') . '/css/pure.min.css';
}
foreach ($css_to_remove as $index => $css_file) {
unset($css[$css_file]);
}
}
/**
* Implements hook_form_alter()
*/
function teamwork_15_subtheme_form_alter(&$form, &$form_state, $form_id) {
$classes = array('pure-form', 'pure-form-aligned');
if (!isset($form['#attributes']['class'])) {
$form['#attributes'] = array('class' => $classes);
}
else {
$form['#attributes']['class'] = array_merge($form['#attributes']['class'], $classes);
}
}
function teamwork_15_subtheme_menu_tree($variables) {
return '<ul class="menu">' . $variables['tree'] . '</ul>';
}
/**
* Overrides theme_form_element_label().
*/
function teamwork_15_subtheme_form_element_label(&$variables) {
$element = $variables['element'];
$title = filter_xss_admin($element['#title']);
// If the element is required, a required marker is appended to the label.
$required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';
// // This is also used in the installer, pre-database setup.
$t = get_t();
$attributes = array();
if (!empty($element['#id'])) {
$attributes['for'] = $element['#id'];
}
$output = '';
if (isset($variables['#children'])) {
if ($element['#type'] === "radio")
{
$output .= $variables['#children'];
}
if ($element['#type'] === "checkbox")
{
$output .= $variables['#children'];
}
}
return ' <label' . backdrop_attributes($attributes) . '></label><div>' . $t('!title', array('!title' => $title)) . "</div> \n";
}
/**
* Implements theme_preprocess_menu_link().
*/
function teamwork_15_subtheme_menu_link(array $variables) {
$element = $variables['element'];
$classes = array('pure-menu-item');
$element['#attributes']['class'] = array_merge($element['#attributes']['class'], $classes);
$sub_menu = '';
if ($element['#below']) {
$sub_menu = backdrop_render($element['#below']);
}
$output = l($element['#title'], $element['#href'], $element['#localized_options']);
return '<li' . backdrop_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}
| backdrop-contrib/teamwork_15 | teamwork_15_subtheme/template.php | PHP | gpl-2.0 | 10,165 |
/*
* Copyright (c) 2017 Red Hat, Inc. and/or its affiliates.
*
* 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.
*
*/
/**
* @test TestMemoryMXBeans
* @key gc
* @summary Test JMX memory beans
* @modules java.base/jdk.internal.misc
* java.management
* @run main/othervm -XX:+UseShenandoahGC -Xmx1g TestMemoryMXBeans -1 1024
* @run main/othervm -XX:+UseShenandoahGC -Xms1g -Xmx1g TestMemoryMXBeans 1024 1024
* @run main/othervm -XX:+UseShenandoahGC -Xms128m -Xmx1g TestMemoryMXBeans 128 1024
*/
import java.lang.management.*;
import java.util.*;
public class TestMemoryMXBeans {
public static void main(String[] args) throws Exception {
if (args.length < 2) {
throw new IllegalStateException("Should provide expected heap sizes");
}
long initSize = 1L * Integer.parseInt(args[0]) * 1024 * 1024;
long maxSize = 1L * Integer.parseInt(args[1]) * 1024 * 1024;
testMemoryBean(initSize, maxSize);
}
public static void testMemoryBean(long initSize, long maxSize) {
MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
long heapInit = memoryMXBean.getHeapMemoryUsage().getInit();
long heapMax = memoryMXBean.getHeapMemoryUsage().getMax();
long nonHeapInit = memoryMXBean.getNonHeapMemoryUsage().getInit();
long nonHeapMax = memoryMXBean.getNonHeapMemoryUsage().getMax();
if (initSize > 0 && heapInit != initSize) {
throw new IllegalStateException("Init heap size is wrong: " + heapInit + " vs " + initSize);
}
if (maxSize > 0 && heapMax != maxSize) {
throw new IllegalStateException("Max heap size is wrong: " + heapMax + " vs " + maxSize);
}
}
}
| ojdkbuild/lookaside_java-1.8.0-openjdk | hotspot/test/gc/shenandoah/TestMemoryMXBeans.java | Java | gpl-2.0 | 2,609 |
jQuery(function($) {
///////////////////////////////////////////////////////////////////
///// META BOXES JS
///////////////////////////////////////////////////////////////////
jQuery('.repeatable-add').live('click', function() {
var field = jQuery(this).closest('td').find('.custom_repeatable li:last').clone(true);
var fieldLocation = jQuery(this).closest('td').find('.custom_repeatable li:last');
field.find('input.regular-text, textarea, select').val('');
field.find('input, textarea, select').attr('name', function(index, name) {
return name.replace(/(\d+)/, function(fullMatch, n) {
return Number(n) + 1;
});
});
field.insertAfter(fieldLocation, jQuery(this).closest('td'));
var fieldsCount = jQuery('.repeatable-remove').length;
if( fieldsCount > 1 ) {
jQuery('.repeatable-remove').css('display','inline');
}
return false;
});
var fieldsCount = jQuery('.repeatable-remove').length;
if( fieldsCount == 1 ) {
jQuery('.repeatable-remove').css('display','none');
}
jQuery('.repeatable-remove').live('click', function() {
jQuery(this).parent().remove();
var fieldsCount = jQuery('.repeatable-remove').length;
if( fieldsCount == 1 ) {
jQuery('.repeatable-remove').css('display','none');
}
return false;
});
jQuery('.custom_repeatable').sortable({
opacity: 0.6,
revert: true,
cursor: 'move',
handle: '.sort'
});
// the upload image button, saves the id and outputs a preview of the image
var imageFrame;
$('.rg-bb_upload_image_button').live('click', function(event) {
event.preventDefault();
var options, attachment;
$self = $(event.target);
$div = $self.closest('div.rg-bb_image');
// if the frame already exists, open it
if ( imageFrame ) {
imageFrame.open();
return;
}
// set our settings
imageFrame = wp.media({
title: 'Choose Image',
multiple: true,
library: {
type: 'image'
},
button: {
text: 'Use This Image'
}
});
// set up our select handler
imageFrame.on( 'select', function() {
selection = imageFrame.state().get('selection');
if ( ! selection )
return;
// loop through the selected files
selection.each( function( attachment ) {
console.log(attachment);
var src = attachment.attributes.sizes.full.url;
var id = attachment.id;
$div.find('.rg-bb_preview_image').attr('src', src);
$div.find('.rg-bb_upload_image').val(id);
} );
});
// open the frame
imageFrame.open();
});
// the remove image link, removes the image id from the hidden field and replaces the image preview
$('.rg-bb_clear_image_button').live('click', function() {
var defaultImage = $(this).parent().siblings('.rg-bb_default_image').text();
$(this).parent().siblings('.rg-bb_upload_image').val('');
$(this).parent().siblings('.rg-bb_preview_image').attr('src', defaultImage);
return false;
});
// function to create an array of input values
function ids(inputs) {
var a = [];
for (var i = 0; i < inputs.length; i++) {
a.push(inputs[i].val);
}
//$("span").text(a.join(" "));
}
// repeatable fields
$('.toggle').on("click", function() {
console.log($(this).parent().siblings().toggleClass('closed'));
});
$('.meta_box_repeatable_add').live('click', function(e) {
e.preventDefault();
// clone
var row = $(this).closest('.meta_box_repeatable').find('tbody tr:last-child');
var clone = row.clone();
var defaultImage = clone.find('.meta_box_default_image').text();
clone.find('select.chosen').removeAttr('style', '').removeAttr('id', '').removeClass('chzn-done').data('chosen', null).next().remove();
// clone.find('input.regular-text, textarea, select').val('');
clone.find('.meta_box_preview_image').attr('src', defaultImage).removeClass('loaded');
clone.find('input[type=checkbox], input[type=radio]').attr('checked', false);
row.after(clone);
// increment name and id
clone.find('input, textarea, select').attr('name', function(index, name) {
return name.replace(/(\d+)/, function(fullMatch, n) {
return Number(n) + 1;
});
});
var arr = [];
$('input.repeatable_id:text').each(function(){ arr.push($(this).val()); });
clone.find('input.repeatable_id')
.val(Number(Math.max.apply( Math, arr )) + 1);
if (!!$.prototype.chosen) {
clone.find('select.chosen')
.chosen({allow_single_deselect: true});
}
});
$('.meta_box_repeatable_remove').live('click', function(e){
e.preventDefault();
$(this).closest('tr').remove();
});
$('.meta_box_repeatable tbody').sortable({
opacity: 0.6,
revert: true,
cursor: 'move',
handle: '.hndle'
});
// post_drop_sort
$('.sort_list').sortable({
connectWith: '.sort_list',
opacity: 0.6,
revert: true,
cursor: 'move',
cancel: '.post_drop_sort_area_name',
items: 'li:not(.post_drop_sort_area_name)',
update: function(event, ui) {
var result = $(this).sortable('toArray');
var thisID = $(this).attr('id');
$('.store-' + thisID).val(result)
}
});
$('.sort_list').disableSelection();
// turn select boxes into something magical
if (!!$.prototype.chosen)
$('.chosen').chosen({ allow_single_deselect: true });
}); | StefanDindyal/wordpresser | wp-content/themes/bobbarnyc/inc/settings-panel/js/custom-admin.js | JavaScript | gpl-2.0 | 5,266 |
<?php
/**
* @version $Id: mod_communitysurvey.php 01 2011-11-08 11:37:09Z maverick $
* @package CoreJoomla.Surveys
* @subpackage Modules.site
* @copyright Copyright (C) 2009 - 2012 corejoomla.com, Inc. All rights reserved.
* @author Maverick
* @link http://www.corejoomla.com/
* @license License GNU General Public License version 2 or later
*/
//don't allow other scripts to grab and execute our file
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
defined('S_APP_NAME') or define('S_APP_NAME', 'com_communitysurveys');
// include the helper file
require_once(dirname(__FILE__).'/helper.php');
require_once(JPATH_SITE.'/components/com_communitysurveys/router.php');
require_once(JPATH_SITE.'/components/com_communitysurveys/helpers/constants.php');
require_once(JPATH_SITE.'/components/com_communitysurveys/helpers/helper.php');
// CJLib includes
$cjlib = JPATH_ROOT.'/components/com_cjlib/framework.php';
if(file_exists($cjlib)){
require_once $cjlib;
}else{
die('CJLib (CoreJoomla API Library) component not found. Please download and install it to continue.');
}
CJLib::import('corejoomla.framework.core');
// Get the properties
$show_latest = intval($params->get('show_latest','1'));
$show_popular = intval($params->get('show_most_popular','1'));
$show_tabs = intval($params->get('show_tabs','1'));
$tab_order = trim($params->get('tab_order', 'L,M'));
// Get the item id for community answers
$itemid = CJFunctions::get_active_menu_id(true, 'index.php?option='.S_APP_NAME.'&view=survey');
$document = JFactory::getDocument();
$document->addStyleSheet(JURI::base(true).'/modules/mod_communitysurveys/assets/communitysurveys.css');
// get the items to display from the helper
$order = explode(',', $tab_order);
if($show_tabs == 1){
CJLib::import('corejoomla.ui.bootstrap', true);
echo '<div id="cj-wrapper">';
echo '<ul class="nav nav-tabs" data-tabs="tabs">';
foreach ($order as $i=>$tab){
if((strcmp($tab, "L") == 0) && $show_latest){
echo '<li'.($i == 0 ? ' class="active"' : '').'><a href="#cstab-1" data-toggle="tab">'.JText::_('LBL_LATEST_SURVEYS').'</a></li>';
}
if((strcmp($tab, 'M') == 0) && $show_popular){
echo '<li'.($i == 0 ? ' class="active"' : '').'><a href="#cstab-2" data-toggle="tab">'.JText::_('LBL_MOST_POPULAR_SURVEYS').'</a></li>';
}
}
echo '</ul>';
foreach ($order as $i=>$tab){
if((strcmp($tab,'L') == 0) && $show_latest){
$latest_surveys = modCommunitySurveysHelper::getLatestSurveys($params);
echo '<div id="cstab-1" class="tab-pane fade'.($i == 0 ? ' in active' : '').'">';
require(JModuleHelper::getLayoutPath('mod_communitysurveys','latest_surveys'));
echo '</div>';
}
if((strcmp($tab,'M') == 0) && $show_popular){
$popular_surveys = modCommunitySurveysHelper::getMostPopularSurveys($params);
echo '<div id="cstab-2" class="tab-pane fade'.($i == 0 ? ' in active' : '').'">';
require(JModuleHelper::getLayoutPath('mod_communitysurveys','most_popular'));
echo '</div>';
}
}
echo '</div>';
}else{
foreach ($order as $tab){
if((strcmp($tab,'L') == 0) && $show_latest){
$latest_surveys = modCommunitySurveysHelper::getLatestSurveys($params);
require(JModuleHelper::getLayoutPath('mod_communitysurveys','latest_surveys'));
}
if((strcmp($tab,'M') == 0) && $show_popular){
$popular_surveys = modCommunitySurveysHelper::getMostPopularSurveys($params);
require(JModuleHelper::getLayoutPath('mod_communitysurveys','most_popular'));
}
}
}
?>
| LauraRey/oacfdc | modules/mod_communitysurveys/mod_communitysurveys.php | PHP | gpl-2.0 | 3,653 |
"""
SALTS XBMC Addon
Copyright (C) 2015 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import xbmcaddon
import xbmcplugin
import xbmcgui
import xbmc
import xbmcvfs
import urllib
import urlparse
import sys
import os
import re
addon = xbmcaddon.Addon()
get_setting = addon.getSetting
show_settings = addon.openSettings
def get_path():
return addon.getAddonInfo('path').decode('utf-8')
def get_profile():
return addon.getAddonInfo('profile').decode('utf-8')
def translate_path(path):
return xbmc.translatePath(path).decode('utf-8')
def set_setting(id, value):
if not isinstance(value, basestring): value = str(value)
addon.setSetting(id, value)
def get_version():
return addon.getAddonInfo('version')
def get_id():
return addon.getAddonInfo('id')
def get_name():
return addon.getAddonInfo('name')
def get_plugin_url(queries):
try:
query = urllib.urlencode(queries)
except UnicodeEncodeError:
for k in queries:
if isinstance(queries[k], unicode):
queries[k] = queries[k].encode('utf-8')
query = urllib.urlencode(queries)
return sys.argv[0] + '?' + query
def end_of_directory(cache_to_disc=True):
xbmcplugin.endOfDirectory(int(sys.argv[1]), cacheToDisc=cache_to_disc)
def set_content(content):
xbmcplugin.setContent(int(sys.argv[1]), content)
def create_item(queries, label, thumb='', fanart='', is_folder=None, is_playable=None, total_items=0, menu_items=None, replace_menu=False):
list_item = xbmcgui.ListItem(label, iconImage=thumb, thumbnailImage=thumb)
add_item(queries, list_item, fanart, is_folder, is_playable, total_items, menu_items, replace_menu)
def add_item(queries, list_item, fanart='', is_folder=None, is_playable=None, total_items=0, menu_items=None, replace_menu=False):
if menu_items is None: menu_items = []
if is_folder is None:
is_folder = False if is_playable else True
if is_playable is None:
playable = 'false' if is_folder else 'true'
else:
playable = 'true' if is_playable else 'false'
liz_url = get_plugin_url(queries)
if fanart: list_item.setProperty('fanart_image', fanart)
list_item.setInfo('video', {'title': list_item.getLabel()})
list_item.setProperty('isPlayable', playable)
list_item.addContextMenuItems(menu_items, replaceItems=replace_menu)
xbmcplugin.addDirectoryItem(int(sys.argv[1]), liz_url, list_item, isFolder=is_folder, totalItems=total_items)
def parse_query(query):
q = {'mode': 'main'}
if query.startswith('?'): query = query[1:]
queries = urlparse.parse_qs(query)
for key in queries:
if len(queries[key]) == 1:
q[key] = queries[key][0]
else:
q[key] = queries[key]
return q
def notify(header=None, msg='', duration=2000, sound=None):
if header is None: header = get_name()
if sound is None: sound = get_setting('mute_notifications') == 'false'
icon_path = os.path.join(get_path(), 'icon.png')
try:
xbmcgui.Dialog().notification(header, msg, icon_path, duration, sound)
except:
builtin = "XBMC.Notification(%s,%s, %s, %s)" % (header, msg, duration, icon_path)
xbmc.executebuiltin(builtin)
def get_current_view():
skinPath = translate_path('special://skin/')
xml = os.path.join(skinPath, 'addon.xml')
f = xbmcvfs.File(xml)
read = f.read()
f.close()
try: src = re.search('defaultresolution="([^"]+)', read, re.DOTALL).group(1)
except: src = re.search('<res.+?folder="([^"]+)', read, re.DOTALL).group(1)
src = os.path.join(skinPath, src, 'MyVideoNav.xml')
f = xbmcvfs.File(src)
read = f.read()
f.close()
match = re.search('<views>([^<]+)', read, re.DOTALL)
if match:
views = match.group(1)
for view in views.split(','):
if xbmc.getInfoLabel('Control.GetLabel(%s)' % (view)): return view
| azumimuo/family-xbmc-addon | plugin.video.salts/salts_lib/kodi.py | Python | gpl-2.0 | 4,540 |
using System;
using System.Collections.Generic;
using UnityEngine;
using YinYang.CodeProject.Projects.SimplePathfinding.PathFinders.AStar;
namespace YinYang.CodeProject.Projects.SimplePathfinding.PathFinders
{
public abstract class BaseGraphSearchMap<TNode, TValue> where TNode : BaseGraphSearchNode<TNode, TValue>
{
#region | Fields |
private Dictionary<TValue, TNode> nodes;
#endregion
#region | Properties |
/// <summary>
/// Gets the open nodes count.
/// </summary>
public Int32 OpenCount
{
get { return OnGetCount(); }
}
public Dictionary<TValue, TNode> Nodes
{
get { return nodes; }
}
#endregion
#region | Indexers |
/// <summary>
/// Gets the <see cref="AStarNode"/> on a given coordinates.
/// </summary>
public TNode this[TValue value]
{
get { return nodes[value]; }
}
#endregion
#region | Constructors |
/// <summary>
/// Initializes a new instance of the <see cref="BaseGraphSearchMap{TNode}"/> class.
/// </summary>
protected BaseGraphSearchMap()
{
nodes = new Dictionary<TValue, TNode>();
}
#endregion
#region | Helper methods |
private void OpenNodeInternal(TValue value, TNode result)
{
nodes[value] = result;
OnAddNewNode(result);
}
#endregion
#region | Virtual/abstract methods |
protected abstract TNode OnCreateFirstNode(TValue startPosition, TValue endPosition);
protected abstract TNode OnCreateNode(TValue position, TNode origin, params object[] arguments);
protected abstract Int32 OnGetCount();
protected abstract void OnAddNewNode(TNode result);
protected abstract TNode OnGetTopNode();
protected abstract void OnClear();
#endregion
#region | Methods |
/// <summary>
/// Creates new open node on a map at given coordinates and parameters.
/// </summary>
public void OpenNode(TValue value, TNode origin, params object[] arguments)
{
TNode result = OnCreateNode(value, origin, arguments);
OpenNodeInternal(value, result);
}
public void OpenFirstNode(TValue startPosition, TValue endPosition)
{
TNode result = OnCreateFirstNode(startPosition, endPosition);
OpenNodeInternal(startPosition, result);
}
/// <summary>
/// Creates the empty node at given point.
/// </summary>
/// <param name="position">The point.</param>
/// <returns></returns>
public TNode CreateEmptyNode(TValue position)
{
return OnCreateNode(position, null);
}
/// <summary>
/// Returns top node (best estimated score), and closes it.
/// </summary>
/// <returns></returns>
public TNode CloseTopNode()
{
TNode result = OnGetTopNode();
result.MarkClosed();
return result;
}
/// <summary>
/// Clears map for another round.
/// </summary>
public void Clear()
{
nodes.Clear();
OnClear();
}
#endregion
}
}
| lauw/Albion-Online-Bot | Albion/Merlin/Pathing/BaseGraphSearchMap.cs | C# | gpl-2.0 | 3,406 |
/*---------------------------------------------------------------------------*\
========= |
\\ / 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
Class
Foam::DICGaussSeidelSmoother
Description
Combined DIC/GaussSeidel smoother for symmetric
matrices in which DIC smoothing is followed by GaussSeidel to ensure that
any "spikes" created by the DIC sweeps are smoothed-out.
SourceFiles
DICGaussSeidelSmoother.C
\*---------------------------------------------------------------------------*/
#ifndef DICGaussSeidelSmoother_H
#define DICGaussSeidelSmoother_H
#include "DICSmoother.H"
#include "GaussSeidelSmoother.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class DICGaussSeidelSmoother Declaration
\*---------------------------------------------------------------------------*/
class DICGaussSeidelSmoother
:
public lduSmoother
{
// Private data
DICSmoother dicSmoother_;
GaussSeidelSmoother gsSmoother_;
public:
//- Runtime type information
TypeName("DICGaussSeidel");
// Constructors
//- Construct from matrix components
DICGaussSeidelSmoother
(
const lduMatrix& matrix,
const FieldField<Field, scalar>& coupleBouCoeffs,
const FieldField<Field, scalar>& coupleIntCoeffs,
const lduInterfaceFieldPtrsList& interfaces
);
// Member Functions
//- Execute smoothing
virtual void smooth
(
scalarField& psi,
const scalarField& Source,
const direction cmpt,
const label nSweeps
) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| Unofficial-Extend-Project-Mirror/openfoam-extend-Core-OpenFOAM-1.5-dev | src/OpenFOAM/matrices/lduMatrix/smoothers/DICGaussSeidel/DICGaussSeidelSmoother.H | C++ | gpl-2.0 | 3,048 |
/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*-
this file is part of rcssserver3D
Fri May 9 2003
Copyright (C) 2002,2003 Koblenz University
Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group
$Id$
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "soccerbase.h"
#include <oxygen/physicsserver/rigidbody.h>
#include <oxygen/physicsserver/spherecollider.h>
#include <oxygen/agentaspect/perceptor.h>
#include <oxygen/agentaspect/agentaspect.h>
#include <oxygen/sceneserver/sceneserver.h>
#include <oxygen/sceneserver/scene.h>
#include <oxygen/sceneserver/transform.h>
#include <oxygen/controlaspect/controlaspect.h>
#include <oxygen/gamecontrolserver/gamecontrolserver.h>
#include <gamestateaspect/gamestateaspect.h>
#include <soccerruleaspect/soccerruleaspect.h>
#include <agentstate/agentstate.h>
#include <ball/ball.h>
#include <oxygen/physicsserver/space.h>
#include <zeitgeist/leaf.h>
using namespace boost;
using namespace zeitgeist;
using namespace oxygen;
using namespace std;
using namespace salt;
bool
SoccerBase::GetSceneServer(const Leaf& base,
boost::shared_ptr<SceneServer>& scene_server)
{
scene_server = static_pointer_cast<SceneServer>
(base.GetCore()->Get("/sys/server/scene"));
if (scene_server.get() == 0)
{
base.GetLog()->Error()
<< "Error: (SoccerBase: " << base.GetName()
<< ") scene server not found.\n";
return false;
}
return true;
}
bool
SoccerBase::GetTransformParent(const Leaf& base,
boost::shared_ptr<Transform>& transform_parent)
{
transform_parent = dynamic_pointer_cast<Transform>
((base.FindParentSupportingClass<Transform>()).lock());
if (transform_parent.get() == 0)
{
base.GetLog()->Error()
<< "Error: (SoccerBase: " << base.GetName()
<< ") parent node is not derived from TransformNode\n";
return false;
}
return true;
}
bool
SoccerBase::GetAgentState(const boost::shared_ptr<Transform> transform,
boost::shared_ptr<AgentState>& agent_state)
{
agent_state =
dynamic_pointer_cast<AgentState>(transform->GetChild("AgentState", true));
if (agent_state.get() == 0)
{
return false;
}
return true;
}
bool
SoccerBase::GetAgentBody(const boost::shared_ptr<Transform> transform,
boost::shared_ptr<RigidBody>& agent_body)
{
agent_body = transform->FindChildSupportingClass<RigidBody>(true);
if (agent_body.get() == 0)
{
transform->GetLog()->Error()
<< "(SoccerBase) ERROR: " << transform->GetName()
<< " node has no Body child\n";
return false;
}
return true;
}
bool
SoccerBase::GetAgentBody(const Leaf& base, TTeamIndex idx,
int unum, boost::shared_ptr<RigidBody>& agent_body)
{
boost::shared_ptr<AgentState> agentState;
boost::shared_ptr<Transform> parent;
// get matching AgentState
if (!GetAgentState(base, idx, unum, agentState))
return false;
// get AgentAspect
if (!GetTransformParent(*agentState, parent))
return false;
// call GetAgentBody with matching AgentAspect
return GetAgentBody(parent, agent_body);
}
bool
SoccerBase::GetAgentState(const Leaf& base,
boost::shared_ptr<AgentState>& agent_state)
{
boost::shared_ptr<Transform> parent;
if (! GetTransformParent(base,parent))
{
return false;
}
return GetAgentState(parent,agent_state);
}
bool
SoccerBase::GetAgentState(const Leaf& base, TTeamIndex idx,
int unum, boost::shared_ptr<AgentState>& agentState)
{
static TAgentStateMap mAgentStateMapLeft;
static TAgentStateMap mAgentStateMapRight;
if (idx == TI_NONE)
return false;
// do we have a cached reference?
if (
idx == TI_LEFT &&
!mAgentStateMapLeft.empty()
)
{
TAgentStateMap::iterator iter = mAgentStateMapLeft.find(unum);
if (iter != mAgentStateMapLeft.end())
{
// is the pointer to the parent (AgentAspect) still valid
// (maybe the agent disconnected)?
if (!(iter->second)->GetParent().lock().get())
{
base.GetLog()->Error() << "(SoccerBase) WARNING: "
<< "AgentState has invalid parent! "
<< "The agent probably disconnected, removing from map."
<< "\n";
mAgentStateMapLeft.erase(iter);
}
else
{
agentState = (*iter).second;
return true;
}
}
}
else if (
idx == TI_RIGHT &&
!mAgentStateMapRight.empty()
)
{
TAgentStateMap::iterator iter = mAgentStateMapRight.find(unum);
if (iter != mAgentStateMapRight.end())
{
// is the pointer to the parent (AgentAspect) still valid
// (maybe the agent disconnected)?
if ((iter->second)->GetParent().lock().get() == 0)
{
base.GetLog()->Error() << "(SoccerBase) WARNING: "
<< "AgentState has invalid parent! "
<< "The agent probably disconnected, removing from map."
<< "\n";
mAgentStateMapRight.erase(iter);
}
else
{
agentState = (*iter).second;
return true;
}
}
}
// we have to get all agent states for this team
TAgentStateList agentStates;
GetAgentStates(base, agentStates, idx);
for (TAgentStateList::iterator iter = agentStates.begin();
iter != agentStates.end();
++iter)
{
if ((*iter)->GetUniformNumber() == unum)
{
agentState = *iter;
if (idx == TI_LEFT)
{
mAgentStateMapLeft[unum] = agentState;
}
else
{
mAgentStateMapRight[unum] = agentState;
}
return true;
}
}
return false;
}
bool
SoccerBase::GetAgentStates(const zeitgeist::Leaf& base,
TAgentStateList& agentStates,
TTeamIndex idx)
{
static boost::shared_ptr<GameControlServer> gameCtrl;
if (gameCtrl.get() == 0)
{
GetGameControlServer(base, gameCtrl);
if (gameCtrl.get() == 0)
{
base.GetLog()->Error() << "(SoccerBase) ERROR: can't get "
<< "GameControlServer\n";
return false;
}
}
GameControlServer::TAgentAspectList aspectList;
gameCtrl->GetAgentAspectList(aspectList);
GameControlServer::TAgentAspectList::iterator iter;
boost::shared_ptr<AgentState> agentState;
for (
iter = aspectList.begin();
iter != aspectList.end();
++iter
)
{
agentState = dynamic_pointer_cast<AgentState>((*iter)->GetChild("AgentState", true));
if (
agentState.get() != 0 &&
(
agentState->GetTeamIndex() == idx ||
idx == TI_NONE
)
)
{
agentStates.push_back(agentState);
}
}
return true;
}
bool
SoccerBase::GetGameState(const Leaf& base,
boost::shared_ptr<GameStateAspect>& game_state)
{
game_state = dynamic_pointer_cast<GameStateAspect>
(base.GetCore()->Get("/sys/server/gamecontrol/GameStateAspect"));
if (game_state.get() == 0)
{
base.GetLog()->Error()
<< "Error: (SoccerBase: " << base.GetName()
<< ") found no GameStateAspect\n";
return false;
}
return true;
}
bool
SoccerBase::GetSoccerRuleAspect(const Leaf& base,
boost::shared_ptr<SoccerRuleAspect> & soccer_rule_aspect)
{
soccer_rule_aspect = dynamic_pointer_cast<SoccerRuleAspect>
(base.GetCore()->Get("/sys/server/gamecontrol/SoccerRuleAspect"));
if (soccer_rule_aspect.get() == 0)
{
base.GetLog()->Error()
<< "Error: (SoccerBase: " << base.GetName()
<< " found no SoccerRuleAspect\n";
return false;
}
return true;
}
bool
SoccerBase::GetGameControlServer(const Leaf& base,
boost::shared_ptr<GameControlServer> & game_control_server)
{
static boost::shared_ptr<GameControlServer> gameControlServer;
if (gameControlServer.get() == 0)
{
gameControlServer = boost::dynamic_pointer_cast<GameControlServer>
(base.GetCore()->Get("/sys/server/gamecontrol"));
if (gameControlServer.get() == 0)
{
base.GetLog()->Error()
<< "Error: (SoccerBase: " << base.GetName()
<< " found no GameControlServer\n";
return false;
}
}
game_control_server = gameControlServer;
return true;
}
bool
SoccerBase::GetActiveScene(const Leaf& base,
boost::shared_ptr<Scene>& active_scene)
{
static boost::shared_ptr<SceneServer> sceneServer;
if (sceneServer.get() == 0)
{
if (! GetSceneServer(base,sceneServer))
{
base.GetLog()->Error()
<< "(SoccerBase) ERROR: " << base.GetName()
<< ", could not get SceneServer\n";
return false;
}
}
active_scene = sceneServer->GetActiveScene();
if (active_scene.get() == 0)
{
base.GetLog()->Error()
<< "ERROR: (SoccerBase: " << base.GetName()
<< ", SceneServer reports no active scene\n";
return false;
}
return true;
}
bool
SoccerBase::GetBody(const Leaf& base, boost::shared_ptr<RigidBody>& body)
{
boost::shared_ptr<Transform> parent;
if (! GetTransformParent(base,parent))
{
base.GetLog()->Error() << "(SoccerBase) ERROR: no transform parent "
<< "found in GetBody()\n";
return false;
}
body = dynamic_pointer_cast<RigidBody>(parent->FindChildSupportingClass<RigidBody>());
if (body.get() == 0)
{
base.GetLog()->Error()
<< "ERROR: (SoccerBase: " << base.GetName()
<< ") parent node has no Body child.";
return false;
}
return true;
}
bool
SoccerBase::GetBall(const Leaf& base, boost::shared_ptr<Ball>& ball)
{
static boost::shared_ptr<Scene> scene;
static boost::shared_ptr<Ball> ballRef;
if (scene.get() == 0)
{
if (! GetActiveScene(base,scene))
{
base.GetLog()->Error()
<< "(SoccerBase) ERROR: " << base.GetName()
<< ", could not get active scene.\n";
return false;
}
}
if (ballRef.get() == 0)
{
ballRef = dynamic_pointer_cast<Ball>
(base.GetCore()->Get(scene->GetFullPath() + "Ball"));
if (ballRef.get() == 0)
{
base.GetLog()->Error()
<< "(SoccerBase) ERROR: " << base.GetName()
<< ", found no ball node\n";
return false;
}
}
ball = ballRef;
return true;
}
bool
SoccerBase::GetBallBody(const Leaf& base, boost::shared_ptr<RigidBody>& body)
{
static boost::shared_ptr<Scene> scene;
static boost::shared_ptr<RigidBody> bodyRef;
if (scene.get() == 0)
{
if (! GetActiveScene(base,scene))
{
base.GetLog()->Error()
<< "(SoccerBase) ERROR: " << base.GetName()
<< ", could not get active scene.\n";
return false;
}
}
if (bodyRef.get() == 0)
{
bodyRef = dynamic_pointer_cast<RigidBody>
(base.GetCore()->Get(scene->GetFullPath() + "Ball/physics"));
if (bodyRef.get() == 0)
{
base.GetLog()->Error()
<< "(SoccerBase) ERROR: " << base.GetName()
<< ", found no ball body node\n";
return false;
}
}
body = bodyRef;
return true;
}
bool
SoccerBase::GetBallCollider(const zeitgeist::Leaf& base,
boost::shared_ptr<oxygen::SphereCollider>& sphere)
{
static boost::shared_ptr<Scene> scene;
static boost::shared_ptr<SphereCollider> sphereRef;
if (scene.get() == 0)
{
if (! GetActiveScene(base,scene))
{
base.GetLog()->Error()
<< "(SoccerBase) ERROR: " << base.GetName()
<< ", could not get active scene.\n";
return false;
}
}
if (sphereRef.get() == 0)
{
sphereRef = dynamic_pointer_cast<SphereCollider>
(base.GetCore()->Get(scene->GetFullPath() + "Ball/geometry"));
if (sphereRef.get() == 0)
{
base.GetLog()->Error()
<< "(SoccerBase) ERROR:" << base.GetName()
<< ", Ball got no SphereCollider node\n";
return false;
}
}
sphere = sphereRef;
return true;
}
salt::Vector3f
SoccerBase::FlipView(const salt::Vector3f& pos, TTeamIndex ti)
{
salt::Vector3f newPos;
switch (ti)
{
case TI_RIGHT:
newPos[0] = -pos[0];
newPos[1] = -pos[1];
newPos[2] = pos[2];
break;
case TI_NONE:
case TI_LEFT:
newPos = pos;
break;
}
return newPos;
}
TTeamIndex
SoccerBase::OpponentTeam(TTeamIndex ti)
{
switch (ti)
{
case TI_RIGHT:
return TI_LEFT;
case TI_LEFT:
return TI_RIGHT;
default:
return TI_NONE;
}
}
string
SoccerBase::PlayMode2Str(const TPlayMode mode)
{
switch (mode)
{
case PM_BeforeKickOff:
return STR_PM_BeforeKickOff;
case PM_KickOff_Left:
return STR_PM_KickOff_Left;
case PM_KickOff_Right:
return STR_PM_KickOff_Right;
case PM_PlayOn:
return STR_PM_PlayOn;
case PM_KickIn_Left:
return STR_PM_KickIn_Left;
case PM_KickIn_Right:
return STR_PM_KickIn_Right;
case PM_CORNER_KICK_LEFT:
return STR_PM_CORNER_KICK_LEFT;
case PM_CORNER_KICK_RIGHT:
return STR_PM_CORNER_KICK_RIGHT;
case PM_GOAL_KICK_LEFT:
return STR_PM_GOAL_KICK_LEFT;
case PM_GOAL_KICK_RIGHT:
return STR_PM_GOAL_KICK_RIGHT;
case PM_OFFSIDE_LEFT:
return STR_PM_OFFSIDE_LEFT;
case PM_OFFSIDE_RIGHT:
return STR_PM_OFFSIDE_RIGHT;
case PM_GameOver:
return STR_PM_GameOver;
case PM_Goal_Left:
return STR_PM_Goal_Left;
case PM_Goal_Right:
return STR_PM_Goal_Right;
case PM_FREE_KICK_LEFT:
return STR_PM_FREE_KICK_LEFT;
case PM_FREE_KICK_RIGHT:
return STR_PM_FREE_KICK_RIGHT;
default:
return STR_PM_Unknown;
};
}
boost::shared_ptr<ControlAspect>
SoccerBase::GetControlAspect(const zeitgeist::Leaf& base,const string& name)
{
static const string gcsPath = "/sys/server/gamecontrol/";
boost::shared_ptr<ControlAspect> aspect = dynamic_pointer_cast<ControlAspect>
(base.GetCore()->Get(gcsPath + name));
if (aspect.get() == 0)
{
base.GetLog()->Error()
<< "ERROR: (SoccerBase: " << base.GetName()
<< ") found no ControlAspect " << name << "\n";
}
return aspect;
}
bool
SoccerBase::MoveAgent(boost::shared_ptr<Transform> agent_aspect, const Vector3f& pos)
{
Vector3f agentPos = agent_aspect->GetWorldTransform().Pos();
boost::shared_ptr<Transform> parent = dynamic_pointer_cast<Transform>
(agent_aspect->FindParentSupportingClass<Transform>().lock());
if (parent.get() == 0)
{
agent_aspect->GetLog()->Error() << "(MoveAgent) ERROR: can't get parent node.\n";
return false;
}
Leaf::TLeafList leafList;
parent->ListChildrenSupportingClass<RigidBody>(leafList, true);
if (leafList.size() == 0)
{
agent_aspect->GetLog()->Error()
<< "(MoveAgent) ERROR: agent aspect doesn't have "
<< "children of type Body\n";
return false;
}
Leaf::TLeafList::iterator iter = leafList.begin();
// move all child bodies
for (; iter != leafList.end(); ++iter)
{
boost::shared_ptr<RigidBody> childBody =
dynamic_pointer_cast<RigidBody>(*iter);
Vector3f childPos = childBody->GetPosition();
childBody->SetPosition(pos + (childPos-agentPos));
childBody->SetVelocity(Vector3f(0,0,0));
childBody->SetAngularVelocity(Vector3f(0,0,0));
}
return true;
}
bool
SoccerBase::MoveAndRotateAgent(boost::shared_ptr<Transform> agent_aspect, const Vector3f& pos, float angle)
{
boost::shared_ptr<Transform> parent = dynamic_pointer_cast<Transform>
(agent_aspect->FindParentSupportingClass<Transform>().lock());
if (parent.get() == 0)
{
agent_aspect->GetLog()->Error() << "(MoveAndRotateAgent) ERROR: can't get parent node.\n";
return false;
}
Leaf::TLeafList leafList;
parent->ListChildrenSupportingClass<RigidBody>(leafList, true);
if (leafList.size() == 0)
{
agent_aspect->GetLog()->Error()
<< "(MoveAndRotateAgent) ERROR: agent aspect doesn't have "
<< "children of type Body\n";
return false;
}
boost::shared_ptr<RigidBody> body;
GetAgentBody(agent_aspect, body);
const Vector3f& agentPos = body->GetPosition();
Matrix bodyR = body->GetRotation();
bodyR.InvertRotationMatrix();
Matrix mat;
mat.RotationZ(gDegToRad(angle));
mat *= bodyR;
Leaf::TLeafList::iterator iter = leafList.begin();
// move all child bodies
for (;
iter != leafList.end();
++iter
)
{
boost::shared_ptr<RigidBody> childBody =
dynamic_pointer_cast<RigidBody>(*iter);
Vector3f childPos = childBody->GetPosition();
Matrix childR = childBody->GetRotation();
childR = mat*childR;
childBody->SetPosition(pos + mat.Rotate(childPos-agentPos));
childBody->SetVelocity(Vector3f(0,0,0));
childBody->SetAngularVelocity(Vector3f(0,0,0));
childBody->SetRotation(childR);
}
return true;
}
AABB3 SoccerBase::GetAgentBoundingBox(const Leaf& base)
{
AABB3 boundingBox;
boost::shared_ptr<Space> parent = base.FindParentSupportingClass<Space>().lock();
if (!parent)
{
base.GetLog()->Error()
<< "(GetAgentBoundingBox) ERROR: can't get parent node.\n";
return boundingBox;
}
/* We can't simply use the GetWorldBoundingBox of the space node, becuase
* (at least currently) it'll return a wrong answer. Currently, the space
* object is always at (0,0,0) which is encapsulated in the result of it's
* GetWorldBoundingBox method call.
*/
Leaf::TLeafList baseNodes;
parent->ListChildrenSupportingClass<BaseNode>(baseNodes);
if (baseNodes.empty())
{
base.GetLog()->Error()
<< "(GetAgentBoundingBox) ERROR: space object doesn't have any"
<< " children of type BaseNode.\n";
}
for (Leaf::TLeafList::iterator i = baseNodes.begin(); i!= baseNodes.end(); ++i)
{
boost::shared_ptr<BaseNode> node = static_pointer_cast<BaseNode>(*i);
boundingBox.Encapsulate(node->GetWorldBoundingBox());
}
return boundingBox;
}
AABB2 SoccerBase::GetAgentBoundingRect(const Leaf& base)
{
AABB2 boundingRect;
boost::shared_ptr<Space> parent = base.FindParentSupportingClass<Space>().lock();
if (!parent)
{
base.GetLog()->Error()
<< "(GetAgentBoundingBox) ERROR: can't get parent node.\n";
return boundingRect;
}
/* We can't simply use the GetWorldBoundingBox of the space node, becuase
* (at least currently) it'll return a wrong answer. Currently, the space
* object is always at (0,0,0) which is encapsulated in the result of it's
* GetWorldBoundingBox method call.
*/
Leaf::TLeafList baseNodes;
parent->ListChildrenSupportingClass<Collider>(baseNodes,true);
if (baseNodes.empty())
{
base.GetLog()->Error()
<< "(GetAgentBoundingBox) ERROR: space object doesn't have any"
<< " children of type BaseNode.\n";
}
for (Leaf::TLeafList::iterator i = baseNodes.begin(); i!= baseNodes.end(); ++i)
{
boost::shared_ptr<BaseNode> node = static_pointer_cast<BaseNode>(*i);
const AABB3 &box = node->GetWorldBoundingBox();
boundingRect.Encapsulate(box.minVec.x(), box.minVec.y());
boundingRect.Encapsulate(box.maxVec.x(), box.maxVec.y());
}
return boundingRect;
}
std::string SoccerBase::SPLState2Str(const spl::TSPLState state)
{
switch (state)
{
case spl::Initial:
return STR_SPL_STATE_INITIAL;
case spl::Ready:
return STR_SPL_STATE_READY;
case spl::Set:
return STR_SPL_STATE_SET;
case spl::Playing:
return STR_SPL_STATE_PLAYING;
case spl::Finished:
return STR_SPL_STATE_FINISHED;
case spl::Penalized:
return STR_SPL_STATE_PENALIZED;
default:
return STR_SPL_STATE_UNKNOWN;
}
}
| xuyuan/rcssserver3d-spl-release | plugin/soccer/soccerbase/soccerbase.cpp | C++ | gpl-2.0 | 22,704 |
# -*- coding: utf-8 -*-
#
# HnTool rules - php
# Copyright (C) 2009-2010 Candido Vieira <cvieira.br@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 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 os
import ConfigParser
import HnTool.modules.util
from HnTool.modules.rule import Rule as MasterRule
class Rule(MasterRule):
def __init__(self, options):
MasterRule.__init__(self, options)
self.short_name="php"
self.long_name="Checks security problems on php config file"
self.type="config"
self.required_files = ['/etc/php5/apache2/php.ini', '/etc/php5/cli/php.ini', '/etc/php.ini']
def requires(self):
return self.required_files
def analyze(self, options):
check_results = self.check_results
conf_files = self.required_files
for php_conf in conf_files:
if os.path.isfile(php_conf):
config = ConfigParser.ConfigParser()
try:
config.read(php_conf)
except ConfigParser.ParsingError, (errno, strerror):
check_results['info'].append('Could not parse %s: %s' % (php_conf, strerror))
continue
if not config.has_section('PHP'):
check_results['info'].append('%s is not a PHP config file' % (php_conf))
continue
if config.has_option('PHP', 'register_globals'):
rg = config.get('PHP', 'register_globals').lower()
if rg == 'on':
check_results['medium'].append('Register globals is on (%s)' % (php_conf))
elif rg == 'off':
check_results['ok'].append('Register globals is off (%s)' % (php_conf))
else:
check_results['info'].append('Unknown value for register globals (%s)' % (php_conf))
else:
check_results['info'].append('Register globals not found (%s)' % (php_conf))
if config.has_option('PHP', 'safe_mode'):
sm = config.get('PHP', 'safe_mode').lower()
if sm == 'on':
check_results['low'].append('Safe mode is on (fake security) (%s)' % (php_conf))
elif sm == 'off':
check_results['info'].append('Safe mode is off (%s)' % (php_conf))
else:
check_results['info'].append('Unknown value for safe mode (%s)' % (php_conf))
else:
check_results['info'].append('Safe mode not found (%s)' % (php_conf))
if config.has_option('PHP', 'display_errors'):
de = config.get('PHP', 'display_errors').lower()
if de == 'on':
check_results['medium'].append('Display errors is on (stdout) (%s)' % (php_conf))
elif de == 'off':
check_results['ok'].append('Display errors is off (%s)' % (php_conf))
elif de == 'stderr':
check_results['info'].append('Display errors set to stderr (%s)' % (php_conf))
else:
check_results['info'].append('Unknown value for display errors (%s)' % (php_conf))
else:
check_results['info'].append('Display errors not found (%s)' % (php_conf))
if config.has_option('PHP', 'expose_php'):
ep = config.get('PHP', 'expose_php').lower()
if ep == 'on':
check_results['low'].append('Expose PHP is on (%s)' % (php_conf))
elif ep == 'off':
check_results['ok'].append('Expose PHP is off (%s)' % (php_conf))
else:
check_results['info'].append('Unknown value for expose PHP (%s)' % (php_conf))
else:
check_results['info'].append('Expose PHP not found (%s)' % (php_conf))
return check_results
| hdoria/HnTool | HnTool/modules/php.py | Python | gpl-2.0 | 4,760 |
/* JavaScript User Interface Library -- Common datatypes for user elements
* Copyright 2010 Jaakko-Heikki Heusala <jhh@jhh.me>
* $Id: common.js 415 2010-10-15 05:00:51Z jheusala $
*/
/** Simple message box constructor
* @params type The message type: error, notice, info or success
* @params msg Message
*/
function UIMessage(type, msg) {
var undefined;
if(this instanceof arguments.callee) {
if(type === undefined) throw TypeError("type undefined");
if(msg === undefined) {
msg = type;
type = undefined;
}
this.type = type || "info";
this.msg = ""+msg;
} else {
return new UIMessage(type, msg);
}
}
/** Get the message as a string */
UIMessage.prototype.toString = function() {
return this.type + ": " + this.msg;
}
/** Convert to JSON using JSONObject extension */
UIMessage.prototype.toJSON = function() {
return new JSONObject("UIMessage", this.type + ":" + this.msg );
};
/* Setup reviver for JSONObject */
JSONObject.revivers.UIMessage = function(value) {
var parts = (""+value).split(":");
return new UIMessage(parts.shift(), parts.join(":"));
};
/* EOF */
| jheusala/jsui | lib/jsui/common.js | JavaScript | gpl-2.0 | 1,101 |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace PlaneGame
{
class ProgressBar
{
public Rectangle rc, fon;
protected int maxValue;
protected int value;
protected Texture2D texture;
protected int step;
public int maxLenght;
public ProgressBar(Texture2D textur, int height = 30, int value = 0, int maxValue = 100, int maxLenght = 200)
{
this.texture = textur;
this.value = value;
this.maxValue = maxValue;
this.maxLenght = maxLenght;
step = maxLenght / maxValue;
rc = new Rectangle(0, 0, 1, height);
fon = new Rectangle(0, 0, this.maxLenght, height);
}
public void setValue(int val)
{
this.value = val;
this.rc.Width = (int)(value * step);
if (this.rc.Width > this.maxLenght)
{
this.rc.Width = this.maxLenght;
}
if (this.rc.Width < 1)
{
this.rc.Width = 1;
}
}
public void Draw(SpriteBatch sb,bool powernut, Color color, Color fonColor,float alpha,int x = 0, int y = 0)
{
if (powernut == true)
{
fon.X = rc.X = x;
fon.Y = rc.Y = y;
sb.Draw(texture, fon, null, fonColor * alpha, 0, Vector2.Zero, SpriteEffects.None, 0.9f);
sb.Draw(texture, rc, null, color * alpha, 0, Vector2.Zero, SpriteEffects.None, 1);
}
else
{
fon.X = rc.X = x+this.maxLenght;
fon.Y = rc.Y = y + this.fon.Height;
sb.Draw(texture, fon, null, fonColor * alpha, MathHelper.Pi, new Vector2(0, 0), SpriteEffects.None, 0.9f);
sb.Draw(texture, rc, null, color * alpha, MathHelper.Pi, new Vector2(0, 0), SpriteEffects.None, 1);
}
}
}
}
| macrocephalus/MegaGamesVortexLimited | MegaGamesVortexLimited/MegaGamesVortexLimited/ProgressBar.cs | C# | gpl-2.0 | 2,237 |
<!DOCTYPE html>
<html class="no-js" <?php language_attributes(); ?>>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title><?php wp_title(''); ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php wp_head(); ?>
<!--[if lt IE 9]><script src="<?php echo get_template_directory_uri(); ?>/assets/js/html5shiv.min.js"></script><![endif]-->
<link rel="alternate" type="application/rss+xml" title="<?php echo get_bloginfo('name'); ?> Feed" href="<?php echo home_url(); ?>/feed/">
</head>
| brandonhimpfen/Darkly-WordPress | templates/head.php | PHP | gpl-2.0 | 564 |
<?php
/**
* Shows a welcome or update message after the plugin is installed/updated
*/
class Tribe__Events__Activation_Page {
/** @var self */
private static $instance = null;
public function add_hooks() {
add_action( 'admin_init', array( $this, 'maybe_redirect' ), 10, 0 );
add_action( 'admin_menu', array( $this, 'register_page' ), 100, 0 ); // come in after the default page is registered
add_action( 'update_plugin_complete_actions', array( $this, 'update_complete_actions' ), 15, 2 );
add_action( 'update_bulk_plugins_complete_actions', array( $this, 'update_complete_actions' ), 15, 2 );
}
/**
* Filter the Default WordPress actions when updating the plugin to prevent users to be redirected if they have an
* specfific intention of going back to the plugins page.
*
* @param array $actions The Array of links (html)
* @param string $plugin Which plugins are been updated
* @return array The filtered Links
*/
public function update_complete_actions( $actions, $plugin ) {
$plugins = array();
if ( ! empty( $_GET['plugins'] ) ) {
$plugins = explode( ',', esc_attr( $_GET['plugins'] ) );
}
if ( ! in_array( Tribe__Events__Main::instance()->pluginDir . 'the-events-calendar.php', $plugins ) ){
return $actions;
}
if ( isset( $actions['plugins_page'] ) ) {
$actions['plugins_page'] = '<a href="' . esc_url( self_admin_url( 'plugins.php?tec-skip-welcome' ) ) . '" title="' . esc_attr__( 'Go to plugins page' ) . '" target="_parent">' . esc_html__( 'Return to Plugins page' ) . '</a>';
if ( ! current_user_can( 'activate_plugins' ) ){
unset( $actions['plugins_page'] );
}
}
if ( isset( $actions['updates_page'] ) ) {
$actions['updates_page'] = '<a href="' . esc_url( self_admin_url( 'update-core.php?tec-skip-welcome' ) ) . '" title="' . esc_attr__( 'Go to WordPress Updates page' ) . '" target="_parent">' . esc_html__( 'Return to WordPress Updates' ) . '</a>';
}
return $actions;
}
public function maybe_redirect() {
if ( ! empty( $_POST ) ) {
return; // don't interrupt anything the user's trying to do
}
if ( ! is_admin() || defined( 'DOING_AJAX' ) ) {
return;
}
if ( defined( 'IFRAME_REQUEST' ) && IFRAME_REQUEST ) {
return; // probably the plugin update/install iframe
}
if ( isset( $_GET['tec-welcome-message'] ) || isset( $_GET['tec-update-message'] ) ) {
return; // no infinite redirects
}
if ( isset( $_GET['tec-skip-welcome'] ) ) {
return; // a way to skip these checks and
}
// bail if we aren't activating a plugin
if ( ! get_transient( '_tribe_events_activation_redirect' ) ) {
return;
}
delete_transient( '_tribe_events_activation_redirect' );
if ( ! current_user_can( Tribe__Events__Settings::instance()->requiredCap ) ){
return;
}
if ( $this->showed_update_message_for_current_version() ) {
return;
}
// the redirect might be intercepted by another plugin, but
// we'll go ahead and mark it as viewed right now, just in case
// we end up in a redirect loop
// see #31088
$this->log_display_of_message_page();
if ( $this->is_new_install() ) {
$this->redirect_to_welcome_page();
}
/*
* TODO: determine if we wish to keep the update splash screen in the future
else {
$this->redirect_to_update_page();
}
*/
}
/**
* Have we shown the welcome/update message for the current version?
*
* @return bool
*/
protected function showed_update_message_for_current_version() {
$tec = Tribe__Events__Main::instance();
$message_version_displayed = $tec->getOption( 'last-update-message' );
if ( empty( $message_version_displayed ) ) {
return false;
}
if ( version_compare( $message_version_displayed, Tribe__Events__Main::VERSION, '<' ) ) {
return false;
}
return true;
}
protected function log_display_of_message_page() {
$tec = Tribe__Events__Main::instance();
$tec->setOption( 'last-update-message', Tribe__Events__Main::VERSION );
}
/**
* The previous_ecp_versions option will be empty or set to 0
* if the current version is the first version to be installed.
*
* @return bool
* @see Tribe__Events__Main::maybeSetTECVersion()
*/
protected function is_new_install() {
$tec = Tribe__Events__Main::instance();
$previous_versions = $tec->getOption( 'previous_ecp_versions' );
return empty( $previous_versions ) || ( end( $previous_versions ) == '0' );
}
protected function redirect_to_welcome_page() {
$url = $this->get_message_page_url( 'tec-welcome-message' );
wp_safe_redirect( $url );
exit();
}
protected function redirect_to_update_page() {
$url = $this->get_message_page_url( 'tec-update-message' );
wp_safe_redirect( $url );
exit();
}
protected function get_message_page_url( $slug ) {
$settings = Tribe__Events__Settings::instance();
// get the base settings page url
$url = apply_filters(
'tribe_settings_url', add_query_arg(
array(
'post_type' => Tribe__Events__Main::POSTTYPE,
'page' => $settings->adminSlug,
), admin_url( 'edit.php' )
)
);
$url = esc_url_raw( add_query_arg( $slug, 1, $url ) );
return $url;
}
public function register_page() {
// tribe_events_page_tribe-events-calendar
if ( isset( $_GET['tec-welcome-message'] ) ) {
$this->disable_default_settings_page();
add_action( 'tribe_events_page_tribe-events-calendar', array( $this, 'display_welcome_page' ) );
} elseif ( isset( $_GET['tec-update-message'] ) ) {
$this->disable_default_settings_page();
add_action( 'tribe_events_page_tribe-events-calendar', array( $this, 'display_update_page' ) );
}
}
protected function disable_default_settings_page() {
remove_action( 'tribe_events_page_tribe-events-calendar', array( Tribe__Events__Settings::instance(), 'generatePage' ) );
}
public function display_welcome_page() {
do_action( 'tribe_settings_top' );
echo '<div class="tribe_settings tribe_welcome_page wrap">';
echo '<h1>';
echo $this->welcome_page_title();
echo '</h1>';
echo $this->welcome_page_content();
echo '</div>';
do_action( 'tribe_settings_bottom' );
$this->log_display_of_message_page();
}
protected function welcome_page_title() {
return __( 'Welcome to The Events Calendar', 'the-events-calendar' );
}
protected function welcome_page_content() {
return $this->load_template( 'admin-welcome-message' );
}
public function display_update_page() {
do_action( 'tribe_settings_top' );
echo '<div class="tribe_settings tribe_update_page wrap">';
echo '<h1>';
echo $this->update_page_title();
echo '</h1>';
echo $this->update_page_content();
echo '</div>';
do_action( 'tribe_settings_bottom' );
$this->log_display_of_message_page();
}
protected function update_page_title() {
return __( 'Thanks for Updating The Events Calendar', 'the-events-calendar' );
}
protected function update_page_content() {
return $this->load_template( 'admin-update-message' );
}
protected function load_template( $name ) {
ob_start();
include trailingslashit( Tribe__Events__Main::instance()->pluginPath ) . 'src/admin-views/' . $name . '.php';
return ob_get_clean();
}
/**
* Initialize the global instance of the class.
*/
public static function init() {
self::instance()->add_hooks();
}
/**
* @return self
*/
public static function instance() {
if ( empty( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
}
| casedot/AllYourBaseTemplate | wp-content/plugins/the-events-calendar/src/Tribe/Activation_Page.php | PHP | gpl-2.0 | 7,703 |
<?php
/**
* @version 1.0 $Id$
* @package Joomla
* @subpackage redEVENT
* @copyright redEVENT (C) 2008 redCOMPONENT.com / EventList (C) 2005 - 2008 Christoph Lukes
* @license GNU/GPL, see LICENSE.php
* redEVENT is based on EventList made by Christoph Lukes from schlu.net
* redEVENT can be downloaded from www.redcomponent.com
* redEVENT is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License 2
* as published by the Free Software Foundation.
* redEVENT 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 redEVENT; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
defined('_JEXEC') or die('Restricted access');
?>
<form action="index.php" method="post" name="adminForm" id="adminForm">
<table class="adminform">
<tr>
<td width="100%">
<?php echo JText::_('COM_REDEVENT_SEARCH' );?>
<input type="text" name="search" id="search" value="<?php echo $this->lists['search']; ?>" class="text_area" onChange="document.adminForm.submit();" />
<button onclick="this.form.submit();"><?php echo JText::_('COM_REDEVENT_Go' ); ?></button>
<button onclick="this.form.getElementById('search').value='';this.form.submit();"><?php echo JText::_('COM_REDEVENT_Reset' ); ?></button>
</td>
</tr>
</table>
<table class="adminlist" cellspacing="1">
<thead>
<tr>
<th width="5">#</th>
<th width="20"><input type="checkbox" name="toggle" value="" onClick="checkAll(<?php echo count( $this->rows ); ?>);" /></th>
<th width="30%" class="title"><?php echo JHTML::_('grid.sort', 'COM_REDEVENT_GROUP_NAME', 'name', $this->lists['order_Dir'], $this->lists['order'] ); ?></th>
<th><?php echo JText::_('COM_REDEVENT_DESCRIPTION' ); ?></th>
<th width="5"><?php echo JText::_('COM_REDEVENT_Default' ); ?></th>
<th width="5"><?php echo JText::_('COM_REDEVENT_Members' ); ?></th>
<th width="5"><?php echo JText::_('COM_REDEVENT_Group_ACL' ); ?></th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="7">
<?php echo $this->pageNav->getListFooter(); ?>
</td>
</tr>
</tfoot>
<tbody>
<?php
$k = 0;
for($i=0, $n=count( $this->rows ); $i < $n; $i++) {
$row = &$this->rows[$i];
$link = 'index.php?option=com_redevent&controller=groups&task=edit&cid[]='.$row->id;
$checked = JHTML::_('grid.checkedout', $row, $i );
?>
<tr class="<?php echo "row$k"; ?>">
<td><?php echo $this->pageNav->getRowOffset( $i ); ?></td>
<td><?php echo $checked; ?></td>
<td>
<?php
if ( $row->checked_out && ( $row->checked_out != $this->user->get('id') ) ) {
echo htmlspecialchars($row->name, ENT_QUOTES, 'UTF-8');
} else {
?>
<span class="editlinktip hasTip" title="<?php echo JText::_('COM_REDEVENT_EDIT_GROUP' );?>::<?php echo $row->name; ?>">
<a href="<?php echo $link; ?>">
<?php echo htmlspecialchars($row->name, ENT_QUOTES, 'UTF-8'); ?>
</a></span>
<?php } ?>
</td>
<td><?php echo htmlspecialchars($row->description, ENT_QUOTES, 'UTF-8'); ?></td>
<td><?php echo ($row->isdefault ? 'yes' : 'no'); ?></td>
<td style="text-align:center;"><?php echo JHTML::link('index.php?option=com_redevent&controller=groups&task=editmembers&group_id='.$row->id,
$row->members . ' ' . JHTML::_( 'image', 'administrator/components/com_redevent/assets/images/groupmembers.png',
JText::_('COM_REDEVENT_Edit_group_members' ),
'title= "'. JText::_('COM_REDEVENT_Edit_group_members' ) . '"' )); ?>
</td>
<td style="text-align:center;"><?php echo JHTML::link('index.php?option=com_redevent&controller=groups&task=groupacl&group_id='.$row->id,
JHTML::_( 'image', 'administrator/components/com_redevent/assets/images/icon-16-categories.png',
JText::_('COM_REDEVENT_Edit_group_ACL' ),
'title= "'. JText::_('COM_REDEVENT_Edit_group_ACL' ) . '"' )); ?>
</td>
</tr>
<?php $k = 1 - $k; } ?>
</tbody>
</table>
<input type="hidden" name="boxchecked" value="0" />
<input type="hidden" name="option" value="com_redevent" />
<input type="hidden" name="controller" value="groups" />
<input type="hidden" name="view" value="groups" />
<input type="hidden" name="task" value="" />
<input type="hidden" name="filter_order" value="<?php echo $this->lists['order']; ?>" />
<input type="hidden" name="filter_order_Dir" value="<?php echo $this->lists['order_Dir']; ?>" />
</form> | jaanusnurmoja/redjoomla | administrator/components/com_redevent/views/groups/tmpl/default.php | PHP | gpl-2.0 | 4,833 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# progreso.py
#
# Copyright 2010 Jesús Hómez <jesus@jesus-laptop>
#
# 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 gtk, time
import threading
import thread
import gobject
#Iniciando el hilo sin usarlo
gtk.gdk.threads_init()
#La clase App hereda threading.Thread
class App(threading.Thread):
def __init__(self):
#Método constructor, asociando los widgets
self.glade_file = "progreso.glade"
self.glade = gtk.Builder()
self.glade.add_from_file(self.glade_file)
self.window1 = self.glade.get_object('window1')
self.togglebutton1 = self.glade.get_object('togglebutton1')
self.button1 = self.glade.get_object('button1')
self.progressbar1 = self.glade.get_object('progressbar1')
self.new_val = 0.0
self.rango =60
#Definiendo el valor inicial de la barra de proceso, definiendo los saltos en 0.1
self.progressbar1.set_fraction(self.new_val)
self.progressbar1.set_pulse_step(0.1)
self.window1.connect("destroy",self.on_window1_destroy)
self.button1.connect('clicked', self.on_button1_clicked)
self.togglebutton1.connect('toggled',self.on_togglebutton1_toggled)
#Iniciando el hilo en el constructor
threading.Thread.__init__(self)
self.window1.show_all()
def __iteracion__(self):
#Iteración en segundos cambiando el valor en la barra de progreso.
for i in range(self.rango):
if self.togglebutton1.get_active() == True:
self.new_val = self.progressbar1.get_fraction() + 0.01
if self.new_val > 1.0:
self.new_val = 0.0
self.togglebutton1.set_active(False)
break
else:
time.sleep(1)
self.x = self.new_val*100
self.progressbar1.set_text("%s" %self.x)
self.progressbar1.set_fraction(self.new_val)
else:
return
def on_togglebutton1_toggled(self,*args):
#Si cambia el evento en el boton biestado se inicia la iteración entre
los hilos.
variable = self.togglebutton1.get_active()
self.rango = 100
if variable == True:
lock = thread.allocate_lock()
lock.acquire()
thread.start_new_thread( self.__iteracion__, ())
lock.release()
else:
#Se detiene la barra de progreso
self.progressbar1.set_fraction(self.new_val)
self.progressbar1.set_text("%s" %self.x)
| jehomez/pymeadmin | progreso.py | Python | gpl-2.0 | 3,388 |
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2014 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
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 "Battery.hpp"
#ifdef HAVE_BATTERY
#if (defined(_WIN32_WCE) && !defined(GNAV))
#include <windows.h>
namespace Power
{
namespace Battery{
unsigned Temperature = 0;
unsigned RemainingPercent = 0;
bool RemainingPercentValid = false;
batterystatus Status = UNKNOWN;
};
namespace External{
externalstatus Status = UNKNOWN;
};
};
void
UpdateBatteryInfo()
{
SYSTEM_POWER_STATUS_EX2 sps;
// request the power status
DWORD result = GetSystemPowerStatusEx2(&sps, sizeof(sps), TRUE);
if (result >= sizeof(sps)) {
if (sps.BatteryLifePercent != BATTERY_PERCENTAGE_UNKNOWN){
Power::Battery::RemainingPercent = sps.BatteryLifePercent;
Power::Battery::RemainingPercentValid = true;
}
else
Power::Battery::RemainingPercentValid = false;
switch (sps.BatteryFlag) {
case BATTERY_FLAG_HIGH:
Power::Battery::Status = Power::Battery::HIGH;
break;
case BATTERY_FLAG_LOW:
Power::Battery::Status = Power::Battery::LOW;
break;
case BATTERY_FLAG_CRITICAL:
Power::Battery::Status = Power::Battery::CRITICAL;
break;
case BATTERY_FLAG_CHARGING:
Power::Battery::Status = Power::Battery::CHARGING;
break;
case BATTERY_FLAG_NO_BATTERY:
Power::Battery::Status = Power::Battery::NOBATTERY;
break;
case BATTERY_FLAG_UNKNOWN:
default:
Power::Battery::Status = Power::Battery::UNKNOWN;
}
switch (sps.ACLineStatus) {
case AC_LINE_OFFLINE:
Power::External::Status = Power::External::OFF;
break;
case AC_LINE_BACKUP_POWER:
case AC_LINE_ONLINE:
Power::External::Status = Power::External::ON;
break;
case AC_LINE_UNKNOWN:
default:
Power::External::Status = Power::External::UNKNOWN;
}
} else {
Power::Battery::Status = Power::Battery::UNKNOWN;
Power::External::Status = Power::External::UNKNOWN;
}
}
#endif
#ifdef KOBO
#include "OS/FileUtil.hpp"
#include <string.h>
#include <stdlib.h>
namespace Power
{
namespace Battery{
unsigned Temperature = 0;
unsigned RemainingPercent = 0;
bool RemainingPercentValid = false;
batterystatus Status = UNKNOWN;
};
namespace External{
externalstatus Status = UNKNOWN;
};
};
void
UpdateBatteryInfo()
{
// assume failure at entry
Power::Battery::RemainingPercentValid = false;
Power::Battery::Status = Power::Battery::UNKNOWN;
Power::External::Status = Power::External::UNKNOWN;
// code shamelessly copied from OS/SystemLoad.cpp
char line[256];
if (!File::ReadString("/sys/bus/platform/drivers/pmic_battery/pmic_battery.1/power_supply/mc13892_bat/uevent",
line, sizeof(line)))
return;
char field[80], value[80];
int n;
char* ptr = line;
while (sscanf(ptr, "%[^=]=%[^\n]\n%n", field, value, &n)==2) {
ptr += n;
if (!strcmp(field,"POWER_SUPPLY_STATUS")) {
if (!strcmp(value,"Not charging") || !strcmp(value,"Charging")) {
Power::External::Status = Power::External::ON;
} else if (!strcmp(value,"Discharging")) {
Power::External::Status = Power::External::OFF;
}
} else if (!strcmp(field,"POWER_SUPPLY_CAPACITY")) {
int rem = atoi(value);
Power::Battery::RemainingPercentValid = true;
Power::Battery::RemainingPercent = rem;
if (Power::External::Status == Power::External::OFF) {
if (rem>30) {
Power::Battery::Status = Power::Battery::HIGH;
} else if (rem>10) {
Power::Battery::Status = Power::Battery::LOW;
} else if (rem<10) {
Power::Battery::Status = Power::Battery::CRITICAL;
}
} else {
Power::Battery::Status = Power::Battery::CHARGING;
}
}
}
}
#endif
#endif
| robertscottbeattie/xcsoardev | src/Hardware/Battery.cpp | C++ | gpl-2.0 | 4,640 |
<?php
/**
* KohaRest ILS Driver
*
* PHP version 7
*
* Copyright (C) The National Library of Finland 2017-2019.
*
* 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.
*
* 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
*
* @category VuFind
* @package ILS_Drivers
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @author Juha Luoma <juha.luoma@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:ils_drivers Wiki
*/
namespace Finna\ILS\Driver;
use VuFind\Exception\ILS as ILSException;
/**
* VuFind Driver for Koha, using REST API
*
* Minimum Koha Version: work in progress as of 23 Jan 2017
*
* @category VuFind
* @package ILS_Drivers
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @author Juha Luoma <juha.luoma@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:ils_drivers Wiki
*/
class KohaRest extends \VuFind\ILS\Driver\KohaRest
{
/**
* Mappings from Koha messaging preferences
*
* @var array
*/
protected $messagingPrefTypeMap = [
'Advance_Notice' => 'dueDateAlert',
'Hold_Filled' => 'pickUpNotice',
'Item_Check_in' => 'checkinNotice',
'Item_Checkout' => 'checkoutNotice',
'Item_Due' => 'dueDateNotice'
];
/**
* Whether to use location in addition to branch when grouping holdings
*
* @param bool
*/
protected $groupHoldingsByLocation;
/**
* Priority settings for the order of branches or branch/location combinations
*
* @var array
*/
protected $holdingsBranchOrder;
/**
* Priority settings for the order of locations (in branches)
*
* @var array
*/
protected $holdingsLocationOrder;
/**
* Initialize the driver.
*
* Validate configuration and perform all resource-intensive tasks needed to
* make the driver active.
*
* @throws ILSException
* @return void
*/
public function init()
{
parent::init();
$this->groupHoldingsByLocation
= isset($this->config['Holdings']['group_by_location'])
? $this->config['Holdings']['group_by_location']
: '';
if (isset($this->config['Holdings']['holdings_branch_order'])) {
$values = explode(
':', $this->config['Holdings']['holdings_branch_order']
);
foreach ($values as $i => $value) {
$parts = explode('=', $value, 2);
$idx = $parts[1] ?? $i;
$this->holdingsBranchOrder[$parts[0]] = $idx;
}
}
$this->holdingsLocationOrder
= isset($this->config['Holdings']['holdings_location_order'])
? explode(':', $this->config['Holdings']['holdings_location_order'])
: [];
$this->holdingsLocationOrder = array_flip($this->holdingsLocationOrder);
}
/**
* Get Holding
*
* This is responsible for retrieving the holding information of a certain
* record.
*
* @param string $id The record id to retrieve the holdings for
* @param array $patron Patron data
* @param array $options Extra options
*
* @throws \VuFind\Exception\ILS
* @return array On success, an associative array with the following
* keys: id, availability (boolean), status, location, reserve, callnumber,
* duedate, number, barcode.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getHolding($id, array $patron = null, array $options = [])
{
$data = parent::getHolding($id, $patron);
if (!empty($data['holdings'])) {
$summary = $this->getHoldingsSummary($data['holdings']);
// Remove request counts before adding the summary if necessary
if (isset($this->config['Holdings']['display_item_hold_counts'])
&& !$this->config['Holdings']['display_item_hold_counts']
) {
foreach ($data['holdings'] as &$item) {
unset($item['requests_placed']);
}
}
$data['holdings'][] = $summary;
}
return $data;
}
/**
* Get Status
*
* This is responsible for retrieving the status information of a certain
* record.
*
* @param string $id The record id to retrieve the holdings for
*
* @return array An associative array with the following keys:
* id, availability (boolean), status, location, reserve, callnumber.
*/
public function getStatus($id)
{
$data = parent::getStatus($id);
if (!empty($data)) {
$summary = $this->getHoldingsSummary($data);
$data[] = $summary;
}
return $data;
}
/**
* Get Statuses
*
* This is responsible for retrieving the status information for a
* collection of records.
*
* @param array $ids The array of record ids to retrieve the status for
*
* @return mixed An array of getStatus() return values on success.
*/
public function getStatuses($ids)
{
$items = [];
foreach ($ids as $id) {
$statuses = $this->getItemStatusesForBiblio($id);
if (isset($statuses['holdings'])) {
$items[] = array_merge(
$statuses['holdings'],
$statuses['electronic_holdings']
);
} else {
$items[] = $statuses;
}
}
return $items;
}
/**
* Get Patron Fines
*
* This is responsible for retrieving all fines by a specific patron.
*
* @param array $patron The patron array from patronLogin
*
* @throws DateException
* @throws ILSException
* @return array Array of the patron's fines on success.
*/
public function getMyFines($patron)
{
$fines = parent::getMyFines($patron);
foreach ($fines as &$fine) {
$fine['payableOnline'] = true;
}
return $fines;
}
/**
* Get Patron Profile
*
* This is responsible for retrieving the profile for a specific patron.
*
* @param array $patron The patron array
*
* @throws ILSException
* @return array Array of the patron's profile data on success.
*/
public function getMyProfile($patron)
{
$result = $this->makeRequest(
['v1', 'patrons', $patron['id']], false, 'GET', $patron
);
$expirationDate = !empty($result['dateexpiry'])
? $this->dateConverter->convertToDisplayDate(
'Y-m-d', $result['dateexpiry']
) : '';
$guarantor = [];
$guarantees = [];
if (!empty($result['guarantorid'])) {
$guarantorRecord = $this->makeRequest(
['v1', 'patrons', $result['guarantorid']], false, 'GET', $patron
);
if ($guarantorRecord) {
$guarantor['firstname'] = $guarantorRecord['firstname'];
$guarantor['lastname'] = $guarantorRecord['surname'];
}
} else {
// Assume patron can have guarantees only if there is no guarantor
$guaranteeRecords = $this->makeRequest(
['v1', 'patrons'], ['guarantorid' => $patron['id']], 'GET',
$patron
);
foreach ($guaranteeRecords as $guarantee) {
$guarantees[] = [
'firstname' => $guarantee['firstname'],
'lastname' => $guarantee['surname']
];
}
}
list($resultCode, $messagingPrefs) = $this->makeRequest(
['v1', 'messaging_preferences'],
['borrowernumber' => $patron['id']],
'GET',
$patron,
true
);
$messagingSettings = [];
if (200 === $resultCode) {
foreach ($messagingPrefs as $type => $prefs) {
$typeName = isset($this->messagingPrefTypeMap[$type])
? $this->messagingPrefTypeMap[$type] : $type;
$settings = [
'type' => $typeName
];
if (isset($prefs['transport_types'])) {
$settings['settings']['transport_types'] = [
'type' => 'multiselect'
];
foreach ($prefs['transport_types'] as $key => $active) {
$settings['settings']['transport_types']['options'][$key] = [
'active' => $active
];
}
}
if (isset($prefs['digest'])) {
$settings['settings']['digest'] = [
'type' => 'boolean',
'name' => '',
'active' => $prefs['digest']['value'],
'readonly' => !$prefs['digest']['configurable']
];
}
if (isset($prefs['days_in_advance'])
&& ($prefs['days_in_advance']['configurable']
|| null !== $prefs['days_in_advance']['value'])
) {
$options = [];
for ($i = 0; $i <= 30; $i++) {
$options[$i] = [
'name' => $this->translate(
1 === $i ? 'messaging_settings_num_of_days'
: 'messaging_settings_num_of_days_plural',
['%%days%%' => $i]
),
'active' => $i == $prefs['days_in_advance']['value']
];
}
$settings['settings']['days_in_advance'] = [
'type' => 'select',
'value' => $prefs['days_in_advance']['value'],
'options' => $options,
'readonly' => !$prefs['days_in_advance']['configurable']
];
}
$messagingSettings[$type] = $settings;
}
}
$phoneField = isset($this->config['Profile']['phoneNumberField'])
? $this->config['Profile']['phoneNumberField']
: 'mobile';
return [
'firstname' => $result['firstname'],
'lastname' => $result['surname'],
'phone' => $phoneField && !empty($result[$phoneField])
? $result[$phoneField] : '',
'smsnumber' => $result['smsalertnumber'],
'email' => $result['email'],
'address1' => $result['address'],
'address2' => $result['address2'],
'zip' => $result['zipcode'],
'city' => $result['city'],
'country' => $result['country'],
'category' => $result['categorycode'] ?? '',
'expiration_date' => $expirationDate,
'hold_identifier' => $result['othernames'],
'guarantor' => $guarantor,
'guarantees' => $guarantees,
'loan_history' => $result['privacy'],
'messagingServices' => $messagingSettings,
'notes' => $result['opacnote'],
'full_data' => $result
];
}
/**
* Purge Patron Transaction History
*
* @param array $patron The patron array from patronLogin
*
* @throws ILSException
* @return array Associative array of the results
*/
public function purgeTransactionHistory($patron)
{
list($code, $result) = $this->makeRequest(
['v1', 'checkouts', 'history'],
['borrowernumber' => $patron['id']],
'DELETE',
$patron,
true
);
if (!in_array($code, [200, 202, 204])) {
return [
'success' => false,
'status' => 'Purging the loan history failed',
'sys_message' => $result['error'] ?? $code
];
}
return [
'success' => true,
'status' => 'loan_history_purged',
'sys_message' => ''
];
}
/**
* Update Patron Transaction History State
*
* Enable or disable patron's transaction history
*
* @param array $patron The patron array from patronLogin
* @param mixed $state Any of the configured values
*
* @return array Associative array of the results
*/
public function updateTransactionHistoryState($patron, $state)
{
$request = [
'privacy' => (int)$state
];
list($code, $result) = $this->makeRequest(
['v1', 'patrons', $patron['id']],
json_encode($request),
'PATCH',
$patron,
true
);
if (!in_array($code, [200, 202, 204])) {
return [
'success' => false,
'status' => 'Changing the checkout history state failed',
'sys_message' => $result['error'] ?? $code
];
}
return [
'success' => true,
'status' => $code == 202
? 'request_change_done' : 'request_change_accepted',
'sys_message' => ''
];
}
/**
* Update patron's phone number
*
* @param array $patron Patron array
* @param string $phone Phone number
*
* @throws ILSException
*
* @return array Associative array of the results
*/
public function updatePhone($patron, $phone)
{
$request = [
'mobile' => $phone
];
list($code, $result) = $this->makeRequest(
['v1', 'patrons', $patron['id']],
json_encode($request),
'PATCH',
$patron,
true
);
if (!in_array($code, [200, 202, 204])) {
return [
'success' => false,
'status' => 'Changing the phone number failed',
'sys_message' => $result['error'] ?? $code
];
}
return [
'success' => true,
'status' => $code == 202
? 'request_change_done' : 'request_change_accepted',
'sys_message' => ''
];
}
/**
* Update patron's SMS alert number
*
* @param array $patron Patron array
* @param string $number SMS alert number
*
* @throws ILSException
*
* @return array Associative array of the results
*/
public function updateSmsNumber($patron, $number)
{
$fields = !empty($this->config['updateSmsNumber']['fields'])
? explode(',', $this->config['updateSmsNumber']['fields'])
: ['smsalertnumber'];
$request = [];
foreach ($fields as $field) {
$request[$field] = $number;
}
list($code, $result) = $this->makeRequest(
['v1', 'patrons', $patron['id']],
json_encode($request),
'PATCH',
$patron,
true
);
if (!in_array($code, [200, 202, 204])) {
return [
'success' => false,
'status' => 'Changing the phone number failed',
'sys_message' => $result['error'] ?? $code
];
}
return [
'success' => true,
'status' => $code == 202
? 'request_change_done' : 'request_change_accepted',
'sys_message' => ''
];
}
/**
* Update patron's email address
*
* @param array $patron Patron array
* @param String $email Email address
*
* @throws ILSException
*
* @return array Associative array of the results
*/
public function updateEmail($patron, $email)
{
$request = [
'email' => $email
];
list($code, $result) = $this->makeRequest(
['v1', 'patrons', $patron['id']],
json_encode($request),
'PATCH',
$patron,
true
);
if (!in_array($code, [200, 202, 204])) {
return [
'success' => false,
'status' => 'Changing the email address failed',
'sys_message' => $result['error'] ?? $code
];
}
return [
'success' => true,
'status' => $code == 202
? 'request_change_done' : 'request_change_accepted',
'sys_message' => ''
];
}
/**
* Update patron contact information
*
* @param array $patron Patron array
* @param array $details Associative array of patron contact information
*
* @throws ILSException
*
* @return array Associative array of the results
*/
public function updateAddress($patron, $details)
{
$addressFields = [];
$fieldConfig = isset($this->config['updateAddress']['fields'])
? $this->config['updateAddress']['fields'] : [];
foreach ($fieldConfig as $field) {
$parts = explode(':', $field, 2);
if (isset($parts[1])) {
$addressFields[$parts[1]] = $parts[0];
}
}
// Pick the configured fields from the request
$request = [];
foreach ($details as $key => $value) {
if (isset($addressFields[$key])) {
$request[$key] = $value;
}
}
list($code, $result) = $this->makeRequest(
['v1', 'patrons', $patron['id']],
json_encode($request),
'PATCH',
$patron,
true
);
if (!in_array($code, [200, 202, 204])) {
if (409 === $code && !empty($result['conflict'])) {
$keys = array_keys($result['conflict']);
$key = reset($keys);
$fieldName = isset($addressFields[$key])
? $this->translate($addressFields[$key])
: '???';
$status = $this->translate(
'request_change_value_already_in_use',
['%%field%%' => $fieldName]
);
} else {
$status = 'Changing the contact information failed';
}
return [
'success' => false,
'status' => $status,
'sys_message' => $result['error'] ?? $code
];
}
return [
'success' => true,
'status' => $code == 202
? 'request_change_done' : 'request_change_accepted',
'sys_message' => ''
];
}
/**
* Update patron messaging settings
*
* @param array $patron Patron array
* @param array $details Associative array of messaging settings
*
* @throws ILSException
*
* @return array Associative array of the results
*/
public function updateMessagingSettings($patron, $details)
{
$messagingPrefs = $this->makeRequest(
['v1', 'messaging_preferences'],
['borrowernumber' => $patron['id']],
'GET',
$patron
);
$messagingSettings = [];
foreach ($details as $prefId => $pref) {
$result = [];
foreach ($pref['settings'] as $settingId => $setting) {
if (!empty($setting['readonly'])) {
continue;
}
if ('boolean' === $setting['type']) {
$result[$settingId] = [
'value' => $setting['active']
];
} elseif ('select' === $setting['type']) {
$result[$settingId] = [
'value' => ctype_digit($setting['value'])
? (int)$setting['value'] : $setting['value']
];
} else {
foreach ($setting['options'] as $optionId => $option) {
$result[$settingId][$optionId] = $option['active'];
}
}
}
$messagingSettings[$prefId] = $result;
}
list($code, $result) = $this->makeRequest(
['v1', 'messaging_preferences'],
[
'borrowernumber' => $patron['id'],
'##body##' => json_encode($messagingSettings)
],
'PUT',
$patron,
true
);
if ($code >= 300) {
return [
'success' => false,
'status' => 'Changing the preferences failed',
'sys_message' => $result['error'] ?? $code
];
}
return [
'success' => true,
'status' => $code == 202
? 'request_change_done' : 'request_change_accepted',
'sys_message' => ''
];
}
/**
* Change pickup location
*
* This is responsible for changing the pickup location of a hold
*
* @param string $patron Patron array
* @param string $holdDetails The request details
*
* @return array Associative array of the results
*/
public function changePickupLocation($patron, $holdDetails)
{
$requestId = $holdDetails['requestId'];
$pickUpLocation = $holdDetails['pickupLocationId'];
if (!$this->pickUpLocationIsValid($pickUpLocation, $patron, $holdDetails)) {
return $this->holdError('hold_invalid_pickup');
}
$request = [
'branchcode' => $pickUpLocation
];
list($code, $result) = $this->makeRequest(
['v1', 'holds', $requestId],
json_encode($request),
'PUT',
$patron,
true
);
if ($code >= 300) {
return $this->holdError($code, $result);
}
return ['success' => true];
}
/**
* Change request status
*
* This is responsible for changing the status of a hold request
*
* @param string $patron Patron array
* @param string $holdDetails The request details (at the moment only 'frozen'
* is supported)
*
* @return array Associative array of the results
*/
public function changeRequestStatus($patron, $holdDetails)
{
$requestId = $holdDetails['requestId'];
$frozen = !empty($holdDetails['frozen']);
$request = [
'suspend' => $frozen
];
list($code, $result) = $this->makeRequest(
['v1', 'holds', $requestId],
json_encode($request),
'PUT',
$patron,
true
);
if ($code >= 300) {
return $this->holdError($code, $result);
}
return ['success' => true];
}
/**
* Return total amount of fees that may be paid online.
*
* @param array $patron Patron
* @param array $fines Patron's fines
*
* @throws ILSException
* @return array Associative array of payment info,
* false if an ILSException occurred.
*/
public function getOnlinePayableAmount($patron, $fines)
{
if (!empty($fines)) {
$amount = 0;
foreach ($fines as $fine) {
$amount += $fine['balance'];
}
$config = $this->getConfig('onlinePayment');
$nonPayableReason = false;
if (isset($config['minimumFee']) && $amount < $config['minimumFee']) {
$nonPayableReason = 'online_payment_minimum_fee';
}
$res = ['payable' => empty($nonPayableReason), 'amount' => $amount];
if ($nonPayableReason) {
$res['reason'] = $nonPayableReason;
}
return $res;
}
return [
'payable' => false,
'amount' => 0,
'reason' => 'online_payment_minimum_fee'
];
}
/**
* Mark fees as paid.
*
* This is called after a successful online payment.
*
* @param array $patron Patron
* @param int $amount Amount to be registered as paid
* @param string $transactionId Transaction ID
* @param int $transactionNumber Internal transaction number
*
* @throws ILSException
* @return boolean success
*/
public function markFeesAsPaid($patron, $amount, $transactionId,
$transactionNumber
) {
$request = [
'amount' => $amount / 100,
'note' => "Online transaction $transactionId"
];
$operator = $patron;
if (!empty($this->config['onlinePayment']['userId'])
&& !empty($this->config['onlinePayment']['userPassword'])
) {
$operator = [
'cat_username' => $this->config['onlinePayment']['userId'],
'cat_password' => $this->config['onlinePayment']['userPassword']
];
}
list($code, $result) = $this->makeRequest(
['v1', 'patrons', $patron['id'], 'payment'],
json_encode($request),
'POST',
$operator,
true
);
if ($code != 204) {
$error = "Failed to mark payment of $amount paid for patron"
. " {$patron['id']}: $code: " . print_r($result, true);
$this->error($error);
throw new ILSException($error);
}
// Clear patron's block cache
$cacheId = 'blocks|' . $patron['id'];
$this->removeCachedData($cacheId);
return true;
}
/**
* Get a password recovery token for a user
*
* @param array $params Required params such as cat_username and email
*
* @return array Associative array of the results
*/
public function getPasswordRecoveryToken($params)
{
$request = [
'cardnumber' => $params['cat_username'],
'email' => $params['email'],
'skip_email' => true
];
$operator = [];
if (!empty($this->config['PasswordRecovery']['userId'])
&& !empty($this->config['PasswordRecovery']['userPassword'])
) {
$operator = [
'cat_username' => $this->config['PasswordRecovery']['userId'],
'cat_password' => $this->config['PasswordRecovery']['userPassword']
];
}
list($code, $result) = $this->makeRequest(
['v1', 'patrons', 'password', 'recovery'],
json_encode($request),
'POST',
$operator,
true
);
if (201 != $code) {
if (404 != $code) {
throw new ILSException("Failed to get a recovery token: $code");
}
return [
'success' => false,
'error' => $result['error']
];
}
return [
'success' => true,
'token' => $result['uuid']
];
}
/**
* Recover user's password with a token from getPasswordRecoveryToken
*
* @param array $params Required params such as cat_username, token and new
* password
*
* @return array Associative array of the results
*/
public function recoverPassword($params)
{
$request = [
'uuid' => $params['token'],
'new_password' => $params['password'],
'confirm_new_password' => $params['password']
];
$operator = [];
if (!empty($this->config['passwordRecovery']['userId'])
&& !empty($this->config['passwordRecovery']['userPassword'])
) {
$operator = [
'cat_username' => $this->config['passwordRecovery']['userId'],
'cat_password' => $this->config['passwordRecovery']['userPassword']
];
}
list($code, $result) = $this->makeRequest(
['v1', 'patrons', 'password', 'recovery', 'complete'],
json_encode($request),
'POST',
$operator,
true
);
if (200 != $code) {
return [
'success' => false,
'error' => $result['error']
];
}
return [
'success' => true
];
}
/**
* Get Patron Holds
*
* This is responsible for retrieving all holds by a specific patron.
*
* @param array $patron The patron array from patronLogin
*
* @throws DateException
* @throws ILSException
* @return array Array of the patron's holds on success.
*/
public function getMyHolds($patron)
{
$result = $this->makeRequest(
['v1', 'holds'],
['borrowernumber' => $patron['id']],
'GET',
$patron
);
if (!isset($result)) {
return [];
}
$holds = [];
foreach ($result as $entry) {
$bibId = $entry['biblionumber'] ?? null;
$itemId = $entry['itemnumber'] ?? null;
$title = '';
$volume = '';
if ($itemId) {
$item = $this->getItem($itemId);
$bibId = $item['biblionumber'] ?? null;
$volume = $item['enumchron'] ?? '';
}
if (!empty($bibId)) {
$bib = $this->getBibRecord($bibId);
$title = $bib['title'] ?? '';
if (!empty($bib['title_remainder'])) {
$title .= ' ' . $bib['title_remainder'];
$title = trim($title);
}
}
$frozen = false;
if (!empty($entry['suspend'])) {
$frozen = !empty($entry['suspend_until']) ? $entry['suspend_until']
: true;
}
$available = !empty($entry['waitingdate']);
$inTransit = isset($entry['found'])
&& strtolower($entry['found']) == 't';
$holds[] = [
'id' => $bibId,
'item_id' => $itemId ? $itemId : $entry['reserve_id'],
'location' => $entry['branchcode'],
'create' => $this->dateConverter->convertToDisplayDate(
'Y-m-d', $entry['reservedate']
),
'expire' => !empty($entry['expirationdate'])
? $this->dateConverter->convertToDisplayDate(
'Y-m-d', $entry['expirationdate']
) : '',
'position' => $entry['priority'],
'available' => $available,
'in_transit' => $inTransit,
'requestId' => $entry['reserve_id'],
'title' => $title,
'volume' => $volume,
'frozen' => $frozen,
'is_editable' => !$available && !$inTransit
];
}
return $holds;
}
/**
* Public Function which retrieves renew, hold and cancel settings from the
* driver ini file.
*
* @param string $function The name of the feature to be checked
* @param array $params Optional feature-specific parameters (array)
*
* @return array An array with key-value pairs.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getConfig($function, $params = null)
{
if ('getPasswordRecoveryToken' === $function
|| 'recoverPassword' === $function
) {
return !empty($this->config['PasswordRecovery']['enabled'])
? $this->config['PasswordRecovery'] : false;
} elseif ('getPatronStaffAuthorizationStatus' === $function) {
return ['enabled' => true];
}
$functionConfig = parent::getConfig($function, $params);
if ($functionConfig && 'onlinePayment' === $function) {
if (!isset($functionConfig['exactBalanceRequired'])) {
$functionConfig['exactBalanceRequired'] = false;
}
}
return $functionConfig;
}
/**
* Check if patron belongs to staff.
*
* @param array $patron The patron array from patronLogin
*
* @return bool True if patron is staff, false if not
*/
public function getPatronStaffAuthorizationStatus($patron)
{
$username = $patron['cat_username'];
if ($this->sessionCache->patron != $username) {
if (!$this->renewPatronCookie($patron)) {
return false;
}
}
return !empty(
array_intersect(
['superlibrarian', 'catalogue'],
$this->sessionCache->patronPermissions
)
);
}
/**
* Get Pick Up Locations
*
* This is responsible for gettting a list of valid library locations for
* holds / recall retrieval
*
* @param array $patron Patron information returned by the patronLogin
* method.
* @param array $holdDetails Optional array, only passed in when getting a list
* in the context of placing a hold; contains most of the same values passed to
* placeHold, minus the patron data. May be used to limit the pickup options
* or may be ignored. The driver must not add new options to the return array
* based on this data or other areas of VuFind may behave incorrectly.
*
* @throws ILSException
* @return array An array of associative arrays with locationID and
* locationDisplay keys
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getPickUpLocations($patron = false, $holdDetails = null)
{
$locations = [];
$section = array_key_exists('StorageRetrievalRequest', $holdDetails ?? [])
? 'StorageRetrievalRequests' : 'Holds';
$excluded = isset($this->config[$section]['excludePickupLocations'])
? explode(':', $this->config[$section]['excludePickupLocations']) : [];
$included = null;
if (!empty($this->config['Catalog']['availabilitySupportsPickupLocations'])
) {
$included = [];
$level = isset($holdDetails['level']) && !empty($holdDetails['level'])
? $holdDetails['level'] : 'copy';
$bibId = $holdDetails['id'];
$itemId = $holdDetails['item_id'] ?? false;
if ('copy' === $level && false === $itemId) {
return [];
}
// Collect branch codes that are to be included
if ('copy' === $level) {
$result = $this->makeRequest(
['v1', 'availability', 'item', 'hold'],
[
'itemnumber' => $itemId,
'borrowernumber' => (int)$patron['id'],
'query_pickup_locations' => 1
],
'GET',
$patron
);
if (empty($result)) {
return [];
}
$pickupLocs
= $result[0]['availability']['notes']['Item::PickupLocations']
?? [];
} else {
$result = $this->makeRequest(
['v1', 'availability', 'biblio', 'hold'],
[
'biblionumber' => $bibId,
'borrowernumber' => (int)$patron['id'],
'query_pickup_locations' => 1
],
'GET',
$patron
);
if (empty($result)) {
return [];
}
$pickupLocs
= $result[0]['availability']['notes']['Biblio::PickupLocations']
?? [];
}
foreach ($pickupLocs['to_libraries'] ?? [] as $code) {
$included[] = $code;
}
}
$result = $this->makeRequest(
['v1', 'libraries'],
false,
'GET',
$patron
);
if (empty($result)) {
return [];
}
foreach ($result as $location) {
$code = $location['branchcode'];
if ((null === $included && !$location['pickup_location'])
|| in_array($code, $excluded)
|| (null !== $included && !in_array($code, $included))
) {
continue;
}
$locations[] = [
'locationID' => $code,
'locationDisplay' => $location['branchname']
];
}
// Do we need to sort pickup locations? If the setting is false, don't
// bother doing any more work. If it's not set at all, default to
// alphabetical order.
$orderSetting = isset($this->config[$section]['pickUpLocationOrder'])
? $this->config[$section]['pickUpLocationOrder'] : 'default';
if (count($locations) > 1 && !empty($orderSetting)) {
$locationOrder = $orderSetting === 'default'
? [] : array_flip(explode(':', $orderSetting));
$sortFunction = function ($a, $b) use ($locationOrder) {
$aLoc = $a['locationID'];
$bLoc = $b['locationID'];
if (isset($locationOrder[$aLoc])) {
if (isset($locationOrder[$bLoc])) {
return $locationOrder[$aLoc] - $locationOrder[$bLoc];
}
return -1;
}
if (isset($locationOrder[$bLoc])) {
return 1;
}
return strcasecmp($a['locationDisplay'], $b['locationDisplay']);
};
usort($locations, $sortFunction);
}
return $locations;
}
/**
* Return summary of holdings items.
*
* @param array $holdings Parsed holdings items
*
* @return array summary
*/
protected function getHoldingsSummary($holdings)
{
$availableTotal = $itemsTotal = $reservationsTotal = 0;
$requests = 0;
$locations = [];
foreach ($holdings as $item) {
if (!empty($item['availability'])) {
$availableTotal++;
}
if (strncmp($item['item_id'], 'HLD_', 4) !== 0) {
$itemsTotal++;
}
$locations[$item['location']] = true;
if ($item['requests_placed'] > $requests) {
$requests = $item['requests_placed'];
}
}
// Since summary data is appended to the holdings array as a fake item,
// we need to add a few dummy-fields that VuFind expects to be
// defined for all elements.
// Use a stupid location name to make sure this doesn't get mixed with
// real items that don't have a proper location.
$result = [
'available' => $availableTotal,
'total' => $itemsTotal,
'locations' => count($locations),
'availability' => null,
'callnumber' => null,
'location' => '__HOLDINGSSUMMARYLOCATION__'
];
if (!empty($this->config['Holdings']['display_total_hold_count'])) {
$result['reservations'] = $requests;
}
return $result;
}
/**
* Return a location for a Koha item
*
* @param array $item Item
*
* @return string
*/
protected function getItemLocationName($item)
{
$result = parent::getItemLocationName($item);
if ($this->groupHoldingsByLocation) {
$location = $this->translateLocation(
$item['location'],
!empty($item['location_description'])
? $item['location_description'] : $item['location']
);
if ($location) {
// Empty translation will result in ‌
$emptyChar = html_entity_decode('‌', ENT_NOQUOTES, 'UTF-8');
if ($result && $result !== $emptyChar) {
$result .= ', ';
}
$result .= $location;
}
}
return $result;
}
/**
* Return a call number for a Koha item
*
* @param array $item Item
*
* @return string
*/
protected function getItemCallNumber($item)
{
$result = [];
if (!empty($item['ccode'])
&& !empty($this->config['Holdings']['display_ccode'])
) {
$result[] = $this->translateCollection(
$item['ccode'],
$item['ccode_description'] ?? $item['ccode']
);
}
if (!$this->groupHoldingsByLocation) {
$result[] = $this->translateLocation(
$item['location'],
!empty($item['location_description'])
? $item['location_description'] : $item['location']
);
}
if ((!empty($item['itemcallnumber'])
|| !empty($item['itemcallnumber_display']))
&& !empty($this->config['Holdings']['display_full_call_number'])
) {
if (!empty($this->config['Holdings']['use_non_display_call_number'])) {
$result[] = $item['itemcallnumber'];
} else {
$result[] = !empty($item['itemcallnumber_display'])
? $item['itemcallnumber_display'] : $item['itemcallnumber'];
}
}
$str = implode(', ', $result);
return $str;
}
/**
* Place Hold
*
* Attempts to place a hold or recall on a particular item and returns
* an array with result details or throws an exception on failure of support
* classes
*
* @param array $holdDetails An array of item and patron data
*
* @throws ILSException
* @return mixed An array of data on the request including
* whether or not it was successful and a system message (if available)
*/
public function placeHold($holdDetails)
{
$patron = $holdDetails['patron'];
$level = isset($holdDetails['level']) && !empty($holdDetails['level'])
? $holdDetails['level'] : 'copy';
$pickUpLocation = !empty($holdDetails['pickUpLocation'])
? $holdDetails['pickUpLocation'] : $this->defaultPickUpLocation;
$itemId = $holdDetails['item_id'] ?? false;
$comment = $holdDetails['comment'] ?? '';
$bibId = $holdDetails['id'];
// Convert last interest date from Display Format to Koha's required format
try {
$lastInterestDate = $this->dateConverter->convertFromDisplayDate(
'Y-m-d', $holdDetails['requiredBy']
);
} catch (DateException $e) {
// Hold Date is invalid
return $this->holdError('hold_date_invalid');
}
if ($level == 'copy' && empty($itemId)) {
throw new ILSException("Hold level is 'copy', but item ID is empty");
}
try {
$checkTime = $this->dateConverter->convertFromDisplayDate(
'U', $holdDetails['requiredBy']
);
if (!is_numeric($checkTime)) {
throw new DateException('Result should be numeric');
}
} catch (DateException $e) {
throw new ILSException('Problem parsing required by date.');
}
if (time() > $checkTime) {
// Hold Date is in the past
return $this->holdError('hold_date_past');
}
// Make sure pickup location is valid
if (!$this->pickUpLocationIsValid($pickUpLocation, $patron, $holdDetails)) {
return $this->holdError('hold_invalid_pickup');
}
$request = [
'biblionumber' => (int)$bibId,
'borrowernumber' => (int)$patron['id'],
'branchcode' => $pickUpLocation,
'reservenotes' => $comment,
'expirationdate' => $this->dateConverter->convertFromDisplayDate(
'Y-m-d', $holdDetails['requiredBy']
)
];
if ($level == 'copy') {
$request['itemnumber'] = (int)$itemId;
}
list($code, $result) = $this->makeRequest(
['v1', 'holds'],
json_encode($request),
'POST',
$patron,
true
);
if ($code >= 300) {
return $this->holdError($code, $result);
}
return ['success' => true];
}
/**
* Get Item Statuses
*
* This is responsible for retrieving the status information of a certain
* record.
*
* @param string $id The record id to retrieve the holdings for
* @param array $patron Patron information, if available
*
* @return array An associative array with the following keys:
* id, availability (boolean), status, location, reserve, callnumber.
*/
protected function getItemStatusesForBiblio($id, $patron = null)
{
$holdings = [];
if (!empty($this->config['Holdings']['use_holding_records'])) {
list($code, $holdingsResult) = $this->makeRequest(
['v1', 'biblios', $id, 'holdings'],
[],
'GET',
$patron,
true
);
if (404 === $code) {
return [];
}
if ($code !== 200) {
throw new ILSException('Problem with Koha REST API.');
}
// Turn the holdings into a keyed array
if (!empty($holdingsResult['holdings'])) {
foreach ($holdingsResult['holdings'] as $holding) {
$holdings[$holding['holding_id']] = $holding;
}
}
}
list($code, $result) = $this->makeRequest(
['v1', 'availability', 'biblio', 'search'],
['biblionumber' => $id],
'GET',
$patron,
true
);
if (404 === $code) {
return [];
}
if ($code !== 200) {
throw new ILSException('Problem with Koha REST API.');
}
$statuses = [];
foreach ($result[0]['item_availabilities'] ?? [] as $i => $item) {
// $holding is a reference!
unset($holding);
if (!empty($item['holding_id'])
&& isset($holdings[$item['holding_id']])
) {
$holding = &$holdings[$item['holding_id']];
if ($holding['suppress']) {
continue;
}
}
$avail = $item['availability'];
$available = $avail['available'];
$statusCodes = $this->getItemStatusCodes($item);
$status = $this->pickStatus($statusCodes);
if (isset($avail['unavailabilities']['Item::CheckedOut']['date_due'])) {
$duedate = $this->dateConverter->convertToDisplayDate(
'Y-m-d\TH:i:sP',
$avail['unavailabilities']['Item::CheckedOut']['date_due']
);
} else {
$duedate = null;
}
$location = $this->getItemLocationName($item);
$callnumber = $this->getItemCallNumber($item);
$sublocation = $item['sub_description'] ?? '';
$branchId = (!$this->useHomeBranch && null !== $item['holdingbranch'])
? $item['holdingbranch'] : $item['homebranch'];
$locationId = $item['location'];
$entry = [
'id' => $id,
'item_id' => $item['itemnumber'],
'location' => $location,
'department' => $sublocation,
'availability' => $available,
'status' => $status,
'status_array' => $statusCodes,
'reserve' => 'N',
'callnumber' => $callnumber,
'duedate' => $duedate,
'number' => $item['enumchron'],
'barcode' => $item['barcode'],
'sort' => $i,
'requests_placed' => max(
[$item['hold_queue_length'], $result[0]['hold_queue_length']]
),
'branchId' => $branchId,
'locationId' => $locationId
];
if (!empty($item['itemnotes'])) {
$entry['item_notes'] = [$item['itemnotes']];
}
if ($patron && $this->itemHoldAllowed($item)) {
$entry['is_holdable'] = true;
$entry['level'] = 'copy';
$entry['addLink'] = 'check';
} else {
$entry['is_holdable'] = false;
}
if ($patron && $this->itemArticleRequestAllowed($item)) {
$entry['storageRetrievalRequest'] = 'auto';
$entry['addStorageRetrievalRequestLink'] = 'check';
}
if (isset($holding)) {
$entry += $this->getHoldingData($holding);
$holding['_hasItems'] = true;
}
$statuses[] = $entry;
}
// $holding is a reference!
unset($holding);
if (!isset($i)) {
$i = 0;
}
// Add holdings that don't have items
if (!empty($holdings)) {
foreach ($holdings as $holding) {
if ($holding['suppress'] || !empty($holding['_hasItems'])) {
continue;
}
$holdingData = $this->getHoldingData($holding, true);
$i++;
$entry = $this->createHoldingEntry($id, $holding, $i);
$entry += $holdingData;
$statuses[] = $entry;
}
}
// See if there are links in holdings
$electronic = [];
if (!empty($holdings)) {
foreach ($holdings as $holding) {
$marc = $this->getHoldingMarc($holding);
if (null === $marc) {
continue;
}
$notes = [];
if ($fields = $marc->getFields('852')) {
foreach ($fields as $field) {
if ($subfield = $field->getSubfield('z')) {
$notes[] = $subfield->getData();
}
}
}
if ($fields = $marc->getFields('856')) {
foreach ($fields as $field) {
if ($subfields = $field->getSubfields()) {
$urls = [];
$desc = [];
$parts = [];
foreach ($subfields as $code => $subfield) {
if ('u' === $code) {
$urls[] = $subfield->getData();
} elseif ('3' === $code) {
$parts[] = $subfield->getData();
} elseif (in_array($code, ['y', 'z'])) {
$desc[] = $subfield->getData();
}
}
foreach ($urls as $url) {
++$i;
$entry
= $this->createHoldingEntry($id, $holding, $i);
$entry['availability'] = true;
$entry['location'] = implode('. ', $desc);
$entry['locationhref'] = $url;
$entry['use_unknown_message'] = false;
$entry['status']
= implode('. ', array_merge($parts, $notes));
$electronic[] = $entry;
}
}
}
}
}
}
usort($statuses, [$this, 'statusSortFunction']);
usort($electronic, [$this, 'statusSortFunction']);
return [
'holdings' => $statuses,
'electronic_holdings' => $electronic
];
}
/**
* Create a holding entry
*
* @param string $id Bib ID
* @param array $holding Holding
* @param int $sortKey Sort key
*
* @return array
*/
protected function createHoldingEntry($id, $holding, $sortKey)
{
$location = $this->getBranchName($holding['holdingbranch']);
$callnumber = '';
if (!empty($holding['ccode'])
&& !empty($this->config['Holdings']['display_ccode'])
) {
$callnumber = $this->translateCollection(
$holding['ccode'],
$holding['ccode_description'] ?? $holding['ccode']
);
}
if ($this->groupHoldingsByLocation) {
$holdingLoc = $this->translateLocation(
$holding['location'],
!empty($holding['location_description'])
? $holding['location_description'] : $holding['location']
);
if ($holdingLoc) {
if ($location) {
$location .= ', ';
}
$location .= $holdingLoc;
}
} else {
if ($callnumber) {
$callnumber .= ', ';
}
$callnumber .= $this->translateLocation(
$holding['location'],
!empty($holding['location_description'])
? $holding['location_description']
: $holding['location']
);
}
if ($holding['callnumber']) {
$callnumber .= ' ' . $holding['callnumber'];
}
$callnumber = trim($callnumber);
$branchId = $holding['holdingbranch'];
$locationId = $holding['location'];
return [
'id' => $id,
'item_id' => 'HLD_' . $holding['biblionumber'],
'location' => $location,
'requests_placed' => 0,
'status' => '',
'use_unknown_message' => true,
'availability' => false,
'duedate' => '',
'barcode' => '',
'callnumber' => $callnumber,
'sort' => $sortKey,
'branchId' => $branchId,
'locationId' => $locationId
];
}
/**
* Return a location for a Koha branch ID
*
* @param string $branchId Branch ID
*
* @return string
*/
protected function getBranchName($branchId)
{
$name = $this->translate("location_$branchId");
if ($name === "location_$branchId") {
$branches = $this->getCachedData('branches');
if (null === $branches) {
$result = $this->makeRequest(
['v1', 'libraries'], false, 'GET'
);
$branches = [];
foreach ($result as $branch) {
$branches[$branch['branchcode']] = $branch['branchname'];
}
$this->putCachedData('branches', $branches);
}
$name = $branches[$branchId] ?? $branchId;
}
return $name;
}
/**
* Get a MARC record for the given holding or null if not available
*
* @param array $holding Holding
*
* @return \File_MARCXML
*/
protected function getHoldingMarc(&$holding)
{
if (!isset($holding['_marcRecord'])) {
foreach ($holding['holdings_metadata'] ?? [$holding['metadata']]
as $metadata
) {
if ('marcxml' === $metadata['format']
&& 'MARC21' === $metadata['marcflavour']
) {
$marc = new \File_MARCXML(
$metadata['metadata'],
\File_MARCXML::SOURCE_STRING
);
$holding['_marcRecord'] = $marc->next();
return $holding['_marcRecord'];
}
}
$holding['_marcRecord'] = null;
}
return $holding['_marcRecord'];
}
/**
* Get holding data from a holding record
*
* @param array $holding Holding record from Koha
*
* @return array
*/
protected function getHoldingData(&$holding)
{
$marc = $this->getHoldingMarc($holding);
if (null === $marc) {
return [];
}
$marcDetails = [];
// Get Notes
$data = $this->getMFHDData(
$marc,
isset($this->config['Holdings']['notes'])
? $this->config['Holdings']['notes']
: '852z'
);
if ($data) {
$marcDetails['notes'] = $data;
}
// Get Summary (may be multiple lines)
$data = $this->getMFHDData(
$marc,
isset($this->config['Holdings']['summary'])
? $this->config['Holdings']['summary']
: '866a'
);
if ($data) {
$marcDetails['summary'] = $data;
}
// Get Supplements
if (isset($this->config['Holdings']['supplements'])) {
$data = $this->getMFHDData(
$marc,
$this->config['Holdings']['supplements']
);
if ($data) {
$marcDetails['supplements'] = $data;
}
}
// Get Indexes
if (isset($this->config['Holdings']['indexes'])) {
$data = $this->getMFHDData(
$marc,
$this->config['Holdings']['indexes']
);
if ($data) {
$marcDetails['indexes'] = $data;
}
}
// Get links
if (isset($this->config['Holdings']['links'])) {
$data = $this->getMFHDData(
$marc,
$this->config['Holdings']['links']
);
if ($data) {
$marcDetails['links'] = $data;
}
}
// Make sure to return an empty array unless we have details to display
if (!empty($marcDetails)) {
$marcDetails['holdings_id'] = $holding['holding_id'];
}
return $marcDetails;
}
/**
* Get specified fields from an MFHD MARC Record
*
* @param object $record File_MARC object
* @param array|string $fieldSpecs Array or colon-separated list of
* field/subfield specifications (3 chars for field code and then subfields,
* e.g. 866az)
*
* @return string|string[] Results as a string if single, array if multiple
*/
protected function getMFHDData($record, $fieldSpecs)
{
if (!is_array($fieldSpecs)) {
$fieldSpecs = explode(':', $fieldSpecs);
}
$results = '';
foreach ($fieldSpecs as $fieldSpec) {
$fieldCode = substr($fieldSpec, 0, 3);
$subfieldCodes = substr($fieldSpec, 3);
if ($fields = $record->getFields($fieldCode)) {
foreach ($fields as $field) {
if ($subfields = $field->getSubfields()) {
$line = '';
foreach ($subfields as $code => $subfield) {
if (!strstr($subfieldCodes, $code)) {
continue;
}
if ($line) {
$line .= ' ';
}
$line .= $subfield->getData();
}
if ($line) {
if (!$results) {
$results = $line;
} else {
if (!is_array($results)) {
$results = [$results];
}
$results[] = $line;
}
}
}
}
}
}
return $results;
}
/**
* Translate location name
*
* @param string $location Location code
* @param string $default Default value if translation is not available
*
* @return string
*/
protected function translateLocation($location, $default = null)
{
if (empty($location)) {
return null !== $default ? $default : '';
}
$prefix = $catPrefix = 'location_';
if (!empty($this->config['Catalog']['id'])) {
$catPrefix .= $this->config['Catalog']['id'] . '_';
}
return $this->translate(
"$catPrefix$location",
null,
$this->translate(
"$prefix$location",
null,
null !== $default ? $default : $location
)
);
}
/**
* Translate collection name
*
* @param string $code Collection code
* @param string $description Collection description
*
* @return string
*/
protected function translateCollection($code, $description)
{
$prefix = 'collection_';
if (!empty($this->config['Catalog']['id'])) {
$prefix .= $this->config['Catalog']['id'] . '_';
}
return $this->translate(
"$prefix$code",
null,
$description
);
}
/**
* Status item sort function
*
* @param array $a First status record to compare
* @param array $b Second status record to compare
*
* @return int
*/
protected function statusSortFunction($a, $b)
{
$orderA = $this->holdingsBranchOrder[$a['branchId'] . '/' . $a['locationId']]
?? $this->holdingsBranchOrder[$a['branchId']]
?? 999;
$orderB = $this->holdingsBranchOrder[$b['branchId'] . '/' . $b['locationId']]
?? $this->holdingsBranchOrder[$b['branchId']]
?? 999;
$result = $orderA - $orderB;
if (0 === $result) {
$orderA = $this->holdingsLocationOrder[$a['locationId']] ?? 999;
$orderB = $this->holdingsLocationOrder[$b['locationId']] ?? 999;
$result = $orderA - $orderB;
}
if (0 === $result) {
$result = strcmp($a['location'], $b['location']);
}
if (0 === $result && $this->sortItemsByEnumChron) {
// Reverse chronological order
$result = strnatcmp($b['number'] ?? '', $a['number'] ?? '');
}
if (0 === $result) {
$result = $a['sort'] - $b['sort'];
}
return $result;
}
}
| arto70/NDL-VuFind2 | module/Finna/src/Finna/ILS/Driver/KohaRest.php | PHP | gpl-2.0 | 64,182 |
package com.github.esadmin.meta.model;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import org.guess.core.orm.IdEntity;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* 索引对象Entity
* @author Joe.zhang
* @version 2015-12-08
*/
@Entity
@Table(name = "meta_dbindex")
@JsonIgnoreProperties(value = {"hibernateLazyInitializer","handler", "columns"})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class DBIndex extends IdEntity {
/**
* 数据表
*/
@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, targetEntity = DBTable.class)
@JoinTable(name = "meta_table_index", joinColumns = { @JoinColumn(name = "index_id") }, inverseJoinColumns = { @JoinColumn(name = "table_id") })
@JsonIgnoreProperties(value = { "hibernateLazyInitializer","handler","datasource"})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private Set<DBTable> tables = new HashSet<DBTable>(0);
/**
* 索引库名
*/
@Column(name="index_name")
private String index_name;
/**
* 索引表名
*/
@Column(name="type_name")
private String type_name;
/**
* 索引类别
*/
@Column(name="index_type")
private Integer indexType;
/**
* 建立者
*/
@Column(name="createby_id")
private Long createbyId;
/**
* 更新者
*/
@Column(name="updateby_id")
private Long updatebyId;
/**
* 建立世间
*/
@Column(name="create_date")
private Date createDate;
/**
* 更新世间
*/
@Column(name="update_date")
private Date updateDate;
/**
* 备注
*/
@Column(name="remark")
private String remark;
@OneToMany(targetEntity = DbColumn.class, fetch = FetchType.LAZY, cascade = CascadeType.ALL,mappedBy="dbindex")
@OrderBy("id ASC")
private Set<DbColumn> columns;
@Column(name="check_label")
private Integer checkLabel;
public Integer getCheckLabel() {
return checkLabel;
}
public void setCheckLabel(Integer checkLabel) {
this.checkLabel = checkLabel;
}
public Set<DBTable> getTables() {
return tables;
}
public void setTables(Set<DBTable> tables) {
this.tables = tables;
}
public String getIndex_name() {
return index_name;
}
public void setIndex_name(String index_name) {
this.index_name = index_name;
}
public String getType_name() {
return type_name;
}
public void setType_name(String type_name) {
this.type_name = type_name;
}
public Integer getIndexType() {
return indexType;
}
public void setIndexType(Integer indexType) {
this.indexType = indexType;
}
public Long getCreatebyId() {
return createbyId;
}
public void setCreatebyId(Long createbyId) {
this.createbyId = createbyId;
}
public Set<DbColumn> getColumns() {
return columns;
}
public void setColumns(Set<DbColumn> columns) {
this.columns = columns;
}
public Long getUpdatebyId() {
return updatebyId;
}
public void setUpdatebyId(Long updatebyId) {
this.updatebyId = updatebyId;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
} | joezxh/DATAX-UI | eshbase-proxy/src/main/java/com/github/esadmin/meta/model/DBIndex.java | Java | gpl-2.0 | 3,790 |
<?php
/* core/themes/stable/templates/block/block--system-messages-block.html.twig */
class __TwigTemplate_0c8ec01fa0528f682259cd616ff9ee5ee8ceeeb5ec7cf0b3ece249a3727465d5 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$tags = array();
$filters = array();
$functions = array();
try {
$this->env->getExtension('sandbox')->checkSecurity(
array(),
array(),
array()
);
} catch (Twig_Sandbox_SecurityError $e) {
$e->setTemplateFile($this->getTemplateName());
if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
$e->setTemplateLine($tags[$e->getTagName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
$e->setTemplateLine($filters[$e->getFilterName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
$e->setTemplateLine($functions[$e->getFunctionName()]);
}
throw $e;
}
// line 13
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["content"]) ? $context["content"] : null), "html", null, true));
echo "
";
}
public function getTemplateName()
{
return "core/themes/stable/templates/block/block--system-messages-block.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 43 => 13,);
}
}
/* {#*/
/* /***/
/* * @file*/
/* * Theme override for the messages block.*/
/* **/
/* * Removes wrapper elements from block so that empty block does not appear when*/
/* * there are no messages.*/
/* **/
/* * Available variables:*/
/* * - content: The content of this block.*/
/* *//* */
/* #}*/
/* {{ content }}*/
/* */
| dhrubajs/drupal_8.0.3 | sites/default/files/php/twig/bdd6b639_block--system-messages-block.html.twig_41faf232cd42e8ec796f15a9bb08f1a5f7eaf6bd977aaa861b52c4ad353c5f10/41244d26af175744d9765a17dcb06990bbb9472557ce348f7ba1670b703f8a3d.php | PHP | gpl-2.0 | 2,313 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
( function($) {
} )( jQuery );
var waitForFinalEvent = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) {
uniqueId = "Don't call this twice without a uniqueId";
}
if (timers[uniqueId]) {
clearTimeout (timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})(); | jsxmedia/jgm-wp-theme | js/global-functions.js | JavaScript | gpl-2.0 | 566 |
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information
* 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: Instance_Sunwell_Plateau
SD%Complete: 70%
SDComment:
SDCategory: Sunwell_Plateau
EndScriptData */
#include "precompiled.h"
#include "sunwell_plateau.h"
/* Sunwell Plateau:
0 - Kalecgos and Sathrovarr
1 - Brutallus
2 - Felmyst
3 - Eredar Twins (Alythess and Sacrolash)
4 - M'uru
5 - Kil'Jaeden
*/
static const DialogueEntry aFelmystOutroDialogue[] =
{
{NPC_KALECGOS_MADRIGOSA, 0, 10000},
{SAY_KALECGOS_OUTRO, NPC_KALECGOS_MADRIGOSA, 5000},
{NPC_FELMYST, 0, 5000},
{SPELL_OPEN_BACK_DOOR, 0, 9000},
{NPC_BRUTALLUS, 0, 0},
{0, 0, 0},
};
instance_sunwell_plateau::instance_sunwell_plateau(Map* pMap) : ScriptedInstance(pMap), DialogueHelper(aFelmystOutroDialogue),
m_uiDeceiversKilled(0),
m_uiSpectralRealmTimer(5000),
m_uiKalecRespawnTimer(0),
m_uiMuruBerserkTimer(0),
m_uiKiljaedenYellTimer(90000)
{
Initialize();
}
void instance_sunwell_plateau::Initialize()
{
memset(&m_auiEncounter, 0, sizeof(m_auiEncounter));
InitializeDialogueHelper(this);
}
bool instance_sunwell_plateau::IsEncounterInProgress() const
{
for (uint8 i = 0; i < MAX_ENCOUNTER; ++i)
{
if (m_auiEncounter[i] == IN_PROGRESS)
return true;
}
return false;
}
void instance_sunwell_plateau::OnPlayerEnter(Player* pPlayer)
{
// Return if Felmyst already dead, or Brutallus alive
if (m_auiEncounter[TYPE_BRUTALLUS] != DONE || m_auiEncounter[TYPE_FELMYST] == DONE)
return;
// Return if already summoned
if (GetSingleCreatureFromStorage(NPC_FELMYST, true))
return;
// Summon Felmyst in reload case
pPlayer->SummonCreature(NPC_FELMYST, aMadrigosaLoc[0].m_fX, aMadrigosaLoc[0].m_fY, aMadrigosaLoc[0].m_fZ, aMadrigosaLoc[0].m_fO, TEMPSUMMON_DEAD_DESPAWN, 0);
}
void instance_sunwell_plateau::OnCreatureCreate(Creature* pCreature)
{
switch (pCreature->GetEntry())
{
case NPC_KALECGOS_DRAGON:
case NPC_KALECGOS_HUMAN:
case NPC_SATHROVARR:
case NPC_FLIGHT_TRIGGER_LEFT:
case NPC_FLIGHT_TRIGGER_RIGHT:
case NPC_MADRIGOSA:
case NPC_BRUTALLUS:
case NPC_FELMYST:
case NPC_KALECGOS_MADRIGOSA:
case NPC_ALYTHESS:
case NPC_SACROLASH:
case NPC_MURU:
case NPC_ENTROPIUS:
case NPC_KILJAEDEN_CONTROLLER:
case NPC_KILJAEDEN:
case NPC_KALECGOS:
case NPC_ANVEENA:
case NPC_VELEN:
case NPC_LIADRIN:
m_mNpcEntryGuidStore[pCreature->GetEntry()] = pCreature->GetObjectGuid();
break;
case NPC_DECEIVER:
m_lDeceiversGuidList.push_back(pCreature->GetObjectGuid());
break;
case NPC_WORLD_TRIGGER:
// sort triggers for flightpath
if (pCreature->GetPositionZ() < 51.0f)
m_lAllFlightTriggersList.push_back(pCreature->GetObjectGuid());
break;
case NPC_WORLD_TRIGGER_LARGE:
if (pCreature->GetPositionY() < 523.0f)
m_lBackdoorTriggersList.push_back(pCreature->GetObjectGuid());
break;
}
}
void instance_sunwell_plateau::OnCreatureDeath(Creature* pCreature)
{
if (pCreature->GetEntry() == NPC_DECEIVER)
{
++m_uiDeceiversKilled;
// Spawn Kiljaeden when all deceivers are killed
if (m_uiDeceiversKilled == MAX_DECEIVERS)
{
if (Creature* pController = GetSingleCreatureFromStorage(NPC_KILJAEDEN_CONTROLLER))
{
if (Creature* pKiljaeden = pController->SummonCreature(NPC_KILJAEDEN, pController->GetPositionX(), pController->GetPositionY(), pController->GetPositionZ(), pController->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 0))
pKiljaeden->SetInCombatWithZone();
pController->RemoveAurasDueToSpell(SPELL_ANVEENA_DRAIN);
}
}
}
}
void instance_sunwell_plateau::OnCreatureEvade(Creature* pCreature)
{
// Reset encounter if raid wipes at deceivers
if (pCreature->GetEntry() == NPC_DECEIVER)
SetData(TYPE_KILJAEDEN, FAIL);
}
void instance_sunwell_plateau::OnObjectCreate(GameObject* pGo)
{
switch (pGo->GetEntry())
{
case GO_FORCEFIELD:
case GO_BOSS_COLLISION_1:
case GO_BOSS_COLLISION_2:
case GO_ICE_BARRIER:
break;
case GO_FIRE_BARRIER:
if (m_auiEncounter[TYPE_KALECGOS] == DONE && m_auiEncounter[TYPE_BRUTALLUS] == DONE && m_auiEncounter[TYPE_FELMYST] == DONE)
pGo->SetGoState(GO_STATE_ACTIVE);
break;
case GO_FIRST_GATE:
break;
case GO_SECOND_GATE:
if (m_auiEncounter[TYPE_EREDAR_TWINS] == DONE)
pGo->SetGoState(GO_STATE_ACTIVE);
break;
case GO_MURU_ENTER_GATE:
if (m_auiEncounter[TYPE_EREDAR_TWINS] == DONE)
pGo->SetGoState(GO_STATE_ACTIVE);
break;
case GO_MURU_EXIT_GATE:
if (m_auiEncounter[TYPE_MURU] == DONE)
pGo->SetGoState(GO_STATE_ACTIVE);
break;
case GO_THIRD_GATE:
if (m_auiEncounter[TYPE_MURU] == DONE)
pGo->SetGoState(GO_STATE_ACTIVE);
break;
case GO_ORB_BLUE_FLIGHT_1:
case GO_ORB_BLUE_FLIGHT_2:
case GO_ORB_BLUE_FLIGHT_3:
case GO_ORB_BLUE_FLIGHT_4:
break;
default:
return;
}
m_mGoEntryGuidStore[pGo->GetEntry()] = pGo->GetObjectGuid();
}
void instance_sunwell_plateau::SetData(uint32 uiType, uint32 uiData)
{
switch (uiType)
{
case TYPE_KALECGOS:
m_auiEncounter[uiType] = uiData;
// combat doors
DoUseDoorOrButton(GO_FORCEFIELD);
DoUseDoorOrButton(GO_BOSS_COLLISION_1);
DoUseDoorOrButton(GO_BOSS_COLLISION_2);
if (uiData == FAIL)
{
m_uiKalecRespawnTimer = 20000;
if (Creature* pKalecDragon = GetSingleCreatureFromStorage(NPC_KALECGOS_DRAGON))
pKalecDragon->ForcedDespawn();
if (Creature* pKalecHuman = GetSingleCreatureFromStorage(NPC_KALECGOS_HUMAN))
pKalecHuman->ForcedDespawn();
if (Creature* pSathrovarr = GetSingleCreatureFromStorage(NPC_SATHROVARR))
pSathrovarr->AI()->EnterEvadeMode();
}
break;
case TYPE_BRUTALLUS:
m_auiEncounter[uiType] = uiData;
break;
case TYPE_FELMYST:
m_auiEncounter[uiType] = uiData;
if (uiData == DONE)
StartNextDialogueText(NPC_KALECGOS_MADRIGOSA);
else if (uiData == IN_PROGRESS)
DoSortFlightTriggers();
break;
case TYPE_EREDAR_TWINS:
m_auiEncounter[uiType] = uiData;
if (uiData == DONE)
{
DoUseDoorOrButton(GO_SECOND_GATE);
DoUseDoorOrButton(GO_MURU_ENTER_GATE);
}
break;
case TYPE_MURU:
m_auiEncounter[uiType] = uiData;
// combat door
DoUseDoorOrButton(GO_MURU_ENTER_GATE);
if (uiData == DONE)
{
DoUseDoorOrButton(GO_MURU_EXIT_GATE);
DoUseDoorOrButton(GO_THIRD_GATE);
}
else if (uiData == IN_PROGRESS)
m_uiMuruBerserkTimer = 10 * MINUTE * IN_MILLISECONDS;
break;
case TYPE_KILJAEDEN:
m_auiEncounter[uiType] = uiData;
if (uiData == FAIL)
{
m_uiDeceiversKilled = 0;
// Reset Orbs
DoToggleGameObjectFlags(GO_ORB_BLUE_FLIGHT_1, GO_FLAG_NO_INTERACT, true);
DoToggleGameObjectFlags(GO_ORB_BLUE_FLIGHT_2, GO_FLAG_NO_INTERACT, true);
DoToggleGameObjectFlags(GO_ORB_BLUE_FLIGHT_3, GO_FLAG_NO_INTERACT, true);
DoToggleGameObjectFlags(GO_ORB_BLUE_FLIGHT_4, GO_FLAG_NO_INTERACT, true);
// Respawn deceivers
for (GuidList::const_iterator itr = m_lDeceiversGuidList.begin(); itr != m_lDeceiversGuidList.end(); ++itr)
{
if (Creature* pDeceiver = instance->GetCreature(*itr))
{
if (!pDeceiver->isAlive())
pDeceiver->Respawn();
}
}
}
break;
}
if (uiData == DONE)
{
OUT_SAVE_INST_DATA;
std::ostringstream saveStream;
saveStream << m_auiEncounter[0] << " " << m_auiEncounter[1] << " " << m_auiEncounter[2] << " "
<< m_auiEncounter[3] << " " << m_auiEncounter[4] << " " << m_auiEncounter[5];
m_strInstData = saveStream.str();
SaveToDB();
OUT_SAVE_INST_DATA_COMPLETE;
}
}
uint32 instance_sunwell_plateau::GetData(uint32 uiType) const
{
if (uiType < MAX_ENCOUNTER)
return m_auiEncounter[uiType];
return 0;
}
void instance_sunwell_plateau::Update(uint32 uiDiff)
{
DialogueUpdate(uiDiff);
if (m_uiKalecRespawnTimer)
{
if (m_uiKalecRespawnTimer <= uiDiff)
{
if (Creature* pKalecDragon = GetSingleCreatureFromStorage(NPC_KALECGOS_DRAGON))
pKalecDragon->Respawn();
if (Creature* pKalecHuman = GetSingleCreatureFromStorage(NPC_KALECGOS_HUMAN))
pKalecHuman->Respawn();
m_uiKalecRespawnTimer = 0;
}
else
m_uiKalecRespawnTimer -= uiDiff;
}
// Muru berserk timer; needs to be done here because it involves two distinct creatures
if (m_auiEncounter[TYPE_MURU] == IN_PROGRESS)
{
if (m_uiMuruBerserkTimer < uiDiff)
{
if (Creature* pEntrpius = GetSingleCreatureFromStorage(NPC_ENTROPIUS, true))
pEntrpius->CastSpell(pEntrpius, SPELL_MURU_BERSERK, true);
else if (Creature* pMuru = GetSingleCreatureFromStorage(NPC_MURU))
pMuru->CastSpell(pMuru, SPELL_MURU_BERSERK, true);
m_uiMuruBerserkTimer = 10 * MINUTE * IN_MILLISECONDS;
}
else
m_uiMuruBerserkTimer -= uiDiff;
}
if (m_auiEncounter[TYPE_KILJAEDEN] == NOT_STARTED || m_auiEncounter[TYPE_KILJAEDEN] == FAIL)
{
if (m_uiKiljaedenYellTimer < uiDiff)
{
switch (urand(0, 4))
{
case 0: DoOrSimulateScriptTextForThisInstance(SAY_ORDER_1, NPC_KILJAEDEN_CONTROLLER); break;
case 1: DoOrSimulateScriptTextForThisInstance(SAY_ORDER_2, NPC_KILJAEDEN_CONTROLLER); break;
case 2: DoOrSimulateScriptTextForThisInstance(SAY_ORDER_3, NPC_KILJAEDEN_CONTROLLER); break;
case 3: DoOrSimulateScriptTextForThisInstance(SAY_ORDER_4, NPC_KILJAEDEN_CONTROLLER); break;
case 4: DoOrSimulateScriptTextForThisInstance(SAY_ORDER_5, NPC_KILJAEDEN_CONTROLLER); break;
}
m_uiKiljaedenYellTimer = 90000;
}
else
m_uiKiljaedenYellTimer -= uiDiff;
}
}
void instance_sunwell_plateau::Load(const char* in)
{
if (!in)
{
OUT_LOAD_INST_DATA_FAIL;
return;
}
OUT_LOAD_INST_DATA(in);
std::istringstream loadStream(in);
loadStream >> m_auiEncounter[0] >> m_auiEncounter[1] >> m_auiEncounter[2] >>
m_auiEncounter[3] >> m_auiEncounter[4] >> m_auiEncounter[5];
for (uint8 i = 0; i < MAX_ENCOUNTER; ++i)
{
if (m_auiEncounter[i] == IN_PROGRESS)
m_auiEncounter[i] = NOT_STARTED;
}
OUT_LOAD_INST_DATA_COMPLETE;
}
static bool sortByPositionX(Creature* pFirst, Creature* pSecond)
{
return pFirst && pSecond && pFirst->GetPositionX() > pSecond->GetPositionX();
}
void instance_sunwell_plateau::DoSortFlightTriggers()
{
if (m_lAllFlightTriggersList.empty())
{
script_error_log("Instance Sunwell Plateau: ERROR Failed to load flight triggers for creature id %u.", NPC_FELMYST);
return;
}
std::list<Creature*> lTriggers; // Valid pointers, only used locally
for (GuidList::const_iterator itr = m_lAllFlightTriggersList.begin(); itr != m_lAllFlightTriggersList.end(); ++itr)
{
if (Creature* pTrigger = instance->GetCreature(*itr))
lTriggers.push_back(pTrigger);
}
if (lTriggers.empty())
return;
// sort the flight triggers; first by position X, then group them by Y (left and right)
lTriggers.sort(sortByPositionX);
for (std::list<Creature*>::iterator itr = lTriggers.begin(); itr != lTriggers.end(); ++itr)
{
if ((*itr)->GetPositionY() < 600.0f)
m_vRightFlightTriggersVect.push_back((*itr)->GetObjectGuid());
else
m_vLeftFlightTriggersVect.push_back((*itr)->GetObjectGuid());
}
}
ObjectGuid instance_sunwell_plateau::SelectFelmystFlightTrigger(bool bLeftSide, uint8 uiIndex)
{
// Return the flight trigger from the selected index
GuidVector& vTemp = bLeftSide ? m_vLeftFlightTriggersVect : m_vRightFlightTriggersVect;
if (uiIndex >= vTemp.size())
return ObjectGuid();
return vTemp[uiIndex];
}
void instance_sunwell_plateau::DoEjectSpectralPlayers()
{
for (GuidSet::const_iterator itr = m_spectralRealmPlayers.begin(); itr != m_spectralRealmPlayers.end(); ++itr)
{
if (Player* pPlayer = instance->GetPlayer(*itr))
{
if (!pPlayer->HasAura(SPELL_SPECTRAL_REALM_AURA))
continue;
pPlayer->CastSpell(pPlayer, SPELL_TELEPORT_NORMAL_REALM, true);
pPlayer->CastSpell(pPlayer, SPELL_SPECTRAL_EXHAUSTION, true);
pPlayer->RemoveAurasDueToSpell(SPELL_SPECTRAL_REALM_AURA);
}
}
}
void instance_sunwell_plateau::JustDidDialogueStep(int32 iEntry)
{
switch (iEntry)
{
case NPC_KALECGOS_MADRIGOSA:
if (Creature* pTrigger = GetSingleCreatureFromStorage(NPC_FLIGHT_TRIGGER_LEFT))
{
if (Creature* pKalec = pTrigger->SummonCreature(NPC_KALECGOS_MADRIGOSA, aKalecLoc[0].m_fX, aKalecLoc[0].m_fY, aKalecLoc[0].m_fZ, aKalecLoc[0].m_fO, TEMPSUMMON_CORPSE_DESPAWN, 0))
{
pKalec->SetWalk(false);
pKalec->SetLevitate(true);
pKalec->GetMotionMaster()->MovePoint(0, aKalecLoc[1].m_fX, aKalecLoc[1].m_fY, aKalecLoc[1].m_fZ, false);
}
}
break;
case NPC_FELMYST:
if (Creature* pKalec = GetSingleCreatureFromStorage(NPC_KALECGOS_MADRIGOSA))
pKalec->GetMotionMaster()->MovePoint(0, aKalecLoc[2].m_fX, aKalecLoc[2].m_fY, aKalecLoc[2].m_fZ, false);
break;
case SPELL_OPEN_BACK_DOOR:
if (Creature* pKalec = GetSingleCreatureFromStorage(NPC_KALECGOS_MADRIGOSA))
{
// ToDo: update this when the AoE spell targeting will support many explicit target. Kalec should target all creatures from the list
if (Creature* pTrigger = instance->GetCreature(m_lBackdoorTriggersList.front()))
pKalec->CastSpell(pTrigger, SPELL_OPEN_BACK_DOOR, true);
}
break;
case NPC_BRUTALLUS:
if (Creature* pKalec = GetSingleCreatureFromStorage(NPC_KALECGOS_MADRIGOSA))
{
pKalec->ForcedDespawn(10000);
pKalec->GetMotionMaster()->MovePoint(0, aKalecLoc[3].m_fX, aKalecLoc[3].m_fY, aKalecLoc[3].m_fZ, false);
}
break;
}
}
InstanceData* GetInstanceData_instance_sunwell_plateau(Map* pMap)
{
return new instance_sunwell_plateau(pMap);
}
bool AreaTrigger_at_sunwell_plateau(Player* pPlayer, AreaTriggerEntry const* pAt)
{
if (pAt->id == AREATRIGGER_TWINS)
{
if (pPlayer->isGameMaster() || pPlayer->isDead())
return false;
instance_sunwell_plateau* pInstance = (instance_sunwell_plateau*)pPlayer->GetInstanceData();
if (pInstance && pInstance->GetData(TYPE_EREDAR_TWINS) == NOT_STARTED)
pInstance->SetData(TYPE_EREDAR_TWINS, SPECIAL);
}
return false;
}
void AddSC_instance_sunwell_plateau()
{
Script* pNewScript;
pNewScript = new Script;
pNewScript->Name = "instance_sunwell_plateau";
pNewScript->GetInstanceData = &GetInstanceData_instance_sunwell_plateau;
pNewScript->RegisterSelf();
pNewScript = new Script;
pNewScript->Name = "at_sunwell_plateau";
pNewScript->pAreaTrigger = &AreaTrigger_at_sunwell_plateau;
pNewScript->RegisterSelf();
}
| concept45/TwoScripts | scripts/eastern_kingdoms/sunwell_plateau/instance_sunwell_plateau.cpp | C++ | gpl-2.0 | 17,598 |
package com.cluit.util.dataTypes;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import com.cluit.util.Const;
import com.cluit.util.AoP.MethodMapper;
import com.cluit.util.methods.ClusteringUtils;
import com.cluit.util.structures.KeyPriorityQueue_Max;
import com.cluit.util.structures.Pair;
/**A cluster is a collection of entries.
*
* The class has a lot of utility functions related to clusters such as calculating centoid, finding the entry furthest
* from the centoid and so on.
*
* @author Simon
*
*/
public class Cluster {
//*******************************************************************************************************
//region VARIABLES
//*******************************************************************************************************
private Entry centoid;
public Pair<Double, Entry> cache = new Pair<Double, Entry>( 0.0, new Entry() );
private final int dimensions;
private final Set<Entry> members = new HashSet<>();
private final KeyPriorityQueue_Max<Entry> distanceQueue = new KeyPriorityQueue_Max<Entry>();
//endregion *********************************************************************************************
//region CUNSTRUCTOR
//*******************************************************************************************************
/**
*
* @param position
* @param centoidIsMember
*/
public Cluster(double[] position) {
if( position.length < 1){
API_Exeption("A cluster's position must be defined and have 1 or more dimenstions!");
}
this.centoid = new Entry(position);
this.dimensions = centoid.getDimensions();
};
//endregion *********************************************************************************************
//region STATIC METHODS
//*******************************************************************************************************
/**Calculates a central point (centoid) from a collection of entries. Not that all entries must have the same dimensionality.
*
* @param entries
* @return A new entry, with a position that is the mean of all parameter entries (NULL if entries.lenght == 0)
*/
public static Entry calculateCentoid(Entry[] entries){
if( entries.length == 0)
return null;
//Fetch dimensionality for the entries and set up the coordinate array
int dim = entries[0].getDimensions();
double[] centoidCoordinates = new double[dim];
//Add all entries positions together (for example, add all entries x-values together in one array slot,
//and all y-values together in the next array slot).
for( Entry p : entries ){
for( int i = 0; i < p.getDimensions(); i++ )
centoidCoordinates[i] += p.getCoordinateAt(i);
}
//Divide each position by the number of entries (to get the mean of each dimension's position
for( int i = 0; i < centoidCoordinates.length; i++)
centoidCoordinates[i] /= entries.length;
return new Entry(centoidCoordinates);
}
/**Calculates the sum of squared errors for a given set of entries, given a centoid.<br>
* The calculation is simply: For each point, calculate the euclidian distance from that point to the centoid, and square the distance
*
* @param centoid The mean position of the entries (see @link {@link Cluster.calculateCentoid} )
* @param entries
* @return
*/
public static double calculateSquaredError(Entry centoid, Entry[] entries){
double out = 0;
double dist = 0;
for(Entry e : entries ){
dist = ClusteringUtils.eucDistance(centoid, e);
out += (dist*dist);
}
return out;
}
//endregion *********************************************************************************************
//region PUBLIC
//*******************************************************************************************************
public int getNumberOfMembers(){
return distanceQueue.size() == members.size() ? distanceQueue.size() : -1;
}
/**Returns the distance to the centoid for the point which is farthest from the centoid
*
* @return The distance, if there are any members of the cluster. -1 otherwise
*/
public double getFurthestMembersDistance(){
if( distanceQueue.size() == 0 )
return -1;
return distanceQueue.peekKey();
}
/** Calculates a new centoid for the cluster. This method also update each points distance to the centoid
* <br><br>
* Complexity = <b>O(n * d)</b>,
* where <b>n</b> is the number of elements in the cluster
* where <b>d</b> the number of dimensions for each point
*/
public void calculateCentoid(){
int dim = centoid.getDimensions();
double[] newCentoidCoordinates = new double[dim];
for( Entry p : distanceQueue.values() ){
for( int i = 0; i < p.getDimensions(); i++ )
newCentoidCoordinates[i] += p.getCoordinateAt(i);
}
for( int i = 0; i < newCentoidCoordinates.length; i++)
newCentoidCoordinates[i] /= distanceQueue.size();
centoid = new Entry(newCentoidCoordinates );
updateMemberDistances();
}
/**Fetches a <b>copy</b> of the centoid of the cluster
*
* @return A new Entry, which is a copy of the cluster's centoid
*/
public Entry getCentoid(){
return new Entry(centoid);
}
/**Adds an entry to the cluster. The same entry cannot be added twice to the same cluster.
* This does not automatically update the cluster centoid. To do that, call "UpdateCentoid"
*
* @param e
* @return True if the entry was added, false if it was not
*/
public boolean add(Entry e){
if( e.getDimensions() != dimensions ){
API_Exeption("An entry cannot be added to a cluster if their dimenstions does not match! Cluster.dim = "+dimensions+" Entry.dim = "+e.getDimensions() );
return false;
}
if( members.contains(e) ){
API_Exeption("An entry cannot be added to a cluster twice! The entry "+e+" is already present in the cluster" );
return false;
}
double dist;
if( e == cache.right )
dist = cache.left;
else
dist = ClusteringUtils.eucDistance(e, centoid);
boolean a = distanceQueue.put(dist, e);
boolean b = members.add(e);
return a & b;
}
/**Removes a point from the cluster
*
* @param e The point to be removed
* @return True if it was found. False if the point wasn't found.
*/
public boolean removeEntry(Entry e){
boolean a = distanceQueue.remove(e);
boolean b = members.remove(e);
return a & b;
}
/**Calculates a points distance to the clusters centoid.
* The result is cached (the cache stores only 1 element), to prevent
* the result from having to be re-computed in the near future.
* <br>It is therefore recommended that whenever a point checks its distance to
* all clusters, it should be added to a cluster before another point checks
* it's distances.
*
* @param p The point
* @return Distance to the centoid
*/
public double distanceToCentoid(Entry p){
double dist = ClusteringUtils.eucDistance(p, centoid);
cache = new Pair<Double, Entry>(dist, p);
return dist;
}
/**Checks whether a given point is member of this cluster or not
*
* @param p The point
* @return True if the point is found within the cluster
*/
public boolean isMember(Entry e) {
return members.contains(e);
}
/**Fetches an array of all entries that are present within this cluster. This array can have a lenght of 0, in case no
* entries are registered within this cluster
*/
public Entry[] getMembers() {
return members.toArray( new Entry[0] );
}
/**Calculates the sum of squared errors for this cluster
*
* @return
*/
public double getSquaredError(){
return Cluster.calculateSquaredError(centoid, getMembers()) ;
}
public String toString(){
String out = "[ ";
for( Entry e : members ){
out += e.toString() + " : ";
}
return members.size() > 0 ? out.substring(0, out.length() - 3) + " ]" : "[ ]";
}
//endregion *********************************************************************************************
//region PRIVATE
//*******************************************************************************************************
/**Update each member's distance to the centoid
*
*/
private void updateMemberDistances() {
ArrayList<Entry> list = distanceQueue.values();
distanceQueue.clear();
for(Entry p : list){
double newDistance = ClusteringUtils.eucDistance(centoid, p);
distanceQueue.add(newDistance, p);
}
}
private int API_Exeption(String s){
MethodMapper.invoke(Const.METHOD_EXCEPTION_GENERAL, "Error in Cluster.java! " + s +" " + com.cluit.util.methods.MiscUtils.getStackPos(), new Exception() );
return -1;
}
//endregion *********************************************************************************************
//*******************************************************************************************************
}
| Gikkman/CluIt | CluIt/src/com/cluit/util/dataTypes/Cluster.java | Java | gpl-2.0 | 8,826 |
<?php
/**
* SFN Live Report.
*
* @package SFN Live Report
* @author Hampus Persson <hampus@hampuspersson.se>
* @license GPL-2.0+
* @link http://
* @copyright 2013 Swedish Football Network
*/
/**
* Plugin class.
*
*
* @package SNF_Live_Report
* @author Hampus Persson <hampus@hampuspersson.se>
*/
class SFN_Live_Report {
/**
* Plugin version, used for cache-busting of style and script file references.
*
* @since 1.0.0
*
* @var string
*/
protected $version = '1.1.0';
/**
* Unique identifier for your plugin.
*
* Use this value (not the variable name) as the text domain when internationalizing strings of text. It should
* match the Text Domain file header in the main plugin file.
*
* @since 1.0.0
*
* @var string
*/
protected $plugin_slug = 'sfn-live-report';
/**
* Instance of this class.
*
* @since 1.0.0
*
* @var object
*/
protected static $instance = null;
/**
* Slug of the plugin screen.
*
* @since 1.0.0
*
* @var string
*/
protected $plugin_screen_hook_suffix = null;
/**
* Initialize the plugin by setting localization, filters, and administration functions.
*
* @since 1.0.0
*/
private function __construct() {
// Load plugin text domain
add_action( 'init', array( $this, 'load_plugin_textdomain' ) );
// At this point no options are needed but if the need arises this is
// how to add the options page and menu item.
// add_action( 'admin_menu', array( $this, 'add_plugin_admin_menu' ) );
// Load admin style sheet and JavaScript.
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_styles' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
// Load public-facing style sheet and JavaScript.
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_styles' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
// Add actions to remove some unwanted scripts and styles that wp_head() forces on us
// add_action( 'wp_print_scripts', array( $this, 'sfn_live_report_remove_scripts' ) );
// add_action( 'wp_print_styles', array( $this, 'sfn_live_report_remove_styles' ) );
// Setup callback for AJAX, through WPs admin-ajax
add_action('wp_ajax_sfn-submit', array( $this, 'sfn_live_report_callback' ));
// Add the shortcode that sets up the whole operation
add_shortcode( 'sfn-live-report', array( $this, 'report_games' ) );
}
/**
* Return an instance of this class.
*
* @since 1.0.0
*
* @return object A single instance of this class.
*/
public static function get_instance() {
// If the single instance hasn't been set, set it now.
if ( null == self::$instance ) {
self::$instance = new self;
}
return self::$instance;
}
/**
* Fired when the plugin is activated.
*
* @since 1.0.0
*
* @param boolean $network_wide True if WPMU superadmin uses "Network Activate" action, false if WPMU is disabled or plugin is activated on an individual blog.
*/
public static function activate( $network_wide ) {
// TODO: Define activation functionality here
}
/**
* Fired when the plugin is deactivated.
*
* @since 1.0.0
*
* @param boolean $network_wide True if WPMU superadmin uses "Network Deactivate" action, false if WPMU is disabled or plugin is deactivated on an individual blog.
*/
public static function deactivate( $network_wide ) {
// TODO: Define deactivation functionality here
}
/**
* Load the plugin text domain for translation.
*
* @since 1.0.0
*/
public function load_plugin_textdomain() {
$domain = $this->plugin_slug;
$locale = apply_filters( 'plugin_locale', get_locale(), $domain );
load_textdomain( $domain, WP_LANG_DIR . '/' . $domain . '/' . $domain . '-' . $locale . '.mo' );
load_plugin_textdomain( $domain, FALSE, dirname( plugin_basename( __FILE__ ) ) . '/lang/' );
}
/**
* Register and enqueue admin-specific style sheet.
*
* @since 1.0.0
*
* @return null Return early if no settings page is registered.
*/
public function enqueue_admin_styles() {
if ( ! isset( $this->plugin_screen_hook_suffix ) ) {
return;
}
$screen = get_current_screen();
if ( $screen->id == $this->plugin_screen_hook_suffix ) {
wp_enqueue_style( $this->plugin_slug .'-admin-styles', plugins_url( 'assets/css/admin.css', __FILE__ ), array(), $this->version );
}
}
/**
* Register and enqueue admin-specific JS.
*
* @since 1.0.0
*
* @return null Return early if no settings page is registered.
*/
public function enqueue_admin_scripts() {
if ( ! isset( $this->plugin_screen_hook_suffix ) ) {
return;
}
$screen = get_current_screen();
if ( $screen->id == $this->plugin_screen_hook_suffix ) {
wp_enqueue_script( $this->plugin_slug . '-admin-script', plugins_url( 'assets/javascripts/admin.js', __FILE__ ), array( 'jquery' ), $this->version );
}
}
/**
* Register and enqueue public-facing style sheet.
*
* @since 1.0.0
*/
public function enqueue_styles() {
wp_enqueue_style( $this->plugin_slug . '-plugin-styles', plugins_url( 'assets/css/style.css', __FILE__ ), array(), $this->version );
}
/**
* Register and enqueues public-facing JS files.
*
* @since 1.0.0
*/
public function enqueue_scripts() {
wp_enqueue_script( $this->plugin_slug . '-plugin-script', plugins_url( 'assets/javascripts/main.min.js', __FILE__ ), array( 'jquery' ), $this->version );
// Set an object with the ajaxurl for use in main JS
wp_localize_script( $this->plugin_slug . '-plugin-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
/**
* Since this plugin doesn't use any other plugins we can remove all scripts that are queued and registered properly
*
* @since 1.0.0
*/
public function sfn_live_report_remove_scripts() {
global $wp_scripts;
foreach( $wp_scripts->queue as $handle ) :
if( 'jquery' != $handle && 'sfn-live-report-plugin-script' != $handle ) {
wp_deregister_script( $handle );
wp_dequeue_script( $handle );
}
endforeach;
}
/**
* Since this plugin doesn't use any other plugins we can remove all styles that are queued and registered properly
*
* @since 1.0.0
*/
public function sfn_live_report_remove_styles() {
global $wp_styles;
foreach( $wp_styles->queue as $handle ) :
if( 'sfn-live-report-plugin-styles' != $handle ) {
wp_deregister_style( $handle );
wp_dequeue_style( $handle );
}
endforeach;
}
/**
* Register the administration menu for this plugin into the WordPress Dashboard menu.
*
* @since 1.0.0
*/
public function add_plugin_admin_menu() {
$this->plugin_screen_hook_suffix = add_plugins_page(
__( 'SFN Live Report', $this->plugin_slug ),
__( 'Settings', $this->plugin_slug ),
'read',
$this->plugin_slug,
array( $this, 'display_plugin_admin_page' )
);
}
/**
* Render the settings page for this plugin.
*
* @since 1.0.0
*/
public function display_plugin_admin_page() {
include_once( 'views/admin.php' );
}
/**
* Callback for ajax call when the form is submitted
*
* @since 1.0.0
*/
public function sfn_live_report_callback() {
// Check that the user has access rights
if ( !$this->check_access() ) {
echo '<p>Du har inte behörighet att komma åt detta verktyg.</p>';
echo '<h3><a href="' . wp_login_url( site_url( $_SERVER["REQUEST_URI"] ) ) . '">Logga in</a></h3>';
die();
}
// If everything checks out and a game is submitted we'll update the meta
if( $_POST['game'] ) {
update_post_meta($_POST['game'], 'hemmares', $_POST['home']);
update_post_meta($_POST['game'], 'bortares', $_POST['away']);
update_post_meta($_POST['game'], 'matchtid', $_POST['time']);
if( "true" === $_POST['sendToTwitter'] ) {
$url = "http://www.swedishfootballnetwork.se/games/" . $_POST['game'];
if( "true" === $_POST['finalScore'] ) {
$time = ' (Slut)';
} else {
$time = empty($_POST['time']) ? '' : ' (' . $_POST['time'] . ')';
}
$tweet = $_POST['home-team'] . ' - ' . $_POST['away-team'] . ' ' . $_POST['home'] . '-' . $_POST['away'] . $time . '. Mer info om matchen på: ' . $url;
$this->tweetUpdate($tweet);
}
}
}
private function tweetUpdate($tweet) {
require_once('twitteroauth/twitteroauth.php');
define('CONSUMER_KEY', 'VPWk1tJtrYVoTMTWTLe30A');
define('CONSUMER_SECRET', 'EohfFFQzUSlsQnVjG9aVS1fCdxVv6GCzv6wEkTXYSi8');
define('OAUTH_CALLBACK', 'http://example.com/twitteroauth/callback.php');
/* TOP SECRET STUFF, DO NOT SHARE! */
$access_token = array(
"oauth_token" => "1080024924-NpA52OvkNMzzeJivBpHKEEenBzfVdrutsr4qJy4",
"oauth_token_secret" => "Xuk19qsgsrlnkTr3VCLnvtwjg1yUnW1u6ykCnbOjkE"
);
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$parameters = array('status' => $tweet);
$content = $connection->post('statuses/update', $parameters);
return $content;
}
/**
* Function to output the form to the user
*
* @since 1.0.0
*/
public function report_games( $atts ) {
// Check that the user has access rights
if ( !$this->check_access() ) {
echo '<p>Du har inte behörighet att komma åt detta verktyg.</p>';
echo '<h3><a href="' . wp_login_url( site_url( $_SERVER["REQUEST_URI"] ) ) . '">Logga in</a></h3>';
die();
}
// Store the output we want in a variable
$return_page = include('views/public.php');
return $return_page;
}
private function check_access() {
$allowed_users = array(
6, // Hampus Persson, SFN
373 // Carl Klimfors, LG
);
$current_user = wp_get_current_user();
if ( in_array($current_user->ID, $allowed_users) ) {
return true;
}
return false;
}
} | swedish-football-network/wp-live-report | class-sfn-live-report.php | PHP | gpl-2.0 | 9,879 |
# encoding: utf-8
# Copyright (c) 2012 Novell, Inc.
#
# All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of version 2 of the GNU General Public License as published
# by the Free Software Foundation.
#
# 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, contact Novell, Inc.
#
# To contact Novell about this file by physical or electronic mail, you may
# find current contact information at www.novell.com.
require "yast"
module UI
# UI layout helpers.
#
# These started out in the Expert Partitioner in yast2-storage.
# The use case is reusing pieces of this legacy code in the new
# yast2-partitioner.
# That is why the API and the implementation look old.
module Greasemonkey
include Yast::UIShortcuts
extend Yast::UIShortcuts
Builtins = Yast::Builtins
Convert = Yast::Convert
Ops = Yast::Ops
Yast.import "Directory"
@handlers = [
:VStackFrames,
:FrameWithMarginBox,
:ComboBoxSelected,
:LeftRadioButton,
:LeftRadioButtonWithAttachment,
:LeftCheckBox,
:LeftCheckBoxWithAttachment,
:IconAndHeading
]
# The compatibility API needs CamelCase method names
# rubocop:disable MethodName
# Wrap terms in a VBox with small vertical spacings in between.
# @param old [Yast::Term]
# @return [Yast::Term]
# @example
# term(
# :VStackFrames,
# Frame("f1"),
# Frame("f2"),
# Frame("f3")
# )
# ->
# VBox(
# Frame("f1"),
# VSpacing(0.45),
# Frame("f2"),
# VSpacing(0.45),
# Frame("f3")
# )
def VStackFrames(old)
frames = Convert.convert(
Builtins.argsof(old),
from: "list",
to: "list <term>"
)
new = VBox()
Builtins.foreach(frames) do |frame|
new = Builtins.add(new, VSpacing(0.45)) if Builtins.size(new) != 0
new = Builtins.add(new, frame)
end
new
end
module_function :VStackFrames
# @param old [Yast::Term]
# @return [Yast::Term]
# @example
# term(:FrameWithMarginBox, "Title", "arg1", "arg2")
# ->
# Frame("Title", MarginBox(1.45, 0.45, "arg1", "arg2"))
def FrameWithMarginBox(old)
title = Ops.get_string(old, 0, "error")
args = Builtins.sublist(Builtins.argsof(old), 1)
Frame(
title,
Builtins.toterm(:MarginBox, Builtins.union([1.45, 0.45], args))
)
end
module_function :FrameWithMarginBox
# @param old [Yast::Term]
# @return [Yast::Term]
# @example
# term(
# :ComboBoxSelected,
# Id(:wish), Opt(:notify), "Wish",
# [
# Item(Id(:time), "Time"),
# Item(Id(:love), "Love"),
# Item(Id(:money), "Money")
# ],
# Id(:love)
# )
# ->
# ComboBox(
# Id(:wish), Opt(:notify), "Wish",
# [
# Item(Id(:time), "Time", false),
# Item(Id(:love), "Love", true),
# Item(Id(:money), "Money", false)
# ]
# )
def ComboBoxSelected(old)
args = Builtins.argsof(old)
tmp = Builtins.sublist(args, 0, Ops.subtract(Builtins.size(args), 2))
items = Ops.get_list(args, Ops.subtract(Builtins.size(args), 2), [])
id = Ops.get_term(args, Ops.subtract(Builtins.size(args), 1), Id())
items = Builtins.maplist(items) do |item|
Item(Ops.get(item, 0), Ops.get(item, 1), Ops.get(item, 0) == id)
end
Builtins.toterm(:ComboBox, Builtins.add(tmp, items))
end
module_function :ComboBoxSelected
# @param old [Yast::Term]
# @return [Yast::Term]
# @example
# term(:LeftRadioButton, Id(...), "args")
# ->
# Left(RadioButton(Id(...), "args"))
def LeftRadioButton(old)
Left(Builtins.toterm(:RadioButton, Builtins.argsof(old)))
end
module_function :LeftRadioButton
# NOTE that it does not expand the nested
# Greasemonkey term LeftRadioButton! {#transform} does that.
# @param old [Yast::Term]
# @return [Yast::Term]
# @example
# term(:LeftRadioButtonWithAttachment, "foo", "bar", "contents")
# ->
# VBox(
# term(:LeftRadioButton, "foo", "bar"),
# HBox(HSpacing(4), "contents")
# )
def LeftRadioButtonWithAttachment(old)
args = Builtins.argsof(old)
tmp1 = Builtins.sublist(args, 0, Ops.subtract(Builtins.size(args), 1))
tmp2 = Ops.get(args, Ops.subtract(Builtins.size(args), 1))
if tmp2 == Empty() # rubocop:disable Style/GuardClause
return VBox(Builtins.toterm(:LeftRadioButton, tmp1))
else
return VBox(
Builtins.toterm(:LeftRadioButton, tmp1),
HBox(HSpacing(4), tmp2)
)
end
end
module_function :LeftRadioButtonWithAttachment
# @param old [Yast::Term]
# @return [Yast::Term]
# @example
# term(:LeftCheckBox, Id(...), "args")
# ->
# Left(CheckBox(Id(...), "args"))
def LeftCheckBox(old)
Left(Builtins.toterm(:CheckBox, Builtins.argsof(old)))
end
module_function :LeftCheckBox
# NOTE that it does not expand the nested
# Greasemonkey term LeftCheckBox! {#transform} does that.
# @param old [Yast::Term]
# @return [Yast::Term]
# @example
# term(:LeftCheckBoxWithAttachment, "foo", "bar", "contents")
# ->
# VBox(
# term(:LeftCheckBox, "foo", "bar"),
# HBox(HSpacing(4), "contents")
# )
def LeftCheckBoxWithAttachment(old)
args = Builtins.argsof(old)
tmp1 = Builtins.sublist(args, 0, Ops.subtract(Builtins.size(args), 1))
tmp2 = Ops.get(args, Ops.subtract(Builtins.size(args), 1))
if tmp2 == Empty() # rubocop:disable Style/GuardClause
return VBox(Builtins.toterm(:LeftCheckBox, tmp1))
else
return VBox(
Builtins.toterm(:LeftCheckBox, tmp1),
HBox(HSpacing(4), tmp2)
)
end
end
module_function :LeftCheckBoxWithAttachment
# @param old [Yast::Term]
# @return [Yast::Term]
# @example
# term(:IconAndHeading, "title", "icon")
# ->
# Left(
# HBox(
# Image("/usr/share/YaST2/theme/current/icons/22x22/apps/icon", ""),
# Heading("title")
# )
# )
def IconAndHeading(old)
args = Builtins.argsof(old)
title = Ops.get_string(args, 0, "")
icon = Ops.get_string(args, 1, "")
Left(HBox(Image(icon, ""), Heading(title)))
end
module_function :IconAndHeading
# Recursively apply all Greasemonkey methods on *old*
# @param old [Yast::Term]
# @return [Yast::Term]
def Transform(old)
s = Builtins.symbolof(old)
handler = Greasemonkey.method(s) if @handlers.include?(s)
return Transform(handler.call(old)) if !handler.nil?
new = Builtins::List.reduce(Builtins.toterm(s), Builtins.argsof(old)) do |tmp, arg|
arg = Transform(Convert.to_term(arg)) if Ops.is_term?(arg)
Builtins.add(tmp, arg)
end
new
end
module_function :Transform
alias_method :transform, :Transform
module_function :transform
end
end
| mchf/yast-yast2 | library/general/src/lib/ui/greasemonkey.rb | Ruby | gpl-2.0 | 7,562 |
using NetworkProbe.Port.Services;
using System.Collections.Generic;
using System.Net;
using NetworkProbe.Port;
using NetworkProbe.Model;
using System.Threading.Tasks;
using System.Linq;
namespace NetworkProbe
{
public static class Probe
{
/// <summary>
/// Initiates a service scan on a single service to a single network device
/// </summary>
public static ProbeResult Single(ProbeEntity entity)
{
var result = Task.Run(() => ReturnSingleResult(entity));
return result.Result;
}
/// <summary>
/// Initiates a service scan on multiple services on multiple devices
/// </summary>
public static IEnumerable<ProbeResult> Multiple(IEnumerable<ProbeEntity> entities)
{
List<ProbeResult> results = new List<ProbeResult>();
//Run each probe in parallel
Parallel.ForEach(entities, x =>
{
var result = Task.Run(() => ReturnSingleResult(x));
results.Add(result.Result);
});
//Order results due to some tasks finishing earlier than others ***this adds around 5-7 seconds on 254 address scan :-( ***
return results.OrderBy(x => int.Parse(x.IP.ToString().Split('.')[3]));
}
private async static Task<ProbeResult> ReturnSingleResult(ProbeEntity entity)
{
var service = ServiceFactory.Create(entity.Type, entity.IP, entity.Port);
await service.ReturnPortData();
PortStatus status = service.PortLive ? PortStatus.Live : PortStatus.Dead;
bool isData = service.PortResult != null && service.PortResult.Count > 0 ? true : false;
Dictionary<string, string> data = isData ? service.PortResult : new Dictionary<string, string>();
return new ProbeResult(entity.Type, entity.Port, entity.IP, status, isData, data);
}
}
}
| K1tson/Network-Probe | NetworkProbe/Probe.cs | C# | gpl-2.0 | 1,951 |
import urllib2
def sumaDos():
print 10*20
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
| DiegoBalandran/prueba | archivo.py | Python | gpl-2.0 | 1,301 |
class EmailToken < ActiveRecord::Base
belongs_to :user
validates_presence_of :token
validates_presence_of :user_id
validates_presence_of :email
before_validation(:on => :create) do
self.token = EmailToken.generate_token
end
after_create do
# Expire the previous tokens
EmailToken.update_all 'expired = true', ['user_id = ? and id != ?', self.user_id, self.id]
end
def self.token_length
16
end
def self.valid_after
1.week.ago
end
def self.unconfirmed
where(confirmed: false)
end
def self.active
where(expired: false).where('created_at > ?', valid_after)
end
def self.generate_token
SecureRandom.hex(EmailToken.token_length)
end
def self.confirm(token)
return unless token.present?
return unless token.length/2 == EmailToken.token_length
email_token = EmailToken.where("token = ? AND expired = FALSE and created_at >= ?", token, EmailToken.valid_after).includes(:user).first
return if email_token.blank?
user = email_token.user
User.transaction do
row_count = EmailToken.update_all 'confirmed = true', ['id = ? AND confirmed = false', email_token.id]
if row_count == 1
# If we are activating the user, send the welcome message
user.send_welcome_message = !user.active?
user.active = true
user.email = email_token.email
user.save!
end
end
user
rescue ActiveRecord::RecordInvalid
# If the user's email is already taken, just return nil (failure)
nil
end
end
| Ocramius/discourse | app/models/email_token.rb | Ruby | gpl-2.0 | 1,540 |
/** IneoRealTimeFileFormat class implementation.
@file IneoRealTimeFileFormat.cpp
This file belongs to the SYNTHESE project (public transportation specialized software)
Copyright (C) 2002 Hugues Romain - RCSmobility <contact@rcsmobility.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.
*/
#include "IneoRealTimeFileFormat.hpp"
#include "Import.hpp"
#include "DataSource.h"
#include "DataSourceTableSync.h"
#include "DBTransaction.hpp"
#include "ImportableTableSync.hpp"
#include "ScheduledServiceTableSync.h"
#include "StopPointTableSync.hpp"
#include "CommercialLineTableSync.h"
#include "JourneyPatternTableSync.hpp"
#include "DesignatedLinePhysicalStop.hpp"
#include "LineStopTableSync.h"
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
using namespace boost::posix_time;
using namespace gregorian;
namespace synthese
{
using namespace data_exchange;
using namespace pt;
using namespace server;
using namespace util;
using namespace impex;
using namespace db;
using namespace graph;
using namespace util;
namespace util
{
template<> const string FactorableTemplate<FileFormat, IneoRealTimeFileFormat>::FACTORY_KEY("ineo_temps_reel");
}
namespace data_exchange
{
const string IneoRealTimeFileFormat::Importer_::PARAMETER_PLANNED_DATASOURCE_ID("ps");
const string IneoRealTimeFileFormat::Importer_::PARAMETER_COURSE_ID("ci");
const string IneoRealTimeFileFormat::Importer_::PARAMETER_DB_CONN_STRING("conn_string");
const string IneoRealTimeFileFormat::Importer_::PARAMETER_STOP_CODE_PREFIX("stop_code_prefix");
bool IneoRealTimeFileFormat::Importer_::_read(
) const {
if(_database.empty() || !_plannedDataSource.get())
{
return false;
}
DataSource& dataSource(*_import.get<DataSource>());
boost::shared_ptr<DB> db;
if(_dbConnString)
{
db = DBModule::GetDBForStandaloneUse(*_dbConnString);
}
else
{
db = DBModule::GetDBSPtr();
}
date today(day_clock::local_day());
string todayStr("'"+ to_iso_extended_string(today) +"'");
// Services linked to the planned source
ImportableTableSync::ObjectBySource<StopPointTableSync> stops(*_plannedDataSource, _env);
ImportableTableSync::ObjectBySource<CommercialLineTableSync> lines(*_plannedDataSource, _env);
if(!_courseId)
{
BOOST_FOREACH(const ImportableTableSync::ObjectBySource<CommercialLineTableSync>::Map::value_type& itLine, lines.getMap())
{
BOOST_FOREACH(const ImportableTableSync::ObjectBySource<CommercialLineTableSync>::Map::mapped_type::value_type& line, itLine.second)
{
JourneyPatternTableSync::Search(_env, line->getKey());
ScheduledServiceTableSync::Search(_env, optional<RegistryKeyType>(), line->getKey());
BOOST_FOREACH(const Path* route, line->getPaths())
{
LineStopTableSync::Search(_env, route->getKey());
}
} }
// 1 : clean the old references to the current source
ImportableTableSync::ObjectBySource<ScheduledServiceTableSync> sourcedServices(dataSource, _env);
BOOST_FOREACH(const ImportableTableSync::ObjectBySource<ScheduledServiceTableSync>::Map::value_type& itService, sourcedServices.getMap())
{
BOOST_FOREACH(const ImportableTableSync::ObjectBySource<ScheduledServiceTableSync>::Map::mapped_type::value_type& obj, itService.second)
{
obj->removeSourceLinks(dataSource);
}
}
}
else
{
// 1 : clean the old references to the current source
ImportableTableSync::ObjectBySource<ScheduledServiceTableSync> sourcedServices(dataSource, _env);
set<ScheduledService*> services(sourcedServices.get(*_courseId));
BOOST_FOREACH(ScheduledService* service, services)
{
service->removeSourceLinks(dataSource);
_services.insert(service);
}
}
// 2 : loop on the services present in the database and link to existing or new services
stringstream query;
query << "SELECT c.ref, c.chainage, c.ligne, l.mnemo as ligne_ref FROM " << _database << ".COURSE c " <<
"INNER JOIN " << _database << ".LIGNE l on c.ligne=l.ref AND l.jour=c.jour " <<
"WHERE c.jour=" << todayStr << " AND c.type='C'";
if(_courseId)
{
query << " AND c.ref=" << *_courseId;
}
DBResultSPtr result(db->execQuery(query.str()));
while(result->next())
{
string serviceRef(result->getText("ref"));
string chainage(result->getText("chainage"));
string ligneRef(result->getText("ligne_ref"));
_logDebug(
"Processing serviceRef="+ serviceRef +" chainage="+ chainage +" ligneRef="+ ligneRef
);
CommercialLine* line(
_getLine(
lines,
ligneRef,
*_plannedDataSource
) );
if(!line)
{
_logWarning(
"Line "+ ligneRef +" was not found for service "+ serviceRef
);
continue;
}
stringstream chainageQuery;
chainageQuery << "SELECT a.mnemol AS mnemol, h.htd AS htd, h.hta AS hta, h.type AS type, c.pos AS pos FROM "
<< _database << ".ARRETCHN c " <<
"INNER JOIN " << _database << ".ARRET a ON a.ref=c.arret AND a.jour=c.jour " <<
"INNER JOIN " << _database << ".HORAIRE h ON h.arretchn=c.ref AND h.jour=a.jour " <<
"INNER JOIN " << _database << ".COURSE o ON o.chainage=c.chainage AND o.ref=h.course AND c.jour=o.jour " <<
"WHERE h.course='" << serviceRef << "' AND h.jour=" << todayStr << " ORDER BY c.pos";
DBResultSPtr chainageResult(db->execQuery(chainageQuery.str()));
JourneyPattern::StopsWithDepartureArrivalAuthorization servedStops;
SchedulesBasedService::Schedules departureSchedules;
SchedulesBasedService::Schedules arrivalSchedules;
while(chainageResult->next())
{
string type(chainageResult->getText("type"));
string stopCode(chainageResult->getText("mnemol"));
time_duration departureTime(duration_from_string(chainageResult->getText("htd")));
time_duration arrivalTime(duration_from_string(chainageResult->getText("hta")));
MetricOffset stopPos(chainageResult->getInt("pos"));
bool referenceStop(type != "N");
std::set<StopPoint*> stopsSet(
_getStopPoints(
stops,
_stopCodePrefix + stopCode,
boost::optional<const std::string&>()
) );
if(stopsSet.empty())
{
_logWarning(
"Can't find stops for code "+ _stopCodePrefix + stopCode
);
continue;
}
servedStops.push_back(
JourneyPattern::StopWithDepartureArrivalAuthorization(
stopsSet,
stopPos,
(type != "A"),
(type != "D"),
referenceStop
) );
// Ignoring interpolated times
if(referenceStop)
{
// If the bus leaves after midnight, the hours are stored as 0 instead of 24
if( !departureSchedules.empty() && departureTime < *departureSchedules.rbegin())
{
departureTime += hours(24);
}
if( !arrivalSchedules.empty() && arrivalTime < *arrivalSchedules.rbegin())
{
arrivalTime += hours(24);
}
// round of the seconds
departureTime -= seconds(departureTime.seconds());
if(arrivalTime.seconds())
{
arrivalTime += seconds(60 - arrivalTime.seconds());
}
// storage of the times
departureSchedules.push_back(departureTime);
arrivalSchedules.push_back(arrivalTime);
}
}
set<JourneyPattern*> routes(
_getRoutes(
*line,
servedStops,
*_plannedDataSource
) );
if(routes.empty())
{
stringstream routeQuery;
routeQuery << "SELECT * FROM " << _database << ".CHAINAGE c " <<
"WHERE c.ref='" << chainage << "' AND c.jour=" << todayStr;
DBResultSPtr routeResult(db->execQuery(routeQuery.str()));
if(routeResult->next())
{
string routeName(routeResult->getText("nom"));
bool wayBack(routeResult->getText("sens") != "A");
_logCreation(
"Creation of route "+ routeName
);
JourneyPattern* result = new JourneyPattern(
JourneyPatternTableSync::getId()
);
result->setCommercialLine(line);
line->addPath(result);
result->setName(routeName);
result->setWayBack(wayBack);
result->addCodeBySource(*_plannedDataSource, string());
_env.getEditableRegistry<JourneyPattern>().add(boost::shared_ptr<JourneyPattern>(result));
routes.insert(result);
size_t rank(0);
BOOST_FOREACH(const JourneyPattern::StopWithDepartureArrivalAuthorization stop, servedStops)
{
boost::shared_ptr<LineStop> ls(
new LineStop(
LineStopTableSync::getId(),
result,
rank,
rank+1 < servedStops.size() && stop._departure,
rank > 0 && stop._arrival,
*stop._metricOffset,
**stop._stop.begin()
) );
ls->set<ScheduleInput>(stop._withTimes ? *stop._withTimes : true);
ls->link(_env, true);
_env.getEditableRegistry<LineStop>().add(ls);
++rank;
} }
}
assert(!routes.empty());
ScheduledService* service(NULL);
BOOST_FOREACH(JourneyPattern* route, routes)
{
boost::shared_lock<util::shared_recursive_mutex> sharedServicesLock(
*route->sharedServicesMutex
);
BOOST_FOREACH(Service* sservice, route->getAllServices())
{
service = dynamic_cast<ScheduledService*>(sservice);
if(!service)
{
continue;
}
if( service->isActive(today) &&
service->comparePlannedSchedules(departureSchedules, arrivalSchedules)
){
_logLoad(
"Use of service "+ lexical_cast<string>(service->getKey()) +" ("+ lexical_cast<string>(departureSchedules[0]) +") on route "+ lexical_cast<string>(route->getKey()) +" ("+ route->getName() +")"
);
service->addCodeBySource(dataSource, serviceRef);
_services.insert(service);
break;
}
service = NULL;
}
if(service)
{
break;
}
}
if(!service)
{
if (!departureSchedules.empty() && !arrivalSchedules.empty())
{
JourneyPattern* route(*routes.begin());
service = new ScheduledService(
ScheduledServiceTableSync::getId(),
string(),
route
);
service->setDataSchedules(departureSchedules, arrivalSchedules);
service->setPath(route);
service->addCodeBySource(dataSource, serviceRef);
service->setActive(today);
route->addService(*service, false);
_env.getEditableRegistry<ScheduledService>().add(boost::shared_ptr<ScheduledService>(service));
_services.insert(service);
_logCreation(
"Creation of service ("+ lexical_cast<string>(departureSchedules[0]) +") on route "+ lexical_cast<string>(route->getKey()) +" ("+ route->getName() +")"
);
}
else
{
_logWarning(
"Service (ref="+ serviceRef +") has empty departure or arrival schedules, not creating"
);
}
}
}
// 3 : loop on the planned services and remove current day of run if not linked to current source
BOOST_FOREACH(const ImportableTableSync::ObjectBySource<CommercialLineTableSync>::Map::value_type& itLine, lines.getMap())
{
BOOST_FOREACH(const ImportableTableSync::ObjectBySource<CommercialLineTableSync>::Map::mapped_type::value_type& obj, itLine.second)
{
BOOST_FOREACH(Path* route, obj->getPaths())
{
// Avoid junctions
if(!dynamic_cast<JourneyPattern*>(route))
{
continue;
}
JourneyPattern* jp(static_cast<JourneyPattern*>(route));
if(!jp->hasLinkWithSource(*_plannedDataSource))
{
continue;
}
boost::shared_lock<util::shared_recursive_mutex> sharedServicesLock(
*jp->sharedServicesMutex
);
BOOST_FOREACH(const Service* service, jp->getAllServices())
{
const ScheduledService* sservice(dynamic_cast<const ScheduledService*>(service));
if( sservice &&
sservice->isActive(today) &&
!sservice->hasLinkWithSource(dataSource)
){
const_cast<ScheduledService*>(sservice)->setInactive(today);
_logInfo(
"Deactivating unlinked service "+ lexical_cast<string>(sservice->getKey()) +
" on route "+ lexical_cast<string>(sservice->getRoute()->getKey()) +" (" +
sservice->getRoute()->getName() +")"
);
}
}
}
} }
return true;
}
IneoRealTimeFileFormat::Importer_::Importer_(
util::Env& env,
const impex::Import& import,
impex::ImportLogLevel minLogLevel,
const std::string& logPath,
boost::optional<std::ostream&> outputStream,
util::ParametersMap& pm
): Importer(env, import, minLogLevel, logPath, outputStream, pm),
DatabaseReadImporter<IneoRealTimeFileFormat>(env, import, minLogLevel, logPath, outputStream, pm),
PTFileFormat(env, import, minLogLevel, logPath, outputStream, pm)
{}
util::ParametersMap IneoRealTimeFileFormat::Importer_::_getParametersMap() const
{
ParametersMap map;
if(_plannedDataSource.get())
{
map.insert(PARAMETER_PLANNED_DATASOURCE_ID, _plannedDataSource->getKey());
}
if(_courseId)
{
map.insert(PARAMETER_COURSE_ID, *_courseId);
}
if(_dbConnString)
{
map.insert(PARAMETER_DB_CONN_STRING, *_dbConnString);
}
if(!_stopCodePrefix.empty())
{
map.insert(PARAMETER_STOP_CODE_PREFIX, _stopCodePrefix);
}
return map;
}
void IneoRealTimeFileFormat::Importer_::_setFromParametersMap( const util::ParametersMap& map )
{
if(map.isDefined(PARAMETER_PLANNED_DATASOURCE_ID)) try
{
_plannedDataSource = DataSourceTableSync::Get(map.get<RegistryKeyType>(PARAMETER_PLANNED_DATASOURCE_ID), _env);
}
catch(ObjectNotFoundException<DataSource>&)
{
throw Exception("No such planned data source");
}
_courseId = map.getOptional<string>(PARAMETER_COURSE_ID);
_dbConnString = map.getOptional<string>(PARAMETER_DB_CONN_STRING);
_stopCodePrefix = map.getDefault<string>(PARAMETER_STOP_CODE_PREFIX, "");
}
db::DBTransaction IneoRealTimeFileFormat::Importer_::_save() const
{
DBTransaction transaction;
if(_courseId)
{
BOOST_FOREACH(ScheduledService* service, _services)
{
JourneyPatternTableSync::Save(static_cast<JourneyPattern*>(service->getPath()), transaction);
BOOST_FOREACH(LineStop* edge, static_cast<JourneyPattern*>(service->getPath())->getLineStops())
{
LineStopTableSync::Save(edge, transaction);
}
ScheduledServiceTableSync::Save(service, transaction);
} }
else
{
BOOST_FOREACH(const Registry<JourneyPattern>::value_type& journeyPattern, _env.getRegistry<JourneyPattern>())
{
JourneyPatternTableSync::Save(journeyPattern.second.get(), transaction);
}
BOOST_FOREACH(Registry<LineStop>::value_type lineStop, _env.getRegistry<LineStop>())
{
LineStopTableSync::Save(lineStop.second.get(), transaction);
}
BOOST_FOREACH(const Registry<ScheduledService>::value_type& service, _env.getRegistry<ScheduledService>())
{
ScheduledServiceTableSync::Save(service.second.get(), transaction);
}
}
return transaction;
}
}
}
| Open-Transport/synthese | server/src/61_data_exchange/IneoRealTimeFileFormat.cpp | C++ | gpl-2.0 | 15,751 |
// =================================================================================================
// ADOBE SYSTEMS INCORPORATED
// Copyright 2011 Adobe Systems Incorporated
// All Rights Reserved
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
// of the Adobe license agreement accompanying it.
// =================================================================================================
#include "Module.h"
#include "HostAPI.h"
namespace XMP_PLUGIN
{
static bool CheckAPICompatibility_V1 ( const PluginAPIRef pluginAPIs )
{
// these plugin APIs are mandatory to run an XMP file handler
if ( pluginAPIs->mTerminatePluginProc
&& pluginAPIs->mSetHostAPIProc
&& pluginAPIs->mInitializeSessionProc
&& pluginAPIs->mTerminateSessionProc
&& pluginAPIs->mCheckFileFormatProc
&& pluginAPIs->mCheckFolderFormatProc
&& pluginAPIs->mGetFileModDateProc
&& pluginAPIs->mCacheFileDataProc
&& pluginAPIs->mUpdateFileProc
&& pluginAPIs->mWriteTempFileProc )
{
return true;
}
return false;
}
static bool CheckAPICompatibility_V2 ( const PluginAPIRef pluginAPIs )
{
if ( CheckAPICompatibility_V1 ( pluginAPIs ) )
{
if ( pluginAPIs->mFillMetadataFilesProc
&& pluginAPIs->mFillAssociatedResourcesProc )
{
return true;
}
}
return false;
}
static bool CheckAPICompatibility_V3 ( const PluginAPIRef pluginAPIs )
{
if ( CheckAPICompatibility_V2 ( pluginAPIs ) )
{
if ( pluginAPIs->mIsMetadataWritableProc )
{
return true;
}
}
return false;
}
static bool CheckAPICompatibility ( const PluginAPIRef pluginAPIs )
{
// Note: This is the place where we can reject old plugins.
// For example if we consider all functionality of
// plugin API version 2 mandatory we can reject
// plugin version 1 by returning false in case 1.
switch ( pluginAPIs->mVersion )
{
case 1:
return CheckAPICompatibility_V1 ( pluginAPIs );
break;
case 2:
return CheckAPICompatibility_V2 ( pluginAPIs );
break;
case 3:
return CheckAPICompatibility_V3 ( pluginAPIs );
break;
default:
// The loaded plugin is newer than the host.
// Only basic functionality to run the plugin is required.
return CheckAPICompatibility_V1 ( pluginAPIs );
break;
}
}
PluginAPIRef Module::getPluginAPIs()
{
//
// return ref. to Plugin API, load module if not yet loaded
//
if ( !mPluginAPIs || mLoaded != kModuleLoaded )
{
if ( !load() )
{
XMP_Throw ( "Plugin API not available.", kXMPErr_Unavailable );
}
}
return mPluginAPIs;
}
bool Module::load()
{
XMP_AutoLock lock ( &mLoadingLock, kXMP_WriteLock );
return loadInternal();
}
void Module::unload()
{
XMP_AutoLock lock (&mLoadingLock, kXMP_WriteLock);
unloadInternal();
}
void Module::unloadInternal()
{
WXMP_Error error;
//
// terminate plugin
//
if( mPluginAPIs != NULL )
{
if( mPluginAPIs->mTerminatePluginProc )
{
mPluginAPIs->mTerminatePluginProc( &error );
}
delete mPluginAPIs;
mPluginAPIs = NULL;
}
//
// unload plugin module
//
if( mLoaded != kModuleNotLoaded )
{
UnloadModule(mHandle, false);
mHandle = NULL;
if( mLoaded == kModuleLoaded )
{
//
// Reset mLoaded to kModuleNotLoaded, if the module was loaded successfully.
// Otherwise let it remain kModuleErrorOnLoad so that we won't try to load
// it again if some other handler ask to do so.
//
mLoaded = kModuleNotLoaded;
}
}
CheckError( error );
}
bool Module::loadInternal()
{
if( mLoaded == kModuleNotLoaded )
{
const char * errorMsg = NULL;
//
// load module
//
mLoaded = kModuleErrorOnLoad;
mHandle = LoadModule(mPath, false);
if( mHandle != NULL )
{
//
// get entry point function pointer
//
InitializePluginProc InitializePlugin = reinterpret_cast<InitializePluginProc>(
GetFunctionPointerFromModuleImpl(mHandle, "InitializePlugin") ); // legacy entry point
InitializePlugin2Proc InitializePlugin2 = reinterpret_cast<InitializePlugin2Proc>(
GetFunctionPointerFromModuleImpl(mHandle, "InitializePlugin2") );
if( InitializePlugin2 != NULL || InitializePlugin != NULL )
{
std::string moduleID;
GetResourceDataFromModule(mHandle, "MODULE_IDENTIFIER", "txt", moduleID);
mPluginAPIs = new PluginAPI();
memset( mPluginAPIs, 0, sizeof(PluginAPI) );
mPluginAPIs->mSize = sizeof(PluginAPI);
mPluginAPIs->mVersion = XMP_PLUGIN_VERSION; // informational: the latest version that the host knows about
WXMP_Error error;
//
// initialize plugin by calling entry point function
//
if( InitializePlugin2 != NULL )
{
HostAPIRef hostAPI = PluginManager::getHostAPI( XMP_HOST_API_VERSION );
InitializePlugin2( moduleID.c_str(), hostAPI, mPluginAPIs, &error );
if ( error.mErrorID == kXMPErr_NoError )
{
// check all function pointers are correct based on version numbers
if( CheckAPICompatibility( mPluginAPIs ) )
{
mLoaded = kModuleLoaded;
}
else
{
errorMsg = "Incompatible plugin API version.";
}
}
else
{
errorMsg = "Plugin initialization failed.";
}
}
else if( InitializePlugin != NULL )
{
// initialize through legacy plugin entry point
InitializePlugin( moduleID.c_str(), mPluginAPIs, &error );
if ( error.mErrorID == kXMPErr_NoError ) {
// check all function pointers are correct based on version numbers
bool compatibleAPIs = CheckAPICompatibility(mPluginAPIs);
if ( compatibleAPIs )
{
//
// set host API at plugin
//
HostAPIRef hostAPI = PluginManager::getHostAPI( mPluginAPIs->mVersion );
mPluginAPIs->mSetHostAPIProc( hostAPI, &error );
if( error.mErrorID == kXMPErr_NoError )
{
mLoaded = kModuleLoaded;
}
else
{
errorMsg = "Plugin API incomplete.";
}
}
else
{
errorMsg = "Incompatible plugin API version.";
}
}
else
{
errorMsg = "Plugin initialization failed.";
}
}
}
if( mLoaded != kModuleLoaded )
{
//
// plugin wasn't loaded and initialized successfully,
// so unload the module
//
this->unloadInternal();
}
}
else
{
errorMsg = "Can't load module";
}
if ( mLoaded != kModuleLoaded && errorMsg )
{
//
// error occurred
//
throw XMP_Error( kXMPErr_InternalFailure, errorMsg);
}
}
return ( mLoaded == kModuleLoaded );
}
} //namespace XMP_PLUGIN
| yanburman/sjcam_raw2dng | xmp_sdk/XMPFiles/source/PluginHandler/Module.cpp | C++ | gpl-2.0 | 6,540 |
package storm.starter.trident.homework.state;
import storm.trident.operation.TridentCollector;
import storm.trident.state.BaseStateUpdater;
import storm.trident.tuple.TridentTuple;
import java.util.ArrayList;
import java.util.List;
/**
* Updater class that updates the state with the new tweets.
* Created by Parth Satra on 4/5/15.
*/
public class TopKStateUpdater extends BaseStateUpdater<TopKState> {
@Override
public void updateState(TopKState topKState, List<TridentTuple> list, TridentCollector tridentCollector) {
for(TridentTuple tuple : list) {
// Gets all the space separated hashtags.
String hashTags = tuple.getString(0);
String[] tag = hashTags.split(" ");
// Creates the list to be added to the state
List<TopTweet> tweetList = new ArrayList<TopTweet>();
for(String t : tag) {
if(t != null && t.trim().length() != 0) {
TopTweet tt = new TopTweet(t, 1);
tweetList.add(tt);
}
}
// Adds the list to the state.
topKState.add(tweetList);
}
}
}
| parthsatra/TwitterTopKTrends | apache-storm-0.9.3/examples/storm-starter/src/jvm/storm/starter/trident/homework/state/TopKStateUpdater.java | Java | gpl-2.0 | 1,167 |
</div>
<footer>
<p>copyright <a href="mailto:pengmaradi@gmail.com">@Xiaoling Peng</a> <a href="0763363847">call me</a></p>
</footer>
</body>
</html>
| pengmaradi/xp_cms | system/cms/views/footer.php | PHP | gpl-2.0 | 182 |
<?php
/**
* @package gantry
* @subpackage core.params
* @version 3.2.11 September 8, 2011
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2011 RocketTheme, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*
* Gantry uses the Joomla Framework (http://www.joomla.org), a GNU/GPLv2 content management system
*
*/
defined('GANTRY_VERSION') or die();
gantry_import('core.params.gantryparamoverride');
/**
* @package gantry
* @subpackage core.params
*/
class GantrySessionParamOverride extends GantryParamOverride {
function store(){
global $gantry;
foreach($gantry->_setinsession as $session_var){
if ($gantry->_working_params[$session_var]['setby'] != 'menuitem') {
if ($gantry->_working_params[$session_var]['value'] != $gantry->_working_params[$session_var]['sitebase'] && $gantry->_working_params[$session_var]['type'] != 'preset'){
$gantry->session->set($gantry->template_prefix.$gantry->_base_params_checksum."-".$session_var,$gantry->_working_params[$session_var]['value']);
}
else {
$gantry->session->set($gantry->template_prefix.$this->_base_params_checksum."-".$session_var,null);
}
}
}
}
function clean(){
global $gantry;
foreach($gantry->_setinsession as $session_var){
$gantry->session->set($gantry->template_prefix.$this->_base_params_checksum."-".$session_var,null);
}
}
function populate(){
global $gantry;
// get any session param overrides and set to that
// set preset values
foreach($gantry->_preset_names as $param_name) {
$session_param_name = $gantry->template_prefix.$gantry->_base_params_checksum."-".$param_name;
if (in_array($param_name, $gantry->_setbysession) && $gantry->session->get($session_param_name)) {
$param =& $gantry->_working_params[$param_name];
$session_value = $gantry->session->get($session_param_name);
$session_preset_params = $gantry->presets[$param_name][$session_value];
foreach($session_preset_params as $session_preset_param_name => $session_preset_param_value) {
if (array_key_exists($session_preset_param_name, $gantry->_working_params) && !is_null($session_preset_param_value)){
$gantry->_working_params[$session_preset_param_name]['value'] = $session_preset_param_value;
$gantry->_working_params[$session_preset_param_name]['setby'] = 'session';
}
}
}
}
// set individual values
foreach($gantry->_param_names as $param_name) {
$session_param_name = $gantry->template_prefix.$gantry->_base_params_checksum."-".$param_name;
if (in_array($param_name, $gantry->_setbysession) && $gantry->session->get($session_param_name)) {
$param =& $gantry->_working_params[$param_name];
$session_value = $gantry->session->get($session_param_name);
if (!is_null($session_value)){
$gantry->_working_params[$param['name']]['value'] = $session_value;
$gantry->_working_params[$param['name']]['setby'] = 'session';
}
}
}
}
} | epireve/joomla | libraries/gantry/core/params/overrides/gantrysessionparamoverride.class.php | PHP | gpl-2.0 | 3,459 |
"""Module computes indentation for block
It contains implementation of indenters, which are supported by katepart xml files
"""
import logging
logger = logging.getLogger('qutepart')
from PyQt4.QtGui import QTextCursor
def _getSmartIndenter(indenterName, qpart, indenter):
"""Get indenter by name.
Available indenters are none, normal, cstyle, haskell, lilypond, lisp, python, ruby, xml
Indenter name is not case sensitive
Raise KeyError if not found
indentText is indentation, which shall be used. i.e. '\t' for tabs, ' ' for 4 space symbols
"""
indenterName = indenterName.lower()
if indenterName in ('haskell', 'lilypond'): # not supported yet
logger.warning('Smart indentation for %s not supported yet. But you could be a hero who implemented it' % indenterName)
from qutepart.indenter.base import IndentAlgNormal as indenterClass
elif 'none' == indenterName:
from qutepart.indenter.base import IndentAlgBase as indenterClass
elif 'normal' == indenterName:
from qutepart.indenter.base import IndentAlgNormal as indenterClass
elif 'cstyle' == indenterName:
from qutepart.indenter.cstyle import IndentAlgCStyle as indenterClass
elif 'python' == indenterName:
from qutepart.indenter.python import IndentAlgPython as indenterClass
elif 'ruby' == indenterName:
from qutepart.indenter.ruby import IndentAlgRuby as indenterClass
elif 'xml' == indenterName:
from qutepart.indenter.xmlindent import IndentAlgXml as indenterClass
elif 'haskell' == indenterName:
from qutepart.indenter.haskell import IndenterHaskell as indenterClass
elif 'lilypond' == indenterName:
from qutepart.indenter.lilypond import IndenterLilypond as indenterClass
elif 'lisp' == indenterName:
from qutepart.indenter.lisp import IndentAlgLisp as indenterClass
elif 'scheme' == indenterName:
from qutepart.indenter.scheme import IndentAlgScheme as indenterClass
else:
raise KeyError("Indenter %s not found" % indenterName)
return indenterClass(qpart, indenter)
class Indenter:
"""Qutepart functionality, related to indentation
Public attributes:
width Indent width
useTabs Indent uses Tabs (instead of spaces)
"""
_DEFAULT_INDENT_WIDTH = 4
_DEFAULT_INDENT_USE_TABS = False
def __init__(self, qpart):
self._qpart = qpart
self.width = self._DEFAULT_INDENT_WIDTH
self.useTabs = self._DEFAULT_INDENT_USE_TABS
self._smartIndenter = _getSmartIndenter('normal', self._qpart, self)
def setSyntax(self, syntax):
"""Choose smart indentation algorithm according to syntax"""
self._smartIndenter = self._chooseSmartIndenter(syntax)
def text(self):
"""Get indent text as \t or string of spaces
"""
if self.useTabs:
return '\t'
else:
return ' ' * self.width
def triggerCharacters(self):
"""Trigger characters for smart indentation"""
return self._smartIndenter.TRIGGER_CHARACTERS
def autoIndentBlock(self, block, char = '\n'):
"""Indent block after Enter pressed or trigger character typed
"""
cursor = QTextCursor(block)
currentText = block.text()
spaceAtStartLen = len(currentText) - len(currentText.lstrip())
currentIndent = currentText[:spaceAtStartLen]
indent = self._smartIndenter.computeIndent(block, char)
if indent is not None and indent != currentIndent:
self._qpart.replaceText(block.position(), spaceAtStartLen, indent)
def onChangeSelectedBlocksIndent(self, increase, withSpace=False):
"""Tab or Space pressed and few blocks are selected, or Shift+Tab pressed
Insert or remove text from the beginning of blocks
"""
def blockIndentation(block):
text = block.text()
return text[:len(text) - len(text.lstrip())]
def cursorAtSpaceEnd(block):
cursor = QTextCursor(block)
cursor.setPosition(block.position() + len(blockIndentation(block)))
return cursor
def indentBlock(block):
cursor = cursorAtSpaceEnd(block)
cursor.insertText(' ' if withSpace else self.text())
def spacesCount(text):
return len(text) - len(text.rstrip(' '))
def unIndentBlock(block):
currentIndent = blockIndentation(block)
if currentIndent.endswith('\t'):
charsToRemove = 1
elif withSpace:
charsToRemove = 1 if currentIndent else 0
else:
if self.useTabs:
charsToRemove = min(spacesCount(currentIndent), self.width)
else: # spaces
if currentIndent.endswith(self.text()): # remove indent level
charsToRemove = self.width
else: # remove all spaces
charsToRemove = min(spacesCount(currentIndent), self.width)
if charsToRemove:
cursor = cursorAtSpaceEnd(block)
cursor.setPosition(cursor.position() - charsToRemove, QTextCursor.KeepAnchor)
cursor.removeSelectedText()
cursor = self._qpart.textCursor()
startBlock = self._qpart.document().findBlock(cursor.selectionStart())
endBlock = self._qpart.document().findBlock(cursor.selectionEnd())
# If end is positioned in the beginning of a block, do not indent this
# block, since no text is selected in it (beginning of line)
if endBlock.position()==cursor.selectionEnd():
endBlock=endBlock.previous()
indentFunc = indentBlock if increase else unIndentBlock
if startBlock != endBlock: # indent multiply lines
stopBlock = endBlock.next()
block = startBlock
with self._qpart:
while block != stopBlock:
indentFunc(block)
block = block.next()
newCursor = QTextCursor(startBlock)
newCursor.setPosition(endBlock.position() + len(endBlock.text()), QTextCursor.KeepAnchor)
self._qpart.setTextCursor(newCursor)
else: # indent 1 line
indentFunc(startBlock)
def onShortcutIndentAfterCursor(self):
"""Tab pressed and no selection. Insert text after cursor
"""
cursor = self._qpart.textCursor()
def insertIndent():
if self.useTabs:
cursor.insertText('\t')
else: # indent to integer count of indents from line start
charsToInsert = self.width - (len(self._qpart.textBeforeCursor()) % self.width)
cursor.insertText(' ' * charsToInsert)
if cursor.positionInBlock() == 0: # if no any indent - indent smartly
block = cursor.block()
self.autoIndentBlock(block, '')
# if no smart indentation - just insert one indent
if self._qpart.textBeforeCursor() == '':
insertIndent()
else:
insertIndent()
def onShortcutUnindentWithBackspace(self):
"""Backspace pressed, unindent
"""
assert self._qpart.textBeforeCursor().endswith(self.text())
charsToRemove = len(self._qpart.textBeforeCursor()) % len(self.text())
if charsToRemove == 0:
charsToRemove = len(self.text())
cursor = self._qpart.textCursor()
cursor.setPosition(cursor.position() - charsToRemove, QTextCursor.KeepAnchor)
cursor.removeSelectedText()
def onAutoIndentTriggered(self):
"""Indent current line or selected lines
"""
cursor = self._qpart.textCursor()
startBlock = self._qpart.document().findBlock(cursor.selectionStart())
endBlock = self._qpart.document().findBlock(cursor.selectionEnd())
if startBlock != endBlock: # indent multiply lines
stopBlock = endBlock.next()
block = startBlock
with self._qpart:
while block != stopBlock:
self.autoIndentBlock(block, '')
block = block.next()
else: # indent 1 line
self.autoIndentBlock(startBlock, '')
def _chooseSmartIndenter(self, syntax):
"""Get indenter for syntax
"""
if syntax.indenter is not None:
try:
return _getSmartIndenter(syntax.indenter, self._qpart, self)
except KeyError:
logger.error("Indenter '%s' is not finished yet. But you can do it!" % syntax.indenter)
try:
return _getSmartIndenter(syntax.name, self._qpart, self)
except KeyError:
pass
return _getSmartIndenter('normal', self._qpart, self)
| amirgeva/coide | qutepart/indenter/__init__.py | Python | gpl-2.0 | 8,924 |