answer
stringlengths
15
1.25M
package edu.ku.brc.specify.datamodel.busrules; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.text.DateFormat; import java.util.List; import java.util.Set; import java.util.Vector; import javax.swing.<API key>; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.<API key>; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import edu.ku.brc.af.core.AppContextMgr; import edu.ku.brc.af.core.db.DBFieldInfo; import edu.ku.brc.af.core.db.DBTableIdMgr; import edu.ku.brc.af.core.db.DBTableInfo; import edu.ku.brc.af.core.expresssearch.<API key>; import edu.ku.brc.af.ui.forms.FormViewObj; import edu.ku.brc.af.ui.forms.Viewable; import edu.ku.brc.af.ui.forms.persist.AltViewIFace.CreationMode; import edu.ku.brc.af.ui.forms.validation.UIValidator; import edu.ku.brc.af.ui.forms.validation.ValComboBox; import edu.ku.brc.af.ui.forms.validation.<API key>; import edu.ku.brc.af.ui.forms.validation.ValTextField; import edu.ku.brc.dbsupport.DataProviderFactory; import edu.ku.brc.dbsupport.<API key>; import edu.ku.brc.dbsupport.<API key>.QueryIFace; import edu.ku.brc.specify.config.<API key>; import edu.ku.brc.specify.conversion.BasicSQLUtils; import edu.ku.brc.specify.datamodel.CollectionMember; import edu.ku.brc.specify.datamodel.Discipline; import edu.ku.brc.specify.datamodel.SpTaskSemaphore; import edu.ku.brc.specify.datamodel.TreeDefIface; import edu.ku.brc.specify.datamodel.TreeDefItemIface; import edu.ku.brc.specify.datamodel.<API key>; import edu.ku.brc.specify.datamodel.Treeable; import edu.ku.brc.specify.dbsupport.TaskSemaphoreMgr; import edu.ku.brc.specify.dbsupport.TaskSemaphoreMgr.USER_ACTION; import edu.ku.brc.specify.dbsupport.<API key>; import edu.ku.brc.specify.dbsupport.TreeDefStatusMgr; import edu.ku.brc.specify.treeutils.TreeDataService; import edu.ku.brc.specify.treeutils.<API key>; import edu.ku.brc.specify.treeutils.TreeHelper; import edu.ku.brc.ui.GetSetValueIFace; import edu.ku.brc.ui.UIRegistry; /** * @author rod * * (original author was JDS) * * @code_status Alpha * * Jan 10, 2008 * * @param <T> * @param <D> * @param <I> */ public abstract class BaseTreeBusRules<T extends Treeable<T,D,I>, D extends TreeDefIface<T,D,I>, I extends TreeDefItemIface<T,D,I>> extends <API key> { public static final boolean <API key> = true; public static final long <API key> = 60000; private static final Logger log = Logger.getLogger(BaseTreeBusRules.class); private boolean processedRules = false; /** * Constructor. * * @param dataClasses a var args list of classes that this business rules implementation handles */ public BaseTreeBusRules(Class<?>... dataClasses) { super(dataClasses); } /* (non-Javadoc) * @see edu.ku.brc.ui.forms.BaseBusRules#initialize(edu.ku.brc.ui.forms.Viewable) */ @Override public void initialize(Viewable viewableArg) { super.initialize(viewableArg); GetSetValueIFace parentField = (GetSetValueIFace)formViewObj.getControlByName("parent"); Component comp = formViewObj.getControlByName("definitionItem"); if (comp instanceof ValComboBox) { final ValComboBox rankComboBox = (ValComboBox)comp; final JCheckBox acceptedCheckBox = (JCheckBox)formViewObj.getControlByName("isAccepted"); Component apComp = formViewObj.getControlByName("acceptedParent"); final <API key> <API key> = apComp instanceof <API key> ? (<API key> )apComp : null; if (parentField instanceof <API key>) { final <API key> parentCBX = (<API key>)parentField; if (parentCBX != null && rankComboBox != null) { parentCBX.<API key>(new <API key>() { public void valueChanged(ListSelectionEvent e) { if (e == null || !e.getValueIsAdjusting()) { parentChanged(formViewObj, parentCBX, rankComboBox, acceptedCheckBox, <API key>); } } }); rankComboBox.getComboBox().addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { rankChanged(formViewObj, parentCBX, rankComboBox, acceptedCheckBox, <API key>); } }); } } if (acceptedCheckBox != null && <API key> != null) { acceptedCheckBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (acceptedCheckBox.isSelected()) { <API key>.setValue(null, null); <API key>.setChanged(true); // This should be done automatically <API key>.setEnabled(false); } else { <API key>.setEnabled(true); } } }); } } } /** * @return list of foreign key relationships for purposes of checking * if a record can be deleted. * The list contains two entries for each relationship. The first entry * is the related table name. The second is the name of the foreign key field in the related table. */ public abstract String[] <API key>(); /** * @return list of ass foreign key relationships. * The list contains two entries for each relationship. The first entry * is the related table name. The second is the name of the foreign key field in the related table. */ public String[] <API key>() { return <API key>(); } /* (non-Javadoc) * @see edu.ku.brc.af.ui.forms.BaseBusRules#okToEnableDelete(java.lang.Object) */ @SuppressWarnings("unchecked") @Override public boolean okToEnableDelete(Object dataObj) { // This is a little weak and chessey, but it gets the job done. // Becase both the Tree and Definition want/need to share Business Rules. String viewName = formViewObj.getView().getName(); if (StringUtils.contains(viewName, "TreeDef")) { final I treeDefItem = (I)dataObj; if (treeDefItem != null && treeDefItem.getTreeDef() != null) { return treeDefItem.getTreeDef().isRequiredLevel(treeDefItem.getRankId()); } } return super.okToEnableDelete(dataObj); } /** * @param node * @return */ @SuppressWarnings("unchecked") public boolean okToDeleteNode(T node) { if (node.getDefinition() != null && !node.getDefinition().<API key>() && !node.getDefinition().isUploadInProgress()) { //Scary. If nodes are not up to date, tree rules may not work. //The application should prevent edits to items/trees whose tree numbers are not up to date except while uploading //workbenches. throw new RuntimeException(node.getDefinition().getName() + " has out of date node numbers."); } if (node.getDefinition() != null && node.getDefinition().isUploadInProgress()) { //don't think this will ever get called during an upload/upload-undo, but just in case. return true; } Integer id = node.getTreeId(); if (id == null) { return true; } String[] relationships = <API key>(); // if the given node can't be deleted, return false if (!super.okToDelete(relationships, node.getTreeId())) { return false; } // now check the children // get a list of all descendent IDs <API key> session = null; List<Integer> childIDs = null; try { session = DataProviderFactory.getInstance().createSession(); String queryStr = "SELECT n.id FROM " + node.getClass().getName() + " n WHERE n.nodeNumber <= :highChild AND n.nodeNumber > :nodeNum ORDER BY n.rankId DESC"; QueryIFace query = session.createQuery(queryStr, false); query.setParameter("highChild", node.<API key>()); query.setParameter("nodeNum", node.getNodeNumber()); childIDs = (List<Integer>)query.list(); } catch (Exception ex) { edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BaseTreeBusRules.class, ex); // Error Dialog ex.printStackTrace(); } finally { if (session != null) { session.close(); } } // if there are no descendent nodes, return true if (childIDs != null && childIDs.size() == 0) { return true; } // break the descendent checks up into chunks or queries // This is an arbitrary number. Trial and error will determine a good value. This determines // the number of IDs that wind up in the "IN" clause of the query run inside okToDelete(). int chunkSize = 250; int lastRecordChecked = -1; boolean childrenDeletable = true; while (lastRecordChecked + 1 < childIDs.size() && childrenDeletable) { int startOfChunk = lastRecordChecked + 1; int endOfChunk = Math.min(lastRecordChecked+1+chunkSize, childIDs.size()); // grabs selected subset, exclusive of the last index List<Integer> chunk = childIDs.subList(startOfChunk, endOfChunk); Integer[] idChunk = chunk.toArray(new Integer[1]); childrenDeletable = super.okToDelete(relationships, idChunk); lastRecordChecked = endOfChunk - 1; } return childrenDeletable; } @Override protected String <API key>(DBTableInfo tableInfo) { String result = super.<API key>(tableInfo); if (CollectionMember.class.isAssignableFrom(tableInfo.getClassObj())) { Vector<Object> cols = BasicSQLUtils.querySingleCol("select distinct CollectionID from collection " + "where DisciplineID = " + AppContextMgr.getInstance().getClassObject(Discipline.class).getId()); if (cols != null) { String colList = ""; for (Object col : cols) { if (!"".equals(colList)) { colList += ","; } colList += col; } if (!"".equals(colList)) { result = "((" + result + ") or " + tableInfo.getAbbrev() + ".CollectionMemberID in(" + colList + "))"; } } } return result; } @SuppressWarnings("unchecked") protected void rankChanged(final FormViewObj form, final <API key> parentComboBox, final ValComboBox rankComboBox, final JCheckBox acceptedCheckBox, final <API key> <API key>) { if (form.getAltView().getMode() != CreationMode.EDIT) { return; } //log.debug("form was validated: calling <API key>()"); Object objInForm = form.getDataObj(); //log.debug("form data object = " + objInForm); if (objInForm == null) { return; } final T formNode = (T)objInForm; T parent = null; if (parentComboBox.getValue() instanceof String) { // the data is still in the VIEW mode for some reason log.debug("Form is in mode (" + form.getAltView().getMode() + ") but the parent data is a String"); parentComboBox.getValue(); parent = formNode.getParent(); } else { parent = (T)parentComboBox.getValue(); } final T theParent = parent; I rankObj = (I )rankComboBox.getValue(); final int rank = rankObj == null ? -2 : rankObj.getRankId(); SwingUtilities.invokeLater(new Runnable() { public void run() { boolean canSynonymize = false; if (canAccessSynonymy(formNode, rank)) { canSynonymize = formNode.getDefinition() != null && formNode.getDefinition() .getSynonymizedLevel() <= rank && formNode.getDescendantCount() == 0; } if (acceptedCheckBox != null && <API key> != null) { acceptedCheckBox.setEnabled(canSynonymize && theParent != null); if (acceptedCheckBox.isSelected() && acceptedCheckBox.isEnabled()) { <API key>.setValue(null, null); <API key>.setChanged(true); // This should be done automatically <API key>.setEnabled(false); } } form.getValidator().validateForm(); } }); } @SuppressWarnings("unchecked") protected void parentChanged(final FormViewObj form, final <API key> parentComboBox, final ValComboBox rankComboBox, final JCheckBox acceptedCheckBox, final <API key> <API key>) { if (form.getAltView().getMode() != CreationMode.EDIT) { return; } //log.debug("form was validated: calling <API key>()"); Object objInForm = form.getDataObj(); //log.debug("form data object = " + objInForm); if (objInForm == null) { return; } final T formNode = (T)objInForm; // set the contents of this combobox based on the value chosen as the parent <API key>(parentComboBox, rankComboBox, formNode); T parent = null; if (parentComboBox.getValue() instanceof String) { // the data is still in the VIEW mode for some reason log.debug("Form is in mode (" + form.getAltView().getMode() + ") but the parent data is a String"); parentComboBox.getValue(); parent = formNode.getParent(); } else { parent = (T)parentComboBox.getValue(); } // set the tree def for the object being edited by using the parent node's tree def // set the parent too??? (lookups for the AcceptedParent QueryComboBox need this) if (parent != null) { formNode.setDefinition(parent.getDefinition()); formNode.setParent(parent); } SwingUtilities.invokeLater(new Runnable() { public void run() { boolean rnkEnabled = rankComboBox.getComboBox().getModel().getSize() > 0; rankComboBox.setEnabled(rnkEnabled); JLabel label = form.getLabelFor(rankComboBox); if (label != null) { label.setEnabled(rnkEnabled); } if (rankComboBox.hasFocus() && !rnkEnabled) { parentComboBox.requestFocus(); } rankChanged(formViewObj, parentComboBox, rankComboBox, acceptedCheckBox, <API key>); form.getValidator().validateForm(); } }); } /** * @param parentField * @param rankComboBox * @param nodeInForm */ @SuppressWarnings("unchecked") protected void <API key>(final GetSetValueIFace parentField, final ValComboBox rankComboBox, final T nodeInForm) { log.debug("Adjusting the model for the 'rank' combo box in a tree node form"); if (nodeInForm == null) { return; } log.debug("nodeInForm = " + nodeInForm.getName()); <API key><I> model = (<API key><I>)rankComboBox.getModel(); model.removeAllElements(); // this is the highest rank the edited item can possibly be I topItem = null; // this is the lowest rank the edited item can possibly be I bottomItem = null; Object value = parentField.getValue(); T parent = null; if (value instanceof String) { // this happens when the combobox is in view mode, which means it's really a textfield // in that case, the parent of the node in the form will do, since the user can't change the parents parent = nodeInForm.getParent(); } else { parent = (T)parentField.getValue(); } if (parent == null) { return; } // grab all the def items from just below the parent's item all the way to the next enforced level // or to the level of the highest ranked child topItem = parent.getDefinitionItem().getChild(); log.debug("highest valid tree level: " + topItem); if (topItem == null) { // this only happens if a parent was chosen that cannot have children b/c it is at the // lowest defined level in the tree log.warn("Chosen node cannot be a parent node. It is at the lowest defined level of the tree."); return; } // find the child with the highest rank and set that child's def item as the bottom of the range if (!nodeInForm.getChildren().isEmpty()) { for (T child: nodeInForm.getChildren()) { if (bottomItem==null || child.getRankId()>bottomItem.getRankId()) { bottomItem = child.getDefinitionItem().getParent(); } } } log.debug("lowest valid tree level: " + bottomItem); I item = topItem; boolean done = false; while (!done) { model.addElement(item); if (item.getChild()==null || item.getIsEnforced()==Boolean.TRUE || (bottomItem != null && item.getRankId().intValue()==bottomItem.getRankId().intValue()) ) { done = true; } item = item.getChild(); } if (nodeInForm.getDefinitionItem() != null) { I defItem = nodeInForm.getDefinitionItem(); for (int i = 0; i < model.getSize(); ++i) { I modelItem = (I)model.getElementAt(i); if (modelItem.getRankId().equals(defItem.getRankId())) { log.debug("setting rank selected value to " + modelItem); model.setSelectedItem(modelItem); } } // if (model.getIndexOf(defItem) != -1) // model.setSelectedItem(defItem); } else if (model.getSize() == 1) { Object defItem = model.getElementAt(0); log.debug("setting rank selected value to the only available option: " + defItem); model.setSelectedItem(defItem); } } /* (non-Javadoc) * @see edu.ku.brc.ui.forms.BaseBusRules#afterFillForm(java.lang.Object) */ @SuppressWarnings("unchecked") @Override public void afterFillForm(final Object dataObj) { // This is a little weak and cheesey, but it gets the job done. // Because both the Tree and Definition want/need to share Business Rules. String viewName = formViewObj.getView().getName(); if (StringUtils.contains(viewName, "TreeDef")) { if (formViewObj.getAltView().getMode() != CreationMode.EDIT) { // when we're not in edit mode, we don't need to setup any listeners since the user can't change anything //log.debug("form is not in edit mode: no special listeners will be attached"); return; } if (!StringUtils.contains(viewName, "TreeDefItem")) { return; } final I nodeInForm = (I)formViewObj.getDataObj(); //disable FullName -related fields if TreeDefItem is used by nodes in the tree //NOTE: Can remove the edit restriction. Tree rebuilds now update fullname fields. Need to add tree rebuild after fullname def edits. if (nodeInForm != null && nodeInForm.getTreeDef() != null) { // boolean <API key> = nodeInForm.hasTreeEntries(); // if (<API key>) // ValTextField ftCtrl = (ValTextField )formViewObj.getControlByName("textAfter"); // if (ftCtrl != null) // ftCtrl.setEnabled(false); // ftCtrl = (ValTextField )formViewObj.getControlByName("textBefore"); // if (ftCtrl != null) // ftCtrl.setEnabled(false); // ftCtrl = (ValTextField )formViewObj.getControlByName("fullNameSeparator"); // if (ftCtrl != null) // ftCtrl.setEnabled(false); // ValCheckBox ftBox = (ValCheckBox )formViewObj.getControlByName("isInFullName"); // if (ftBox != null) // ftBox.setEnabled(false); if (!viewName.endsWith("TreeDefItem")) { return; } //disabling editing of name and rank for standard levels. List<<API key>> stds = nodeInForm.getTreeDef().getStandardLevels(); <API key> stdLevel = null; for (<API key> std : stds) { //if (std.getTitle().equals(nodeInForm.getName()) && std.getRank() == nodeInForm.getRankId()) if (std.getRank() == nodeInForm.getRankId()) { stdLevel = std; break; } } if (stdLevel != null) { ValTextField nameCtrl = (ValTextField )formViewObj.getControlByName("name"); Component rankCtrl = formViewObj.getControlByName("rankId"); if (nameCtrl != null) { nameCtrl.setEnabled(false); } if (rankCtrl != null) { rankCtrl.setEnabled(false); } if (nodeInForm.getTreeDef().isRequiredLevel(stdLevel.getRank())) { Component enforcedCtrl = formViewObj.getControlByName("isEnforced"); if (enforcedCtrl != null) { enforcedCtrl.setEnabled(false); } } } } return; } final T nodeInForm = (T) formViewObj.getDataObj(); if (formViewObj.getAltView().getMode() != CreationMode.EDIT) { if (nodeInForm != null) { //XXX this MAY be necessary due to a bug with <API key>?? // <API key>.setValue() does nothing because of a null adapter member. Component comp = formViewObj.getControlByName("definitionItem"); if (comp instanceof JTextField) { ((JTextField )comp).setText(nodeInForm.getDefinitionItem().getName()); } } } else { processedRules = false; GetSetValueIFace parentField = (GetSetValueIFace) formViewObj .getControlByName("parent"); Component comp = formViewObj.getControlByName("definitionItem"); if (comp instanceof ValComboBox) { final ValComboBox rankComboBox = (ValComboBox) comp; if (parentField instanceof <API key>) { final <API key> parentCBX = (<API key>) parentField; if (parentCBX != null && rankComboBox != null && nodeInForm != null) { parentCBX.<API key>(new <API key>(nodeInForm, rankComboBox, <API key>.PARENT)); } } if (nodeInForm != null && nodeInForm.getDefinitionItem() != null) { // log.debug("node in form already has a set rank: forcing a call to // <API key>()"); UIValidator.<API key>(this, true); <API key>(parentField, rankComboBox, nodeInForm); UIValidator.<API key>(this, false); } // TODO: the form system MUST require the accepted parent widget to be present if // the // isAccepted checkbox is present final JCheckBox acceptedCheckBox = (JCheckBox) formViewObj .getControlByName("isAccepted"); final <API key> <API key> = (<API key>) formViewObj .getControlByName("acceptedParent"); if (canAccessSynonymy(nodeInForm)) { if (acceptedCheckBox != null && <API key> != null) { if (acceptedCheckBox.isSelected() && nodeInForm != null && nodeInForm.getDefinition() != null) { // disable if necessary boolean canSynonymize = nodeInForm.getDefinition() .getSynonymizedLevel() <= nodeInForm .getRankId() && nodeInForm.getDescendantCount() == 0; acceptedCheckBox.setEnabled(canSynonymize); } <API key>.setEnabled(!acceptedCheckBox .isSelected() && acceptedCheckBox.isEnabled()); if (acceptedCheckBox.isSelected()) { <API key>.setValue(null, null); } if (nodeInForm != null && <API key> != null && rankComboBox != null) { <API key> .<API key>(new <API key>( nodeInForm, rankComboBox, <API key>.ACCEPTED_PARENT)); } } } else { if (acceptedCheckBox != null) { acceptedCheckBox.setEnabled(false); } if (<API key> != null) { <API key>.setEnabled(false); } } if (parentField instanceof <API key>) { parentChanged(formViewObj, (<API key>) parentField, rankComboBox, acceptedCheckBox, <API key>); } } } } /** * @param tableInfo * * @return Select (i.e. everything before where clause) of sqlTemplate */ protected String <API key>(final DBTableInfo tableInfo) { StringBuilder sb = new StringBuilder(); sb.append("select %s1 FROM "); //$NON-NLS-1$ sb.append(tableInfo.getClassName()); sb.append(" as "); //$NON-NLS-1$ sb.append(tableInfo.getAbbrev()); String joinSnipet = <API key>.getInstance().getJoinClause(tableInfo, true, null, false); //arg 2: false means SQL if (joinSnipet != null) { sb.append(' '); sb.append(joinSnipet); } sb.append(' '); return sb.toString(); } /** * @param dataObj * * return true if acceptedParent and accepted fields should be enabled on data forms. */ @SuppressWarnings("unchecked") protected boolean canAccessSynonymy(final T dataObj) { if (dataObj == null) { return false; } if (dataObj.getChildren().size() > 0) { return false; } TreeDefItemIface<?,?,?> defItem = dataObj.getDefinitionItem(); if (defItem == null) { return false; } TreeDefIface<?,?,?> def = dataObj.getDefinition(); if (def == null) { def = ((<API key> )AppContextMgr.getInstance()).getTreeDefForClass((Class<? extends Treeable<?,?,?>> )dataObj.getClass()); } if (!def.isSynonymySupported()) { return false; } return defItem.getRankId() >= def.getSynonymizedLevel(); } /** * @param dataObj * @param rank * @return true if the rank is synonymizable according to the relevant TreeDefinition * * For use when dataObj's rank has not yet been assigned or updated. */ @SuppressWarnings("unchecked") protected boolean canAccessSynonymy(final T dataObj, final int rank) { if (dataObj == null) { return false; } if (dataObj.getChildren().size() > 0) { return false; } TreeDefIface<?,?,?> def = ((<API key> )AppContextMgr.getInstance()).getTreeDefForClass((Class<? extends Treeable<?,?,?>> )dataObj.getClass()); if (!def.isSynonymySupported()) { return false; } return rank >= def.getSynonymizedLevel(); } /** * Updates the fullname field of any nodes effected by changes to <code>node</code> that are about * to be saved to the DB. * * @param node * @param session * @param nameChanged * @param parentChanged * @param rankChanged */ @SuppressWarnings("unchecked") protected void <API key>(T node, <API key> session) { if (!(node.getDefinition().<API key>() && node.getDefinition().<API key>())) { return; } if (node.getTreeId() == null) { // this is a new node // it shouldn't need updating since we set the fullname at creation time return; } boolean updateNodeFullName = false; boolean updateDescFullNames = false; // we need a way to determine if the name changed // load a fresh copy from the DB and get the values needed for comparison <API key> tmpSession = DataProviderFactory.getInstance().createSession(); T fromDB = (T)tmpSession.get(node.getClass(), node.getTreeId()); tmpSession.close(); if (fromDB == null) { // this node is new and hasn't yet been flushed to the DB, so we don't need to worry about updating fullnames //return; fromDB = node; } T origParent = fromDB.getParent(); boolean parentChanged = false; T currentParent = node.getParent(); if ((currentParent == null && origParent != null) || (currentParent != null && origParent == null)) { // I can't imagine how this would ever happen, but just in case parentChanged = true; } if (currentParent != null && origParent != null && !currentParent.getTreeId().equals(origParent.getTreeId())) { // the parent ID changed parentChanged = true; } boolean <API key> = false; if (parentChanged) { <API key> = <API key>(node); <API key> |= <API key>(fromDB); } if (parentChanged && <API key>) { updateNodeFullName = true; updateDescFullNames = true; } boolean nameChanged = !(fromDB.getName().equals(node.getName())); boolean rankChanged = !(fromDB.getRankId().equals(node.getRankId())); if (rankChanged || nameChanged) { updateNodeFullName = true; if (booleanValue(fromDB.getDefinitionItem().getIsInFullName(), false) == true) { updateDescFullNames = true; } if (booleanValue(node.getDefinitionItem().getIsInFullName(), false) == true) { updateDescFullNames = true; } } else if (fromDB == node) { updateNodeFullName = true; } if (updateNodeFullName) { if (updateDescFullNames) { // this could take a long time TreeHelper.<API key>(node); } else { // this should be really fast String fullname = TreeHelper.generateFullname(node); node.setFullName(fullname); } } } protected boolean <API key>(T node) { boolean <API key> = false; // this doesn't necessarily mean the fullname has to be changed // if no higher levels are included in the fullname, then nothing needs updating // so, let's see if higher levels factor into the fullname T l = node.getParent(); while (l != null) { if ((l.getDefinitionItem().getIsInFullName() != null) && (l.getDefinitionItem().getIsInFullName().booleanValue() == true)) { <API key> = true; break; } l = l.getParent(); } return <API key>; } /* (non-Javadoc) * @see edu.ku.brc.specify.datamodel.busrules.BaseBusRules#beforeSave(java.lang.Object, edu.ku.brc.dbsupport.<API key>) */ @SuppressWarnings("unchecked") @Override public void beforeSave(Object dataObj, <API key> session) { super.beforeSave(dataObj, session); if (dataObj instanceof Treeable) { // NOTE: the instanceof check can't check against 'T' since T isn't a class // this has a SMALL amount of risk to it T node = (T)dataObj; if (!node.getDefinition().<API key>() && !node.getDefinition().isUploadInProgress()) { //Scary. If nodes are not up to date, tree rules may not work (actually this one is OK. (for now)). //The application should prevent edits to items/trees whose tree numbers are not up to date except while uploading //workbenches. throw new RuntimeException(node.getDefinition().getName() + " has out of date node numbers."); } // set it's fullname String fullname = TreeHelper.generateFullname(node); node.setFullName(fullname); } } /* (non-Javadoc) * @see edu.ku.brc.specify.datamodel.busrules.BaseBusRules#afterSaveCommit(java.lang.Object) */ @SuppressWarnings("unchecked") @Override public boolean beforeSaveCommit(final Object dataObj, final <API key> session) throws Exception { // PLEASE NOTE! // If any changes are made to this check to make sure no one (Like GeologicTimePeriod) is overriding this method // and make the appropriate changes there also. if (!super.beforeSaveCommit(dataObj, session)) { return false; } boolean success = true; // compare the dataObj values to the nodeBeforeSave values to determine if a node was moved or added if (dataObj instanceof Treeable) { // NOTE: the instanceof check can't check against 'T' since T isn't a class // this has a SMALL amount of risk to it T node = (T)dataObj; if (!node.getDefinition().<API key>() && !node.getDefinition().isUploadInProgress()) { //Scary. If nodes are not up to date, tree rules may not work. //The application should prevent edits to items/trees whose tree numbers are not up to date except while uploading //workbenches. throw new RuntimeException(node.getDefinition().getName() + " has out of date node numbers."); } // if the node doesn't have any assigned node number, it must be new boolean added = (node.getNodeNumber() == null); if (node.getDefinition().<API key>() && node.getDefinition().<API key>()) { log.info("Saved tree node was added. Updating node numbers appropriately."); TreeDataService<T,D,I> dataServ = <API key>.createService(); if (added) { success = dataServ.<API key>(node, session); } else { success = dataServ.<API key>(node, session); } } else { node.getDefinition().<API key>(false); } } return success; } /* (non-Javadoc) * @see edu.ku.brc.af.ui.forms.BaseBusRules#beforeDeleteCommit(java.lang.Object, edu.ku.brc.dbsupport.<API key>) */ /* * NOTE: If this method is overridden, freeLocks() MUST be called when result is false * !! * */ @Override public boolean beforeDeleteCommit(Object dataObj, <API key> session) throws Exception { if (!super.beforeDeleteCommit(dataObj, session)) { return false; } if (dataObj != null && (formViewObj == null || !StringUtils.contains(formViewObj.getView().getName(), "TreeDef")) && BaseTreeBusRules.<API key> && viewable != null) { return getRequiredLocks(dataObj); } else { return true; } } /* (non-Javadoc) * @see edu.ku.brc.ui.forms.BaseBusRules#afterDeleteCommit(java.lang.Object) */ @SuppressWarnings("unchecked") @Override public void afterDeleteCommit(Object dataObj) { try { if (dataObj instanceof Treeable) { // NOTE: the instanceof check can't check against 'T' since T // isn't a class // this has a SMALL amount of risk to it T node = (T) dataObj; if (!node.getDefinition().<API key>() && !node.getDefinition().isUploadInProgress()) { // Scary. If nodes are not up to date, tree rules may not // work. // The application should prevent edits to items/trees whose // tree numbers are not up to date except while uploading // workbenches. throw new RuntimeException(node.getDefinition().getName() + " has out of date node numbers."); } if (node.getDefinition().<API key>() && node.getDefinition().<API key>()) { log .info("A tree node was deleted. Updating node numbers appropriately."); TreeDataService<T, D, I> dataServ = <API key> .createService(); // apparently a refresh() is necessary. node can hold // obsolete values otherwise. // Possibly needs to be done for all business rules?? <API key> session = null; try { session = DataProviderFactory.getInstance() .createSession(); // rods - 07/28/08 commented out because the node is // already deleted // session.refresh(node); dataServ.<API key>(node, session); } catch (Exception ex) { edu.ku.brc.exceptions.ExceptionTracker.getInstance() .capture(BaseTreeBusRules.class, ex); ex.printStackTrace(); } finally { if (session != null) { session.close(); } } } else { node.getDefinition().<API key>(false); } } } finally { if (BaseTreeBusRules.<API key> && viewable != null) { this.freeLocks(); } } } /** * Handles the {@link #beforeSave(Object)} method if the passed in {@link Object} * is an instance of {@link TreeDefItemIface}. The real work of this method is to * update the 'fullname' field of all {@link Treeable} objects effected by the changes * to the passed in {@link TreeDefItemIface}. * * @param defItem the {@link TreeDefItemIface} being saved */ @SuppressWarnings("unchecked") protected void <API key>(I defItem) { // we need a way to determine if the 'isInFullname' value changed // load a fresh copy from the DB and get the values needed for comparison <API key> tmpSession = DataProviderFactory.getInstance().createSession(); I fromDB = (I)tmpSession.load(defItem.getClass(), defItem.getTreeDefItemId()); tmpSession.close(); <API key> session = DataProviderFactory.getInstance().createSession(); session.attach(defItem); boolean changeThisLevel = false; boolean <API key> = false; boolean fromDBIsInFullname = makeNotNull(fromDB.getIsInFullName()); boolean currentIsInFullname = makeNotNull(defItem.getIsInFullName()); if (fromDBIsInFullname != currentIsInFullname) { <API key> = true; } // look for changes in the 'textBefore', 'textAfter' or 'fullNameSeparator' fields String fromDbBeforeText = makeNotNull(fromDB.getTextBefore()); String fromDbAfterText = makeNotNull(fromDB.getTextAfter()); String fromDbSeparator = makeNotNull(fromDB.<API key>()); String before = makeNotNull(defItem.getTextBefore()); String after = makeNotNull(defItem.getTextAfter()); String separator = makeNotNull(defItem.<API key>()); boolean textFieldChanged = false; boolean beforeChanged = !before.equals(fromDbBeforeText); boolean afterChanged = !after.equals(fromDbAfterText); boolean sepChanged = !separator.equals(fromDbSeparator); if (beforeChanged || afterChanged || sepChanged) { textFieldChanged = true; } if (textFieldChanged) { if (currentIsInFullname) { <API key> = true; } changeThisLevel = true; } if (changeThisLevel && !<API key>) { Set<T> levelNodes = defItem.getTreeEntries(); for (T node: levelNodes) { String generated = TreeHelper.generateFullname(node); node.setFullName(generated); } } else if (changeThisLevel && <API key>) { Set<T> levelNodes = defItem.getTreeEntries(); for (T node: levelNodes) { TreeHelper.<API key>(node); } } else if (!changeThisLevel && <API key>) { Set<T> levelNodes = defItem.getTreeEntries(); for (T node: levelNodes) { // grab all child nodes and go from there for (T child: node.getChildren()) { TreeHelper.<API key>(child); } } } // else don't change anything session.close(); } protected boolean booleanValue(Boolean bool, boolean defaultIfNull) { if (bool != null) { return bool.booleanValue(); } return defaultIfNull; } /** * Converts a null string into an empty string. If the provided String is not * null, it is returned unchanged. * * @param s a string * @return the string or " ", if null */ private String makeNotNull(String s) { return (s == null) ? "" : s; } /** * Returns the provided {@link Boolean}, or <code>false</code> if null * * @param b the {@link Boolean} to convert to non-null * @return the provided {@link Boolean}, or <code>false</code> if null */ private boolean makeNotNull(Boolean b) { return (b == null) ? false : b.booleanValue(); } /* (non-Javadoc) * @see edu.ku.brc.ui.forms.BaseBusRules#beforeDelete(java.lang.Object, edu.ku.brc.dbsupport.<API key>) */ @Override public Object beforeDelete(Object dataObj, <API key> session) { super.beforeDelete(dataObj, session); if (dataObj instanceof Treeable<?,?,?>) { Treeable<?, ?, ?> node = (Treeable<?,?,?> )dataObj; if (node.getAcceptedParent() != null) { node.getAcceptedParent().getAcceptedChildren().remove(node); node.setAcceptedParent(null); } } return dataObj; } /** * @param parentDataObj * @param dataObj * @return */ @SuppressWarnings("unchecked") protected boolean <API key>(final Object parentDataObj, final Object dataObj) { if (dataObj instanceof Treeable<?,?,?>) { Treeable<T, D, I> node = (Treeable<T,D,I> )dataObj; Treeable<T, D, I> parent = parentDataObj == null ? node.getParent() : (Treeable<T, D, I> )parentDataObj; if (parent != null) { //XXX the sql below will only work if all Treeable tables use fields named 'isAccepted' and 'name' to store //the name and isAccepted properties. String tblName = DBTableIdMgr.getInstance().getInfoById(node.getTableId()).getName(); String sql = "SELECT count(*) FROM " + tblName + " where isAccepted " + "and name = " + BasicSQLUtils.<API key>(node.getName()); if (parent.getTreeId() != null) { sql += " and parentid = " + parent.getTreeId(); } if (node.getTreeId() != null) { sql += " and " + tblName + "id != " + node.getTreeId(); } return BasicSQLUtils.getNumRecords(sql) > 0; } } return false; } /** * @param parentDataObj * @param dataObj * @param isExistingObject * @return */ @SuppressWarnings("unchecked") public STATUS <API key>(final Object parentDataObj, final Object dataObj, final boolean isExistingObject) { STATUS result = STATUS.OK; if (<API key>(parentDataObj, dataObj)) { String parentName; if (parentDataObj == null) { parentName = ((Treeable<T,D,I> )dataObj).getParent().getFullName(); } else { parentName = ((Treeable<T,D,I> )parentDataObj).getFullName(); } boolean saveIt = UIRegistry.displayConfirm( UIRegistry.getResourceString("BaseTreeBusRules.<API key>"), String.format(UIRegistry.getResourceString("BaseTreeBusRules.<API key>"), parentName, ((Treeable<T,D,I> )dataObj).getName()), UIRegistry.getResourceString("SAVE"), UIRegistry.getResourceString("CANCEL"), JOptionPane.QUESTION_MESSAGE); if (!saveIt) { //Adding to reasonList prevents blank "Issue of Concern" popup - //but causes annoying second "duplicate child" nag. reasonList .add(UIRegistry .getResourceString("BaseTreeBusRules.<API key>")); // XXX // i18n result = STATUS.Error; } } return result; } /** * @param dataObj * @return OK if required data is present. * * Checks for requirements that can't be defined in the database schema. */ protected STATUS <API key>(Object dataObj) { if (dataObj instanceof Treeable<?,?,?>) { STATUS result = STATUS.OK; Treeable<?,?,?> obj = (Treeable<?,?,?> )dataObj; if (obj.getParent() == null ) { if (obj.getDefinitionItem() != null && obj.getDefinitionItem().getParent() == null) { //it's the root, null parent is OK. return result; } result = STATUS.Error; DBTableInfo info = DBTableIdMgr.getInstance().getInfoById(obj.getTableId()); DBFieldInfo fld = info.<API key>("Parent"); String fldTitle = fld != null ? fld.getTitle() : UIRegistry.getResourceString("PARENT"); reasonList.add(String.format(UIRegistry.getResourceString("<API key>"), fldTitle)); } //check that non-accepted node has an 'AcceptedParent' if (obj.getIsAccepted() == null || !obj.getIsAccepted() && obj.getAcceptedParent() == null) { result = STATUS.Error; DBTableInfo info = DBTableIdMgr.getInstance().getInfoById(obj.getTableId()); DBFieldInfo fld = info.<API key>("AcceptedParent"); String fldTitle = fld != null ? fld.getTitle() : UIRegistry.getResourceString("ACCEPTED"); reasonList.add(String.format(UIRegistry.getResourceString("<API key>"), fldTitle)); } return result; } return STATUS.None; } /* (non-Javadoc) * @see edu.ku.brc.af.ui.forms.BaseBusRules#<API key>(java.lang.Object, java.lang.Object, boolean) */ @Override public STATUS <API key>(Object parentDataObj, Object dataObj, boolean isExistingObject) { reasonList.clear(); STATUS result = STATUS.OK; if (!processedRules && dataObj instanceof Treeable<?, ?, ?>) { result = <API key>(parentDataObj, dataObj, isExistingObject); if (result == STATUS.OK) { result = <API key>(dataObj); } if (result == STATUS.OK) { processedRules = true; } } return result; } /* (non-Javadoc) * @see edu.ku.brc.af.ui.forms.BaseBusRules#isOkToSave(java.lang.Object, edu.ku.brc.dbsupport.<API key>) */ /* * NOTE: If this method is overridden, freeLocks() MUST be called when result is false * !! * */ @Override public boolean isOkToSave(Object dataObj, <API key> session) { boolean result = super.isOkToSave(dataObj, session); if (result && dataObj != null && !StringUtils.contains(formViewObj.getView().getName(), "TreeDef") && BaseTreeBusRules.<API key>) { if (!getRequiredLocks(dataObj)) { result = false; reasonList.add(getUnableToLockMsg()); } } return result; } /** * @return true if locks were aquired. * * Locks necessary tables prior to a save. * Only used when <API key> is true. */ protected boolean getRequiredLocks(Object dataObj) { TreeDefIface<?,?,?> treeDef = ((Treeable<?,?,?>)dataObj).getDefinition(); boolean result = !TreeDefStatusMgr.isRenumberingNodes(treeDef) && TreeDefStatusMgr.<API key>(treeDef); if (!result) { try { Thread.sleep(1500); result = !TreeDefStatusMgr.isRenumberingNodes(treeDef) && TreeDefStatusMgr.<API key>(treeDef); } catch (Exception e) { result = false; } } if (result) { TaskSemaphoreMgr.USER_ACTION r = TaskSemaphoreMgr.lock(<API key>(), getFormSaveLockName(), "save", TaskSemaphoreMgr.SCOPE.Discipline, false, new <API key>(){ /* (non-Javadoc) * @see edu.ku.brc.specify.dbsupport.<API key>#resolveConflict(edu.ku.brc.specify.datamodel.SpTaskSemaphore, boolean, java.lang.String) */ @Override public USER_ACTION resolveConflict( SpTaskSemaphore semaphore, boolean previouslyLocked, String prevLockBy) { if (System.currentTimeMillis() - semaphore.getLockedTime().getTime() > <API key>) { //something is clearly wrong with the lock. Ignore it and re-use it. It will be cleared when save succeeds. log.warn("automatically overriding expired " + <API key>() + " lock set by " + prevLockBy + " at " + DateFormat.getDateTimeInstance().format(semaphore.getLockedTime())); return USER_ACTION.OK; } else { return USER_ACTION.Error; } } }, false); result = r == TaskSemaphoreMgr.USER_ACTION.OK; } return result; } /** * @return the class for the generic parameter <T> */ protected abstract Class<?> getNodeClass(); /** * @return the title for the form save lock. */ protected String <API key>() { return String.format(UIRegistry.getResourceString("BaseTreeBusRules.SaveLockTitle"), getNodeClass().getSimpleName()); } /** * @return the name for the form save lock. */ protected String getFormSaveLockName() { return getNodeClass().getSimpleName() + "Save"; } /** * @return localized message to display in case of failure to lock for saving. */ protected String getUnableToLockMsg() { return UIRegistry.getResourceString("BaseTreeBusRules.UnableToLockForSave"); } /** * Free locks acquired for saving. */ protected void freeLocks() { TaskSemaphoreMgr.unlock(<API key>(), getFormSaveLockName(), TaskSemaphoreMgr.SCOPE.Discipline); } /* (non-Javadoc) * @see edu.ku.brc.af.ui.forms.BaseBusRules#afterSaveCommit(java.lang.Object, edu.ku.brc.dbsupport.<API key>) */ @Override public boolean afterSaveCommit(Object dataObj, <API key> session) { boolean result = false; if (!super.afterSaveCommit(dataObj, session)) { result = false; } if (BaseTreeBusRules.<API key> && viewable != null) { freeLocks(); } return result; } /* (non-Javadoc) * @see edu.ku.brc.af.ui.forms.BaseBusRules#afterSaveFailure(java.lang.Object, edu.ku.brc.dbsupport.<API key>) */ @Override public void afterSaveFailure(Object dataObj, <API key> session) { super.afterSaveFailure(dataObj, session); if (BaseTreeBusRules.<API key> && viewable != null) { freeLocks(); } } /* (non-Javadoc) * @see edu.ku.brc.af.ui.forms.BaseBusRules#<API key>(java.lang.Object) */ @Override public STATUS <API key>(Object dataObj) { STATUS result = STATUS.OK; if (!processedRules) { result = super.<API key>(dataObj); if (result == STATUS.OK) { result = <API key>(null, dataObj, false); } if (result == STATUS.OK) { result = <API key>(dataObj); } } else { processedRules = false; } return result; } }
<?php class Cmsms_Profiles { function Cmsms_Profiles() { $cmsms_option = <API key>(); $profile_labels = array( 'name' => __('Profiles', '<API key>'), 'singular_name' => __('Profiles', '<API key>'), 'menu_name' => __('Profiles', '<API key>'), 'all_items' => __('All Profiles', '<API key>'), 'add_new' => __('Add New', '<API key>'), 'add_new_item' => __('Add New Profile', '<API key>'), 'edit_item' => __('Edit Profile', '<API key>'), 'new_item' => __('New Profile', '<API key>'), 'view_item' => __('View Profile', '<API key>'), 'search_items' => __('Search Profiles', '<API key>'), 'not_found' => __('No Profiles found', '<API key>'), 'not_found_in_trash' => __('No Profiles found in Trash', '<API key>') ); $profile_args = array( 'labels' => $profile_labels, 'query_var' => 'profile', 'capability_type' => 'post', 'menu_position' => 52, 'menu_icon' => 'dashicons-id', 'public' => true, 'show_ui' => true, 'hierarchical' => false, 'has_archive' => true, 'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'page-attributes' ), 'rewrite' => array( 'slug' => $cmsms_option[CMSMS_SHORTNAME . '_profile_post_slug'], 'with_front' => true ) ); register_post_type('profile', $profile_args); add_filter('<API key>', array(&$this, 'edit_columns')); add_filter('<API key>', array(&$this, '<API key>')); register_taxonomy('pl-categs', array('profile'), array( 'hierarchical' => true, 'label' => __('Profile Categories', '<API key>'), 'singular_label' => __('Profile Category', '<API key>'), 'rewrite' => array( 'slug' => 'pl-categs', 'with_front' => true ) )); add_action('<API key>', array(&$this, 'custom_columns')); } function edit_columns($columns) { unset($columns['author']); unset($columns['comments']); unset($columns['date']); $new_columns = array( 'cb' => '<input type="checkbox" />', 'title' => __('Title', '<API key>'), 'pl_avatar' => __('Avatar', '<API key>'), 'pl_categs' => __('Categories', '<API key>'), 'comments' => '<span class="vers"><div title="' . __('Comments', '<API key>') . '" class="comment-grey-bubble"></div></span>', 'menu_order' => '<span class="vers"><div class="dashicons dashicons-sort" title="' . __('Order', '<API key>') . '"></div></span>' ); $result_columns = array_merge($columns, $new_columns); return $result_columns; } function custom_columns($column) { switch ($column) { case 'pl_avatar': if (has_post_thumbnail() != '') { echo <API key>(get_the_ID(), 'thumbnail', array( 'alt' => cmsms_title(get_the_ID(), false), 'title' => cmsms_title(get_the_ID(), false), 'style' => 'width:75px; height:75px;' )); } else { echo '<em>' . __('No Avatar', '<API key>') . '</em>'; } break; case 'pl_categs': if (get_the_terms(0, 'pl-categs') != '') { $pl_categs = get_the_terms(0, 'pl-categs'); $pl_categs_html = array(); foreach ($pl_categs as $pl_categ) { array_push($pl_categs_html, '<a href="' . get_term_link($pl_categ->slug, 'pl-categs') . '">' . $pl_categ->name . '</a>'); } echo implode($pl_categs_html, ', '); } else { echo '<em>' . __('Uncategorized', '<API key>') . '</em>'; } break; case 'menu_order': $custom_pl_post = get_post(get_the_ID()); $custom_pl_ord = $custom_pl_post->menu_order; echo $custom_pl_ord; break; } } function <API key>($columns) { $columns['menu_order'] = 'menu_order'; return $columns; } } function cmsms_profiles_init() { global $pl; $pl = new Cmsms_Profiles(); } add_action('init', 'cmsms_profiles_init');
<?php namespace Goetas\XML\XSDReader\Schema\Element; interface ElementSingle extends ElementItem { /** * @return \Goetas\XML\XSDReader\Schema\Type\Type */ public function getType(); /** * * @return int */ public function getMin(); /** * * @param int $qualified */ public function setMin($min); /** * * @return int */ public function getMax(); /** * * @param int $qualified */ public function setMax($max); /** * * @return bool */ public function isQualified(); /** * * @param boolean $qualified */ public function setQualified($qualified); /** * * @return bool */ public function isNil(); /** * * @param boolean $qualified */ public function setNil($nil); }
#include <QComboBox> #include <QDialogButtonBox> #include <QGroupBox> #include <QHBoxLayout> #include <QMessageBox> #include <QPushButton> #include <QTabWidget> #include <QVBoxLayout> #include "DolphinQt2/Config/Mapping/MappingWindow.h" #include "Common/FileUtil.h" #include "Common/IniFile.h" #include "Core/Core.h" #include "Core/HW/GCPad.h" #include "DolphinQt2/Config/Mapping/GCKeyboardEmu.h" #include "DolphinQt2/Config/Mapping/GCPadEmu.h" #include "DolphinQt2/Config/Mapping/GCPadWiiU.h" #include "DolphinQt2/Config/Mapping/WiimoteEmuExtension.h" #include "DolphinQt2/Config/Mapping/WiimoteEmuGeneral.h" #include "DolphinQt2/Config/Mapping/<API key>.h" #include "DolphinQt2/Settings.h" #include "InputCommon/ControllerEmu/ControllerEmu.h" #include "InputCommon/ControllerInterface/Device.h" #include "InputCommon/InputConfig.h" #include "InputCommon/ControllerInterface/ControllerInterface.h" MappingWindow::MappingWindow(QWidget* parent, int port_num) : QDialog(parent), m_port(port_num) { setWindowTitle(tr("Port %1").arg(port_num + 1)); CreateDevicesLayout(); <API key>(); CreateResetLayout(); CreateMainLayout(); ConnectWidgets(); } void MappingWindow::CreateDevicesLayout() { m_devices_layout = new QHBoxLayout(); m_devices_box = new QGroupBox(tr("Devices")); m_devices_combo = new QComboBox(); m_devices_refresh = new QPushButton(tr("Refresh")); m_devices_refresh->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); m_devices_layout->addWidget(m_devices_combo); m_devices_layout->addWidget(m_devices_refresh); m_devices_box->setLayout(m_devices_layout); } void MappingWindow::<API key>() { m_profiles_layout = new QVBoxLayout(); m_profiles_box = new QGroupBox(tr("Profiles")); m_profiles_combo = new QComboBox(); m_profiles_load = new QPushButton(tr("Load")); m_profiles_save = new QPushButton(tr("Save")); m_profiles_delete = new QPushButton(tr("Delete")); auto* button_layout = new QHBoxLayout(); m_profiles_box->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_profiles_combo->setEditable(true); m_profiles_layout->addWidget(m_profiles_combo); button_layout->addWidget(m_profiles_load); button_layout->addWidget(m_profiles_save); button_layout->addWidget(m_profiles_delete); m_profiles_layout->addItem(button_layout); m_profiles_box->setLayout(m_profiles_layout); } void MappingWindow::CreateResetLayout() { m_reset_layout = new QVBoxLayout(); m_reset_box = new QGroupBox(tr("Reset")); m_reset_clear = new QPushButton(tr("Clear")); m_reset_default = new QPushButton(tr("Default")); m_reset_box->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); m_reset_layout->addWidget(m_reset_clear); m_reset_layout->addWidget(m_reset_default); m_reset_box->setLayout(m_reset_layout); } void MappingWindow::CreateMainLayout() { m_main_layout = new QVBoxLayout(); m_config_layout = new QHBoxLayout(); m_tab_widget = new QTabWidget(); m_button_box = new QDialogButtonBox(QDialogButtonBox::Ok); m_config_layout->addWidget(m_profiles_box); m_config_layout->addWidget(m_reset_box); m_main_layout->addWidget(m_devices_box); m_main_layout->addItem(m_config_layout); m_main_layout->addWidget(m_tab_widget); m_main_layout->addWidget(m_button_box); setLayout(m_main_layout); } void MappingWindow::ConnectWidgets() { connect(m_devices_refresh, &QPushButton::clicked, this, &MappingWindow::RefreshDevices); connect(m_devices_combo, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &MappingWindow::OnDeviceChanged); connect(m_reset_clear, &QPushButton::clicked, this, [this] { emit ClearFields(); }); connect(m_reset_default, &QPushButton::clicked, this, &MappingWindow::<API key>); connect(m_profiles_save, &QPushButton::clicked, this, &MappingWindow::<API key>); connect(m_profiles_load, &QPushButton::clicked, this, &MappingWindow::<API key>); connect(m_profiles_delete, &QPushButton::clicked, this, &MappingWindow::<API key>); connect(m_button_box, &QDialogButtonBox::accepted, this, &MappingWindow::accept); } void MappingWindow::<API key>() { auto& settings = Settings::Instance(); const QString profile_name = m_profiles_combo->currentText(); if (!settings.GetProfiles(m_config).contains(profile_name)) { QMessageBox error; error.setIcon(QMessageBox::Critical); error.setText(tr("The profile '%1' does not exist").arg(profile_name)); error.exec(); return; } QMessageBox confirm(this); confirm.setIcon(QMessageBox::Warning); confirm.setText(tr("Are you sure that you want to delete '%1'?").arg(profile_name)); confirm.setInformativeText(tr("This cannot be undone!")); confirm.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel); if (confirm.exec() != QMessageBox::Yes) { return; } m_profiles_combo->removeItem(m_profiles_combo->currentIndex()); QMessageBox result(this); std::string profile_path = settings.GetProfileINIPath(m_config, profile_name).toStdString(); File::CreateFullPath(profile_path); File::Delete(profile_path); result.setIcon(QMessageBox::Information); result.setText(tr("Successfully deleted '%1'.").arg(profile_name)); } void MappingWindow::<API key>() { const QString profile_name = m_profiles_combo->currentText(); if (profile_name.isEmpty()) return; std::string profile_path = Settings::Instance().GetProfileINIPath(m_config, profile_name).toStdString(); File::CreateFullPath(profile_path); IniFile ini; ini.Load(profile_path); m_controller->LoadConfig(ini.GetOrCreateSection("Profile")); m_controller->UpdateReferences(<API key>); emit Update(); RefreshDevices(); } void MappingWindow::<API key>() { const QString profile_name = m_profiles_combo->currentText(); if (profile_name.isEmpty()) return; std::string profile_path = Settings::Instance().GetProfileINIPath(m_config, profile_name).toStdString(); File::CreateFullPath(profile_path); IniFile ini; m_controller->SaveConfig(ini.GetOrCreateSection("Profile")); ini.Save(profile_path); if (m_profiles_combo->currentIndex() == 0) { m_profiles_combo->addItem(profile_name); m_profiles_combo->setCurrentIndex(m_profiles_combo->count() - 1); } } void MappingWindow::OnDeviceChanged(int index) { const auto device = m_devices_combo->currentText().toStdString(); m_devq.FromString(device); m_controller->default_device.FromString(device); } void MappingWindow::RefreshDevices() { m_devices_combo->clear(); const bool paused = Core::PauseAndLock(true); <API key>.RefreshDevices(); m_controller->UpdateReferences(<API key>); m_controller->UpdateDefaultDevice(); const auto default_device = m_controller->default_device.ToString(); m_devices_combo->addItem(QString::fromStdString(default_device)); for (const auto& name : <API key>.GetAllDeviceStrings()) { if (name != default_device) m_devices_combo->addItem(QString::fromStdString(name)); } m_devices_combo->setCurrentIndex(0); Core::PauseAndLock(false, paused); } void MappingWindow::ChangeMappingType(MappingWindow::Type type) { if (m_mapping_type == type) return; ClearWidgets(); m_controller = nullptr; MappingWidget* widget; switch (type) { case Type::MAPPING_GC_KEYBOARD: widget = new GCKeyboardEmu(this); AddWidget(tr("GameCube Keyboard"), widget); setWindowTitle(tr("GameCube Keyboard at Port %1").arg(GetPort() + 1)); break; case Type::MAPPING_GC_BONGOS: case Type::<API key>: case Type::MAPPING_GC_DANCEMAT: case Type::MAPPING_GCPAD: widget = new GCPadEmu(this); setWindowTitle(tr("GameCube Controller at Port %1").arg(GetPort() + 1)); AddWidget(tr("GameCube Controller"), widget); break; case Type::MAPPING_GCPAD_WIIU: widget = new GCPadWiiU(this); setWindowTitle(tr("GameCube Adapter for Wii U at Port %1").arg(GetPort() + 1)); AddWidget(tr("GameCube Adapter for Wii U"), widget); break; case Type::MAPPING_WIIMOTE_EMU: case Type::<API key>: { auto* extension = new WiimoteEmuExtension(this); widget = new WiimoteEmuGeneral(this, extension); setWindowTitle(tr("Wii Remote at Port %1").arg(GetPort() + 1)); AddWidget(tr("General and Options"), widget); AddWidget(tr("Motion Controls and IR"), new <API key>(this)); AddWidget(tr("Extension"), extension); break; } default: return; } widget->LoadSettings(); m_profiles_combo->clear(); m_config = widget->GetConfig(); if (m_config) { m_controller = m_config->GetController(GetPort()); m_profiles_combo->addItem(QStringLiteral("")); for (const auto& item : Settings::Instance().GetProfiles(m_config)) m_profiles_combo->addItem(item); } SetLayoutComplex(type != Type::MAPPING_GCPAD_WIIU); if (m_controller != nullptr) RefreshDevices(); m_mapping_type = type; } void MappingWindow::ClearWidgets() { m_tab_widget->clear(); } void MappingWindow::AddWidget(const QString& name, QWidget* widget) { m_tab_widget->addTab(widget, name); } void MappingWindow::SetLayoutComplex(bool is_complex) { m_reset_box->setHidden(!is_complex); m_profiles_box->setHidden(!is_complex); m_devices_box->setHidden(!is_complex); m_is_complex = is_complex; } int MappingWindow::GetPort() const { return m_port; } const ciface::Core::DeviceQualifier& MappingWindow::GetDeviceQualifier() const { return m_devq; } std::shared_ptr<ciface::Core::Device> MappingWindow::GetDevice() const { return <API key>.FindDevice(m_devq); } void MappingWindow::SetBlockInputs(const bool block) { m_block = block; } bool MappingWindow::event(QEvent* event) { if (!m_block) return QDialog::event(event); return false; }
<?php namespace DecoratorPattern; class VisaPayment implements PaymentMethod { public function getDescription() { return "Visa description"; } }
#ifdef CONFIG_COMPAT #include <linux/compat.h> /* for compat_old_sigset_t */ #endif #include <linux/sched.h> #include <linux/kernel.h> #include <linux/signal.h> #include <linux/errno.h> #include <linux/wait.h> #include <linux/ptrace.h> #include <linux/tracehook.h> #include <linux/unistd.h> #include <linux/mm.h> #include <linux/tty.h> #include <linux/binfmts.h> #include <linux/bitops.h> #include <asm/uaccess.h> #include <asm/ptrace.h> #include <asm/pgtable.h> #include <asm/fpumacro.h> #include <asm/uctx.h> #include <asm/siginfo.h> #include <asm/visasm.h> #include "entry.h" #include "systbls.h" #define _BLOCKABLE (~(sigmask(SIGKILL) | sigmask(SIGSTOP))) /* {set, get}context() needed for 64-bit SparcLinux userland. */ asmlinkage void sparc64_set_context(struct pt_regs *regs) { struct ucontext __user *ucp = (struct ucontext __user *) regs->u_regs[UREG_I0]; mc_gregset_t __user *grp; unsigned long pc, npc, tstate; unsigned long fp, i7; unsigned char fenab; int err; flush_user_windows(); if (get_thread_wsaved() || (((unsigned long)ucp) & (sizeof(unsigned long)-1)) || (!__access_ok(ucp, sizeof(*ucp)))) goto do_sigsegv; grp = &ucp->uc_mcontext.mc_gregs; err = __get_user(pc, &((*grp)[MC_PC])); err |= __get_user(npc, &((*grp)[MC_NPC])); if (err || ((pc | npc) & 3)) goto do_sigsegv; if (regs->u_regs[UREG_I1]) { sigset_t set; if (_NSIG_WORDS == 1) { if (__get_user(set.sig[0], &ucp->uc_sigmask.sig[0])) goto do_sigsegv; } else { if (__copy_from_user(&set, &ucp->uc_sigmask, sizeof(sigset_t))) goto do_sigsegv; } sigdelsetmask(&set, ~_BLOCKABLE); spin_lock_irq(&current->sighand->siglock); current->blocked = set; recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); } if (test_thread_flag(TIF_32BIT)) { pc &= 0xffffffff; npc &= 0xffffffff; } regs->tpc = pc; regs->tnpc = npc; err |= __get_user(regs->y, &((*grp)[MC_Y])); err |= __get_user(tstate, &((*grp)[MC_TSTATE])); regs->tstate &= ~(TSTATE_ASI | TSTATE_ICC | TSTATE_XCC); regs->tstate |= (tstate & (TSTATE_ASI | TSTATE_ICC | TSTATE_XCC)); err |= __get_user(regs->u_regs[UREG_G1], (&(*grp)[MC_G1])); err |= __get_user(regs->u_regs[UREG_G2], (&(*grp)[MC_G2])); err |= __get_user(regs->u_regs[UREG_G3], (&(*grp)[MC_G3])); err |= __get_user(regs->u_regs[UREG_G4], (&(*grp)[MC_G4])); err |= __get_user(regs->u_regs[UREG_G5], (&(*grp)[MC_G5])); err |= __get_user(regs->u_regs[UREG_G6], (&(*grp)[MC_G6])); /* Skip %g7 as that's the thread register in userspace. */ err |= __get_user(regs->u_regs[UREG_I0], (&(*grp)[MC_O0])); err |= __get_user(regs->u_regs[UREG_I1], (&(*grp)[MC_O1])); err |= __get_user(regs->u_regs[UREG_I2], (&(*grp)[MC_O2])); err |= __get_user(regs->u_regs[UREG_I3], (&(*grp)[MC_O3])); err |= __get_user(regs->u_regs[UREG_I4], (&(*grp)[MC_O4])); err |= __get_user(regs->u_regs[UREG_I5], (&(*grp)[MC_O5])); err |= __get_user(regs->u_regs[UREG_I6], (&(*grp)[MC_O6])); err |= __get_user(regs->u_regs[UREG_I7], (&(*grp)[MC_O7])); err |= __get_user(fp, &(ucp->uc_mcontext.mc_fp)); err |= __get_user(i7, &(ucp->uc_mcontext.mc_i7)); err |= __put_user(fp, (&(((struct reg_window __user *)(STACK_BIAS+regs->u_regs[UREG_I6]))->ins[6]))); err |= __put_user(i7, (&(((struct reg_window __user *)(STACK_BIAS+regs->u_regs[UREG_I6]))->ins[7]))); err |= __get_user(fenab, &(ucp->uc_mcontext.mc_fpregs.mcfpu_enab)); if (fenab) { unsigned long *fpregs = current_thread_info()->fpregs; unsigned long fprs; fprs_write(0); err |= __get_user(fprs, &(ucp->uc_mcontext.mc_fpregs.mcfpu_fprs)); if (fprs & FPRS_DL) err |= copy_from_user(fpregs, &(ucp->uc_mcontext.mc_fpregs.mcfpu_fregs), (sizeof(unsigned int) * 32)); if (fprs & FPRS_DU) err |= copy_from_user(fpregs+16, ((unsigned long __user *)&(ucp->uc_mcontext.mc_fpregs.mcfpu_fregs))+16, (sizeof(unsigned int) * 32)); err |= __get_user(current_thread_info()->xfsr[0], &(ucp->uc_mcontext.mc_fpregs.mcfpu_fsr)); err |= __get_user(current_thread_info()->gsr[0], &(ucp->uc_mcontext.mc_fpregs.mcfpu_gsr)); regs->tstate &= ~TSTATE_PEF; } if (err) goto do_sigsegv; return; do_sigsegv: force_sig(SIGSEGV, current); } asmlinkage void sparc64_get_context(struct pt_regs *regs) { struct ucontext __user *ucp = (struct ucontext __user *) regs->u_regs[UREG_I0]; mc_gregset_t __user *grp; mcontext_t __user *mcp; unsigned long fp, i7; unsigned char fenab; int err; <API key>(); if (get_thread_wsaved() || clear_user(ucp, sizeof(*ucp))) goto do_sigsegv; #if 1 fenab = 0; /* IMO get_context is like any other system call, thus modifies FPU state -jj */ #else fenab = (current_thread_info()->fpsaved[0] & FPRS_FEF); #endif mcp = &ucp->uc_mcontext; grp = &mcp->mc_gregs; /* Skip over the trap instruction, first. */ if (test_thread_flag(TIF_32BIT)) { regs->tpc = (regs->tnpc & 0xffffffff); regs->tnpc = (regs->tnpc + 4) & 0xffffffff; } else { regs->tpc = regs->tnpc; regs->tnpc += 4; } err = 0; if (_NSIG_WORDS == 1) err |= __put_user(current->blocked.sig[0], (unsigned long __user *)&ucp->uc_sigmask); else err |= __copy_to_user(&ucp->uc_sigmask, &current->blocked, sizeof(sigset_t)); err |= __put_user(regs->tstate, &((*grp)[MC_TSTATE])); err |= __put_user(regs->tpc, &((*grp)[MC_PC])); err |= __put_user(regs->tnpc, &((*grp)[MC_NPC])); err |= __put_user(regs->y, &((*grp)[MC_Y])); err |= __put_user(regs->u_regs[UREG_G1], &((*grp)[MC_G1])); err |= __put_user(regs->u_regs[UREG_G2], &((*grp)[MC_G2])); err |= __put_user(regs->u_regs[UREG_G3], &((*grp)[MC_G3])); err |= __put_user(regs->u_regs[UREG_G4], &((*grp)[MC_G4])); err |= __put_user(regs->u_regs[UREG_G5], &((*grp)[MC_G5])); err |= __put_user(regs->u_regs[UREG_G6], &((*grp)[MC_G6])); err |= __put_user(regs->u_regs[UREG_G7], &((*grp)[MC_G7])); err |= __put_user(regs->u_regs[UREG_I0], &((*grp)[MC_O0])); err |= __put_user(regs->u_regs[UREG_I1], &((*grp)[MC_O1])); err |= __put_user(regs->u_regs[UREG_I2], &((*grp)[MC_O2])); err |= __put_user(regs->u_regs[UREG_I3], &((*grp)[MC_O3])); err |= __put_user(regs->u_regs[UREG_I4], &((*grp)[MC_O4])); err |= __put_user(regs->u_regs[UREG_I5], &((*grp)[MC_O5])); err |= __put_user(regs->u_regs[UREG_I6], &((*grp)[MC_O6])); err |= __put_user(regs->u_regs[UREG_I7], &((*grp)[MC_O7])); err |= __get_user(fp, (&(((struct reg_window __user *)(STACK_BIAS+regs->u_regs[UREG_I6]))->ins[6]))); err |= __get_user(i7, (&(((struct reg_window __user *)(STACK_BIAS+regs->u_regs[UREG_I6]))->ins[7]))); err |= __put_user(fp, &(mcp->mc_fp)); err |= __put_user(i7, &(mcp->mc_i7)); err |= __put_user(fenab, &(mcp->mc_fpregs.mcfpu_enab)); if (fenab) { unsigned long *fpregs = current_thread_info()->fpregs; unsigned long fprs; fprs = current_thread_info()->fpsaved[0]; if (fprs & FPRS_DL) err |= copy_to_user(&(mcp->mc_fpregs.mcfpu_fregs), fpregs, (sizeof(unsigned int) * 32)); if (fprs & FPRS_DU) err |= copy_to_user( ((unsigned long __user *)&(mcp->mc_fpregs.mcfpu_fregs))+16, fpregs+16, (sizeof(unsigned int) * 32)); err |= __put_user(current_thread_info()->xfsr[0], &(mcp->mc_fpregs.mcfpu_fsr)); err |= __put_user(current_thread_info()->gsr[0], &(mcp->mc_fpregs.mcfpu_gsr)); err |= __put_user(fprs, &(mcp->mc_fpregs.mcfpu_fprs)); } if (err) goto do_sigsegv; return; do_sigsegv: force_sig(SIGSEGV, current); } struct rt_signal_frame { struct sparc_stackf ss; siginfo_t info; struct pt_regs regs; __siginfo_fpu_t __user *fpu_save; stack_t stack; sigset_t mask; __siginfo_fpu_t fpu_state; }; static long _sigpause_common(old_sigset_t set) { set &= _BLOCKABLE; spin_lock_irq(&current->sighand->siglock); current->saved_sigmask = current->blocked; siginitset(&current->blocked, set); recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); current->state = TASK_INTERRUPTIBLE; schedule(); set_restore_sigmask(); return -ERESTARTNOHAND; } asmlinkage long sys_sigpause(unsigned int set) { return _sigpause_common(set); } asmlinkage long sys_sigsuspend(old_sigset_t set) { return _sigpause_common(set); } static inline int restore_fpu_state(struct pt_regs *regs, __siginfo_fpu_t __user *fpu) { unsigned long *fpregs = current_thread_info()->fpregs; unsigned long fprs; int err; err = __get_user(fprs, &fpu->si_fprs); fprs_write(0); regs->tstate &= ~TSTATE_PEF; if (fprs & FPRS_DL) err |= copy_from_user(fpregs, &fpu->si_float_regs[0], (sizeof(unsigned int) * 32)); if (fprs & FPRS_DU) err |= copy_from_user(fpregs+16, &fpu->si_float_regs[32], (sizeof(unsigned int) * 32)); err |= __get_user(current_thread_info()->xfsr[0], &fpu->si_fsr); err |= __get_user(current_thread_info()->gsr[0], &fpu->si_gsr); current_thread_info()->fpsaved[0] |= fprs; return err; } void do_rt_sigreturn(struct pt_regs *regs) { struct rt_signal_frame __user *sf; unsigned long tpc, tnpc, tstate; __siginfo_fpu_t __user *fpu_save; sigset_t set; int err; /* Always make any pending restarted system calls return -EINTR */ current_thread_info()->restart_block.fn = <API key>; <API key> (); sf = (struct rt_signal_frame __user *) (regs->u_regs [UREG_FP] + STACK_BIAS); /* 1. Make sure we are not getting garbage from the user */ if (((unsigned long) sf) & 3) goto segv; err = get_user(tpc, &sf->regs.tpc); err |= __get_user(tnpc, &sf->regs.tnpc); if (test_thread_flag(TIF_32BIT)) { tpc &= 0xffffffff; tnpc &= 0xffffffff; } err |= ((tpc | tnpc) & 3); /* 2. Restore the state */ err |= __get_user(regs->y, &sf->regs.y); err |= __get_user(tstate, &sf->regs.tstate); err |= copy_from_user(regs->u_regs, sf->regs.u_regs, sizeof(regs->u_regs)); /* User can only change condition codes and %asi in %tstate. */ regs->tstate &= ~(TSTATE_ASI | TSTATE_ICC | TSTATE_XCC); regs->tstate |= (tstate & (TSTATE_ASI | TSTATE_ICC | TSTATE_XCC)); err |= __get_user(fpu_save, &sf->fpu_save); if (fpu_save) err |= restore_fpu_state(regs, &sf->fpu_state); err |= __copy_from_user(&set, &sf->mask, sizeof(sigset_t)); err |= do_sigaltstack(&sf->stack, NULL, (unsigned long)sf); if (err) goto segv; regs->tpc = tpc; regs->tnpc = tnpc; /* Prevent syscall restart. */ <API key>(regs); sigdelsetmask(&set, ~_BLOCKABLE); spin_lock_irq(&current->sighand->siglock); current->blocked = set; recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); return; segv: force_sig(SIGSEGV, current); } /* Checks if the fp is valid */ static int <API key>(void __user *fp, int fplen) { if (((unsigned long) fp) & 15) return 1; return 0; } static inline int save_fpu_state(struct pt_regs *regs, __siginfo_fpu_t __user *fpu) { unsigned long *fpregs = current_thread_info()->fpregs; unsigned long fprs; int err = 0; fprs = current_thread_info()->fpsaved[0]; if (fprs & FPRS_DL) err |= copy_to_user(&fpu->si_float_regs[0], fpregs, (sizeof(unsigned int) * 32)); if (fprs & FPRS_DU) err |= copy_to_user(&fpu->si_float_regs[32], fpregs+16, (sizeof(unsigned int) * 32)); err |= __put_user(current_thread_info()->xfsr[0], &fpu->si_fsr); err |= __put_user(current_thread_info()->gsr[0], &fpu->si_gsr); err |= __put_user(fprs, &fpu->si_fprs); return err; } static inline void __user *get_sigframe(struct k_sigaction *ka, struct pt_regs *regs, unsigned long framesize) { unsigned long sp = regs->u_regs[UREG_FP] + STACK_BIAS; /* * If we are on the alternate signal stack and would overflow it, don't. * Return an always-bogus address instead so we will die with SIGSEGV. */ if (on_sig_stack(sp) && !likely(on_sig_stack(sp - framesize))) return (void __user *) -1L; /* This is the X/Open sanctioned signal stack switching. */ if (ka->sa.sa_flags & SA_ONSTACK) { if (sas_ss_flags(sp) == 0) sp = current->sas_ss_sp + current->sas_ss_size; } sp -= framesize; /* Always align the stack frame. This handles two cases. First, * sigaltstack need not be mindful of platform specific stack * alignment. Second, if we took this signal because the stack * is not aligned properly, we'd like to take the signal cleanly * and report that. */ sp &= ~15UL; return (void __user *) sp; } static inline void setup_rt_frame(struct k_sigaction *ka, struct pt_regs *regs, int signo, sigset_t *oldset, siginfo_t *info) { struct rt_signal_frame __user *sf; int sigframe_size, err; /* 1. Make sure everything is clean */ <API key>(); save_and_clear_fpu(); sigframe_size = sizeof(struct rt_signal_frame); if (!(current_thread_info()->fpsaved[0] & FPRS_FEF)) sigframe_size -= sizeof(__siginfo_fpu_t); sf = (struct rt_signal_frame __user *) get_sigframe(ka, regs, sigframe_size); if (<API key> (sf, sigframe_size)) goto sigill; if (get_thread_wsaved() != 0) goto sigill; /* 2. Save the current process state */ err = copy_to_user(&sf->regs, regs, sizeof (*regs)); if (current_thread_info()->fpsaved[0] & FPRS_FEF) { err |= save_fpu_state(regs, &sf->fpu_state); err |= __put_user((u64)&sf->fpu_state, &sf->fpu_save); } else { err |= __put_user(0, &sf->fpu_save); } /* Setup sigaltstack */ err |= __put_user(current->sas_ss_sp, &sf->stack.ss_sp); err |= __put_user(sas_ss_flags(regs->u_regs[UREG_FP]), &sf->stack.ss_flags); err |= __put_user(current->sas_ss_size, &sf->stack.ss_size); err |= copy_to_user(&sf->mask, oldset, sizeof(sigset_t)); err |= copy_in_user((u64 __user *)sf, (u64 __user *)(regs->u_regs[UREG_FP]+STACK_BIAS), sizeof(struct reg_window)); if (info) err |= <API key>(&sf->info, info); else { err |= __put_user(signo, &sf->info.si_signo); err |= __put_user(SI_NOINFO, &sf->info.si_code); } if (err) goto sigsegv; /* 3. signal handler back-trampoline and parameters */ regs->u_regs[UREG_FP] = ((unsigned long) sf) - STACK_BIAS; regs->u_regs[UREG_I0] = signo; regs->u_regs[UREG_I1] = (unsigned long) &sf->info; /* The sigcontext is passed in this way because of how it * is defined in GLIBC's /usr/include/bits/sigcontext.h * for sparc64. It includes the 128 bytes of siginfo_t. */ regs->u_regs[UREG_I2] = (unsigned long) &sf->info; /* 5. signal handler */ regs->tpc = (unsigned long) ka->sa.sa_handler; regs->tnpc = (regs->tpc + 4); if (test_thread_flag(TIF_32BIT)) { regs->tpc &= 0xffffffff; regs->tnpc &= 0xffffffff; } /* 4. return to kernel instructions */ regs->u_regs[UREG_I7] = (unsigned long)ka->ka_restorer; return; sigill: do_exit(SIGILL); sigsegv: force_sigsegv(signo, current); } static inline void handle_signal(unsigned long signr, struct k_sigaction *ka, siginfo_t *info, sigset_t *oldset, struct pt_regs *regs) { setup_rt_frame(ka, regs, signr, oldset, (ka->sa.sa_flags & SA_SIGINFO) ? info : NULL); spin_lock_irq(&current->sighand->siglock); sigorsets(&current->blocked,&current->blocked,&ka->sa.sa_mask); if (!(ka->sa.sa_flags & SA_NOMASK)) sigaddset(&current->blocked,signr); recalc_sigpending(); spin_unlock_irq(&current->sighand->siglock); } static inline void syscall_restart(unsigned long orig_i0, struct pt_regs *regs, struct sigaction *sa) { switch (regs->u_regs[UREG_I0]) { case <API key>: case ERESTARTNOHAND: <API key>: regs->u_regs[UREG_I0] = EINTR; regs->tstate |= (TSTATE_ICARRY|TSTATE_XCARRY); break; case ERESTARTSYS: if (!(sa->sa_flags & SA_RESTART)) goto <API key>; /* fallthrough */ case ERESTARTNOINTR: regs->u_regs[UREG_I0] = orig_i0; regs->tpc -= 4; regs->tnpc -= 4; } } static void do_signal(struct pt_regs *regs, unsigned long orig_i0) { struct k_sigaction ka; int restart_syscall; sigset_t *oldset; siginfo_t info; int signr; if (pt_regs_is_syscall(regs) && (regs->tstate & (TSTATE_XCARRY | TSTATE_ICARRY))) { restart_syscall = 1; } else restart_syscall = 0; if (current_thread_info()->status & TS_RESTORE_SIGMASK) oldset = &current->saved_sigmask; else oldset = &current->blocked; #ifdef CONFIG_COMPAT if (test_thread_flag(TIF_32BIT)) { extern void do_signal32(sigset_t *, struct pt_regs *, int restart_syscall, unsigned long orig_i0); do_signal32(oldset, regs, restart_syscall, orig_i0); return; } #endif signr = <API key>(&info, &ka, regs, NULL); /* If the debugger messes with the program counter, it clears * the software "in syscall" bit, directing us to not perform * a syscall restart. */ if (restart_syscall && !pt_regs_is_syscall(regs)) restart_syscall = 0; if (signr > 0) { if (restart_syscall) syscall_restart(orig_i0, regs, &ka.sa); handle_signal(signr, &ka, &info, oldset, regs); /* A signal was successfully delivered; the saved * sigmask will have been stored in the signal frame, * and will be restored by sigreturn, so we can simply * clear the TS_RESTORE_SIGMASK flag. */ current_thread_info()->status &= ~TS_RESTORE_SIGMASK; <API key>(signr, &info, &ka, regs, 0); return; } if (restart_syscall && (regs->u_regs[UREG_I0] == ERESTARTNOHAND || regs->u_regs[UREG_I0] == ERESTARTSYS || regs->u_regs[UREG_I0] == ERESTARTNOINTR)) { /* replay the system call when we are done */ regs->u_regs[UREG_I0] = orig_i0; regs->tpc -= 4; regs->tnpc -= 4; } if (restart_syscall && regs->u_regs[UREG_I0] == <API key>) { regs->u_regs[UREG_G1] = <API key>; regs->tpc -= 4; regs->tnpc -= 4; } /* If there's no signal to deliver, we just put the saved sigmask * back */ if (current_thread_info()->status & TS_RESTORE_SIGMASK) { current_thread_info()->status &= ~TS_RESTORE_SIGMASK; sigprocmask(SIG_SETMASK, &current->saved_sigmask, NULL); } } void do_notify_resume(struct pt_regs *regs, unsigned long orig_i0, unsigned long thread_info_flags) { if (thread_info_flags & _TIF_SIGPENDING) do_signal(regs, orig_i0); if (thread_info_flags & _TIF_NOTIFY_RESUME) { clear_thread_flag(TIF_NOTIFY_RESUME); <API key>(regs); if (current-><API key>) <API key>(); } }
#ifndef __PAROLE_MODULE_H #define __PAROLE_MODULE_H #include <glib-object.h> #include <src/misc/parole.h> #include "<API key>.h" G_BEGIN_DECLS #define <API key> (<API key> () ) #define <API key>(o) (<API key> ((o), <API key>, <API key>)) #define <API key>(klass) (<API key> ((klass), <API key>, <API key>)) #define <API key>(o) (<API key> ((o), <API key>)) #define <API key>(klass) (<API key> ((klass), <API key>)) #define <API key>(o) (<API key>((o), <API key>, <API key>)) typedef struct <API key> <API key>; typedef struct <API key> <API key>; struct <API key> { GTypeModule parent; GModule *library; ParolePluginPlayer *player; GType (*initialize) (<API key> *module); void (*shutdown) (void); GType provider_type; gboolean active; gpointer instance; gchar *desktop_file; }; struct <API key> { GTypeModuleClass parent_class; } ; GType <API key> (void) G_GNUC_CONST; <API key> *<API key> (const gchar *filename, const gchar *desktop_file); gboolean <API key> (<API key> *module); void <API key> (<API key> *module); gboolean <API key> (<API key> *module); G_END_DECLS #endif /* __PAROLE_MODULE_H */
/** * @file cp_campaign.h * @brief Header file for single player campaign control. */ #ifndef CP_CAMPAIGN_H #define CP_CAMPAIGN_H extern memPool_t *cp_campaignPool; struct aircraft_s; struct installation_s; struct employee_s; struct ugv_s; struct campaign_s; struct uiNode_s; /**< @todo remove this once the uiNode_t usage is cleaned up */ #define MAX_CAMPAIGNS 16 #define MAX_ASSEMBLIES 16 /** @todo rename this after merging with savegame breakage branch and also change the value to -1 */ #define BYTES_NONE 0xFF #include "cp_rank.h" #include "cp_save.h" #include "cp_parse.h" #include "cp_event.h" #include "cp_ufopedia.h" #include "cp_research.h" #include "cp_radar.h" #include "cp_aircraft.h" #include "cp_base.h" #include "cp_employee.h" #include "cp_transfer.h" #include "cp_nation.h" #include "cp_installation.h" #include "cp_produce.h" #include "cp_uforecovery.h" #include "cp_airfight.h" #include "cp_messageoptions.h" #include "cp_alienbase.h" #include "cp_market.h" #include "cp_statistics.h" /* check for water */ /* blue value is 64 */ #define MapIsWater(color) (color[0] == 0 && color[1] == 0 && color[2] == 64) /* terrain types */ #define MapIsArctic(color) (color[0] == 128 && color[1] == 255 && color[2] == 255) #define MapIsDesert(color) (color[0] == 255 && color[1] == 128 && color[2] == 0) #define MapIsMountain(color) (color[0] == 255 && color[1] == 0 && color[2] == 0) #define MapIsTropical(color) (color[0] == 128 && color[1] == 128 && color[2] == 255) #define MapIsGrass(color) (color[0] == 128 && color[1] == 255 && color[2] == 0) #define MapIsWasted(color) (color[0] == 128 && color[1] == 0 && color[2] == 128) #define MapIsCold(color) (color[0] == 0 && color[1] == 0 && color[2] == 255) /* culture types */ #define MapIsWestern(color) (color[0] == 128 && color[1] == 255 && color[2] == 255) #define MapIsEastern(color) (color[0] == 255 && color[1] == 128 && color[2] == 0) #define MapIsOriental(color) (color[0] == 255 && color[1] == 0 && color[2] == 0) #define MapIsAfrican(color) (color[0] == 128 && color[1] == 128 && color[2] == 255) /* population types */ #define MapIsUrban(color) (color[0] == 128 && color[1] == 255 && color[2] == 255) #define MapIsSuburban(color) (color[0] == 255 && color[1] == 128 && color[2] == 0) #define MapIsVillage(color) (color[0] == 255 && color[1] == 0 && color[2] == 0) #define MapIsRural(color) (color[0] == 128 && color[1] == 128 && color[2] == 255) #define MapIsNopopulation(color) (color[0] == 128 && color[1] == 255 && color[2] == 0) /* RASTER enables a better performance for <API key> set it to 1-6 * the higher the value the better the performance, but the smaller the coverage */ #define RASTER 2 /* nation happiness constants */ #define <API key> -0.15 #define <API key> -0.02 #define <API key> 0.02 #define <API key> 0.005 #define <API key> 0.07 /* Maximum alien groups per alien team category */ #define <API key> 4 /* Maximum alien team category defined in scripts */ #define ALIENCATEGORY_MAX 8 #define BID_FACTOR 0.9 #define <API key> 32 /** * @brief The amount of time (in hours) it takes for the interest to increase by 1. Is later affected by difficulty. */ #define <API key> 22 /** * @brief Determines the interest interval for a single campaign */ #define <API key> 20 #define <API key> 1000 /** * @brief The length of a single mission spawn cycle */ #define <API key> 4 /** * @brief The minimum and maximum amount of missions per mission cycle. * @note some of the missions can be non-occurrence missions. */ #define <API key> 5 #define <API key> 40 /** * @brief The probability that any new alien mission will be a non-occurrence mission. */ #define <API key> 0.65 /** possible map types */ typedef enum mapType_s { MAPTYPE_TERRAIN, MAPTYPE_CULTURE, MAPTYPE_POPULATION, MAPTYPE_NATIONS, MAPTYPE_MAX } mapType_t; /** @brief possible mission detection status */ typedef enum <API key> { <API key>, /**< Mission can't be seen on geoscape */ <API key>, /**< Mission is seen on geoscape, whatever it's position */ <API key> /**< Mission may be seen on geoscape, if a probability test is done */ } <API key>; /** possible campaign interest categories: type of missions that aliens can undertake */ typedef enum interestCategory_s { <API key>, /**< No mission */ <API key>, /**< Aerial recon mission or ground mission (UFO may or not land) */ <API key>, /**< Terror attack */ <API key>, /**< Alien attack a phalanx base */ <API key>, /**< Alien build a new base or subverse governments */ <API key>, /**< Alien supply one of their bases */ <API key>, /**< Alien try to spread XVI */ <API key>, /**< Alien try to intercept PHALANX aircraft */ <API key>, /**< Alien try to harvest */ <API key>, /**< Alien base already built on earth * @note This is not a mission alien can undertake, but the result of * <API key> */ <API key>, <API key> } interestCategory_t; /** possible stage for campaign missions (i.e. possible actions for UFO) */ typedef enum missionStage_s { STAGE_NOT_ACTIVE, /**< mission did not begin yet */ <API key>, /**< UFO is arriving */ STAGE_RECON_AIR, /**< Aerial Recon */ STAGE_MISSION_GOTO, /**< Going to a new position */ STAGE_RECON_GROUND, /**< Ground Recon */ <API key>, /**< Terror mission */ STAGE_BUILD_BASE, /**< Building a base */ STAGE_BASE_ATTACK, /**< Base attack */ STAGE_SUBVERT_GOV, /**< Subvert government */ STAGE_SUPPLY, /**< Supply already existing base */ STAGE_SPREAD_XVI, /**< Spreading XVI Virus */ STAGE_INTERCEPT, /**< UFO attacks any encountered PHALANX aircraft or attack an installation */ <API key>, /**< PHALANX discovered the base */ STAGE_HARVEST, /**< Harvesting */ <API key>, /**< UFO is going back to base */ STAGE_OVER /**< Mission is over */ } missionStage_t; /** @brief alien team group definition. * @note This is the definition of one groups of aliens (several races) that can * be used on the same map. * @sa alienTeamCategory_s */ typedef struct alienTeamGroup_s { int idx; /**< idx of the group in the alien team category */ int categoryIdx; /**< idx of category it's used in */ int minInterest; /**< Minimum interest value this group should be used with. */ int maxInterest; /**< Maximum interest value this group should be used with. */ teamDef_t *alienTeams[<API key>]; /**< different alien teams available * that will be used in mission */ int numAlienTeams; /**< Number of alienTeams defined in this group. */ } alienTeamGroup_t; /** @brief alien team category definition * @note This is the definition of all groups of aliens that can be used for * a mission category * @sa alienTeamGroup_s */ typedef struct alienTeamCategory_s { char id[MAX_VAR]; /**< id of the category */ interestCategory_t missionCategories[<API key>]; /**< Mission category that should use this * alien team Category. */ int <API key>; /**< Number of category using this alien team Category. */ linkedList_t *equipment; /**< Equipment definitions that may be used for this def. */ alienTeamGroup_t alienTeamGroups[<API key>]; /**< Different alien group available * for this category */ int numAlienTeamGroups; /**< Number of alien group defined for this category */ } alienTeamCategory_t; /** @brief mission definition * @note A mission is different from a map: a mission is the whole set of actions aliens will carry. * For example, coming with a UFO on earth, land, explore earth, and leave with UFO */ typedef struct mission_s { int idx; /**< unique id of this mission */ char id[MAX_VAR]; /**< script id */ mapDef_t* mapDef; /**< mapDef used for this mission */ qboolean active; /**< aircraft at place? */ union missionData_t { base_t *base; aircraft_t *aircraft; installation_t *installation; alienBase_t *alienBase; } data; /**< may be related to mission type (like pointer to base attacked, or to alien base) */ char location[MAX_VAR]; /**< The name of the ground mission that will appear on geoscape */ interestCategory_t category; /**< The category of the event */ missionStage_t stage; /**< in which stage is this event? */ int <API key>; /**< The overall interest value when this event has been created */ int <API key>; /**< The individual interest value (of type type) when this event has been created */ date_t startDate; /**< Date when the event should start */ date_t finalDate; /**< Date when the event should finish (e.g. for aerial recon) * if finaleDate.day == 0, then delay is not a limitating factor for next stage */ vec2_t pos; /**< Position of the mission */ aircraft_t *ufo; /**< UFO on geoscape fulfilling the mission (may be NULL) */ qboolean onGeoscape; /**< Should the mission be displayed on geoscape */ qboolean crashed; /**< is UFO crashed ? (only used if mission is spawned from a UFO */ char onwin[MAX_VAR]; /**< trigger command after you've won a battle, @sa <API key> */ char onlose[MAX_VAR]; /**< trigger command after you've lost a battle, @sa <API key> */ qboolean posAssigned; /**< is the position of this mission already set? */ } mission_t; /** * @brief iterates through missions */ #define MIS_Foreach(var) LIST_Foreach(ccs.missions, mission_t, var) /** battlescape parameters that were used */ typedef struct battleParam_s { mission_t *mission; alienTeamGroup_t *alienTeamGroup; /**< Races of aliens present in battle */ char *param; /**< in case of a random map assembly we can't use the param from mapDef - because * this is global for the mapDef - but we need a local mission param */ char alienEquipment[MAX_VAR]; /**< Equipment of alien team */ char civTeam[MAX_VAR]; /**< Type of civilian (European, ...) */ qboolean day; /**< Mission is played during day */ const char *zoneType; /**< Terrain type (used for texture replacement in some missions (base, ufocrash)) */ int aliens, civilians; /**< number of aliens and civilians in that particular mission */ struct nation_s *nation; /**< nation where the mission takes place */ float probability; } battleParam_t; /** @brief Structure with mission info needed to create results summary at menu won. */ typedef struct missionResults_s { qboolean won; qboolean recovery; /**< @c true if player secured a UFO (landed or crashed). */ qboolean crashsite; /**< @c true if secured UFO was crashed one. */ ufoType_t ufotype; /**< Type of UFO secured during the mission. */ float ufoCondition; /**< How much the UFO is damaged */ float winProbability; /**< the win probability that was calculated for auto missions */ int itemTypes; /**< Types of items gathered from a mission. */ int itemAmount; /**< Amount of items (all) gathered from a mission. */ int aliensKilled; int aliensStunned; int aliensSurvived; int ownKilled; int ownStunned; int <API key>; int ownSurvived; int civiliansKilled; int <API key>; int civiliansSurvived; } missionResults_t; /** salary values for a campaign */ typedef struct salary_s { int base[MAX_EMPL]; int rankBonus[MAX_EMPL]; int admin[MAX_EMPL]; int aircraftFactor; int aircraftDivisor; int baseUpkeep; int adminInitial; float debtInterest; } salary_t; /** campaign definition */ typedef struct campaign_s { int idx; /**< own index in global campaign array */ char id[MAX_VAR]; /**< id of the campaign */ char name[MAX_VAR]; /**< name of the campaign */ int team; /**< what team can play this campaign */ char researched[MAX_VAR]; /**< name of the researched tech list to use on campaign start */ char soldierEquipment[MAX_VAR]; /**< name of the equipment list that is used to equip soldiers on crafts that are added to the first base */ char equipment[MAX_VAR]; /**< name of the equipment list to use on campaign start */ char market[MAX_VAR]; /**< name of the market list containing initial items on market */ char asymptoticMarket[MAX_VAR]; /**< name of the market list containing items on market at the end of the game */ const equipDef_t *marketDef; /**< market definition for this campaign (how many items on the market) containing initial items */ const equipDef_t *asymptoticMarketDef; /**< market definition for this campaign (how many items on the market) containing finale items */ char text[MAX_VAR]; /**< placeholder for gettext stuff */ char map[MAX_VAR]; /**< geoscape map */ int soldiers; /**< start with x soldiers */ int scientists; /**< start with x scientists */ int workers; /**< start with x workers */ int pilots; /**< start with x pilots */ int ugvs; /**< start with x ugvs (robots) */ int credits; /**< start with x credits */ int num; signed int difficulty; /**< difficulty level -4 - 4 */ float minhappiness; /**< minimum value of mean happiness before the game is lost */ int <API key>; /**< bankrupt - negative credits until you've lost the game */ int <API key>; /**< 0 - 100 - the average rate of XVI over all nations before you've lost the game */ qboolean visible; /**< visible in campaign menu? */ date_t date; /**< starting date for this campaign */ int basecost; /**< base building cost for empty base */ char firstBaseTemplate[MAX_VAR]; /**< template to use for setting up the first base */ qboolean finished; const campaignEvents_t *events; salary_t salaries; } campaign_t; int <API key>(const salary_t *salary, employeeType_t type); int <API key>(const salary_t *salary, employeeType_t type); int <API key>(const salary_t *salary, employeeType_t type); int <API key>(const salary_t *salary); int <API key>(const salary_t *salary, const base_t *base); /** possible geoscape actions */ typedef enum mapAction_s { MA_NONE, MA_NEWBASE, /**< build a new base */ MA_NEWINSTALLATION, /**< build a new installation */ MA_INTERCEPT, /**< intercept */ MA_BASEATTACK, /**< base attacking */ MA_UFORADAR /**< ufos are in our radar */ } mapAction_t; /** * @brief client campaign structure * @sa csi_t */ typedef struct ccs_s { equipDef_t eMission; market_t eMarket; /**< Prices, evolution and number of items on market */ linkedList_t *missions; /**< Missions spawned (visible on geoscape or not) */ battleParam_t battleParameters; /**< Structure used to remember every parameter used during last battle */ int <API key>; /**< How many hours since last increase of alien overall interest */ int overallInterest; /**< overall interest of aliens: how far is the player in the campaign */ int interest[<API key>]; /**< interest of aliens: determine which actions aliens will undertake */ int <API key>; /**< How many days since last mission has been spawned */ vec2_t mapPos; /**< geoscape map position (from the menu node) */ vec2_t mapSize; /**< geoscape map size (from the menu node) */ int credits; /**< actual credits amount */ int civiliansKilled; /**< how many civilians were killed already */ int aliensKilled; /**< how many aliens were killed already */ date_t date; /**< current date */ qboolean XVIShowMap; /**< means that PHALANX has a map of XVI - @see CP_IsXVIResearched */ qboolean breathingMailSent; /**< status flag indicating that mail about died aliens due to missing breathing tech was sent */ float timer; vec3_t angles; /**< 3d geoscape rotation */ vec2_t center; /**< latitude and longitude of the point we're looking at on earth */ float zoom; /**< zoom used when looking at earth */ /* Smoothing variables */ qboolean smoothRotation; /**< @c true if the rotation of 3D geoscape must me smooth */ vec3_t <API key>; /**< value of final ccs.angles for a smooth change of angle (see MAP_CenterOnPoint)*/ vec2_t <API key>; /**< value of ccs.center for a smooth change of position (see MAP_CenterOnPoint) */ float smoothDeltaLength; /**< angle/position difference that we need to change when smoothing */ float smoothFinalZoom; /**< value of final ccs.zoom for a smooth change of angle (see MAP_CenterOnPoint)*/ float smoothDeltaZoom; /**< zoom difference that we need to change when smoothing */ float curZoomSpeed; /**< The current zooming speed. Used for smooth zooming. */ float curRotationSpeed; /**< The current rotation speed. Used for smooth rotating.*/ struct { mission_t *selectedMission; /**< Currently selected mission on geoscape */ aircraft_t *selectedAircraft; /**< Currently selected aircraft on geoscape */ aircraft_t *selectedUFO; /**< Currently selected UFO on geoscape */ aircraft_t *interceptAircraft; /**< selected aircraft for interceptions */ aircraft_t *missionAircraft; /**< aircraft pointer for mission handling */ } geoscape; /* == misc == */ /* MA_NEWBASE, MA_INTERCEPT, MA_BASEATTACK, ... */ mapAction_t mapAction; /** @todo move into the base node extra data */ /* BA_NEWBUILDING ... */ baseAction_t baseAction; /* how fast the game is running */ int gameTimeScale; int gameLapse; /* already paid in this month? */ qboolean paid; /** Coordinates to place the new base at (long, lat) */ vec2_t newBasePos; /* == employees == */ /* A list of all phalanx employees (soldiers, scientists, workers, etc...) */ linkedList_t *employees[MAX_EMPL]; /* == technologies == */ /* A list of all research-topics resp. the research-tree. */ technology_t technologies[MAX_TECHNOLOGIES]; /* Total number of technologies. */ int numTechnologies; /* == bases == */ /* A list of _all_ bases ... even unbuilt ones. */ base_t bases[MAX_BASES]; /* Total number of built bases (how many are enabled). */ int numBases; /* a list of all templates for building bases */ baseTemplate_t baseTemplates[MAX_BASETEMPLATES]; int numBaseTemplates; /* == aircraft == */ linkedList_t *aircraft; /* == Alien bases == */ linkedList_t *alienBases; /* == Nations == */ nation_t nations[MAX_NATIONS]; int numNations; /* == Cities == */ linkedList_t *cities; int numCities; /* Projectiles on geoscape (during fights) */ <API key> projectiles[<API key>]; int numProjectiles; /* == Transfers == */ linkedList_t* transfers; /* UFO components. */ int numComponents; components_t components[MAX_ASSEMBLIES]; /* == stored UFOs == */ linkedList_t *storedUFOs; /* Alien Team Definitions. */ teamDef_t *alienTeams[MAX_TEAMDEFS]; int numAliensTD; /* Alien Team Package used during battle */ alienTeamCategory_t alienCategories[ALIENCATEGORY_MAX]; /**< different alien team available * that will be used in mission */ int numAlienCategories; /** number of alien team categories defined */ /* == ufopedia == */ /* A list of all UFOpaedia chapters. */ pediaChapter_t upChapters[MAX_PEDIACHAPTERS]; /* Total number of UFOpaedia chapters */ int numChapters; int numUnreadMails; /**< only for faster access (don't cycle all techs every frame) */ eventMail_t eventMails[MAX_EVENTMAILS]; /**< holds all event mails (cl_event.c) */ int numEventMails; /**< how many eventmails (script-id: mail) parsed */ campaignEvents_t campaignEvents[MAX_CAMPAIGNS]; /**< holds all campaign events (cl_event.c) */ int <API key>; /**< how many event definitions (script-id: events) parsed */ /* == buildings in bases == */ /* A list of all possible unique buildings. */ building_t buildingTemplates[MAX_BUILDINGS]; int <API key>; /* A list of the building-list per base. (new buildings in a base get copied from buildingTypes) */ building_t buildings[MAX_BASES][MAX_BUILDINGS]; /* Total number of buildings per base. */ int numBuildings[MAX_BASES]; /* == installations == */ /* A template for each possible installation with configurable values */ <API key> <API key>[<API key>]; int <API key>; /* A list of _all_ installations ... even unbuilt ones. */ installation_t installations[MAX_INSTALLATIONS]; /* Total number of built installations (how many are enabled). */ int numInstallations; /* UFOs on geoscape */ aircraft_t ufos[MAX_UFOONGEOSCAPE]; int numUFOs; /**< The current amount of UFOS on the geoscape. */ /* message categories */ msgCategory_t messageCategories[<API key>]; int numMsgCategories; /* entries for message categories */ msgCategoryEntry_t msgCategoryEntries[NT_NUM_NOTIFYTYPE + <API key>]; int <API key>; /* == Ranks == */ /* Global list of all ranks defined in medals.ufo. */ rank_t ranks[MAX_RANKS]; /* The number of entries in the list above. */ int numRanks; /* cache for techdef technologies */ technology_t *teamDefTechs[MAX_TEAMDEFS]; /* cache for item technologies */ technology_t *objDefTechs[MAX_OBJDEFS]; campaign_t *curCampaign; /**< Current running campaign */ stats_t campaignStats; missionResults_t missionResults; campaign_t campaigns[MAX_CAMPAIGNS]; int numCampaigns; aircraft_t aircraftTemplates[MAX_AIRCRAFT]; /**< Available aircraft types/templates/samples. */ int <API key>; /**< Number of aircraft templates. */ } ccs_t; /** * @brief Human readable time information in the game. * @note Use this on runtime - please avoid for structs that get saved. * @sa date_t For storage & network transmitting (engine only). * @sa CL_DateConvertLong */ typedef struct dateLong_s { short year; /**< Year in yyyy notation. */ byte month; /**< Number of month (starting with 1). */ byte day; /**< Number of day (starting with 1). */ byte hour; /**< Hour of the day. @todo check what number-range this gives) */ byte min; /**< Minute of the hour. */ byte sec; /**< Second of the minute. */ } dateLong_t; typedef struct { int x, y; } screenPoint_t; extern ccs_t ccs; extern const int DETECTION_INTERVAL; extern cvar_t *cp_campaign; extern cvar_t *cp_missiontest; extern cvar_t *cp_start_employees; #define MAX_CREDITS 10000000 /* Campaign functions */ void CP_InitStartup(void); campaign_t* CL_GetCampaign(const char *name); void CP_CampaignInit(campaign_t *campaign, qboolean load); void <API key>(void); void CL_ReadCampaignData(const campaign_t *campaign); qboolean CP_IsRunning(void); void CL_CampaignRun(campaign_t *campaign); void <API key>(const campaign_t *campaign); void CP_EndCampaign(qboolean won); void CP_Shutdown(void); void <API key>(void); /* Date functions */ void CL_DateConvertLong(const date_t * date, dateLong_t * dateLong); const char* CL_SecondConvert(int second); /* Mission related functions */ int <API key>(void); void <API key>(void); int <API key>(const mission_t const *mission, ufoType_t *ufoTypes); qboolean <API key>(aircraft_t *aircraft, mission_t *mission); void <API key>(const mission_t *mission); void <API key>(const campaign_t* campaign, aircraft_t *ufocraft); void <API key>(qboolean won, const missionResults_t *results); mission_t *CP_CreateNewMission(interestCategory_t category, qboolean beginNow); qboolean CP_ChooseMap(mission_t *mission, const vec2_t pos); void <API key>(void); void CL_HandleNationData(float minHappiness, qboolean won, mission_t * mis, const nation_t *nation, const missionResults_t *results); void <API key>(const base_t *base, const aircraft_t *aircraft); /* Credits management */ qboolean CP_CheckCredits (int costs); void CL_UpdateCredits(int credits); /* Other functions */ void <API key>(struct dbuffer *msg); qboolean <API key>(const campaign_t* campaign, aircraft_t *ufo); aircraft_t* AIR_NewAircraft(base_t * base, const aircraft_t *aircraftTemplate); void <API key>(vec2_t pos, qboolean noWater); qboolean <API key>(vec2_t pos, const linkedList_t *terrainTypes, const linkedList_t *cultureTypes, const linkedList_t *populationTypes, const linkedList_t *nations); void CL_GameAutoGo(mission_t *mission, aircraft_t *aircraft, const campaign_t *campaign, const battleParam_t *battleParameters, missionResults_t *results); qboolean CP_OnGeoscape(void); #endif /* CP_CAMPAIGN_H */
StealDB ==== Get any database file - an app to demonstrate how easy it is maliciously upload and decrypt an android db store
#include <linux/fs.h> #include <linux/pram_fs.h> int pram_block_symlink(struct inode *inode, const char *symname, int len) { struct super_block * sb = inode->i_sb; pram_off_t block; char* blockp; unsigned long flags; int err; err = pram_alloc_blocks (inode, 0, 1); if (err) return err; block = <API key>(inode, 0); blockp = pram_get_block(sb, block); pram_lock_block(sb, blockp); memcpy(blockp, symname, len); blockp[len] = '\0'; pram_unlock_block(sb, blockp); return 0; } static int pram_readlink(struct dentry *dentry, char *buffer, int buflen) { struct inode * inode = dentry->d_inode; struct super_block * sb = inode->i_sb; pram_off_t block; char* blockp; block = <API key>(inode, 0); blockp = pram_get_block(sb, block); return vfs_readlink(dentry, buffer, buflen, blockp); } static int pram_follow_link(struct dentry *dentry, struct nameidata *nd) { struct inode * inode = dentry->d_inode; struct super_block * sb = inode->i_sb; pram_off_t block; char* blockp; block = <API key>(inode, 0); blockp = pram_get_block(sb, block); return vfs_follow_link(nd, blockp); } struct inode_operations <API key> = { readlink: pram_readlink, follow_link: pram_follow_link, };
.pane-bundle-videos { background: white; } .pane-bundle-videos .<API key> { border-bottom: 1px lightgray solid; } .pane-bundle-videos .<API key> { border-top: 10px #231f20 solid; } .pane-bundle-videos { -moz-box-shadow: rgba(0, 0, 0, 0.1) 0 1px 0, rgba(0, 0, 0, 0.1) 0 0 0 1px; -webkit-box-shadow: rgba(0, 0, 0, 0.1) 0 1px 0, rgba(0, 0, 0, 0.1) 0 0 0 1px; box-shadow: rgba(0, 0, 0, 0.1) 0 1px 0, rgba(0, 0, 0, 0.1) 0 0 0 1px; margin: 1px; } .pane-bundle-videos { padding: 0 26px; } .pane-bundle-videos .<API key> { color: #231f20; font-family: "NewsGothicBT-Demi", "Avant Garde", "Futura", "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 18px; font-weight: normal; line-height: 1.3; padding-top: 12px; } .pane-bundle-videos .<API key> a { color: #231f20; } .pane-bundle-videos .<API key> { overflow: hidden; *zoom: 1; padding: 22px 26px; margin: 0 -26px; } .pane-bundle-videos .<API key>:last-of-type { border-bottom: 0; } .pane-bundle-videos .<API key> .<API key> { display: inline; font-size: 22px; font-weight: bold; line-height: 1.3; } .pane-bundle-videos .<API key> .<API key>:hover { text-decoration: underline; } .wide-view .pane-bundle-videos .<API key> .<API key> { max-width: 65%; } @media (min-width: 35.5625em) and (max-width: 44.375em) { .wide-view .pane-bundle-videos .<API key> .<API key> { max-width: 100%; } } @media (max-width: 22.8125em) { .wide-view .pane-bundle-videos .<API key> .<API key> { max-width: 100%; } } @media (min-width: 20.0625em) and (max-width: 35.5em) { .narrow-view .pane-bundle-videos .<API key> .<API key> { max-width: 65%; } } .pane-bundle-videos .<API key> .video-channeltitle, .pane-bundle-videos .<API key> .video-viewcount { font-size: 14px; line-height: 1.2; } .wide-view .pane-bundle-videos .<API key> .video-channeltitle, .wide-view .pane-bundle-videos .<API key> .video-viewcount { max-width: 65%; } @media (min-width: 35.5625em) and (max-width: 44.375em) { .wide-view .pane-bundle-videos .<API key> .video-channeltitle, .wide-view .pane-bundle-videos .<API key> .video-viewcount { max-width: 100%; } } @media (max-width: 22.8125em) { .wide-view .pane-bundle-videos .<API key> .video-channeltitle, .wide-view .pane-bundle-videos .<API key> .video-viewcount { max-width: 100%; } } @media (min-width: 20.0625em) and (max-width: 35.5em) { .narrow-view .pane-bundle-videos .<API key> .video-channeltitle, .narrow-view .pane-bundle-videos .<API key> .video-viewcount { max-width: 65%; } } .pane-bundle-videos .<API key> .video-channeltitle { margin-top: 8px; } .pane-bundle-videos .<API key> .video-channeltitle span { margin-right: 5px; } .pane-bundle-videos .<API key> .video-viewcount { margin-bottom: 8px; } .pane-bundle-videos .<API key> .video-viewcount span { margin-left: 5px; } .pane-bundle-videos .<API key> .<API key> { font-size: 16px; line-height: 1.3; } .wide-view .pane-bundle-videos .<API key> .<API key> { max-width: 65%; } @media (min-width: 35.5625em) and (max-width: 44.375em) { .wide-view .pane-bundle-videos .<API key> .<API key> { max-width: 100%; } } @media (max-width: 22.8125em) { .wide-view .pane-bundle-videos .<API key> .<API key> { max-width: 100%; } } @media (min-width: 20.0625em) and (max-width: 35.5em) { .narrow-view .pane-bundle-videos .<API key> .<API key> { max-width: 65%; } } .pane-bundle-videos .<API key> .group-wrapper-video { position: relative; } .wide-view .pane-bundle-videos .<API key> .group-wrapper-video { float: right; margin-left: 10px; max-width: 125px; } @media (min-width: 35.5625em) and (max-width: 44.375em) { .wide-view .pane-bundle-videos .<API key> .group-wrapper-video { float: none; margin-bottom: 12px; margin-left: 0; max-width: 216px; } } @media (max-width: 22.8125em) { .wide-view .pane-bundle-videos .<API key> .group-wrapper-video { float: none; margin-bottom: 12px; margin-left: 0; max-width: 216px; } } .narrow-view .pane-bundle-videos .<API key> .group-wrapper-video { margin-bottom: 12px; max-width: 216px; } @media (min-width: 20.0625em) and (max-width: 35.5em) { .narrow-view .pane-bundle-videos .<API key> .group-wrapper-video { float: right; margin-left: 10px; max-width: 125px; } } .pane-bundle-videos .<API key> .<API key> .<API key> a.fancybox:before { content: "\f10c"; display: inline; speak: none; text-rendering: optimizeLegibility; -<API key>: grayscale; -<API key>: antialiased; font-smoothing: antialiased; text-transform: none; line-height: 1; font-style: normal; font-variant: normal; font-weight: normal; font-family: 'icons'; } .pane-bundle-videos .<API key> .<API key> .<API key> a.fancybox:before { font-size: 51px; margin-top: -30px; margin-left: -22px; } .pane-bundle-videos .<API key> .<API key> .<API key> a.fancybox:after { content: "\f11a"; display: inline; speak: none; text-rendering: optimizeLegibility; -<API key>: grayscale; -<API key>: antialiased; font-smoothing: antialiased; text-transform: none; line-height: 1; font-style: normal; font-variant: normal; font-weight: normal; font-family: 'icons'; } .pane-bundle-videos .<API key> .<API key> .<API key> a.fancybox:after { font-size: 16px; margin-top: -12px; margin-left: -4px; } .pane-bundle-videos .<API key> .<API key> .field-type-file .<API key> .file-video a:before { content: "\f10c"; display: inline; speak: none; text-rendering: optimizeLegibility; -<API key>: grayscale; -<API key>: antialiased; font-smoothing: antialiased; text-transform: none; line-height: 1; font-style: normal; font-variant: normal; font-weight: normal; font-family: 'icons'; } .pane-bundle-videos .<API key> .<API key> .field-type-file .<API key> .file-video a:before { font-size: 51px; margin-top: -30px; margin-left: -22px; } .pane-bundle-videos .<API key> .<API key> .field-type-file .<API key> .file-video a:after { content: "\f11a"; display: inline; speak: none; text-rendering: optimizeLegibility; -<API key>: grayscale; -<API key>: antialiased; font-smoothing: antialiased; text-transform: none; line-height: 1; font-style: normal; font-variant: normal; font-weight: normal; font-family: 'icons'; } .pane-bundle-videos .<API key> .<API key> .field-type-file .<API key> .file-video a:after { font-size: 16px; margin-top: -12px; margin-left: -4px; } .pane-bundle-videos .<API key> .video-duration { background: #231f20; color: white; display: inline-block; float: right; font-size: 11px; font-weight: bold; line-height: 1.2; padding: 4px; position: absolute; right: 0; bottom: 2px; }
function c91754175.initial_effect(c) --atk up local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(91754175,0)) e1:SetCategory(CATEGORY_TOGRAVE+CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_QUICK_O) e1:SetCode(<API key>) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetCondition(c91754175.condition) e1:SetTarget(c91754175.target) e1:SetOperation(c91754175.operation) c:RegisterEffect(e1) end function c91754175.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetAttackTarget()~=nil end function c91754175.tgfilter(c) return c:IsRace(RACE_BEAST+RACE_BEASTWARRIOR+RACE_WINDBEAST) and c:IsAbleToGrave() end function c91754175.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.<API key>(c91754175.tgfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_HAND+LOCATION_DECK) end function c91754175.operation(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c91754175.tgfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,1,nil) local c=e:GetHandler() local tc=g:GetFirst() if tc and Duel.SendtoGrave(tc,REASON_EFFECT)~=0 and tc:IsLocation(LOCATION_GRAVE) and c:IsRelateToBattle() and c:IsFaceup() then local lv=tc:GetLevel() local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(<API key>) e1:SetValue(lv*100) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_BATTLE) c:RegisterEffect(e1) end end
CREATE TABLE IF NOT EXISTS `#<API key>` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `form_id` int(20) NOT NULL, `group_id` int(20) NOT NULL, `ip` varchar(20) NOT NULL, `ord_date` datetime NOT NULL, `ord_last_modified` datetime NOT NULL, `status` varchar(50) NOT NULL, `full_name` varchar(100) NOT NULL, `email` varchar(50) NOT NULL, `phone` varchar(50) NOT NULL, `mobile_phone` varchar(255) NOT NULL, `fax` varchar(255) NOT NULL, `address` varchar(300) NOT NULL, `paypal_info` text NOT NULL, `without_paypal_info` text NOT NULL, `ipn` varchar(20) NOT NULL, `checkout_method` varchar(20) NOT NULL, `tax` float NOT NULL, `shipping` float NOT NULL, `shipping_type` varchar(200) NOT NULL, `read` int(11) NOT NULL, `total` float NOT NULL, `currency` varchar(24) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
.ds-users-list .modal-body input:nth-child(2), .ds-permission-list .modal-body input:nth-child(2), .ds-group-list .modal-body input:nth-child(2) { margin-bottom: 1em; } .ds-users-list tbody tr, .ds-permission-list tbody tr, .ds-group-list tbody tr { cursor: pointer; } .ds-users-list padding: 0.1em 0 1em 0; } .ds-users-list margin-top: 0.25em; float: left; } .ds-users-list text-decoration: none; cursor: pointer; float: right; margin-top: 1em; } .ds-users-list padding: 0; } .ds-logs-view table { white-space: nowrap; } .ds-logs-view > div:nth-child(1) { padding: 0.1em 0 1em 0; } .ds-logs-view > div:nth-child(1) div { margin-bottom: 0; } .ds-user-edit, .ds-permission-edit, .ds-group-edit { margin: 1em 0 7em 0; } .ds-user-edit .btn, .ds-permission-edit .btn, .ds-group-edit .btn { margin-bottom: 1em; } .ds-user-edit .btn-danger, .ds-permission-edit .btn-danger, .ds-group-edit .btn-danger { float: right; } .ds-user-edit > h4, .ds-permission-edit > h4, .ds-group-edit > h4 { margin: 2em 0 0 0 !important; } .ds-user-edit hr, .ds-permission-edit hr, .ds-group-edit hr { margin-top: 0.5em; } .ds-user-edit table tr td:nth-child(1), .ds-permission-edit table tr td:nth-child(1), .ds-group-edit table tr td:nth-child(1) { font-weight: bold; } .ds-user-edit margin-top: 1em; margin-bottom: 1em; cursor: pointer; } .ds-user-add { padding-top: 1em; } .ds-user-add button { margin-bottom: 1em; } #password-collapse { cursor: pointer; } .permission-check { font-size: 1.2em; padding-bottom: 0.9em; } .permission-check div { padding-left: 0.6em; user-select: none; -moz-user-select: none; -webkit-user-select: none; } /*# sourceMappingURL=administrator.css.map */
PYTHON = `which python2` all: @echo no build make rule yet, just '"make check"' test-end2end: @cd tests/ && PYTHON=${PYTHON} ./testsuite test-unit: PYTHONPATH=..:$${PYTHONPATH} ${PYTHON} -m pytest `[ ! -z ${COVERAGE} ] && echo "--cov distgen"` tests/unittests/ # Note that flake8 reports both W503 and W504 ATM :-/ so ignore W503 for now, # which is what should be considered the right setup. test-lint: flake8 distgen/ --ignore=W503 # Check that testsuite in packaged sources work fine, too. test-sdist-check: rm -rf dist $(PYTHON) setup.py sdist cd dist/ && tar xf *.tar.gz && cd distgen-*/ && $(MAKE) check PYTHON=$(PYTHON) # Check that tarball generated by git-archive also passes the testsuite <API key>: rm -rf archive && mkdir archive git archive --prefix distgen/ HEAD | tar -x -C archive cd archive/distgen && $(MAKE) check PYTHON=$(PYTHON) check: test-unit test-end2end
import sys,os #sys.path.append(os.path.join(os.path.dirname(__file__), '../../..')) #from ethosgame.ethos.level import Level from ..level import Level #from ethosgame.ethos.gameobject import GameObject from ..gameobject import GameObject #from ethosgame.ethos.drawnobject import DrawnObject from ..drawnobject import DrawnObject import pygame from pygame.locals import * from pygame import Color, image, font, sprite class Level0(Level): def __init__(self): super(Level0, self).__init__() self.activeSprites = sprite.RenderClear() self.drawnSprites = [] self.npc = GameObject(image.load('User.png'), 100,50) self.activeSprites.add(self.npc) self.block1 = GameObject(image.load('platform.png'), 100, 400) self.activeSprites.add(self.block1); self.mousex = 0 self.mousey = 0 #The highest height our npc #can climb. If a the dY with a #point is higher than this, the #npc will just fall to his death self.MAX_HILL_HEIGHT = 3 self.toDrawRectTopLeft = (0,0) self.<API key> = (0,0) self.drawing = False self.pts = [] print "Level 0 initialized." def update(self, dT): #print "Running level0" #Character info for gobject in self.activeSprites: if gobject is not self.npc: if not gobject.rect.colliderect(self.npc.rect): #if self.npc.vy < 0.3 and (gobject.rect.y >= self.npc.rect.y + self.npc.rect.height): if self.npc.vy < 0.3: self.npc.vy += 0.1 else: self.npc.vy = 0 gobject.update(dT) collidingPoints = [] for drawnstuff in self.drawnSprites: for point in drawnstuff.pts: x = self.npc.rect.collidepoint(point) if x: collidingPoints.append(point) if(len(collidingPoints) > 0): self.npc.<API key>(collidingPoints) def processKeyDown(self,key): print "You hit the key " + str(key) + "!" if key == pygame.K_RIGHT: self.npc.vx = 0.1 def processMouseMotion(self,pos): #print "Your mouse is at " + str(pos[0]) + " " + str(pos[1]) self.mousex = pos[0] self.mousey = pos[1] if self.drawing and len(self.pts) < 100: self.pts.append( pos ) def <API key>(self, pos): print "Ya clicked at " + str(pos[0]) + " " + str(pos[1]) + " ya goof!" self.drawing = True self.toDrawRectTopLeft = (pos[0],pos[1]) if len(self.pts) > 0: self.pts = [] def <API key>(self, pos): print "Ya let go" if self.drawing is True: self.drawing = False self.drawnSprites.append ( DrawnObject(self.pts) ) self.<API key> = (pos[0], pos[1])
<?php ?> <?php get_header(); ?> <div id="content" class="montagneBackground"> <div class="container_12"> <section class="categories-f-r"> <?php $taxonomy = 'fromages_cat'; $tax_terms = get_terms( $taxonomy, array( 'hide_empty' => 0, 'orderby' => 'id', 'order' => DESC ) ); ?> <div class="text-wrapper"> <h1>Nos Fromages RichesMonts</h1> <h2>Variez les plaisirs ! <br> Découvrez toutes nos Raclettes,<br> Fondues et Tartiflettes !</h2> </div> <div class="categorie-bloc"> <img src="<?php echo <API key>(); ?>/library/images/categorie-fromage-1.jpg" alt=""> <a href="<?php echo get_term_link($tax_terms[0]); ?>"><h3><?php echo $tax_terms[0]->name; ?></h3></a> </div> <div class="categorie-bloc"> <img src="<?php echo <API key>(); ?>/library/images/categorie-fromage-2.jpg" alt=""> <a href="<?php echo get_term_link($tax_terms[1]); ?>"><h3><?php echo $tax_terms[1]->name; ?></h3></a> </div> <div class="categorie-bloc"> <img src="<?php echo <API key>(); ?>/library/images/categorie-fromage-3.jpg" alt=""> <a href="<?php echo get_term_link($tax_terms[2]); ?>"><h3><?php echo $tax_terms[2]->name; ?></h3></a> </div> </section> <div class="clearfix"></div> <?php $the_query = new WP_Query( array('post_type' => 'partenaires', 'showposts' => 5) ); if ( $the_query->have_posts() ) { ?> <section class="partenaires container_12"> <div class="outer-center"> <div class="inner-center"> <h2>Nos partenaires :</h2> <?php while ( $the_query->have_posts() ) { ?> <?php $the_query->the_post(); ?> <?php $image = get_field('logo'); ?> <a href="<?php the_field('lien'); ?>"><img src="<?php echo $image['url'] ?>" alt="<?php the_title(); ?>"></a> <?php } ?> </div> </div> </section> <?php } wp_reset_postdata(); ?> <div class="clearfix"></div> </div> </div> <?php get_footer(); ?>
hr{margin:20px auto;} .wrap{margin: 40px 0 0 60px;padding:30px;} .choice{padding:10px 0;overflow:hidden;} .choice .span1{float:left;} .choice .span2{float:left;margin-top:10px;} .choice input[type=text]{width:300px;margin-left:70px;padding:8px 4px;} .choice textarea{width: 320px;height: 35px;} .choice_radio{margin-left:150px;} .submit{margin-top:20px;margin-right:10px;padding:0;float:left;} .submit input,.submit input:hover,.submit input:active{padding:6px 10px;border:none;border-radius:0;background:#299982;color:#fff;text-shadow:none;}
<?php /** * Set up the WordPress core custom header feature. * * @uses <API key>() */ function <API key>() { add_theme_support( 'custom-header', apply_filters( '<API key>', array( 'default-image' => '', 'default-text-color' => '000000', 'width' => 1000, 'height' => 250, 'flex-height' => true, 'wp-head-callback' => '<API key>', ) ) ); } add_action( 'after_setup_theme', '<API key>' ); if ( ! function_exists( '<API key>' ) ) : /** * Styles the header image and text displayed on the blog. * * @see <API key>(). */ function <API key>() { $header_text_color = <API key>(); /* * If no custom options for text are set, let's bail. * <API key>() options: Any hex value, 'blank' to hide text. Default: HEADER_TEXTCOLOR. */ if ( HEADER_TEXTCOLOR === $header_text_color ) { return; } // If we get this far, we have custom styles. Let's do this. ?> <style type="text/css"> <?php // Has the text been hidden? if ( ! display_header_text() ) : ?> .site-title, .site-description { position: absolute; clip: rect(1px, 1px, 1px, 1px); } <?php // If the user has set a custom color for the text use that. else : ?> .site-title a, .site-description { color: #<?php echo esc_attr( $header_text_color ); ?>; } <?php endif; ?> </style> <?php } endif;
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_55) on Sun Feb 15 12:26:29 PST 2015 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>org.apache.solr.client.solrj.embedded (Solr 5.0.0 API)</title> <meta name="date" content="2015-02-15"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.solr.client.solrj.embedded (Solr 5.0.0 API)"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/apache/solr/analysis/package-summary.html">Prev Package</a></li> <li><a href="../../../../../../org/apache/solr/cloud/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/solr/client/solrj/embedded/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h1 title="Package" class="title">Package&nbsp;org.apache.solr.client.solrj.embedded</h1> <div class="docSummary"> <div class="block"> SolrJ client implementations for embedded solr access.</div> </div> <p>See:&nbsp;<a href="#package_description">Description</a></p> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../org/apache/solr/client/solrj/embedded/EmbeddedSolrServer.html" title="class in org.apache.solr.client.solrj.embedded">EmbeddedSolrServer</a></td> <td class="colLast"> <div class="block">SolrClient that connects directly to SolrCore.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../org/apache/solr/client/solrj/embedded/JettySolrRunner.html" title="class in org.apache.solr.client.solrj.embedded">JettySolrRunner</a></td> <td class="colLast"> <div class="block">Run solr using jetty</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../org/apache/solr/client/solrj/embedded/JettySolrRunner.DebugFilter.html" title="class in org.apache.solr.client.solrj.embedded">JettySolrRunner.DebugFilter</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../org/apache/solr/client/solrj/embedded/JettySolrRunner.Servlet404.html" title="class in org.apache.solr.client.solrj.embedded">JettySolrRunner.Servlet404</a></td> <td class="colLast"> <div class="block">This is a stupid hack to give jetty something to attach to</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../org/apache/solr/client/solrj/embedded/SSLConfig.html" title="class in org.apache.solr.client.solrj.embedded">SSLConfig</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> </ul> <a name="package_description"> </a> <h2 title="Package org.apache.solr.client.solrj.embedded Description">Package org.apache.solr.client.solrj.embedded Description</h2> <div class="block"><p> SolrJ client implementations for embedded solr access. </p> <p> See <a href="../../../../../../../solr-solrj/org/apache/solr/client/solrj/package-summary.html?is-external=true"><code>org.apache.solr.client.solrj</code></a> for additional details. </p></div> </div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/apache/solr/analysis/package-summary.html">Prev Package</a></li> <li><a href="../../../../../../org/apache/solr/cloud/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/solr/client/solrj/embedded/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2015 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
<?php require_once(sfConfig::get('sf_lib_dir').'/filter/base/<API key>.class.php'); /** * CatArt filter form base class. * * @package sf_sandbox * @subpackage filter * @author Your name here * @version SVN: $Id: <API key>.php 16976 2009-04-04 12:47:44Z fabien $ */ class <API key> extends <API key> { public function setup() { $this->setWidgets(array( 'cat_des' => new <API key>(), 'dis_cen' => new <API key>(), 'campo1' => new <API key>(), 'campo2' => new <API key>(), 'campo3' => new <API key>(), 'campo4' => new <API key>(), 'co_us_in' => new <API key>(), 'fe_us_in' => new <API key>(), 'co_us_mo' => new <API key>(), 'fe_us_mo' => new <API key>(), 'co_us_el' => new <API key>(), 'fe_us_el' => new <API key>(), 'revisado' => new <API key>(), 'trasnfe' => new <API key>(), 'co_sucu' => new <API key>(), 'rowguid' => new <API key>(), 'co_imun' => new <API key>(), 'co_reten' => new <API key>(), 'row_id' => new <API key>(), 'movil' => new sfWidgetFormChoice(array('choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no'))), )); $this->setValidators(array( 'cat_des' => new sfValidatorPass(array('required' => false)), 'dis_cen' => new sfValidatorPass(array('required' => false)), 'campo1' => new sfValidatorPass(array('required' => false)), 'campo2' => new sfValidatorPass(array('required' => false)), 'campo3' => new sfValidatorPass(array('required' => false)), 'campo4' => new sfValidatorPass(array('required' => false)), 'co_us_in' => new sfValidatorPass(array('required' => false)), 'fe_us_in' => new sfValidatorPass(array('required' => false)), 'co_us_mo' => new sfValidatorPass(array('required' => false)), 'fe_us_mo' => new sfValidatorPass(array('required' => false)), 'co_us_el' => new sfValidatorPass(array('required' => false)), 'fe_us_el' => new sfValidatorPass(array('required' => false)), 'revisado' => new sfValidatorPass(array('required' => false)), 'trasnfe' => new sfValidatorPass(array('required' => false)), 'co_sucu' => new sfValidatorPass(array('required' => false)), 'rowguid' => new sfValidatorPass(array('required' => false)), 'co_imun' => new sfValidatorPass(array('required' => false)), 'co_reten' => new sfValidatorPass(array('required' => false)), 'row_id' => new sfValidatorPass(array('required' => false)), 'movil' => new sfValidatorChoice(array('required' => false, 'choices' => array('', 1, 0))), )); $this->widgetSchema->setNameFormat('cat_art_filters[%s]'); $this->errorSchema = new <API key>($this->validatorSchema); parent::setup(); } public function getModelName() { return 'CatArt'; } public function getFields() { return array( 'co_cat' => 'Text', 'cat_des' => 'Text', 'dis_cen' => 'Text', 'campo1' => 'Text', 'campo2' => 'Text', 'campo3' => 'Text', 'campo4' => 'Text', 'co_us_in' => 'Text', 'fe_us_in' => 'Text', 'co_us_mo' => 'Text', 'fe_us_mo' => 'Text', 'co_us_el' => 'Text', 'fe_us_el' => 'Text', 'revisado' => 'Text', 'trasnfe' => 'Text', 'co_sucu' => 'Text', 'rowguid' => 'Text', 'co_imun' => 'Text', 'co_reten' => 'Text', 'row_id' => 'Text', 'movil' => 'Boolean', ); } }
require File.join(File.dirname(__FILE__), 'test_helper') class PointTest < Test::Unit::TestCase context "A point" do setup do @point = Pathfinder::Point.new 1, 2 end should "respond to #x and #y" do assert_equal 1, @point.x assert_equal 2, @point.y end should "convert to an Array using #to_a" do assert_equal [1,2], @point.to_a end should "output in ordered-pair notation upon #inspect" do assert_equal "(1,2)", @point.inspect end should "have distance zero from itself" do assert_equal 0.0, @point.distance(@point) end should "use the distance formula to calculate #distance" do origin = Pathfinder::Point.new 0,0 assert_in_delta Math.sqrt(5), @point.distance(origin), 0.0001 end end end
package org.iq4j.webcam; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.KeyEventDispatcher; import java.awt.<API key>; import java.awt.Transparency; import java.awt.color.ColorSpace; import java.awt.color.ICC_ColorSpace; import java.awt.color.ICC_ProfileRGB; import java.awt.event.KeyEvent; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import javax.swing.JPanel; import com.googlecode.javacv.cpp.opencv_core.CvScalar; import com.googlecode.javacv.cpp.opencv_core.IplImage; /** * * @author Samuel Audet * * * Make sure OpenGL or XRender is enabled to get low latency, something like * export _JAVA_OPTIONS=-Dsun.java2d.opengl=True * export _JAVA_OPTIONS=-Dsun.java2d.xrender=True * * @author Sertac ANADOLLU ( anatolian ) * * JPanel version of javacv CanvasFrame * */ public class CanvasPanel extends JPanel { private static final long serialVersionUID = 1L; public static class Exception extends java.lang.Exception { private static final long serialVersionUID = 1L; public Exception(String message) { super(message); } public Exception(String message, Throwable cause) { super(message, cause); } } public static GraphicsDevice <API key>() { return GraphicsEnvironment.<API key>().<API key>(); } public static double getGamma(GraphicsDevice screen) { ColorSpace cs = screen.<API key>().getColorModel().getColorSpace(); if (cs.isCS_sRGB()) { return 2.2; } else { try { return ((ICC_ProfileRGB)((ICC_ColorSpace)cs).getProfile()).getGamma(0); } catch (RuntimeException e) { } } return 0.0; } public CanvasPanel() { this(0.0); } public CanvasPanel(double gamma) { this(gamma, Dimensions.DEFAULT_SIZE); } public CanvasPanel(double gamma, Dimension size) { this.gamma = gamma; setPreferredSize(size); setSize(size); setBackground(Color.LIGHT_GRAY); } private void startCanvas() { Runnable r = new Runnable() { public void run() { <API key>.<API key>().<API key>(keyEventDispatch); GraphicsDevice gd = <API key>().getDevice(); double g = gamma == 0.0 ? getGamma(gd) : gamma; inverseGamma = g == 0.0 ? 1.0 : 1.0/g; setVisible(true); setupCanvas(gamma); try { Thread.sleep(1000); } catch (<API key> e) { // TODO Auto-generated catch block e.printStackTrace(); } }}; if (EventQueue.isDispatchThread()) { r.run(); setCanvasSize(getSize().width, getSize().height); } else { try { EventQueue.invokeAndWait(r); } catch (java.lang.Exception ex) { } } } public void resetCanvas() { canvas = null; } protected void setupCanvas(double gamma) { canvas = new Canvas() { private static final long serialVersionUID = 1L; @Override public void update(Graphics g) { paint(g); } @Override public void paint(Graphics g) { // Calling BufferStrategy.show() here sometimes throws // <API key> or <API key>, // but otherwise seems to work fine. try { BufferStrategy strategy = canvas.getBufferStrategy(); do { do { g = strategy.getDrawGraphics(); if (color != null) { g.setColor(color); g.fillRect(0, 0, getWidth(), getHeight()); } if (image != null) { g.drawImage(image, 0, 0, getWidth(), getHeight(), null); } if (buffer != null) { g.drawImage(buffer, 0, 0, getWidth(), getHeight(), null); } g.dispose(); } while (strategy.contentsRestored()); strategy.show(); } while (strategy.contentsLost()); } catch (<API key> e) { } catch (<API key> e) { } } }; needInitialResize = true; add(canvas); canvas.setVisible(true); canvas.<API key>(2); } // used for example as debugging console... public static CanvasPanel global = null; // Latency is about 60 ms on Metacity and Windows XP, and 90 ms on Compiz Fusion, // but we set the default to twice as much to take into account the roundtrip // camera latency as well, just to be sure public static final long DEFAULT_LATENCY = 200; private long latency = DEFAULT_LATENCY; private KeyEvent keyEvent = null; private KeyEventDispatcher keyEventDispatch = new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() == KeyEvent.KEY_PRESSED) { synchronized (CanvasPanel.this) { keyEvent = e; CanvasPanel.this.notify(); } } return false; } }; protected Canvas canvas = null; protected boolean needInitialResize = false; protected double initialScale = 1.0; protected double inverseGamma = 1.0; private Color color = null; private Image image = null; private BufferedImage buffer = null; private final double gamma; public long getLatency() { // if there exists some way to estimate the latency in real time, // add it here return latency; } public void setLatency(long latency) { this.latency = latency; } public void waitLatency() throws <API key> { Thread.sleep(getLatency()); } public KeyEvent waitKey() throws <API key> { return waitKey(0); } public synchronized KeyEvent waitKey(int delay) throws <API key> { if (delay >= 0) { keyEvent = null; wait(delay); } KeyEvent e = keyEvent; keyEvent = null; return e; } public Canvas getCanvas() { return canvas; } public Dimension getCanvasSize() { return canvas.getSize(); } public void setCanvasSize(final int width, final int height) { Dimension d = getCanvasSize(); if (d.width == width && d.height == height) { return; } Runnable r = new Runnable() { public void run() { // There is apparently a bug in Java code for Linux, and what happens goes like this: // 1. Canvas gets resized, checks the visible area (has not changed) and updates // BufferStrategy with the same size. 2. pack() resizes the frame and changes // the visible area 3. We call Canvas.setSize() with different dimensions, to make // it check the visible area and reallocate the BufferStrategy almost correctly // 4. Finally, we resize the Canvas to the desired size... phew! canvas.setSize(width, height); setSize(width, height); canvas.setSize(width+1, height+1); canvas.setSize(width, height); needInitialResize = false; }}; if (EventQueue.isDispatchThread()) { r.run(); } else { try { EventQueue.invokeAndWait(r); } catch (java.lang.Exception ex) { } } } public double getCanvasScale() { return initialScale; } public void setCanvasScale(double initialScale) { this.initialScale = initialScale; this.needInitialResize = true; } public Graphics2D createGraphics() { if (buffer == null || buffer.getWidth() != canvas.getWidth() || buffer.getHeight() != canvas.getHeight()) { BufferedImage newbuffer = canvas.<API key>().<API key>( canvas.getWidth(), canvas.getHeight(), Transparency.TRANSLUCENT); if (buffer != null) { Graphics g = newbuffer.getGraphics(); g.drawImage(buffer, 0, 0, null); g.dispose(); } buffer = newbuffer; } return buffer.createGraphics(); } public void releaseGraphics(Graphics2D g) { g.dispose(); canvas.paint(null); } public void showColor(CvScalar color) { showColor(new Color((int)color.red(), (int)color.green(), (int)color.blue())); } public void showColor(Color color) { this.color = color; this.image = null; canvas.paint(null); } // Java2D will do gamma correction for TYPE_CUSTOM BufferedImage, but // not for the standard types, so we need to do it manually. public void showImage(IplImage image) { showImage(image, false); } public void showImage(IplImage image, boolean flipChannels) { showImage(image.getBufferedImage(image.<API key>() == BufferedImage.TYPE_CUSTOM ? 1.0 : inverseGamma, flipChannels)); } public void showImage(Image image) { if(canvas == null) { startCanvas(); } if (image == null) { return; } else if (needInitialResize) { int w = (int)Math.round(image.getWidth (null)*initialScale); int h = (int)Math.round(image.getHeight(null)*initialScale); setCanvasSize(w, h); } this.color = null; this.image = image; canvas.paint(null); } }
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.map, name='map'), url(r'^mapSim', views.mapSim, name='mapSim'), url(r'^api/getPos', views.getPos, name='getPos'), url(r'^api/getProjAndPos', views.getProjAndPos, name='getProjAndPos'), ]
// RUN: %clang_cc1 -triple <API key> %s -fsyntax-only -verify #define SA(n, p) int a##n[(p) ? 1 : -1] struct A { int a; }; SA(0, sizeof(A) == 4); struct B { }; SA(1, sizeof(B) == 1); struct C : A, B { }; SA(2, sizeof(C) == 4); struct D { }; struct E : D { }; struct F : E { }; struct G : E, F { }; SA(3, sizeof(G) == 2); struct Empty { Empty(); }; struct I : Empty { Empty e; }; SA(4, sizeof(I) == 2); struct J : Empty { Empty e[2]; }; SA(5, sizeof(J) == 3); template<int N> struct Derived : Empty, Derived<N - 1> { }; template<> struct Derived<0> : Empty { }; struct S1 : virtual Derived<10> { Empty e; }; SA(6, sizeof(S1) == 24); struct S2 : virtual Derived<10> { Empty e[2]; }; SA(7, sizeof(S2) == 24); struct S3 { Empty e; }; struct S4 : Empty, S3 { }; SA(8, sizeof(S4) == 2); struct S5 : S3, Empty {}; SA(9, sizeof(S5) == 2); struct S6 : S5 { }; SA(10, sizeof(S6) == 2); struct S7 : Empty { void *v; }; SA(11, sizeof(S7) == 8); struct S8 : Empty, A { }; SA(12, sizeof(S8) == 4);
using Halsign.DWM.Framework; using System; using System.Collections.Generic; using System.Data; using System.Text; using System.Threading; namespace Halsign.DWM.Domain { public class DwmHost : DwmBase { private int _numCpus = 1; private int _numVCpus; private int _cpuSpeed; private int _numNics = 1; private bool _isPoolMaster; private bool _enabled = true; private string _ipAddress; private bool <API key>; private PowerStatus _powerState; private bool <API key>; private bool <API key>; private bool <API key>; private bool <API key>; private long _memOverhead; private DateTime <API key> = DateTime.MinValue; private <API key> _listVMs; private DwmPifCollection _listPIFs; private DwmPbdCollection _listPBDs; private <API key> _availableStorage; private <API key> _metrics; private static Dictionary<string, int> _uuidCache = new Dictionary<string, int>(); private static Dictionary<string, int> _nameCache = new Dictionary<string, int>(); private static Dictionary<string, string> _uuidNameCache = new Dictionary<string, string>(); private static object _uuidCacheLock = new object(); private static object _nameCacheLock = new object(); private static object _uuidNameCacheLock = new object(); private double _cpuScore; public int NumCpus { get { return this._numCpus; } set { this._numCpus = value; } } public int NumVCpus { get { return this._numVCpus; } set { this._numVCpus = value; } } public int CpuSpeed { get { return this._cpuSpeed; } set { this._cpuSpeed = value; } } public int NumNics { get { return this._numNics; } set { this._numNics = value; } } public string IPAddress { get { return this._ipAddress; } set { this._ipAddress = value; } } public bool IsPoolMaster { get { return this._isPoolMaster; } set { this._isPoolMaster = value; } } public bool Enabled { get { return this._enabled; } set { this._enabled = value; } } public bool <API key> { get { return this.<API key>; } set { this.<API key> = value; } } public PowerStatus PowerState { get { return this._powerState; } set { this._powerState = value; } } public long MemoryOverhead { get { return this._memOverhead; } set { this._memOverhead = value; } } internal bool <API key> { get { return this.<API key>; } set { this.<API key> = value; } } internal bool <API key> { get { return this.<API key>; } set { this.<API key> = value; } } internal bool <API key> { get { return this.<API key>; } set { this.<API key> = value; } } internal bool <API key> { get { return this.<API key>; } set { this.<API key> = value; } } public <API key> VirtualMachines { get { return DwmBase.SafeGetItem<<API key>>(ref this._listVMs); } internal set { this._listVMs = value; } } public DwmPifCollection PIFs { get { return DwmBase.SafeGetItem<DwmPifCollection>(ref this._listPIFs); } } public DwmPbdCollection PBDs { get { return DwmBase.SafeGetItem<DwmPbdCollection>(ref this._listPBDs); } } public <API key> AvailableStorage { get { return DwmBase.SafeGetItem<<API key>>(ref this._availableStorage); } internal set { this._availableStorage = value; } } public <API key> Metrics { get { return DwmBase.SafeGetItem<<API key>>(ref this._metrics); } internal set { this._metrics = value; } } internal double CpuScore { get { this._cpuScore = (double)(this.NumCpus * this.CpuSpeed); if (this.Metrics.MetricsNow != null) { this._cpuScore *= 1.0 - this.Metrics.MetricsNow.<API key>; } return this._cpuScore; } } public DateTime <API key> { get { if (this.<API key> == DateTime.MinValue) { string sqlStatement = "<API key>"; <API key> <API key> = new <API key>(); <API key>.Add(new StoredProcParam("@host_id", base.Id)); using (DBAccess dBAccess = new DBAccess()) { this.<API key> = dBAccess.<API key>(sqlStatement, <API key>); } if (this.<API key> == DateTime.MinValue) { this.<API key> = DateTime.UtcNow.AddMinutes(-1.0); } } return this.<API key>; } set { this.<API key> = value; } } public DwmHost(string uuid, string name, string poolUuid) : base(uuid, name) { base.PoolId = DwmBase.PoolUuidToId(poolUuid); if (!string.IsNullOrEmpty(uuid)) { base.Id = DwmHost.UuidToId(uuid, base.PoolId); } else { if (string.IsNullOrEmpty(name)) { throw new DwmException("The uuid or name of the Physical Host must be specified.", DwmErrorCode.InvalidParameter, null); } base.Id = DwmHost.NameToId(name, base.PoolId); } } public DwmHost(string uuid, string name, int poolId) : base(uuid, name) { base.PoolId = poolId; if (!string.IsNullOrEmpty(uuid)) { base.Id = DwmHost.UuidToId(uuid, base.PoolId); } else { if (string.IsNullOrEmpty(name)) { throw new DwmException("The uuid or name of the Physical Host must be specified.", DwmErrorCode.InvalidParameter, null); } base.Id = DwmHost.NameToId(name, base.PoolId); } } public DwmHost(int hostID) : base(hostID) { } internal static void RefreshCache() { object uuidCacheLock = DwmHost._uuidCacheLock; Monitor.Enter(uuidCacheLock); try { DwmHost._uuidCache.Clear(); } finally { Monitor.Exit(uuidCacheLock); } object nameCacheLock = DwmHost._nameCacheLock; Monitor.Enter(nameCacheLock); try { DwmHost._nameCache.Clear(); } finally { Monitor.Exit(nameCacheLock); } object uuidNameCacheLock = DwmHost._uuidNameCacheLock; Monitor.Enter(uuidNameCacheLock); try { DwmHost._uuidNameCache.Clear(); } finally { Monitor.Exit(uuidNameCacheLock); } } internal static int UuidToId(string uuid, int poolId) { int num = 0; if (!string.IsNullOrEmpty(uuid)) { string key = Localization.Format("{0}|{1}", uuid, poolId); if (!DwmHost._uuidCache.TryGetValue(key, out num)) { using (DBAccess dBAccess = new DBAccess()) { num = dBAccess.ExecuteScalarInt(Localization.Format("select id from hv_host where uuid='{0}' and poolid={1}", uuid.Replace("'", "''"), poolId)); if (num != 0) { object uuidCacheLock = DwmHost._uuidCacheLock; Monitor.Enter(uuidCacheLock); try { if (!DwmHost._uuidCache.ContainsKey(key)) { DwmHost._uuidCache.Add(key, num); } } finally { Monitor.Exit(uuidCacheLock); } } } } } return num; } public static int NameToId(string name, int poolId) { int num = 0; if (!string.IsNullOrEmpty(name)) { string key = Localization.Format("{0}|{1}", name, poolId); if (!DwmHost._nameCache.TryGetValue(key, out num)) { using (DBAccess dBAccess = new DBAccess()) { num = dBAccess.ExecuteScalarInt(Localization.Format("select id from hv_host where name='{0}' and poolid={1}", name.Replace("'", "''"), poolId)); if (num != 0) { object nameCacheLock = DwmHost._nameCacheLock; Monitor.Enter(nameCacheLock); try { if (!DwmHost._nameCache.ContainsKey(key)) { DwmHost._nameCache.Add(key, num); } } finally { Monitor.Exit(nameCacheLock); } } } } } return num; } public static string UuidToName(string uuid, int poolId) { string text = string.Empty; if (!string.IsNullOrEmpty(uuid)) { string key = Localization.Format("{0}|{1}", uuid, poolId); if (!DwmHost._uuidNameCache.TryGetValue(key, out text)) { using (DBAccess dBAccess = new DBAccess()) { text = dBAccess.ExecuteScalarString(Localization.Format("select name from hv_host where uuid='{0}' and poolid={1}", uuid, poolId)); if (string.IsNullOrEmpty(text)) { object uuidNameCacheLock = DwmHost._uuidNameCacheLock; Monitor.Enter(uuidNameCacheLock); try { if (!DwmHost._uuidNameCache.ContainsKey(key)) { DwmHost._uuidNameCache.Add(key, text); } } finally { Monitor.Exit(uuidNameCacheLock); } } } } } return text; } public DwmHost Copy() { return new DwmHost(base.Uuid, base.Name, base.PoolId) { Id = base.Id, CpuSpeed = this.CpuSpeed, Description = base.Description, IsPoolMaster = this.IsPoolMaster, Name = base.Name, NumCpus = this.NumCpus, NumVCpus = this.NumVCpus, NumNics = this.NumNics, <API key> = this.<API key>, <API key> = this.<API key>, <API key> = this.<API key>, <API key> = this.<API key>, PowerState = this.PowerState, MemoryOverhead = this.MemoryOverhead, Metrics = this.Metrics.Copy(), AvailableStorage = this.AvailableStorage.Copy(), VirtualMachines = this.VirtualMachines.Copy() }; } internal static void SetOtherConfig(int hostId, string name, string value) { DwmHost dwmHost = new DwmHost(hostId); dwmHost.SetOtherConfig(name, value); } public void SetOtherConfig(string name, string value) { base.SetOtherConfig("<API key>", "@host_id", name, value); if (Localization.Compare(name, "<API key>", true) == 0) { DwmPool.GenerateFillOrder(base.PoolId); } } public void SetOtherConfig(Dictionary<string, string> config) { base.SetOtherConfig("<API key>", "@host_id", config); if (config.ContainsKey("<API key>")) { DwmPool.GenerateFillOrder(base.PoolId); } } public string GetOtherConfigItem(string itemName) { return base.GetOtherConfigItem("<API key>", "@host_id", itemName); } public Dictionary<string, string> GetOtherConfig() { return base.GetOtherConfig("hv_host_config_get", "@host_id"); } public static void SetEnabled(string hostUuid, string poolUuid, bool enabled) { string sqlStatement = "hv_host_set_enabled"; <API key> <API key> = new <API key>(); <API key>.Add(new StoredProcParam("@host_uuid", hostUuid)); <API key>.Add(new StoredProcParam("@pool_uuid", poolUuid)); <API key>.Add(new StoredProcParam("@enabled", enabled)); using (DBAccess dBAccess = new DBAccess()) { dBAccess.ExecuteNonQuery(sqlStatement, <API key>); } } internal static void SetStatus(int hostId, DwmStatus status) { string sqlStatement = "set_host_status"; <API key> <API key> = new <API key>(); <API key>.Add(new StoredProcParam("@host_id", hostId)); <API key>.Add(new StoredProcParam("@status", (int)status)); using (DBAccess dBAccess = new DBAccess()) { dBAccess.ExecuteNonQuery(sqlStatement, <API key>); } } internal static void SetLastResult(int hostId, DwmStatus result) { string sqlStatement = "<API key>"; <API key> <API key> = new <API key>(); <API key>.Add(new StoredProcParam("@host_id", hostId)); <API key>.Add(new StoredProcParam("@last_result", (int)result)); <API key>.Add(new StoredProcParam("@last_result_time", DateTime.UtcNow)); using (DBAccess dBAccess = new DBAccess()) { dBAccess.ExecuteNonQuery(sqlStatement, <API key>); } } public static void SetPoweredOffByWlb(int hostId, bool poweredOffByWlb) { string sqlStatement = "<API key>"; <API key> <API key> = new <API key>(); <API key>.Add(new StoredProcParam("@host_id", hostId)); if (poweredOffByWlb) { <API key>.Add(new StoredProcParam("@powered_off_by_wlb", 1)); } else { <API key>.Add(new StoredProcParam("@powered_off_by_wlb", 0)); } using (DBAccess dBAccess = new DBAccess()) { dBAccess.ExecuteNonQuery(sqlStatement, <API key>); } } internal bool HasRequiredStorage(<API key> requiredSRs) { bool result = true; int num = 0; while (requiredSRs != null && num < requiredSRs.Count) { if (!this.AvailableStorage.ContainsKey(requiredSRs[num].Id)) { result = false; break; } num++; } return result; } public static void DeleteHost(string hostUuid, string poolUuid) { if (!string.IsNullOrEmpty(hostUuid) && !string.IsNullOrEmpty(poolUuid)) { Logger.Trace("Deleting host {0} by setting active to false", new object[] { hostUuid }); int num = DwmPoolBase.UuidToId(poolUuid); int num2 = DwmHost.UuidToId(hostUuid, num); string sqlStatement = "delete_hv_host"; <API key> <API key> = new <API key>(); <API key>.Add(new StoredProcParam("@pool_id", num)); <API key>.Add(new StoredProcParam("@host_id", num2)); <API key>.Add(new StoredProcParam("@tstamp", DateTime.UtcNow)); using (DBAccess dBAccess = new DBAccess()) { dBAccess.ExecuteNonQuery(sqlStatement, <API key>); } } } internal static DwmHost LoadWithMetrics(IDataReader reader) { string @string = DBAccess.GetString(reader, "uuid"); string string2 = DBAccess.GetString(reader, "name"); int @int = DBAccess.GetInt(reader, "poolid"); return new DwmHost(@string, string2, @int) { Id = DBAccess.GetInt(reader, "id"), NumCpus = DBAccess.GetInt(reader, "num_cpus"), NumVCpus = DBAccess.GetInt(reader, "num_vcpus"), CpuSpeed = DBAccess.GetInt(reader, "cpu_speed"), NumNics = DBAccess.GetInt(reader, "num_pifs"), IsPoolMaster = DBAccess.GetBool(reader, "is_pool_master"), PowerState = (PowerStatus)DBAccess.GetInt(reader, "power_state"), <API key> = DBAccess.GetBool(reader, "can_power"), <API key> = DBAccess.GetBool(reader, "exclude_placements"), <API key> = DBAccess.GetBool(reader, "exclude_evacuations"), Metrics = { FreeCPUs = DBAccess.GetInt(reader, "free_cpus"), PotentialFreeMemory = DBAccess.GetInt64(reader, "<API key>"), FillOrder = DBAccess.GetInt(reader, "fill_order"), TotalMemory = DBAccess.GetInt64(reader, "total_mem"), FreeMemory = DBAccess.GetInt64(reader, "free_mem"), <API key> = DBAccess.GetInt(reader, "<API key>"), <API key> = DBAccess.GetInt(reader, "<API key>"), <API key> = DBAccess.GetInt(reader, "<API key>"), NumHighFullrunVCpus = DBAccess.GetInt(reader, "fullrun_count"), <API key> = DBAccess.GetInt(reader, "partial_run_count"), NumHighBlockedVCpus = DBAccess.GetInt(reader, "blocked_count"), MetricsNow = { AverageFreeMemory = DBAccess.GetInt64(reader, "avg_free_mem_now", 0L), <API key> = DBAccess.GetDouble(reader, "avg_cpu_now", 0.0), <API key> = DBAccess.GetDouble(reader, "avg_pif_read_now", 0.0), <API key> = DBAccess.GetDouble(reader, "avg_pif_write_now", 0.0), <API key> = DBAccess.GetDouble(reader, "avg_pbd_read_now", 0.0), <API key> = DBAccess.GetDouble(reader, "avg_pbd_write_now", 0.0), AverageLoadAverage = DBAccess.GetDouble(reader, "<API key>", 0.0) }, <API key> = { AverageFreeMemory = DBAccess.GetInt64(reader, "avg_free_mem_30", 0L), <API key> = DBAccess.GetDouble(reader, "avg_cpu_30", 0.0), <API key> = DBAccess.GetDouble(reader, "avg_pif_read_30", 0.0), <API key> = DBAccess.GetDouble(reader, "avg_pif_write_30", 0.0), <API key> = DBAccess.GetDouble(reader, "avg_pbd_read_30", 0.0), <API key> = DBAccess.GetDouble(reader, "avg_pbd_write_30", 0.0), AverageLoadAverage = DBAccess.GetDouble(reader, "avg_load_average_30", 0.0) }, MetricsYesterday = { AverageFreeMemory = DBAccess.GetInt64(reader, "<API key>", 0L), <API key> = DBAccess.GetDouble(reader, "avg_cpu_yesterday", 0.0), <API key> = DBAccess.GetDouble(reader, "<API key>", 0.0), <API key> = DBAccess.GetDouble(reader, "<API key>", 0.0), <API key> = DBAccess.GetDouble(reader, "<API key>", 0.0), <API key> = DBAccess.GetDouble(reader, "<API key>", 0.0), AverageLoadAverage = DBAccess.GetDouble(reader, "<API key>", 0.0) } } }; } internal void LoadPif(IDataReader reader) { int @int = DBAccess.GetInt(reader, "pif_id"); string @string = DBAccess.GetString(reader, "pif_uuid"); string string2 = DBAccess.GetString(reader, "pif_name"); int int2 = DBAccess.GetInt(reader, "networkid"); int int3 = DBAccess.GetInt(reader, "poolid"); bool @bool = DBAccess.GetBool(reader, "<API key>"); DwmPif dwmPif = new DwmPif(@string, string2, int2, int3); dwmPif.Id = @int; dwmPif.<API key> = @bool; this.PIFs.Add(dwmPif); } public void Save() { using (DBAccess dBAccess = new DBAccess()) { this.Save(dBAccess); } } public void Save(DBAccess db) { if (db != null) { try { string sqlStatement = "add_update_hv_host"; base.Id = db.ExecuteScalarInt(sqlStatement, new <API key> { new StoredProcParam("@uuid", base.Uuid), new StoredProcParam("@name", (base.Name == null) ? string.Empty : base.Name), new StoredProcParam("@pool_id", base.PoolId), new StoredProcParam("@description", (base.Description == null) ? string.Empty : base.Description), new StoredProcParam("@num_cpus", this._numCpus), new StoredProcParam("@cpu_speed", this._cpuSpeed), new StoredProcParam("@num_nics", this._numNics), new StoredProcParam("@is_pool_master", this._isPoolMaster), new StoredProcParam("@ip_address", this._ipAddress), new StoredProcParam("@memory_overhead", this._memOverhead), new StoredProcParam("@enabled", this._enabled), new StoredProcParam("@power_state", (int)this._powerState) }); StringBuilder stringBuilder = new StringBuilder(); string value = "BEGIN;\n"; string value2 = "COMMIT;\n"; stringBuilder.Append(value); stringBuilder.Append(this.<API key>()); stringBuilder.Append(this.<API key>()); stringBuilder.Append(this.<API key>()); stringBuilder.Append(this.<API key>()); stringBuilder.Append(value2); DwmBase.WriteData(db, stringBuilder); } catch (Exception ex) { Logger.Trace("Caught exception saving host {0} uuid={1}", new object[] { base.Name, base.Uuid }); Logger.LogException(ex); } return; } throw new DwmException("Cannot pass null DBAccess instance to Save", DwmErrorCode.NullReference, null); } private StringBuilder <API key>() { StringBuilder stringBuilder = new StringBuilder(); if (this._availableStorage != null && this._availableStorage.Count > 0) { StringBuilder stringBuilder2 = new StringBuilder(); for (int i = 0; i < this._availableStorage.Count; i++) { stringBuilder.AppendFormat("insert into <API key> (host_id, sr_id) select {0}, {1}\nwhere not exists (select id from <API key> where host_id={0} and sr_id={1});\n", base.Id, this._availableStorage[i].Id); stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._availableStorage[i].Id); } stringBuilder.AppendFormat("delete from <API key> where host_id={0} and sr_id not in ({1});\n", base.Id, stringBuilder2.ToString()); } else { stringBuilder.AppendFormat("delete from <API key> where host_id={0};\n", base.Id); } return stringBuilder; } private StringBuilder <API key>() { StringBuilder stringBuilder = new StringBuilder(); if (this._listVMs != null && this._listVMs.Count > 0) { StringBuilder stringBuilder2 = new StringBuilder(); for (int i = 0; i < this._listVMs.Count; i++) { stringBuilder.AppendFormat("select * from add_update_host_vm( {0}, {1}, '{2}');\n", base.Id, this._listVMs[i].Id, Localization.DateTimeToSqlString(DateTime.UtcNow)); stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._listVMs[i].Id); } stringBuilder.AppendFormat("delete from host_vm where hostid={0} and vmid not in ({1});\nupdate host_vm_history set end_time='{2}' \nwhere host_id={0}\n and end_time is null\n and vm_id not in ({1});\n", base.Id, stringBuilder2.ToString(), Localization.DateTimeToSqlString(DateTime.UtcNow)); } else { stringBuilder.AppendFormat("delete from host_vm where hostid={0};\nupdate host_vm_history set end_time='{1}' \nwhere host_id={0} and end_time is null;\n", base.Id, Localization.DateTimeToSqlString(DateTime.UtcNow)); } return stringBuilder; } private StringBuilder <API key>() { StringBuilder stringBuilder = new StringBuilder(); if (this._listPIFs != null && this._listPIFs.Count > 0) { StringBuilder stringBuilder2 = new StringBuilder(); for (int i = 0; i < this._listPIFs.Count; i++) { stringBuilder.AppendFormat("insert into hv_host_pif (hostid, pif_id, tstamp) select {0}, {1},'{2}'\nwhere not exists (select id from hv_host_pif where hostid={0} and pif_id={1});\n", base.Id, this._listPIFs[i].Id, Localization.DateTimeToSqlString(DateTime.UtcNow)); stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._listPIFs[i].Id); } stringBuilder.AppendFormat("delete from hv_host_pif where hostid={0} and pif_id not in ({1});\n", base.Id, stringBuilder2.ToString()); } else { stringBuilder.AppendFormat("delete from hv_host_pif where hostid={0};\n", base.Id); } return stringBuilder; } private StringBuilder <API key>() { StringBuilder stringBuilder = new StringBuilder(); if (this._listPBDs != null && this._listPBDs.Count > 0) { StringBuilder stringBuilder2 = new StringBuilder(); for (int i = 0; i < this._listPBDs.Count; i++) { stringBuilder.AppendFormat("insert into hv_host_pbd (hostid, pbd_id, tstamp) select {0}, {1}, '{2}'\nwhere not exists (select id from hv_host_pbd where hostid={0} and pbd_id={1});\n", base.Id, this._listPBDs[i].Id, Localization.DateTimeToSqlString(DateTime.UtcNow)); stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._listPBDs[i].Id); } stringBuilder.AppendFormat("delete from hv_host_pbd where hostid={0} and pbd_id not in ({1});\n", base.Id, stringBuilder2.ToString()); } else { stringBuilder.AppendFormat("delete from hv_host_pbd where hostid={0};\n", base.Id); } return stringBuilder; } public void Load() { string sql = "load_host_by_id"; this.InternalLoad(sql, new <API key> { new StoredProcParam("@host_id", base.Id) }); } internal void SimpleLoad() { string sql = "<API key>"; this.InternalLoad(sql, new <API key> { new StoredProcParam("@host_id", base.Id) }); } private void InternalLoad(string sql, <API key> parms) { using (DBAccess dBAccess = new DBAccess()) { dBAccess.UseTransaction = true; using (IDataReader dataReader = dBAccess.ExecuteReader(sql, parms)) { if (dataReader.Read()) { if (string.IsNullOrEmpty(base.Uuid)) { base.Uuid = DBAccess.GetString(dataReader, "uuid"); } if (base.PoolId <= 0) { base.PoolId = DBAccess.GetInt(dataReader, "poolid"); } base.Name = DBAccess.GetString(dataReader, "name"); base.Description = DBAccess.GetString(dataReader, "description"); this.NumCpus = DBAccess.GetInt(dataReader, "num_cpus"); this.CpuSpeed = DBAccess.GetInt(dataReader, "cpu_speed"); this.NumNics = DBAccess.GetInt(dataReader, "num_pifs"); this.IsPoolMaster = DBAccess.GetBool(dataReader, "is_pool_master"); this.Enabled = DBAccess.GetBool(dataReader, "enabled"); this.Metrics.FillOrder = DBAccess.GetInt(dataReader, "fill_order"); this.IPAddress = DBAccess.GetString(dataReader, "ip_address"); this.MemoryOverhead = DBAccess.GetInt64(dataReader, "memory_overhead"); base.Status = (DwmStatus)DBAccess.GetInt(dataReader, "status"); base.LastResult = (DwmStatus)DBAccess.GetInt(dataReader, "last_result"); base.LastResultTime = DBAccess.GetDateTime(dataReader, "last_result_time"); this.Metrics.TotalMemory = DBAccess.GetInt64(dataReader, "total_mem"); if (dataReader.NextResult()) { while (dataReader.Read()) { int @int = DBAccess.GetInt(dataReader, "hostid"); int int2 = DBAccess.GetInt(dataReader, "vmid"); string @string = DBAccess.GetString(dataReader, "name"); string string2 = DBAccess.GetString(dataReader, "uuid"); int int3 = DBAccess.GetInt(dataReader, "poolid"); DwmVirtualMachine dwmVirtualMachine = new DwmVirtualMachine(string2, @string, int3); dwmVirtualMachine.Id = int2; dwmVirtualMachine.Description = DBAccess.GetString(dataReader, "description"); dwmVirtualMachine.<API key> = DBAccess.GetInt64(dataReader, "min_dynamic_memory"); dwmVirtualMachine.<API key> = DBAccess.GetInt64(dataReader, "max_dynamic_memory"); dwmVirtualMachine.MinimumStaticMemory = DBAccess.GetInt64(dataReader, "min_static_memory"); dwmVirtualMachine.MaximumStaticMemory = DBAccess.GetInt64(dataReader, "max_static_memory"); dwmVirtualMachine.TargetMemory = DBAccess.GetInt64(dataReader, "target_memory"); dwmVirtualMachine.MemoryOverhead = DBAccess.GetInt64(dataReader, "memory_overhead"); dwmVirtualMachine.MinimumCpus = DBAccess.GetInt(dataReader, "min_cpus"); dwmVirtualMachine.HvMemoryMultiplier = DBAccess.GetDouble(dataReader, "<API key>"); dwmVirtualMachine.RequiredMemory = DBAccess.GetInt64(dataReader, "required_memory"); dwmVirtualMachine.IsControlDomain = DBAccess.GetBool(dataReader, "is_control_domain"); dwmVirtualMachine.IsAgile = DBAccess.GetBool(dataReader, "is_agile"); dwmVirtualMachine.DriversUpToDate = DBAccess.GetBool(dataReader, "drivers_up_to_date"); dwmVirtualMachine.Status = (DwmStatus)DBAccess.GetInt(dataReader, "status"); dwmVirtualMachine.LastResult = (DwmStatus)DBAccess.GetInt(dataReader, "last_result"); dwmVirtualMachine.LastResultTime = DBAccess.GetDateTime(dataReader, "last_result_time"); this.VirtualMachines.Add(dwmVirtualMachine); } } } } } } public static DwmHost Load(string hostUuid, string poolUuid) { int poolId = DwmPoolBase.UuidToId(poolUuid); int num = DwmHost.UuidToId(hostUuid, poolId); if (num <= 0) { throw new DwmException("Invalid Host uuid", DwmErrorCode.InvalidParameter, null); } return DwmHost.Load(num); } public static DwmHost Load(int hostId) { if (hostId > 0) { DwmHost dwmHost = new DwmHost(hostId); dwmHost.Load(); return dwmHost; } throw new DwmException("Invalid host ID", DwmErrorCode.InvalidParameter, null); } } }
#include "Converter.h" #include <TFormula.h> #include <iomanip> #include <sstream> std::string Converter::doubleToString(double x,int precision,bool scientifiStyle) { std::stringstream xs; if(scientifiStyle) xs<<std::scientific; else xs<<std::fixed; xs<<std::setprecision(precision)<<x; return xs.str(); }; std::string Converter::intToString(int x) { return doubleToString(x,0); }; double Converter::stringToDouble(std::string formula) { TFormula myf("myf",formula.c_str()); return myf.Eval(0); } int Converter::stringToInt(std::string formula) { return (int)(stringToDouble(formula)); }
#include <algorithm> #include <bitset> #include <cassert> #include <cmath> #include <cstdio> #include <cstring> #include <deque> #include <iostream> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <utility> #include <vector> // #pragma GCC optimize("Ofast") // #pragma GCC optimize("inline") // #pragma GCC optimize("-fgcse") // #pragma GCC optimize("-fgcse-lm") // #pragma GCC optimize("-fipa-sra") // #pragma GCC optimize("-ftree-pre") // #pragma GCC optimize("-ftree-vrp") // #pragma GCC optimize("-fpeephole2") // #pragma GCC optimize("-ffast-math") // #pragma GCC optimize("-fsched-spec") // #pragma GCC optimize("unroll-loops") // #pragma GCC optimize("-falign-jumps") // #pragma GCC optimize("-falign-loops") // #pragma GCC optimize("-falign-labels") // #pragma GCC optimize("-fdevirtualize") // #pragma GCC optimize("-fcaller-saves") // #pragma GCC optimize("-fcrossjumping") // #pragma GCC optimize("-fthread-jumps") // #pragma GCC optimize("-funroll-loops") // #pragma GCC optimize("-fwhole-program") // #pragma GCC optimize("-freorder-blocks") // #pragma GCC optimize("-fschedule-insns") // #pragma GCC optimize("inline-functions") // #pragma GCC optimize("-ftree-tail-merge") // #pragma GCC optimize("-fschedule-insns2") // #pragma GCC optimize("-fstrict-aliasing") // #pragma GCC optimize("-fstrict-overflow") // #pragma GCC optimize("-falign-functions") // #pragma GCC optimize("-fcse-skip-blocks") // #pragma GCC optimize("-fcse-follow-jumps") // #pragma GCC optimize("-fsched-interblock") // #pragma GCC optimize("-fpartial-inlining") // #pragma GCC optimize("no-stack-protector") // #pragma GCC optimize("-freorder-functions") // #pragma GCC optimize("-findirect-inlining") // #pragma GCC optimize("-<API key>") // #pragma GCC optimize("-<API key>") // #pragma GCC optimize("<API key>") // #pragma GCC optimize("-<API key>") // #pragma GCC optimize("-<API key>") // #pragma GCC optimize("-<API key>") // #pragma GCC optimize("-<API key>") // #pragma GCC optimize("-<API key>") // #pragma GCC optimize("<API key>") // #pragma GCC optimize("-<API key>") #define rep(i, l, r) for (int i = (l); i <= (r); ++i) #define per(i, l, r) for (int i = (l); i >= (r); --i) using std::cerr; using std::endl; using std::make_pair; using std::pair; typedef pair<int, int> pii; typedef long long ll; typedef unsigned int ui; typedef unsigned long long ull; // #define DEBUG 1 // struct IO { #define MAXSIZE (1 << 20) #define isdigit(x) (x >= '0' && x <= '9') char buf[MAXSIZE], *p1, *p2; char pbuf[MAXSIZE], *pp; #if DEBUG #else IO() : p1(buf), p2(buf), pp(pbuf) {} ~IO() { fwrite(pbuf, 1, pp - pbuf, stdout); } #endif inline char gc() { #if DEBUG return getchar(); #endif if (p1 == p2) p2 = (p1 = buf) + fread(buf, 1, MAXSIZE, stdin); return p1 == p2 ? -1 : *p1++; } inline bool blank(char ch) { return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'; } template <class T> inline void read(T &x) { register double tmp = 1; register bool sign = 0; x = 0; register char ch = gc(); for (; !isdigit(ch); ch = gc()) if (ch == '-') sign = 1; for (; isdigit(ch); ch = gc()) x = x * 10 + (ch - '0'); if (ch == '.') for (ch = gc(); isdigit(ch); ch = gc()) tmp /= 10.0, x += tmp * (ch - '0'); if (sign) x = -x; } inline void read(char *s) { register char ch = gc(); for (; blank(ch); ch = gc()) ; for (; !blank(ch); ch = gc()) *s++ = ch; *s = 0; } inline void read(char &c) { for (c = gc(); blank(c); c = gc()) ; } inline void push(const char &c) { #if DEBUG putchar(c); #else if (pp - pbuf == MAXSIZE) fwrite(pbuf, 1, MAXSIZE, stdout), pp = pbuf; *pp++ = c; #endif } template <class T> inline void write(T x) { if (x < 0) x = -x, push('-'); static T sta[35]; T top = 0; do { sta[top++] = x % 10, x /= 10; } while (x); while (top) push(sta[--top] + '0'); } inline void write(const char *s) { while (*s != '\0') push(*(s++)); } template <class T> inline void write(T x, char lastChar) { write(x), push(lastChar); } } io; int a[510][510]; int main() { #ifdef LOCAL freopen("input", "r", stdin); #endif int n; io.read(n); rep(i, 1, n) { rep(j, i + 1, n) { io.read(a[i][j]); a[j][i] = a[i][j]; } } int ans = 0; rep(i, 1, n) { std::sort(a[i] + 1, a[i] + 1 + n); ans = std::max(ans, a[i][n - 1]); } io.write("1\n"); io.write(ans); return 0; }
/* ScriptData SDName: boss_lord_marrowgar SD%Complete: 0% SDComment: SDCategory: Icecrown Citadel EndScriptData */ #include "precompiled.h" enum { SAY_INTRO = -1631001, SAY_AGGRO = -1631002, SAY_BONE_STORM = -1631003, SAY_BONE_SPIKE_1 = -1631004, SAY_BONE_SPIKE_2 = -1631005, SAY_BONE_SPIKE_3 = -1631006, SAY_SLAY_1 = -1631007, SAY_SLAY_2 = -1631008, SAY_DEATH = -1631009, SAY_BERSERK = -1631010, }; void <API key>() { }
var <API key> = true;//simply flag var jQuery(function () { if (<API key> == 'chosen') { try { if (jQuery("select.<API key>").length) { jQuery("select.<API key>").chosen({ <API key>: 10 }); jQuery.each(jQuery('.<API key> .chosen-container'), function (index, obj) { jQuery(obj).css({'width': jQuery(this).prev('select').data('width')}); }); } } catch (e) { console.log(e); } } if (<API key> == 'ddslick') { try { jQuery.each(jQuery('select.<API key>'), function (index, obj) { var width = jQuery(obj).data('width'); var flag_position = jQuery(obj).data('flag-position'); jQuery(obj).ddslick({ //data: ddData, width: width, imagePosition: flag_position, selectText: "Select currency", //background:'#ff0000', onSelected: function (data) { if (!<API key>) { jQuery(data.selectedItem).closest('form.<API key>').find('input[name="<API key>"]').eq(0).val(data.selectedData.value); jQuery(data.selectedItem).closest('form.<API key>').submit(); } } }); }); } catch (e) { console.log(e); } } //for flags view instead of drop-down jQuery('.<API key>').click(function () { if (jQuery(this).hasClass('<API key>')) { return false; }
package main import ( "bytes" "fmt" "regexp" ) func main() { match, _ := regexp.MatchString("p([a-z]+)ch", "peach") fmt.Println(match) r, _ := regexp.Compile("p([a-z]+)ch") fmt.Println(r.MatchString("peach")) fmt.Println(r.FindString("peach punch")) fmt.Println(r.FindStringIndex("peach punch")) fmt.Println(r.FindStringSubmatch("peach punch")) fmt.Println(r.<API key>("peach punch")) fmt.Println(r.FindAllString("peach punch pinch", -1)) fmt.Println(r.<API key>("peach punch pinch", -1)) fmt.Println(r.FindAllString("peach punch pinch", 2)) fmt.Println(r.Match([]byte("peach"))) r = regexp.MustCompile("p([a+z])ch") fmt.Println(r) fmt.Println(r.ReplaceAllString("a peach", "<fruit>")) in := []byte("a peach") out := r.ReplaceAllFunc(in, bytes.ToUpper) fmt.Println(string(out)) }
<?php namespace Sidus\EAVDataGridBundle\Model; use Sidus\DataGridBundle\Model\DataGrid as BaseDataGrid; use Sidus\EAVFilterBundle\Configuration\<API key>; use Sidus\EAVModelBundle\Model\FamilyInterface; use Sidus\EAVModelBundle\Translator\TranslatableTrait; use Symfony\Component\Translation\TranslatorInterface; /** * Extended datagrid configuration for EAV entities */ class DataGrid extends BaseDataGrid { use TranslatableTrait; /** @var FamilyInterface */ protected $family; /** * DataGrid constructor. * * @param string $code * @param array $configuration * @param TranslatorInterface $translator * * @throws \Exception */ public function __construct($code, array $configuration, TranslatorInterface $translator = null) { $this->translator = $translator; parent::__construct($code, $configuration); } /** * @return FamilyInterface */ public function getFamily() { return $this->family; } /** * @param FamilyInterface $family * * @return DataGrid */ public function setFamily($family) { $this->family = $family; $filterConfig = $this->getFilterConfig(); if ($filterConfig instanceof <API key>) { $filterConfig->setFamily($family); } return $this; } /** * @param string $key * @param array $columnConfiguration * * @throws \Exception */ protected function createColumn($key, array $columnConfiguration) { if ($this->translator) { $columnConfiguration['translator'] = $this->translator; } $this->columns[] = new Column($key, $this, $columnConfiguration); } }
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>food blogging | Introduction to New Media</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="shortcut icon" href="../../misc/favicon.ico" type="image/x-icon" /> <style type="text/css" media="all">@import "../../modules/node/node.css";</style> <style type="text/css" media="all">@import "../../modules/poll/poll.css";</style> <style type="text/css" media="all">@import "../../modules/system/defaults.css";</style> <style type="text/css" media="all">@import "../../modules/system/system.css";</style> <style type="text/css" media="all">@import "../../modules/user/user.css";</style> <style type="text/css" media="all">@import "../../sites/all/modules/tagadelic/tagadelic.css";</style> <style type="text/css" media="all">@import "../../modules/comment/comment.css";</style> <style type="text/css" media="all">@import "../../sites/all/themes/newmedia/style.css";</style> <!--[if IE 6]> <style type="text/css" media="all">@import "../../sites/all/themes/newmedia/ie-fixes/ie6.css";</style> <![endif] <!--[if lt IE 7.]> <script defer type="text/javascript" src="../../sites/all/themes/newmedia/ie-fixes/pngfix.js"></script> <![endif] </head> <body> <div id="page"> <!-- begin wrapper --> <div id="container"> <!-- primary links --> <!-- begin header --> <div id="header"> <!-- site logo --> <!-- end site logo --> <!-- site name --> <h1> <a href="../../index.html" title="Home"> Introduction to New Media </a> </h1> <!-- end site name --> <!-- site slogan --> <!-- end site slogan --> <div id="menu"> <ul class="links-menu"> <li><a href="http://machines.plannedobsolescence.net" title="associate professor of english and media studies">kathleen fitzpatrick</a></li> <li><a href="http: </ul> </div><!-- end primary links --> </div><!-- end header --> <!-- search box in nowhere land - NEEDS WORK--> <!-- end search box --> <!-- content --> <!-- <div id="main">--> <!-- begin main content --> <div id="mainContent" style="width: 530px;"> <div class="breadcrumb"><div class="breadcrumb"><a href="../../index.html">Home</a> » <a href="../../blog/index.html">Blogs</a> » <a href="../../blog/17/index.html">ColoradoGirl&#039;s blog</a></div></div> <h1 class="pageTitle">food blogging</h1> <div class="node"> <div class="submitted">By ColoradoGirl - Posted on 4 February 2007 - 2:06pm.</div> <div class="taxonomy">Tagged: <ul class="links inline"><li class="first taxonomy_term_2"><a href="../../taxonomy/term/2/index.html" rel="tag" title="" class="taxonomy_term_2">blogging</a></li> <li class="last taxonomy_term_39"><a href="../../taxonomy/term/39/index.html" rel="tag" title="" class="taxonomy_term_39">food critics</a></li> </ul></div> <div class="content"><p>I love to eat. Ok, let me clarify that – I love to eat good food. Today while savoring the Sunday NY Times Style section, I saw an article of blogging interest, <a href="http: <p>I am interested in how the blogs critiquing food and restaurants are able to be more open, more honest, and more vicious (??) with their comments. We talked about the emergence of more opinionated political writing in the blogosphere, and I think you'll agree with me that food critiques on blogs are la même chose. </p> <p>What does this upsurge in food bloggers do to reputation of restaurants? I recently dined at a hole-in-the wall sushi place outside L.A. . . . I consider myself to be a sushi expert (having traveled to Japan and consumed mass amounts of the delicious food there and at good sushi joints elsewhere) and what I tasted at this particular restaurant was absolutely sickening. However, a blog I found congratulated this very restaurant on serving "sushi that even sushi haters will love." Hmmm, where's the truth there?!</p> </div> <div class="links"><ul class="links inline"><li class="first last blog_usernames_blog"><a href="../../blog/17/index.html" title="Read ColoradoGirl&#039;s latest blog entries." class="blog_usernames_blog">ColoradoGirl&#039;s blog</a></li> </ul></div> </div> <div id="comments"><a id="comment-38"></a> <div class="comment"> <div class="commentTitle"><a href="index.html#comment-38" class="active">Not Only Good But Healthy</a></div> <div class="submitted">Submitted by Bumpkins on 4 February 2007 - 7:14pm.</div> <div class="content"><p><a href="http: <p>- If this takes away your anonymity feel free to delete it.</p> </div> <div class="links"></div> </div> </div> </div> <!-- Begin Sidebars --> <div id="sideBars-bg" style="width: 415px;"> <div id="sideBars" style="width: 415px;"> <!-- left sidebar --> <div id="leftSidebar"> <div class="block block-block" id="block-block-1"> <h2 class="title"></h2> <div class="content"><p><a href="../../index.html">introduction to new media</a> is the spring 2007 course website for media studies 51 at pomona college in claremont, california.</p> <p><a href="http://machines.plannedobsolescence.net">the professor</a><br /> <a href="../../syllabus/index.html">the syllabus</a><br /> <a href="../../wiki/index.html">the wiki</a><br /> <a href="https://sakai.claremont.edu/portal/site/CX_mtg_26747">the sakai site</a><br /> <a href="../../taxonomy/term/1/index.html">more information</a></p> </div> </div> <div class="block block-tagadelic" id="block-tagadelic-1"> <h2 class="title">tags</h2> <div class="content"><a href="../../taxonomy/term/56/index.html" class="tagadelic level2" rel="tag">Artificial Intelligence</a> <a href="../../taxonomy/term/14/index.html" class="tagadelic level2" rel="tag">blog</a> <a href="../../taxonomy/term/2/index.html" class="tagadelic level10" rel="tag">blogging</a> <a href="../../taxonomy/term/42/index.html" class="tagadelic level8" rel="tag">class discussion</a> <a href="../../taxonomy/term/4/index.html" class="tagadelic level10" rel="tag">class reading</a> <a href="../../taxonomy/term/8/index.html" class="tagadelic level1" rel="tag">community</a> <a href="../../taxonomy/term/1/index.html" class="tagadelic level2" rel="tag">course information</a> <a href="../../taxonomy/term/106/index.html" class="tagadelic level2" rel="tag">cyborg</a> <a href="../../taxonomy/term/77/index.html" class="tagadelic level3" rel="tag">Facade</a> <a href="../../taxonomy/term/119/index.html" class="tagadelic level3" rel="tag">final project</a> <a href="../../taxonomy/term/7/index.html" class="tagadelic level3" rel="tag">first blog</a> <a href="../../taxonomy/term/36/index.html" class="tagadelic level2" rel="tag">Future</a> <a href="../../taxonomy/term/64/index.html" class="tagadelic level2" rel="tag">Machines</a> <a href="../../taxonomy/term/79/index.html" class="tagadelic level2" rel="tag">midterm project</a> <a href="../../taxonomy/term/13/index.html" class="tagadelic level1" rel="tag">Music</a> <a href="../../taxonomy/term/20/index.html" class="tagadelic level3" rel="tag">new generation</a> <a href="../../taxonomy/term/31/index.html" class="tagadelic level6" rel="tag">new media</a> <a href="../../taxonomy/term/70/index.html" class="tagadelic level8" rel="tag">Proposal</a> <a href="../../taxonomy/term/112/index.html" class="tagadelic level2" rel="tag">sight machine</a> <a href="../../taxonomy/term/22/index.html" class="tagadelic level2" rel="tag">social networking</a> <a href="../../taxonomy/term/98/index.html" class="tagadelic level7" rel="tag">term project</a> <a href="../../taxonomy/term/19/index.html" class="tagadelic level7" rel="tag">web 2.0</a> <a href="../../taxonomy/term/24/index.html" class="tagadelic level8" rel="tag">wiki</a> <a href="../../taxonomy/term/18/index.html" class="tagadelic level6" rel="tag">Wikipedia</a> <a href="../../taxonomy/term/34/index.html" class="tagadelic level6" rel="tag">YouTube</a> <div class='more-link'><a href="../../tagadelic/chunk/1/index.html">more tags</a></div></div> </div> <div class="block block-user" id="block-user-1"> <h2 class="title">Navigation</h2> <div class="content"> <ul class="menu"> <li class="leaf"><a href="../../tracker/index.html">Recent posts</a></li> </ul> </div> </div> </div> <!-- right sidebar --> <div id="rightSidebar"> <div class="block block-comment" id="block-comment-0"> <h2 class="title">Recent comments</h2> <div class="content"><div class="item-list"><ul><li><a href="../247/index.html#comment-440">resistance</a><br />3 years 51 weeks ago</li><li><a href="../264/index.html#comment-439">20 hours of source</a><br />3 years 51 weeks ago</li><li><a href="../262/index.html#comment-438">used?</a><br />3 years 51 weeks ago</li><li><a href="../261/index.html#comment-437">it&#039;s everywhere</a><br />3 years 51 weeks ago</li><li><a href="../264/index.html#comment-436">Really good! I liked how you</a><br />3 years 51 weeks ago</li><li><a href="../264/index.html#comment-435">nice!</a><br />3 years 51 weeks ago</li><li><a href="../251/index.html#comment-434">Linux Parody</a><br />3 years 51 weeks ago</li><li><a href="../259/index.html#comment-433">Me Too!</a><br />3 years 51 weeks ago</li><li><a href="../261/index.html#comment-432">McDonald&#039;s</a><br />3 years 51 weeks ago</li><li><a href="../264/index.html#comment-431">Slash Fan Vid</a><br />3 years 51 weeks ago</li></ul></div></div> </div> <div class="block block-block" id="block-block-2"> <h2 class="title"></h2> <div class="content"><h3>social software tools</h3> <ul> <li><a href="http://technorati.com/" target="_blank">Technorati</a></li> <li><a href="http://del.icio.us/" target="_blank">del.icio.us</a></li> <li><a href="http: <li><a href="http: <li><a href="http: </ul> <h3>new media studies sites</h3> <ul> <li><a href="http: </ul> </div> </div> </div> </div><!-- end sidebars --> </div><!-- end sideBars-bg --> <!-- footer --> <div id="footer"> </div><!-- end footer --> </div><!-- end container --> </div><!-- end page --> <!-- Start of StatCounter Code --> <script type="text/javascript"> var sc_project=3034095; var sc_invisible=1; var sc_partition=33; var sc_security="ec028fa0"; </script> <script type="text/javascript" src="http: <!-- End of StatCounter Code --> </body> </html> <!-- Localized -->
CREATE USER 'iasst'@'localhost' IDENTIFIED BY '123456'; GRANT SELECT ON *.* TO 'iasst'@'localhost'; GRANT SELECT, INSERT, UPDATE, REFERENCES, DELETE, CREATE, DROP, ALTER, INDEX, TRIGGER, CREATE VIEW, SHOW VIEW, EXECUTE, ALTER ROUTINE, CREATE ROUTINE, CREATE TEMPORARY TABLES, LOCK TABLES, EVENT ON `iasst`.* TO 'iasst'@'localhost'; GRANT GRANT OPTION ON `iasst`.* TO 'iasst'@'localhost';
package com.mobilerobots.Aria; public class ArDPPTU extends ArPTZ { /* (begin code from javabody_derived typemap) */ private long swigCPtr; /* for internal use by swig only */ public ArDPPTU(long cPtr, boolean cMemoryOwn) { super(AriaJavaJNI.SWIGArDPPTUUpcast(cPtr), cMemoryOwn); swigCPtr = cPtr; } /* for internal use by swig only */ public static long getCPtr(ArDPPTU obj) { return (obj == null) ? 0 : obj.swigCPtr; } /* (end code from javabody_derived typemap) */ protected void finalize() { delete(); } public synchronized void delete() { if(swigCPtr != 0 && swigCMemOwn) { swigCMemOwn = false; AriaJavaJNI.delete_ArDPPTU(swigCPtr); } swigCPtr = 0; super.delete(); } public ArDPPTU(ArRobot robot, ArDPPTU.DeviceType deviceType) { this(AriaJavaJNI.new_ArDPPTU__SWIG_0(ArRobot.getCPtr(robot), robot, deviceType.swigValue()), true); } public ArDPPTU(ArRobot robot) { this(AriaJavaJNI.new_ArDPPTU__SWIG_1(ArRobot.getCPtr(robot), robot), true); } public boolean init() { return AriaJavaJNI.ArDPPTU_init(swigCPtr, this); } public boolean canZoom() { return AriaJavaJNI.ArDPPTU_canZoom(swigCPtr, this); } public boolean blank() { return AriaJavaJNI.ArDPPTU_blank(swigCPtr, this); } public boolean resetCalib() { return AriaJavaJNI.ArDPPTU_resetCalib(swigCPtr, this); } public boolean disableReset() { return AriaJavaJNI.<API key>(swigCPtr, this); } public boolean resetTilt() { return AriaJavaJNI.ArDPPTU_resetTilt(swigCPtr, this); } public boolean resetPan() { return AriaJavaJNI.ArDPPTU_resetPan(swigCPtr, this); } public boolean resetAll() { return AriaJavaJNI.ArDPPTU_resetAll(swigCPtr, this); } public boolean saveSet() { return AriaJavaJNI.ArDPPTU_saveSet(swigCPtr, this); } public boolean restoreSet() { return AriaJavaJNI.ArDPPTU_restoreSet(swigCPtr, this); } public boolean factorySet() { return AriaJavaJNI.ArDPPTU_factorySet(swigCPtr, this); } public boolean panTilt(double pdeg, double tdeg) { return AriaJavaJNI.ArDPPTU_panTilt(swigCPtr, this, pdeg, tdeg); } public boolean pan(double deg) { return AriaJavaJNI.ArDPPTU_pan(swigCPtr, this, deg); } public boolean panRel(double deg) { return AriaJavaJNI.ArDPPTU_panRel(swigCPtr, this, deg); } public boolean tilt(double deg) { return AriaJavaJNI.ArDPPTU_tilt(swigCPtr, this, deg); } public boolean tiltRel(double deg) { return AriaJavaJNI.ArDPPTU_tiltRel(swigCPtr, this, deg); } public boolean panTiltRel(double pdeg, double tdeg) { return AriaJavaJNI.ArDPPTU_panTiltRel(swigCPtr, this, pdeg, tdeg); } public boolean limitEnforce(boolean val) { return AriaJavaJNI.<API key>(swigCPtr, this, val); } public boolean immedExec() { return AriaJavaJNI.ArDPPTU_immedExec(swigCPtr, this); } public boolean slaveExec() { return AriaJavaJNI.ArDPPTU_slaveExec(swigCPtr, this); } public boolean awaitExec() { return AriaJavaJNI.ArDPPTU_awaitExec(swigCPtr, this); } public boolean haltAll() { return AriaJavaJNI.ArDPPTU_haltAll(swigCPtr, this); } public boolean haltPan() { return AriaJavaJNI.ArDPPTU_haltPan(swigCPtr, this); } public boolean haltTilt() { return AriaJavaJNI.ArDPPTU_haltTilt(swigCPtr, this); } public double getMaxPosPan() { return AriaJavaJNI.<API key>(swigCPtr, this); } public double getMaxNegPan() { return AriaJavaJNI.<API key>(swigCPtr, this); } public double getMaxPosTilt() { return AriaJavaJNI.<API key>(swigCPtr, this); } public double getMaxNegTilt() { return AriaJavaJNI.<API key>(swigCPtr, this); } public double getMaxPanSlew() { return AriaJavaJNI.<API key>(swigCPtr, this); } public double getMinPanSlew() { return AriaJavaJNI.<API key>(swigCPtr, this); } public double getMaxTiltSlew() { return AriaJavaJNI.<API key>(swigCPtr, this); } public double getMinTiltSlew() { return AriaJavaJNI.<API key>(swigCPtr, this); } public double getMaxPanAccel() { return AriaJavaJNI.<API key>(swigCPtr, this); } public double getMinPanAccel() { return AriaJavaJNI.<API key>(swigCPtr, this); } public double getMaxTiltAccel() { return AriaJavaJNI.<API key>(swigCPtr, this); } public double getMinTiltAccel() { return AriaJavaJNI.<API key>(swigCPtr, this); } public boolean initMon(double deg1, double deg2, double deg3, double deg4) { return AriaJavaJNI.ArDPPTU_initMon(swigCPtr, this, deg1, deg2, deg3, deg4); } public boolean enMon() { return AriaJavaJNI.ArDPPTU_enMon(swigCPtr, this); } public boolean disMon() { return AriaJavaJNI.ArDPPTU_disMon(swigCPtr, this); } public boolean offStatPower() { return AriaJavaJNI.<API key>(swigCPtr, this); } public boolean regStatPower() { return AriaJavaJNI.<API key>(swigCPtr, this); } public boolean lowStatPower() { return AriaJavaJNI.<API key>(swigCPtr, this); } public boolean highMotPower() { return AriaJavaJNI.<API key>(swigCPtr, this); } public boolean regMotPower() { return AriaJavaJNI.ArDPPTU_regMotPower(swigCPtr, this); } public boolean lowMotPower() { return AriaJavaJNI.ArDPPTU_lowMotPower(swigCPtr, this); } public boolean panAccel(double deg) { return AriaJavaJNI.ArDPPTU_panAccel(swigCPtr, this, deg); } public boolean tiltAccel(double deg) { return AriaJavaJNI.ArDPPTU_tiltAccel(swigCPtr, this, deg); } public boolean basePanSlew(double deg) { return AriaJavaJNI.ArDPPTU_basePanSlew(swigCPtr, this, deg); } public boolean baseTiltSlew(double deg) { return AriaJavaJNI.<API key>(swigCPtr, this, deg); } public boolean upperPanSlew(double deg) { return AriaJavaJNI.<API key>(swigCPtr, this, deg); } public boolean lowerPanSlew(double deg) { return AriaJavaJNI.<API key>(swigCPtr, this, deg); } public boolean upperTiltSlew(double deg) { return AriaJavaJNI.<API key>(swigCPtr, this, deg); } public boolean lowerTiltSlew(double deg) { return AriaJavaJNI.<API key>(swigCPtr, this, deg); } public boolean indepMove() { return AriaJavaJNI.ArDPPTU_indepMove(swigCPtr, this); } public boolean velMove() { return AriaJavaJNI.ArDPPTU_velMove(swigCPtr, this); } public boolean panSlew(double deg) { return AriaJavaJNI.ArDPPTU_panSlew(swigCPtr, this, deg); } public boolean tiltSlew(double deg) { return AriaJavaJNI.ArDPPTU_tiltSlew(swigCPtr, this, deg); } public boolean panSlewRel(double deg) { return AriaJavaJNI.ArDPPTU_panSlewRel(swigCPtr, this, deg); } public boolean tiltSlewRel(double deg) { return AriaJavaJNI.ArDPPTU_tiltSlewRel(swigCPtr, this, deg); } public double getPan() { return AriaJavaJNI.ArDPPTU_getPan(swigCPtr, this); } public double getTilt() { return AriaJavaJNI.ArDPPTU_getTilt(swigCPtr, this); } public double getPanSlew() { return AriaJavaJNI.ArDPPTU_getPanSlew(swigCPtr, this); } public double getTiltSlew() { return AriaJavaJNI.ArDPPTU_getTiltSlew(swigCPtr, this); } public double getBasePanSlew() { return AriaJavaJNI.<API key>(swigCPtr, this); } public double getBaseTiltSlew() { return AriaJavaJNI.<API key>(swigCPtr, this); } public double getPanAccel() { return AriaJavaJNI.ArDPPTU_getPanAccel(swigCPtr, this); } public double getTiltAccel() { return AriaJavaJNI.<API key>(swigCPtr, this); } public final static class DeviceType { public final static DeviceType PANTILT_DEFAULT = new DeviceType("PANTILT_DEFAULT"); public final static DeviceType PANTILT_PTUD47 = new DeviceType("PANTILT_PTUD47"); public final int swigValue() { return swigValue; } public String toString() { return swigName; } public static DeviceType swigToEnum(int swigValue) { if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue) return swigValues[swigValue]; for (int i = 0; i < swigValues.length; i++) if (swigValues[i].swigValue == swigValue) return swigValues[i]; throw new <API key>("No enum " + DeviceType.class + " with value " + swigValue); } private DeviceType(String swigName) { this.swigName = swigName; this.swigValue = swigNext++; } private DeviceType(String swigName, int swigValue) { this.swigName = swigName; this.swigValue = swigValue; swigNext = swigValue+1; } private DeviceType(String swigName, DeviceType swigEnum) { this.swigName = swigName; this.swigValue = swigEnum.swigValue; swigNext = this.swigValue+1; } private static DeviceType[] swigValues = { PANTILT_DEFAULT, PANTILT_PTUD47 }; private static int swigNext = 0; private final int swigValue; private final String swigName; } }
<?php class GraphiteBackendTask extends AppShell{ public $Config = []; private $host; private $port; private $prefix; private $socket; private $lastErrNo; private $hostnameCache = []; private $servicenameCache = []; public function init($Config){ $this->Config = $Config; $this->host = $this->Config['host']; $this->port = $this->Config['port']; $this->prefix = $this->Config['prefix']; } /** * @param array $parsedPerfdata * @param string $hostname * @param string $servicedesc * @param int $timestamp */ public function save($parsedPerfdata, $hostname, $servicedesc, $timestamp){ if($this->connect()){ foreach($parsedPerfdata as $ds => $_data){ $data = $this->buildString($ds, $_data, $hostname, $servicedesc, $timestamp); $this->write($data); } } $this->disconnect(); } private function write($message){ $message .= PHP_EOL; $this->lastErrNo = null; if(!@socket_send($this->socket, $message, strlen($message), 0)){ CakeLog::error(sprintf( 'Graphite save error: %s %s', $this->getLastErrNo(), $this->getLastError() )); return false; } return true; } private function connect(){ $this->socket = socket_create(AF_INET, SOCK_STREAM, IPPROTO_IP); if(!@socket_connect($this->socket, $this->host, $this->port)){ CakeLog::error(sprintf( 'Graphite connection error: %s %s', $this->getLastErrNo(), $this->getLastError() )); return false; } return true; } private function disconnect(){ if(is_resource($this->socket)){ socket_close($this->socket); } $this->socket = null; } private function getLastErrNo(){ if(is_resource($this->socket)){ $this->lastErrNo = socket_last_error($this->socket); return $this->lastErrNo; } return false; } private function getLastError(){ return socket_strerror($this->lastErrNo); } private function buildString($datasource, $data, $hostname, $servicedesc, $timestamp){ $datasource = $this->replaceCharacters($datasource); $hostname = $this->replaceCharacters($hostname); $servicedesc = $this->replaceCharacters($servicedesc); return sprintf( '%s.%s.%s.%s %s %s', $this->prefix, $hostname, $servicedesc, $datasource, $data['current'], $timestamp ); } public function replaceCharacters($str){ return preg_replace($this->Config['replace_characters'], '_', $str); } public function <API key>(){ if($this->Config['<API key>'] === true){ return true; } return false; } public function <API key>(){ if($this->Config['<API key>'] === true){ return true; } return false; } public function requireNameCaching(){ if($this-><API key>() === true){ return true; } if($this-><API key>() === true){ return true; } return false; } public function <API key>($hostname, $hostdisplayname){ $this->hostnameCache[md5($hostname)] = $hostdisplayname; } public function <API key>($hostname){ if(isset($this->hostnameCache[md5($hostname)])){ return $this->hostnameCache[md5($hostname)]; } return null; } public function <API key>($hostname, $servicedesc, $servicedisplayname){ if(!isset($this->servicenameCache[md5($hostname)])){ $this->servicenameCache[md5($hostname)] = []; } $this->servicenameCache[md5($hostname)][md5($servicedesc)] = $servicedisplayname; } public function <API key>($hostname, $servicedesc){ if(isset($this->servicenameCache[md5($hostname)][md5($servicedesc)])){ return $this->servicenameCache[md5($hostname)][md5($servicedesc)]; } return null; } public function clearCache(){ $this->hostnameCache = []; $this->servicenameCache = []; } }
<?php // Global variables global $map_count, $ish_options; $map_count++; // Default SC attributes $defaults = array( 'color' => '', 'zoom' => '15', 'invert_colors' => '', 'height' => '', ); // Extract all attributes $sc_atts = $this-><API key>( $defaults, $atts ); // Add ID if empty as it is necessary for Google Maps to work if ( empty( $sc_atts['id'] ) ){ $sc_atts['id'] = 'ish-gmap-' . $map_count; } // Make sure to include the scripts for Google Maps and the Generation of the marker infoboxes on click wp_enqueue_script( 'ish-gmaps' ); // Convert color class to color value if ( isset( $ish_options[ $sc_atts['color'] ] ) ){ $sc_atts['color'] = $ish_options[ $sc_atts['color'] ]; } // SHORTCODE BEGIN $return = ''; $return .= '<div class="' . apply_filters( 'ish_sc_classes', '<API key>', $tag ) . '"><div class="'; // CLASSES $class = 'ish-sc_map'; $class .= ( '' != $sc_atts['css_class'] ) ? ' ' . esc_attr( $sc_atts['css_class'] ) : '' ; $class .= ( '' != $sc_atts['tooltip'] && '' != $sc_atts['tooltip_color'] ) ? ' ish-tooltip-' . esc_attr( $sc_atts['tooltip_color'] ) : ''; $class .= ( '' != $sc_atts['tooltip'] && '' != $sc_atts['tooltip_text_color'] ) ? ' ish-tooltip-text-' . esc_attr( $sc_atts['tooltip_text_color'] ) : ''; //$return .= apply_filters( 'ish_sc_classes', $class, $tag ); $return .= $class; $return .= '"' ; $return .= ( '' != $sc_atts['id'] ) ? ' id="' . esc_attr( $sc_atts['id'] ) . '"' : ''; // STYLE if ( '' != $sc_atts['style'] || '' != $sc_atts['height'] ){ $return .= ' style="'; $return .= ( '' != $sc_atts['height'] ) ? ' height: ' . esc_attr( $sc_atts['height'] ) . 'px;' : ''; $return .= ( '' != $sc_atts['style'] ) ? ' ' . esc_attr( $sc_atts['style'] ) : ''; $return .= '"'; } // TOOLTIP $return .= ( '' != $sc_atts['tooltip'] ) ? ' data-type="tooltip" title="' . esc_attr( $sc_atts['tooltip'] ) . '"' : '' ; $return .= ( '' != $sc_atts['zoom'] ) ? ' data-zoom="' . esc_attr( $sc_atts['zoom'] ) . '"' : '' ; $return .= ( 'yes' == $sc_atts['invert_colors'] ) ? ' data-invert="' . esc_attr( $sc_atts['invert_colors'] ) . '"' : '' ; $return .= ( '' != $sc_atts['color'] ) ? ' data-color="' . esc_attr( $sc_atts['color'] ) . '"' : '' ; $return .= '>'; $content = <API key>($content, true); // CONTENT $return .= do_shortcode( $content ); // SHORTCODE END $return .= '</div></div>'; echo $return;
<?php class acf_Wysiwyg extends acf_Field { function __construct($parent) { parent::__construct($parent); $this->name = 'wysiwyg'; $this->title = __("Wysiwyg Editor",'acf'); add_action( 'acf_head-input', array( $this, 'acf_head') ); add_filter( 'acf/fields/wysiwyg/toolbars', array( $this, 'toolbars'), 1, 1 ); } /* * get_toolbars * * @description: * @since: 3.5.7 * @created: 10/01/13 */ function toolbars( $toolbars ) { $editor_id = 'acf_settings'; // Full $toolbars['Full'] = array(); $toolbars['Full'][1] = apply_filters('mce_buttons', array('bold', 'italic', 'strikethrough', 'bullist', 'numlist', 'blockquote', 'justifyleft', 'justifycenter', 'justifyright', 'link', 'unlink', 'wp_more', 'spellchecker', 'fullscreen', 'wp_adv' ), $editor_id); $toolbars['Full'][2] = apply_filters('mce_buttons_2', array( 'formatselect', 'underline', 'justifyfull', 'forecolor', 'pastetext', 'pasteword', 'removeformat', 'charmap', 'outdent', 'indent', 'undo', 'redo', 'wp_help', 'code' ), $editor_id); $toolbars['Full'][3] = apply_filters('mce_buttons_3', array(), $editor_id); $toolbars['Full'][4] = apply_filters('mce_buttons_4', array(), $editor_id); // Basic $toolbars['Basic'] = array(); $toolbars['Basic'][1] = apply_filters( 'teeny_mce_buttons', array('bold', 'italic', 'underline', 'blockquote', 'strikethrough', 'bullist', 'numlist', 'justifyleft', 'justifycenter', 'justifyright', 'undo', 'redo', 'link', 'unlink', 'fullscreen'), $editor_id ); // Custom - can be added with acf/fields/wysiwyg/toolbars filter return $toolbars; } function acf_head() { add_action( 'admin_footer', array( $this, 'admin_footer') ); } function admin_footer() { ?> <div style="display:none;"> <?php wp_editor( '', 'acf_settings' ); ?> </div> <?php } function create_options($key, $field) { // vars $defaults = array( 'toolbar' => 'full', 'media_upload' => 'yes', 'the_content' => 'yes', 'default_value' => '', ); $field = array_merge($defaults, $field); ?> <tr class="field_option field_option_<?php echo $this->name; ?>"> <td class="label"> <label><?php _e("Default Value",'acf'); ?></label> </td> <td> <?php do_action('acf/create_field', array( 'type' => 'textarea', 'name' => 'fields['.$key.'][default_value]', 'value' => $field['default_value'], )); ?> </td> </tr> <tr class="field_option field_option_<?php echo $this->name; ?>"> <td class="label"> <label><?php _e("Toolbar",'acf'); ?></label> </td> <td> <?php $toolbars = apply_filters( 'acf/fields/wysiwyg/toolbars', array() ); $choices = array(); if( is_array($toolbars) ) { foreach( $toolbars as $k => $v ) { $label = $k; $name = sanitize_title( $label ); $name = str_replace('-', '_', $name); $choices[ $name ] = $label; } } do_action('acf/create_field', array( 'type' => 'radio', 'name' => 'fields['.$key.'][toolbar]', 'value' => $field['toolbar'], 'layout' => 'horizontal', 'choices' => $choices )); ?> </td> </tr> <tr class="field_option field_option_<?php echo $this->name; ?>"> <td class="label"> <label><?php _e("Show Media Upload Buttons?",'acf'); ?></label> </td> <td> <?php do_action('acf/create_field', array( 'type' => 'radio', 'name' => 'fields['.$key.'][media_upload]', 'value' => $field['media_upload'], 'layout' => 'horizontal', 'choices' => array( 'yes' => __("Yes",'acf'), 'no' => __("No",'acf'), ) )); ?> </td> </tr> <tr class="field_option field_option_<?php echo $this->name; ?>"> <td class="label"> <label><?php _e("Run filter \"the_content\"?",'acf'); ?></label> <p class="description"><?php _e("Enable this filter to use shortcodes within the WYSIWYG field",'acf'); ?></p> <p class="description"><?php _e("Disable this filter if you encounter recursive template problems with plugins / themes",'acf'); ?></p> </td> <td> <?php do_action('acf/create_field', array( 'type' => 'radio', 'name' => 'fields['.$key.'][the_content]', 'value' => $field['the_content'], 'layout' => 'horizontal', 'choices' => array( 'yes' => __("Yes",'acf'), 'no' => __("No",'acf'), ) )); ?> </td> </tr> <?php } function create_field($field) { global $wp_version; // vars $defaults = array( 'toolbar' => 'full', 'media_upload' => 'yes', ); $field = array_merge($defaults, $field); $id = 'wysiwyg-' . $field['id']; ?> <div id="wp-<?php echo $id; ?>-wrap" class="acf_wysiwyg wp-editor-wrap" data-toolbar="<?php echo $field['toolbar']; ?>" data-upload="<?php echo $field['media_upload']; ?>"> <?php if($field['media_upload'] == 'yes'): ?> <?php if( version_compare($wp_version, '3.3', '<') ): ?> <div id="editor-toolbar"> <div id="media-buttons" class="hide-if-no-js"> <?php do_action( 'media_buttons' ); ?> </div> </div> <?php else: ?> <div id="wp-<?php echo $id; ?>-editor-tools" class="wp-editor-tools"> <div id="wp-<?php echo $id; ?>-media-buttons" class="hide-if-no-js wp-media-buttons"> <?php do_action( 'media_buttons' ); ?> </div> </div> <?php endif; ?> <?php endif; ?> <div id="wp-<?php echo $id; ?>-editor-container" class="wp-editor-container"> <textarea id="<?php echo $id; ?>" class="wp-editor-area" name="<?php echo $field['name']; ?>" ><?php echo wp_richedit_pre($field['value']); ?></textarea> </div> </div> <?php } function get_value_for_api($post_id, $field) { // vars $defaults = array( 'the_content' => 'yes', ); $field = array_merge($defaults, $field); $value = parent::get_value($post_id, $field); // filter if( $field['the_content'] == 'yes' ) { $value = apply_filters('the_content',$value); } else { $value = wpautop( $value ); } return $value; } } ?>
<HTML> <HEAD></HEAD> <FONT FACE="'Courier New',Verdana, Arial, Helvetica" SIZE=2> &lt;!DOCTYPE html><br>&lt;html><br>&lt;body><br><br><FONT COLOR=#ff0000>&lt;?php<br>$note=&lt;&lt;&lt;XML<br>&lt;note><br>&lt;to>Tove&lt;/to><br>&lt;from>Jani&lt;/from><br>&lt;heading>Reminder&lt;/heading><br>&lt;body>Don't forget me this weekend!&lt;/body><br>&lt;/note><br>XML;<br><br>$xml=new SimpleXMLElement($note);<br><br>// Add a child element to the body element<br>$xml->body->addChild("date","2014-01-01");<br><br>// Add a child element after the last element inside note<br>$footer=$xml->addChild("footer","Some footer text");<br>&nbsp; <br>echo $xml->asXML();<br>?&gt;</FONT><br><br>&lt;p>Select View Source to see the added date element (inside the body element) and the new footer element.&lt;/p><br><br>&lt;/body><br>&lt;/html><br> </HTML>
#ifndef _WXSFRECTSHAPE_H #define _WXSFRECTSHAPE_H #include <wx/wxsf/ShapeBase.h> // default values /*! \brief Default value of wxSFRectShape::m_nRectSize data member. */ #define sfdvRECTSHAPE_SIZE wxRealPoint(100, 50) /*! \brief Default value of wxSFRectShape::m_Fill data member. */ #define sfdvRECTSHAPE_FILL wxBrush(*wxWHITE) /*! \brief Default value of wxSFRectShape::m_Border data member. */ #define <API key> wxPen(*wxBLACK) /*! * \brief Class encapsulates basic rectangle shape which is used as a base class * for many other shapes that can be bounded by a simple rectangle. The class * provides all functionality needed for manipulating the rectangle's (bounding box) * size and position. */ class WXDLLIMPEXP_SF wxSFRectShape : public wxSFShapeBase { public: <API key>(wxSFRectShape); /*! \brief Default constructor. */ wxSFRectShape(void); /*! * \brief User constructor. * \param pos Initial position * \param size Initial size * \param manager Pointer to parent diagram manager */ wxSFRectShape(const wxRealPoint& pos, const wxRealPoint& size, wxSFDiagramManager* manager); /*! * \brief Copy constructor. * \param obj Reference to the source object */ wxSFRectShape(const wxSFRectShape& obj); /*! \brief Destructor. */ virtual ~wxSFRectShape(void); // public virtual functions /*! * \brief Get shapes's bounding box. The function can be overrided if neccessary. * \return Bounding rectangle */ virtual wxRect GetBoundingBox(); /*! * \brief Get intersection point of the shape border and a line leading from * 'start' point to 'end' point. The function can be overrided if neccessary. * \param start Starting point of the virtual intersection line * \param end Ending point of the virtual intersection line * \return Intersection point */ virtual wxRealPoint GetBorderPoint(const wxRealPoint& start, const wxRealPoint& end); /*! * \brief Function called by the framework responsible for creation of shape handles * at the creation time. The function can be overrided if neccesary. */ virtual void CreateHandles(); /*! * \brief Event handler called during dragging of the shape handle. * The function can be overrided if necessary. * * The function is called by the framework (by the shape canvas). * \param handle Reference to dragged handle */ virtual void OnHandle(wxSFShapeHandle& handle); /*! * \brief Event handler called when the user started to drag the shape handle. * The function can be overrided if necessary. * * The function is called by the framework (by the shape canvas). * \param handle Reference to dragged handle */ virtual void OnBeginHandle(wxSFShapeHandle& handle); /*! \brief Resize the shape to bound all child shapes. The function can be overrided if neccessary. */ virtual void FitToChildren(); /*! * \brief Scale the shape size by in both directions. The function can be overrided if necessary * (new implementation should call default one ore scale shape's children manualy if neccesary). * \param x Horizontal scale factor * \param y Vertical scale factor * \param children TRUE if the shape's children shoould be scaled as well, otherwise the shape will be updated after scaling via Update() function. */ virtual void Scale(double x, double y, bool children = sfWITHCHILDREN); // public data accessors /*! * \brief Set rectangle's fill style. * \param brush Refernce to a brush object */ void SetFill(const wxBrush& brush){m_Fill = brush;} /*! * \brief Get current fill style. * \return Current brush */ wxBrush GetFill() const {return m_Fill;} /*! * \brief Set rectangle's border style. * \param pen Reference to a pen object */ void SetBorder(const wxPen& pen){m_Border = pen;} /*! * \brief Get current border style. * \return Current pen */ wxPen GetBorder() const {return m_Border;} /*! * \brief Set the rectangle size. * \param size New size */ void SetRectSize(const wxRealPoint& size){m_nRectSize = size;} /*! * \brief Set the rectangle size. * \param x Horizontal size * \param y Verical size */ void SetRectSize(double x, double y){m_nRectSize.x = x; m_nRectSize.y = y;} /*! * \brief Get the rectangle size. * \return Current size */ wxRealPoint GetRectSize() const {return m_nRectSize;} protected: // protected data members /*! \brief Pen object used for drawing of the rectangle border. */ wxPen m_Border; /*! \brief Brush object used for drawing of the rectangle body. */ wxBrush m_Fill; /*! \brief The rectangle size. */ wxRealPoint m_nRectSize; // protected virtual functions /*! * \brief Draw the shape in the normal way. The function can be overrided if neccessary. * \param dc Reference to device context where the shape will be drawn to */ virtual void DrawNormal(wxDC& dc); /*! * \brief Draw the shape in the hower mode (the mouse cursor is above the shape). * The function can be overrided if neccessary. * \param dc Reference to device context where the shape will be drawn to */ virtual void DrawHover(wxDC& dc); /*! * \brief Draw the shape in the highlighted mode (another shape is dragged over this * shape and this shape will accept the dragged one if it will be dropped on it). * The function can be overrided if neccessary. * \param dc Reference to device context where the shape will be drawn to */ virtual void DrawHighlighted(wxDC& dc); /*! * \brief Draw shadow under the shape. The function can be overrided if neccessary. * \param dc Reference to device context where the shadow will be drawn to */ virtual void DrawShadow(wxDC& dc); /*! * \brief Event handler called during dragging of the right shape handle. * The function can be overrided if neccessary. * \param handle Reference to dragged shape handle */ virtual void OnRightHandle(wxSFShapeHandle& handle); /*! * \brief Event handler called during dragging of the left shape handle. * The function can be overrided if neccessary. * \param handle Reference to dragged shape handle */ virtual void OnLeftHandle(wxSFShapeHandle& handle); /*! * \brief Event handler called during dragging of the top shape handle. * The function can be overrided if neccessary. * \param handle Reference to dragged shape handle */ virtual void OnTopHandle(wxSFShapeHandle& handle); /*! * \brief Event handler called during dragging of the bottom shape handle. * The function can be overrided if neccessary. * \param handle Reference to dragged shape handle */ virtual void OnBottomHandle(wxSFShapeHandle& handle); private: // private functions /*! \brief Initialize serializable properties. */ void <API key>(); /*! \brief Auxiliary data member. */ wxRealPoint m_nPrevSize; /*! \brief Auxiliary data member. */ wxRealPoint m_nPrevPosition; }; #endif //_WXSFRECTSHAPE_H
// File: $Id: opbranch.h,v 1.1 2001/10/27 22:34:09 ses6442 Exp p334-70f $ // Contributor: Sean Sicher // Discription: Branch module for // Revisions: // $Log: opbranch.h,v $ // Revision 1.1 2001/10/27 22:34:09 ses6442 // Initial revision #ifndef OPBRANCH_H #define OPBRANCH_H #include "operation.h" class OpBranch : public Operation { public: OpBranch(); // Discription: process this instruction and dump if there are any errors. virtual bool process(); }; #endif
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ESPSharp.Enums { public enum PackageScheduleDays : sbyte { Any = -1, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Weekdays, Weekends, Mon_Wed_Fri, Tue_Thur } }
# zoomzoomzoom.js Simple zoom tool for images inside of DIVs. A very small script that is heavily dependent on its HTML structure. Designed to only work in Chrome.
<?php if ( ! function_exists( 'add_action' ) ) { echo "Hi there! I'm just a part of plugin, not much I can do when called directly."; exit; } ?> <div id="poststuff" class="ui-sortable meta-box-sortables"> <div class="postbox"> <div class="handlediv" title="<?php _e('Click to toggle'); ?>"><br/></div> <h3 class="hndle" id="backend_options"><?php _e('Backend Options', <API key> ); ?></h3> <div class="inside"> <?php wp_nonce_field('mw_adminimize_nonce'); ?> <br class="clear" /> <table summary="config" class="widefat"> <tbody> <?php if ( function_exists('is_super_admin') ) { ?> <! <tr valign="top" class="form-invalid"> <td><?php _e( 'Use Global Settings', <API key> ); ?></td> <td> <?php $<API key> = '0'; $select_active = ''; $message = ''; if ( is_multisite() && <API key>( MW_ADMIN_FILE ) ) { $<API key> = 1; $select_active = ' disabled="disabled"'; $message = __( 'The plugin is active in multiste.', <API key> ); } $<API key> = get_option( '<API key>' ); ?> <select name="<API key>"<?php echo $select_active; ?>> <option value="0"<?php if ( '0' === $<API key> ) { echo ' selected="selected"'; } ?>><?php _e( 'False', <API key> ); ?></option> <option value="1"<?php if ( '1' === $<API key> ) { echo ' selected="selected"'; } ?>><?php _e('True', <API key> ); ?></option> </select> <?php _e('Use the settings global in your Multisite network.', <API key> ); echo ' ' . $message; ?> </td> </tr> <tr valign="top" class="form-invalid"> <td><?php _e('Exclude Super Admin', <API key> ); ?></td> <td> <?php $<API key> = <API key>('<API key>'); ?> <select name="<API key>"> <option value="0"<?php if ($<API key> == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', <API key> ); ?></option> <option value="1"<?php if ($<API key> == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', <API key> ); ?></option> </select> <?php _e('Exclude the Super Admin on a WP Multisite Install from all limitations of this plugin.', <API key> ); ?> </td> </tr> <?php } ?> <tr valign="top"> <td><?php _e('User-Info', <API key> ); ?></td> <td> <?php $<API key> = <API key>('<API key>'); ?> <select name="<API key>"> <option value="0"<?php if ($<API key> == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', <API key> ); ?></option> <option value="1"<?php if ($<API key> == '1') { echo ' selected="selected"'; } ?>><?php _e('Hide', <API key> ); ?></option> <option value="2"<?php if ($<API key> == '2') { echo ' selected="selected"'; } ?>><?php _e('Only logout', <API key> ); ?></option> <option value="3"<?php if ($<API key> == '3') { echo ' selected="selected"'; } ?>><?php _e('User &amp; Logout', <API key> ); ?></option> </select> <?php _e('The &quot;User-Info-area&quot; is on the top right side of the backend. You can hide or reduced show.', <API key> ); ?> </td> </tr> <?php if ( ($<API key> == '') || ($<API key> == '1') || ($<API key> == '0') ) $disabled_item = ' disabled="disabled"' ?> <tr valign="top" class="form-invalid"> <td><?php _e('Change User-Info, redirect to', <API key> ); ?></td> <td> <?php $<API key> = <API key>('<API key>'); ?> <select name="<API key>" <?php if ( isset($disabled_item) ) echo $disabled_item; ?>> <option value="0"<?php if ($<API key> == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', <API key> ); ?></option> <option value="1"<?php if ($<API key> == '1') { echo ' selected="selected"'; } ?>><?php _e('Frontpage of the Blog', <API key> ); ?> </select> <?php _e('When the &quot;User-Info-area&quot; change it, then it is possible to change the redirect.', <API key> ); ?> </td> </tr> <tr valign="top"> <td><?php _e('Footer', <API key> ); ?></td> <td> <?php $<API key> = <API key>('<API key>'); ?> <select name="<API key>"> <option value="0"<?php if ($<API key> == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', <API key> ); ?></option> <option value="1"<?php if ($<API key> == '1') { echo ' selected="selected"'; } ?>><?php _e('Hide', <API key> ); ?></option> </select> <?php _e('The Footer-area can hide, include all links and details.', <API key> ); ?> </td> </tr> <tr valign="top"> <td><?php _e('Header', <API key> ); ?></td> <td> <?php $<API key> = <API key>('<API key>'); ?> <select name="<API key>"> <option value="0"<?php if ($<API key> == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', <API key> ); ?></option> <option value="1"<?php if ($<API key> == '1') { echo ' selected="selected"'; } ?>><?php _e('Hide', <API key> ); ?></option> </select> <?php _e('The Header-area can hide, include all links and details.', <API key> ); ?> </td> </tr> <tr valign="top"> <td><?php _e('Timestamp', <API key> ); ?></td> <td> <?php $<API key> = <API key>('<API key>'); ?> <select name="<API key>"> <option value="0"<?php if ($<API key> == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', <API key> ); ?></option> <option value="1"<?php if ($<API key> == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', <API key> ); ?></option> </select> <?php _e('Opens the post timestamp editing fields without you having to click the "Edit" link every time.', <API key> ); ?> </td> </tr> <tr valign="top"> <td><?php _e('Thickbox FullScreen', <API key> ); ?></td> <td> <?php $<API key> = <API key>('<API key>'); ?> <select name="<API key>"> <option value="0"<?php if ($<API key> == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', <API key> ); ?></option> <option value="1"<?php if ($<API key> == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', <API key> ); ?></option> </select> <?php _e('All Thickbox-function use the full area of the browser. Thickbox is for example in upload media-files.', <API key> ); ?> </td> </tr> <tr valign="top"> <td><?php _e('Flashuploader', <API key> ); ?></td> <td> <?php $<API key> = <API key>('<API key>'); ?> <select name="<API key>"> <option value="0"<?php if ($<API key> == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', <API key> ); ?></option> <option value="1"<?php if ($<API key> == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', <API key> ); ?></option> </select> <?php _e('Disable the flashuploader and users use only the standard uploader.', <API key> ); ?> </td> </tr> <tr valign="top"> <td><?php _e('Category Height', <API key> ); ?></td> <td> <?php $<API key> = <API key>('<API key>'); ?> <select name="<API key>"> <option value="0"<?php if ($<API key> == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', <API key> ); ?></option> <option value="1"<?php if ($<API key> == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', <API key> ); ?></option> </select> <?php _e('View the Meta Box with Categories in the full height, no scrollbar or whitespace.', <API key> ); ?> </td> </tr> <tr valign="top"> <td><?php _e('Advice in Footer', <API key> ); ?></td> <td> <?php $<API key> = <API key>('<API key>'); ?> <select name="<API key>"> <option value="0"<?php if ($<API key> == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', <API key> ); ?></option> <option value="1"<?php if ($<API key> == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', <API key> ); ?></option> </select> <textarea style="width: 85%;" class="code" rows="1" cols="60" name="<API key>" id="<API key>" ><?php echo htmlspecialchars(stripslashes(<API key>('<API key>'))); ?></textarea><br /><?php _e('In the Footer you can display an advice for changing the Default-design, (x)HTML is possible.', <API key> ); ?> </td> </tr> <?php // when remove dashboard foreach ($user_roles as $role) { $disabled_menu_[$role] = <API key>('<API key>'. $role .'_items'); $disabled_submenu_[$role] = <API key>('<API key>'. $role .'_items'); } $disabled_menu_all = array(); foreach ($user_roles as $role) { array_push($disabled_menu_all, $disabled_menu_[$role]); array_push($disabled_menu_all, $disabled_submenu_[$role]); } if ( '' != $disabled_menu_all ) { if ( ! <API key>('index.php', $disabled_menu_all) ) { $disabled_item2 = ' disabled="disabled"'; } ?> <tr valign="top" class="form-invalid"> <td><?php _e('Dashboard deactivate, redirect to', <API key> ); ?></td> <td> <?php $<API key> = <API key>('<API key>'); ?> <select name="<API key>"<?php if ( isset($disabled_item2) ) echo $disabled_item2; ?>> <option value="0"<?php if ($<API key> == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', <API key> ); ?> (profile.php)</option> <option value="1"<?php if ($<API key> == '1') { echo ' selected="selected"'; } ?>><?php _e('Manage Posts', <API key> ); ?> (edit.php)</option> <option value="2"<?php if ($<API key> == '2') { echo ' selected="selected"'; } ?>><?php _e('Manage Pages', <API key> ); ?> (edit-pages.php)</option> <option value="3"<?php if ($<API key> == '3') { echo ' selected="selected"'; } ?>><?php _e('Write Post', <API key> ); ?> (post-new.php)</option> <option value="4"<?php if ($<API key> == '4') { echo ' selected="selected"'; } ?>><?php _e('Write Page', <API key> ); ?> (page-new.php)</option> <option value="5"<?php if ($<API key> == '5') { echo ' selected="selected"'; } ?>><?php _e('Comments', <API key> ); ?> (edit-comments.php)</option> <option value="6"<?php if ($<API key> == '6') { echo ' selected="selected"'; } ?>><?php _e('other Page', <API key> ); ?></option> </select> <textarea style="width: 85%;" class="code" rows="1" cols="60" name="<API key>" id="<API key>" ><?php echo htmlspecialchars(stripslashes(<API key>('<API key>'))); ?></textarea> <br /><?php _e('You have deactivated the Dashboard, please select a page for redirection or define custom url, include http://?', <API key> ); ?> </td> </tr> <?php } ?> </tbody> </table> <p id="submitbutton"> <input class="button button-primary" type="submit" name="_mw_adminimize_save" value="<?php _e('Update Options', <API key> ); ?> &raquo;" /><input type="hidden" name="page_options" value="'dofollow_timeout'" /> </p> <p><a class="alignright button" href="javascript:void(0);" onclick="window.scrollTo(0,0);" style="margin:3px 0 0 30px;"><?php _e('scroll to top', <API key>); ?></a><br class="clear" /></p> </div> </div> </div>
<?php /** * Footer functions. * * @package Sento */ /* Assign function for widget area 1 */ function <API key>() { echo '<div id="footer-col1" class="widget-area">'; if ( ! dynamic_sidebar( 'footer-w1' ) ) { echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>', '<div class="error-icon">', '<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 1.', 'sento') . '</p>', '<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>', '</div>'; }; echo '</div>'; } /* Assign function for widget area 2 */ function <API key>() { echo '<div id="footer-col2" class="widget-area">'; if ( ! dynamic_sidebar( 'footer-w2' ) ) { echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>', '<div class="error-icon">', '<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 2.', 'sento') . '</p>', '<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>', '</div>'; }; echo '</div>'; } /* Assign function for widget area 3 */ function <API key>() { echo '<div id="footer-col3" class="widget-area">'; if ( ! dynamic_sidebar( 'footer-w3' ) ) { echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>', '<div class="error-icon">', '<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 3.', 'sento') . '</p>', '<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>', '</div>'; }; echo '</div>'; } /* Assign function for widget area 4 */ function <API key>() { echo '<div id="footer-col4" class="widget-area">'; if ( ! dynamic_sidebar( 'footer-w4' ) ) { echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>', '<div class="error-icon">', '<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 4.', 'sento') . '</p>', '<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>', '</div>'; }; echo '</div>'; } /* Assign function for widget area 5 */ function <API key>() { echo '<div id="footer-col5" class="widget-area">'; if ( ! dynamic_sidebar( 'footer-w5' ) ) { echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>', '<div class="error-icon">', '<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 5.', 'sento') . '</p>', '<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>', '</div>'; }; echo '</div>'; } /* Assign function for widget area 6 */ function <API key>() { echo '<div id="footer-col6" class="widget-area">'; if ( ! dynamic_sidebar( 'footer-w6' ) ) { echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>', '<div class="error-icon">', '<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 6.', 'sento') . '</p>', '<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>', '</div>'; }; echo '</div>'; } /* Add Custom Footer Layout */ function <API key>() { global $<API key>; global $<API key>; if ( $<API key> !== "1" and ! empty( $<API key> ) ) { echo '<div id="footer">'; if ( $<API key> == "option1" ) { echo '<div id="footer-core" class="option1">'; <API key>(); echo '</div>'; } else if ( $<API key> == "option2" ) { echo '<div id="footer-core" class="option2">'; <API key>(); <API key>(); echo '</div>'; } else if ( $<API key> == "option3" ) { echo '<div id="footer-core" class="option3">'; <API key>(); <API key>(); <API key>(); echo '</div>'; } else if ( $<API key> == "option4" ) { echo '<div id="footer-core" class="option4">'; <API key>(); <API key>(); <API key>(); <API key>(); echo '</div>'; } else if ( $<API key> == "option5" ) { echo '<div id="footer-core" class="option5">'; <API key>(); <API key>(); <API key>(); <API key>(); <API key>(); echo '</div>'; } else if ( $<API key> == "option6" ) { echo '<div id="footer-core" class="option6">'; <API key>(); <API key>(); <API key>(); <API key>(); <API key>(); <API key>(); echo '</div>'; } else if ( $<API key> == "option7" ) { echo '<div id="footer-core" class="option7">'; <API key>(); <API key>(); echo '</div>'; } else if ( $<API key> == "option8" ) { echo '<div id="footer-core" class="option8">'; <API key>(); <API key>(); echo '</div>'; } else if ( $<API key> == "option9" ) { echo '<div id="footer-core" class="option9">'; <API key>(); <API key>(); echo '</div>'; } else if ( $<API key> == "option10" ) { echo '<div id="footer-core" class="option10">'; <API key>(); <API key>(); echo '</div>'; } else if ( $<API key> == "option11" ) { echo '<div id="footer-core" class="option11">'; <API key>(); <API key>(); echo '</div>'; } else if ( $<API key> == "option12" ) { echo '<div id="footer-core" class="option12">'; <API key>(); <API key>(); echo '</div>'; } else if ( $<API key> == "option13" ) { echo '<div id="footer-core" class="option13">'; <API key>(); <API key>(); <API key>(); <API key>(); echo '</div>'; } else if ( $<API key> == "option14" ) { echo '<div id="footer-core" class="option14">'; <API key>(); <API key>(); <API key>(); <API key>(); echo '</div>'; } else if ( $<API key> == "option15" ) { echo '<div id="footer-core" class="option15">'; <API key>(); <API key>(); <API key>(); echo '</div>'; } else if ( $<API key> == "option16" ) { echo '<div id="footer-core" class="option16">'; <API key>(); <API key>(); <API key>(); echo '</div>'; } else if ( $<API key> == "option17" ) { echo '<div id="footer-core" class="option17">'; <API key>(); <API key>(); <API key>(); <API key>(); <API key>(); echo '</div>'; } else if ( $<API key> == "option18" ) { echo '<div id="footer-core" class="option18">'; <API key>(); <API key>(); <API key>(); <API key>(); <API key>(); echo '</div>'; } echo '</div>'; } } function <API key>() { printf( __( 'Developed by %1$s. Powered by %2$s.', 'sento' ) , '<a href=" } ?>
<script> var panels = new Array(); function addcattab(id, text, title) { var ccc = document.getElementById('categories'); var tab_id = id + '-tab'; var tab_title = (title) ? (' title="' + title + '"') : ''; var _li = document.createElement('li'); _li.id = tab_id; _li.className = 'tab'; _li.innerHTML = '<a href="' + "#tabs" + '" class="cattab" data-subpanel="' + id + '" role="tab" aria-controls="' + id + '"' + tab_title + '><span>' + text + "</span></a>"; ccc.appendChild(_li); } function is_in_array(elem, array) { for (var i = 0, length = array.length; i < length; i++) { if (array[i] === elem) { return i; } } return -1; } function nextTag(node) { var node = node.nextSibling; return (node && node.nodeType != 1) ? nextTag(node) : node; } </script> <div id="tabs" class="sub-panels" role="tablist"> <ul id="categories" class="tabs"></ul> </div>
/** \file future.c This is responsible for Future Mission planning screen. * */ #include <Buzz_inc.h> #include <externs.h> #include <assert.h> #include <logging.h> //Used to read steps from missStep.dat FILE* MSteps; char missStep[1024]; static inline char B_Mis(char x) {return missStep[x]-0x30;} /*missStep.dat is plain text, with: Mission Number (2 first bytes of each line) A Coded letter, each drawing a different line (1105-1127 for all possible letters) Numbers following each letter, which are the parameters of the function Each line must finish with a Z, so the game stops reading Any other char is ignored, but it's easier to read for a human that way */ <API key>(future) char status[5],lck[5],F1,F2,F3,F4,FMen,F5,Pad; char JointFlag,MarFlag,JupFlag,SatFlag,MisType; GXHEADER vh; struct StepInfo { i16 x_cor; i16 y_cor; } StepBub[MAXBUB]; struct Parameter { char A; /**< DOCKING */ char B; /**< EVA */ char C; /**< LEM */ char D; /**< JOINT */ char E; /**< MANNED/UNMANNED/Duration 0==unmanned 1-6==duration */ char X; /**< the type of mission for assign crew and hardware */ char Z; /**< A duration mission only */ } V[62]; extern int Bub_Count; extern struct mStr Mis; extern struct MisEval Mev[60]; extern int SEG; void Load_FUT_BUT(void) { FILE *fin; unsigned i; fin=sOpen("NFUTBUT.BUT","rb",0); i=fread(screen,1,MAX_X*MAX_Y,fin); fclose(fin); RLED_img((char *)screen,(char *)vh.vptr,(unsigned)i,vh.w,vh.h); return; } void DrawFuture(char plr,int mis,char pad) { int i,j; FILE *fin; unsigned sz; strcpy(IKEY,"k011");strcpy(IDT,"i011"); JointFlag=0; // initialize joint flag F1=F2=F3=F4=FMen=F5=0; for (i=0;i<5;i++) lck[i]=status[i]=0; FadeOut(2,pal,10,0,0); Load_FUT_BUT(); fin=sOpen("FMIN.IMG","rb",0); fread(&pal[0],768,1,fin); sz=fread(screen,1,MAX_X*MAX_Y,fin); fclose(fin); RLED_img((char *)screen,(char *)vhptr.vptr,sz,vhptr.w,vhptr.h); gxClearDisplay(0,0); gr_sync (); if (pad==2) JointFlag=0; // third pad automatic no joint mission else if (Data->P[plr].LaunchFacility[pad+1] == 1) { if (Data->P[plr].Future[pad+1].MissionCode==0) JointFlag=1; // if no mission then set joint flag else if (Data->P[plr].Future[pad+1].part==1) // check if the part of that second mission is set { JointFlag=1; Data->P[plr].Future[pad+1].MissionCode=0; // clear mission Data->P[plr].Future[pad+1].part=0; }; }; if (pad==1 || pad==0) { if (Data->P[plr].LaunchFacility[pad+1]==1) JointFlag=1; } i=Data->Year;j=Data->Season; TRACE3("--- Setting i=Year (%d), j=Season (%d)", i, j); if ((i==60 && j==0) || (i==62 && j==0) || (i==64 && j==0) || (i==66 && j==0) || (i==69 && j==1) || (i==71 && j==1) || (i==73 && j==1)) { gxVirtualVirtual(&vhptr,1,2,12,11,&vhptr,198,153,gxSET); /* Mars */ MarFlag=1; } else MarFlag=0; if ((i==60 || i==64 || i==68 || i==72 || i==73 || i==77)) { gxVirtualVirtual(&vhptr,14,2,64,54,&vhptr,214,130,gxSET); /* Jup */ JupFlag=1; } else JupFlag=0; if (i==61 || i==66 || i==72) { gxVirtualVirtual(&vhptr,66,2,114,53,&vhptr,266,135,gxSET); /* Sat */ SatFlag=1; } else SatFlag=0; RectFill(1,1,318,21,3);RectFill(317,22,318,198,3);RectFill(1,197,316,198,3); RectFill(1,22,2,196,3);OutBox(0,0,319,199);InBox(3,3,30,19); InBox(3,22,316,196); IOBox(242,3,315,19); ShBox(5,24,183,47); ShBox(5,24,201,47); //name box ShBox(5,74,41,82); // RESET ShBox(5,49,53,72); //dur/man ShBox(43,74,53,82); // lock ShBox(80,74,90,82); ShBox(117,74,127,82); ShBox(154,74,164,82); ShBox(191,74,201,82); ShBox(5,84,16,130); //arrows up ShBox(5,132,16,146); //middle box ShBox(5,148,16,194); // down ShBox(203,24,238,31); // new right boxes RectFill(206,36,235,44,7); ShBox(203,33,238,47); InBox(205,35,236,45); UPArrow(8,95);DNArrow(8,157); gxVirtualDisplay(&vh,140,5,5,132,15,146,0); Toggle(5,1);draw_Pie(0);OutBox(5,49,53,72); Toggle(1,1);TogBox(55,49,0); Toggle(2,1);TogBox(92,49,0); Toggle(3,1);TogBox(129,49,0); FMen=F1=F2=F3=F4=F5=0; for (i=1;i<4;i++){ if (status[i]!=0) { Toggle(i,1); } }; if (JointFlag==0) { F4=2;lck[4]=1; Toggle(4,1); InBox(191,74,201,82); PlaceRX(5); TogBox(166,49,1); } else { F4=0; lck[4]=0; status[4]=0; Toggle(4,1); OutBox(191,74,201,82); ClearRX(5); TogBox(166,49,0); }; gr_sync (); Missions(plr,8,37,mis,1); GetMinus(plr); grSetColor(5); /* lines of text are 1:8,30 2:8,37 3:8,44 */ switch(pad) { // These used to say Pad 1, 2, 3 -Leon case 0: PrintAt(8,30,"PAD A:");break; case 1: PrintAt(8,30,"PAD B:");break; case 2: PrintAt(8,30,"PAD C:");break; default:break; }; grSetColor(1); PrintAt(9,80,"RESET"); PrintAt(256,13,"CONTINUE"); grSetColor(11); if (Data->Season==0) PrintAt(200,9,"SPRING"); else PrintAt(205,9,"FALL"); PrintAt(206,16,"19"); DispNum(0,0,Data->Year); grSetColor(1); FlagSm(plr,4,4); DispBig(40,5,"FUTURE MISSIONS",0,-1); FadeIn(2,pal,10,0,0); return; } void ClearDisplay(void) { gxVirtualDisplay(&vhptr,202,48,202,48,241,82,0); gxVirtualDisplay(&vhptr,17,83,17,83,241,195,0); gxVirtualDisplay(&vhptr,242,23,242,23,315,195,0); grSetColor(1); return; } int GetMinus(char plr) { char i;int u; i=PrestMin(plr); RectFill(206,36,235,44,7); if (i<3) u=1; else if (i<9) u=10; //caution else u=19; //danger gxVirtualDisplay(&vh,203,u,203,24,238,31,0); grSetColor(11); if (i>0) PrintAt(210,42,"-"); else grMoveTo(210,42); DispNum(0,0,i); grSetColor(1); return 0; } void SetParameters(void) { int i; FILE *fin; fin=sOpen("MISSION.DAT","rb",0); for (i=0;i<62;i++) { fread(&Mis,sizeof Mis,1,fin); V[i].A=Mis.Doc; V[i].B=Mis.EVA; V[i].C=Mis.LM; V[i].D=Mis.Jt; V[i].E=Mis.Days; V[i].X=Mis.mCrew; V[i].Z=Mis.Dur; } fclose(fin); return; } void DrawLocks(void) { int i; for (i=0;i<5;i++) if (lck[i]==1) PlaceRX(i+1); else ClearRX(i+1); return; } /** set the toggles??? * * \param wh the button * \param i in or out */ void Toggle(int wh,int i) { TRACE3("->Toggle(wh %d, i %d)", wh, i); switch(wh) { case 1:if (i==1) gxVirtualDisplay(&vh,1,21,55,49,89,81,0);else gxVirtualDisplay(&vh,1,56,55,49,89,81,0); break; case 2:if(i==1) gxVirtualDisplay(&vh,38,21,92,49,127,81,0);else gxVirtualDisplay(&vh,38,56,92,49,127,81,0); break; case 3:if(i==1) gxVirtualDisplay(&vh,75,21,129,49,163,81,0);else gxVirtualDisplay(&vh,75,56,129,49,163,81,0); break; case 4:if(i==1) gxVirtualDisplay(&vh,112,21,166,49,200,81,0);else gxVirtualDisplay(&vh,112,56,166,49,200,81,0); break; case 5:if (i==1) gxVirtualDisplay(&vh,153,1,5,49,52,71,0); else gxVirtualDisplay(&vh,153,26,5,49,52,71,0); break; default:break; } TRACE1("<-Toggle()"); return; } void TogBox(int x,int y,int st) { TRACE4("->TogBox(x %d, y %d, st %d)", x, y, st); char sta[2][2]={{2,4},{4,2}}; grSetColor(sta[st][0]); grMoveTo(0+x,y+32);grLineTo(0+x,y+0);grLineTo(34+x,y+0); grSetColor(sta[st][1]); grMoveTo(x+0,y+33);grLineTo(23+x,y+33);grLineTo(23+x,y+23); grLineTo(x+35,y+23);grLineTo(x+35,y+0); TRACE1("<-TogBox()"); return; } void PianoKey(int X) { TRACE2("->PianoKey(X %d)", X); int t; if (F1==0) { if (V[X].A==1) {Toggle(1,1);status[1]=1;} else {Toggle(1,0);PlaceRX(1);status[1]=0;}} if (F2==0) { if (V[X].B==1) {Toggle(2,1);status[2]=1;} else {Toggle(2,0);PlaceRX(2);status[2]=0;}} if (F3==0) { if (V[X].C==1) {Toggle(3,1);status[3]=1;} else {Toggle(3,0);PlaceRX(3);status[3]=0;}} if (F4==0) { if (V[X].D==1) {Toggle(4,0);status[4]=1;} else {Toggle(4,1);status[4]=0; }} if (F5==-1 || (F5==0 && V[X].E==0)) { Toggle(5,0); status[0]=0; } else { Toggle(5,1); t=(F5==0) ? V[X].E : F5; assert(0 <= t); draw_Pie(t); status[0]=t; } DrawLocks(); TRACE1("<-PianoKey()"); return; } /** draw a piechart * * The piechart is indicating the number of astronauts on this mission. * * \param s something of an offset... */ void draw_Pie(int s) { int off; if (s==0) off=1; else off=s*20; gxVirtualDisplay(&vh,off,1,7,51,25,69,0); return; } void PlaceRX(int s) { switch(s) { case 1: RectFill(44,75,52,81,8);break; case 2: RectFill(81,75,89,81,8);break; case 3: RectFill(118,75,126,81,8);break; case 4: RectFill(155,75,163,81,8);break; case 5: RectFill(192,75,200,81,8);break; default:break; } return; } void ClearRX(int s) { switch(s) { case 1: RectFill(44,75,52,81,3);break; case 2: RectFill(81,75,89,81,3);break; case 3: RectFill(118,75,126,81,3);break; case 4: RectFill(155,75,163,81,3);break; case 5: RectFill(192,75,200,81,3);break; default:break; } return; } int UpSearchRout(int num,char plr) { int found=0,orig,c1=0,c2=0,c3=0,c4=0,c5=0,c6=1,c7=1,c8=1; orig=num; if (num >= 56+plr) num=0; else num++; while (found==0) { c1=0;c2=0;c3=0;c4=0;c5=0;c6=1;c7=1;c8=1; if (F1==V[num].A) c1=1; /* condition one is true */ if (F1==0 && V[num].A==1) c1=1; if (F1==2 && V[num].A==0) c1=1; if (F2==V[num].B) c2=1; /* condition two is true */ if (F2==0 && V[num].B==1) c2=1; if (F2==2 && V[num].B==0) c2=1; if (F3==V[num].C) c3=1; /* condition three is true */ if (F3==0 && V[num].C==1) c3=1; if (F3==2 && V[num].C==0) c3=1; if (F4==V[num].D) c4=1; /* condition four is true */ if (F4==0 && V[num].D==1) c4=1; if (F4==2 && V[num].D==0) c4=1; if (num==0) c5=1; else { if (F5==-1 && V[num].Z==0 && V[num].E==0) c5=1; if (F5==0) c5=1; if (F5>1 && V[num].Z==1) c5=1; if (F5==V[num].E) c5=1; }; if ((num==32 || num==36) && F5==2) c5=0; // planet check if (num==10 && MarFlag==0) c6=0; if (num==12 && JupFlag==0) c7=0; if (num==13 && SatFlag==0) c8=0; if (c1 && c2 && c3 && c4 && c5 && c6 && c7 && c8) found=1; if (num==orig) return(0); if (found==0) { if (num==56+plr) num=0; else ++num; } }; /* end while */ return(num); } int DownSearchRout(int num,char plr) { int found=0,orig,c1=0,c2=0,c3=0,c4=0,c5=0,c6=1,c7=1,c8=1; orig=num; if (num<=0) num=56+plr; else --num; while (found==0) { c1=0;c2=0;c3=0;c4=0;c5=0;c6=1;c7=1;c8=1; if (F1==V[num].A) c1=1; if (F1==0 && V[num].A==1) c1=1; /* condition one is true */ if (F1==2 && V[num].A==0) c1=1; if (F2==V[num].B) c2=1; /* condition two is true */ if (F2==0 && V[num].B==1) c2=1; /* condition one is true */ if (F2==2 && V[num].B==0) c2=1; if (F3==V[num].C) c3=1; /* condition three is true */ if (F3==0 && V[num].C==1) c3=1; /* condition one is true */ if (F3==2 && V[num].C==0) c3=1; if (F4==V[num].D) c4=1; /* condition four is true */ if (F4==0 && V[num].D==1) c4=1; /* condition one is true */ if (F4==2 && V[num].D==0) c4=1; if (num==0) c5=1; else { if (F5==-1 && V[num].Z==0 && V[num].E==0) c5=1; // locked on zero duration if (F5==0) c5=1; // nothing set if (F5>1 && V[num].Z==1) c5=1; // set duration with duration mission if (F5==V[num].E) c5=1; // the duration is equal to what is preset }; if ((num==32 || num==36) && F5==2) c5=0; // planet check if (num==10 && MarFlag==0) c6=0; if (num==12 && JupFlag==0) c7=0; if (num==13 && SatFlag==0) c8=0; if (c1 && c2 && c3 && c4 && c5 && c6 && c7 && c8) found=1; if (num==orig) return(0); if (found==0) { if (num==0) num=56+plr; else --num; } }; /* end while */ return(num); } void Future(char plr) { /** \todo the whole Future()-function is 500 >lines and unreadable */ TRACE1("->Future(plr)"); int MisNum = 0, DuraType = 0, MaxDur = 6, i, ii; int setting = -1, prev_setting = -1; int Ok, NewType; GXHEADER local, local2; GV(&local, 166, 9); GV(&local2, 177, 197); GV(&vh,240,90); /* global variable */ begfut: MisNum = FutureCheck(plr, 0); if (MisNum == 5) { DV(&local); DV(&local2); DV(&vh); return; } F1 = F2 = F3 = F4 = FMen = F5 = 0; // memset(buffer, 0x00, 20000); for (i = 0; i < 5; i++) lck[i] = status[i] = 0; SetParameters(); strcpy(IDT, "i011"); Pad = MisNum; DuraType = FMen = MisType = 0; ClrFut(plr, MisNum); DrawFuture(plr, MisType, MisNum); begfut_noredraw: // for (i=0;i<5;i++) ClearRX(i+1); while (1) { GetMouse(); if (mousebuttons == 0) break; } while (1) { GetMouse(); prev_setting = setting; setting = -1; if (key == '-' && SEG > 1) SEG if (key == '+' && SEG < 500) SEG++; if (key >= 65 && key < Bub_Count + 65) setting = key - 65; for (ii = 0; ii < Bub_Count; ii++) { if (x >= StepBub[ii].x_cor && x <= StepBub[ii].x_cor + 7 && y >= StepBub[ii].y_cor && y <= StepBub[ii].y_cor + 7) setting = ii; } if (setting >= 0) { if (prev_setting < 0) gxGetImage(&local, 18, 186, 183, 194, 0); if (prev_setting != setting) { ShBox(18, 186, 183, 194); grSetColor(1); MisStep(21, 192, Mev[setting].loc); } } else if (setting < 0 && prev_setting >= 0) { gxPutImage(&local, gxSET, 18, 186, 0); } if (Mis.Dur <= V[MisType].E && ((x >= 244 && y >= 5 && x <= 313 && y <= 17 && mousebuttons > 0) || key == K_ENTER)) { InBox(244, 5, 313, 17); WaitForMouseUp(); if (key > 0) delay(300); key = 0; OutBox(244, 5, 313, 17); gxGetImage(&local2, 74, 3, 250, 199, 0); NewType = V[MisType].X; Data->P[plr].Future[MisNum].Duration = DuraType; Ok = HardCrewAssign(plr, Pad, MisType, NewType); gxPutImage(&local2, gxSET, 74, 3, 0); // DV(&local2); if (Ok == 1) { Data->P[plr].Future[MisNum].Duration = DuraType; goto begfut; // return to loop } else { ClrFut(plr, MisNum); // DuraType = FMen = MisType = 0; key = 0; goto begfut_noredraw; // DrawFuture(plr, MisType, MisNum); } key = 0; }; // continue if ((((x >= 5 && y >= 49 && x <= 53 && y <= 72) || (x >= 43 && y >= 74 && x <= 53 && y <= 82)) && mousebuttons > 0) || (key == '!' || key == '1')) { if ((x >= 43 && y >= 74 && x <= 53 && y <= 82) || key == '!') { lck[0] = abs(lck[0] - 1); if (lck[0] == 1) InBox(43, 74, 53, 82); else OutBox(43, 74, 53, 82); if (lck[0] == 1) F5 = (status[0] == 0) ? -1 : status[0]; if (lck[0] == 1) PlaceRX(1); else ClearRX(1); if (lck[0] == 0) { F5 = 0; status[0] = 0; } while (1) { GetMouse(); if (mousebuttons == 0) break; } } else if (lck[0] != 1) { InBox(5, 49, 53, 72); if (DuraType == MaxDur) DuraType = 0; else DuraType++; Data->P[plr].Future[MisNum].Duration = DuraType; if (DuraType == 0) Toggle(5, 0); else if (DuraType == 1) Toggle(5, 1); if (DuraType != 0) draw_Pie(DuraType); status[0] = DuraType; while (1) { GetMouse(); if (mousebuttons == 0) break; } grSetColor(34); OutBox(5, 49, 53, 72); }; key = 0; /* Duration */ }; if ((x >= 5 && y >= 74 && x <= 41 && y <= 82 && mousebuttons > 0) || (key == K_ESCAPE)) { InBox(5, 74, 41, 82); while (1) { GetMouse(); if (mousebuttons == 0) break; } MisType = 0; if (DuraType != 0) Toggle(5, 0); FMen = DuraType = F1 = F2 = F3 = F4 = F5 = 0; for (i = 1; i < 4; i++) if (status[i] != 0) Toggle(i, 1); if (JointFlag == 0) { F4 = 2; lck[4] = 1; Toggle(4, 1); InBox(191, 74, 201, 82); PlaceRX(5); TogBox(166, 49, 1); } else { F4 = 0; lck[4] = 0; status[4] = 0; Toggle(4, 1); OutBox(191, 74, 201, 82); ClearRX(5); TogBox(166, 49, 0); }; for (i = 0; i < 4; i++) { lck[i] = status[i] = 0; } OutBox(5, 49, 53, 72); OutBox(43, 74, 53, 82); TogBox(55, 49, 0); OutBox(80, 74, 90, 82); TogBox(92, 49, 0); OutBox(117, 74, 127, 82); TogBox(129, 49, 0); OutBox(154, 74, 164, 82); ClrFut(plr, MisNum); Data->P[plr].Future[MisNum].Duration = 0; Missions(plr, 8, 37, MisType, 1); GetMinus(plr); OutBox(5, 74, 41, 82); key = 0; /* Reset */ }; if ((x >= 55 && y >= 49 && x <= 90 && y <= 82 && mousebuttons > 0) || (key == '2' || key == '@')) { if ((x >= 80 && y >= 74 && x <= 90 && y <= 82) || (key == '@')) { if (lck[1] == 0) InBox(80, 74, 90, 82); else OutBox(80, 74, 90, 82); lck[1] = abs(lck[1] - 1); if (lck[1] == 1) PlaceRX(2); else ClearRX(2); if ((status[1] == 0) && (lck[1] == 1)) F1 = 2; else if ((status[1] == 1) && (lck[1] == 1)) F1 = 1; else F1 = 0; while (1) { GetMouse(); if (mousebuttons == 0) break; } } else if (lck[1] != 1) { TogBox(55, 49, 1); if (status[1] == 0) Toggle(1, 1); else Toggle(1, 0); status[1] = abs(status[1] - 1); while (1) { GetMouse(); if (mousebuttons == 0) break; } TogBox(55, 49, 0); }; /* Docking */ key = 0; }; if ((x >= 92 && y >= 49 && x <= 127 && y <= 82 && mousebuttons > 0) || (key == '3' || key == ' { if ((x >= 117 && y >= 74 && x <= 127 && y <= 82) || (key == ' { if (lck[2] == 0) InBox(117, 74, 127, 82); else OutBox(117, 74, 127, 82); lck[2] = abs(lck[2] - 1); if (lck[2] == 1) PlaceRX(3); else ClearRX(3); if ((status[2] == 0) && (lck[2] == 1)) F2 = 2; else if ((status[2] == 1) && (lck[2] == 1)) F2 = 1; else F2 = 0; while (1) { GetMouse(); if (mousebuttons == 0) break; } } else if (lck[2] != 1) { TogBox(92, 49, 1); if (status[2] == 0) Toggle(2, 1); else { Toggle(2, 0); }; status[2] = abs(status[2] - 1); while (1) { GetMouse(); if (mousebuttons == 0) break; } TogBox(92, 49, 0); }; /* EVA */ key = 0; }; if ((x >= 129 && y >= 49 && x <= 164 && y <= 82 && mousebuttons > 0) || (key == '4' || key == '$')) { if ((x >= 154 && y >= 74 && x <= 164 && y <= 82) || (key == '$')) { if (lck[3] == 0) InBox(154, 74, 164, 82); else OutBox(154, 74, 164, 82); lck[3] = abs(lck[3] - 1); // F3=lck[3]; if (lck[3] == 1) PlaceRX(4); else ClearRX(4); if ((status[3] == 0) && (lck[3] == 1)) F3 = 2; else if ((status[3] == 1) && (lck[3] == 1)) F3 = 1; else F3 = 0; while (1) { GetMouse(); if (mousebuttons == 0) break; } } else if (lck[3] != 1) { TogBox(129, 49, 1); if (status[3] == 0) Toggle(3, 1); else { Toggle(3, 0); }; status[3] = abs(status[3] - 1); while (1) { GetMouse(); if (mousebuttons == 0) break; } TogBox(129, 49, 0); }; /* LEM */ key = 0; }; if (((x >= 166 && y >= 49 && x <= 201 && y <= 82 && mousebuttons > 0) || (key == '5' || key == '%')) && (JointFlag == 1)) { if ((x > 191 && y >= 74 && x <= 201 && y <= 82) || (key == '%')) { if (lck[4] == 0) InBox(191, 74, 201, 82); else OutBox(191, 74, 201, 82); lck[4] = abs(lck[4] - 1); if (lck[4] == 1) PlaceRX(5); else ClearRX(5); if ((status[4] == 0) && (lck[4] == 1)) F4 = 2; else if ((status[4] == 1) && (lck[4] == 1)) F4 = 1; else F4 = 0; while (1) { GetMouse(); if (mousebuttons == 0) break; } } else if (lck[4] != 1) { TogBox(166, 49, 1); status[4] = abs(status[4] - 1); if (status[4] == 0) { Toggle(4, 1); } else { Toggle(4, 0); } while (1) { GetMouse(); if (mousebuttons == 0) break; } TogBox(166, 49, 0); }; /* Joint Launch */ key = 0; }; if ((x >= 5 && y >= 84 && x <= 16 && y <= 130 && mousebuttons > 0) || (key == UP_ARROW)) { InBox(5, 84, 16, 130); for (i = 0; i < 50; i++) { key = 0; GetMouse(); delay(10); if (mousebuttons == 0) { MisType = UpSearchRout(MisType, plr); Data->P[plr].Future[MisNum].MissionCode = MisType; i = 51; } } while (mousebuttons == 1 || key == UP_ARROW) { MisType = UpSearchRout(MisType, plr); Data->P[plr].Future[MisNum].MissionCode = MisType; Missions(plr, 8, 37, MisType, 3); DuraType = status[0]; delay(100); key = 0; GetMouse(); } Missions(plr, 8, 37, MisType, 3); DuraType = status[0]; OutBox(5, 84, 16, 130); key = 0; /* Mission Type plus */ }; if ((x >= 5 && y >= 132 && x < 16 && y <= 146 && mousebuttons > 0) || (key == K_SPACE)) { InBox(5, 132, 16, 146); WaitForMouseUp(); delay(50); MisType = Data->P[plr].Future[MisNum].MissionCode; assert(0 <= MisType); if (MisType != 0){ Missions(plr, 8, 37, MisType, 1); } else{ Missions(plr, 8, 37, MisType, 3); } OutBox(5, 132, 16, 146); key = 0; } if ((x >= 5 && y >= 148 && x <= 16 && y <= 194 && mousebuttons > 0) || (key == DN_ARROW)) { InBox(5, 148, 16, 194); for (i = 0; i < 50; i++) { key = 0; GetMouse(); delay(10); if (mousebuttons == 0) { MisType = DownSearchRout(MisType, plr); Data->P[plr].Future[MisNum].MissionCode = MisType; i = 51; } key = 0; } while (mousebuttons == 1 || key == DN_ARROW) { MisType = DownSearchRout(MisType, plr); Data->P[plr].Future[MisNum].MissionCode = MisType; Missions(plr, 8, 37, MisType, 3); DuraType = status[0]; delay(100); key = 0; GetMouse(); } Missions(plr, 8, 37, MisType, 3); DuraType = status[0]; OutBox(5, 148, 16, 194); key = 0; /* Mission Type minus */ }; } // while TRACE1("<-Future()"); } /** draws the bubble on the screen, * starts with upper left coor * * \param x x-coord of the upper left corner of the bubble * \param y y-coord of the upper left corner of the bubble */ void Bd(int x,int y) { int x1,y1,x2,y2; x1=x-2; y1=y; x2=x-1; y2=y-1; RectFill(x1,y1,x1+8,y1+4,21); RectFill(x2,y2,x2+6,y2+6,21); grSetColor(1); grMoveTo(x,y+4); /** \note references Bub_Count to determine the number of the character to draw in the bubble */ DispChr(65+Bub_Count); StepBub[Bub_Count].x_cor=x1; StepBub[Bub_Count].y_cor=y1; ++Bub_Count; return; } /** Print the duration of a mission * * \param x duration code * * \todo Link this at whatever place the duration is actually defined */ void DurPri(int x) { grSetColor(5); switch(x) { case -1:PrintAt(112,30,"NO DURATION");break; case 0:PrintAt(112,30,"NO DURATION");break; case 1:PrintAt(112,30,"1 - 2 DAYS");break; case 2:PrintAt(112,30,"3 - 5 DAYS");break; case 3:PrintAt(112,30,"6 - 7 DAYS");break; case 4:PrintAt(112,30,"8 - 12 DAYS");break; case 5:PrintAt(112,30,"13 - 16 DAYS");break; case 6:PrintAt(112,30,"17 - 20 DAYS");break; default:break; }; return; } void MissionName(int val,int xx,int yy,int len) { TRACE5("->MissionName(val %d, xx %d, yy %d, len %d)", val, xx, yy, len); int i,j=0; GetMisType(val); grMoveTo(xx,yy); for (i=0;i<50;i++) { if (j>len && Mis.Name[i]==' ') {yy+=7;j=0;grMoveTo(xx,yy);} else DispChr(Mis.Name[i]); j++;if (Mis.Name[i]=='\0') break; }; TRACE1("<-MissionName"); return; } /** Missions() will draw the future missions among other things * * \param plr Player * \param X screen coord for mission name string * \param Y screen coord for mission name string * \param val mission number * \param bub if set to 0 or 3 the function will not draw stuff */ void Missions(char plr,int X,int Y,int val,char bub) { TRACE5("->Missions(plr, X %d, Y %d, val %d, bub %c)", X, Y, val, bub); if (bub==1 || bub==3) { PianoKey(val); Bub_Count=0; // set the initial bub_count ClearDisplay(); RectFill(6,31,182,46,3); RectFill(80,25,175,30,3);grSetColor(5); PrintAt(55,30,"TYPE: ");DispNum(0,0,val); grSetColor(5); if (V[val].E>0) { if (F5 > V[val].E && Mis.Dur==1) DurPri(F5); else DurPri(V[val].E);} else DurPri(F5); } else grSetColor(1); MissionName(val,X,Y,24); if (bub==3) GetMinus(plr); if (bub==0 || bub==3) {return;} MSteps=sOpen("missSteps.dat","r",FT_DATA); if (fgets(missStep, 1024, MSteps) == NULL) memset (missStep, 0, sizeof missStep); while (!feof(MSteps)&&((missStep[0]-0x30)*10+(missStep[1]-0x30))!=val) { if (fgets(missStep, 1024, MSteps) == NULL) break; } fclose(MSteps); int n; for (n=2;missStep[n]!='Z';n++) switch (missStep[n]) { case 'A': Draw_IJ (B_Mis(++n)); break; case 'B': Draw_IJV (B_Mis(++n)); break; case 'C': OrbOut (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3)); n+=3; break; case 'D': LefEarth (B_Mis(n+1),B_Mis(n+2)); n+=2; break; case 'E': OrbIn (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3)); n+=3; break; case 'F': OrbMid (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4)); n+=4; break; case 'G': LefOrb (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4)); n+=4; break; case 'H': Draw_LowS (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4),B_Mis(n+5),B_Mis(n+6)); n+=6; break; case 'I': Fly_By (); break; case 'J': VenMarMerc (B_Mis(++n)); break; case 'K': Draw_PQR (); break; case 'L': Draw_PST (); break; case 'M': Draw_GH (B_Mis(n+1),B_Mis(n+2)); n+=2; break; case 'N': Q_Patch (); break; case 'O': RghtMoon (B_Mis(n+1),B_Mis(n+2)); n+=2; break; case 'P': DrawLunPas (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4)); n+=4; break; case 'Q': DrawLefMoon (B_Mis(n+1),B_Mis(n+2)); n+=2; break; case 'R': DrawSTUV (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4)); n+=4; break; case 'S': Draw_HighS (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3)); n+=3; break; case 'T': DrawMoon (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4),B_Mis(n+5),B_Mis(n+6),B_Mis(n+7)); n+=7; break; case 'U': LefGap (B_Mis(++n)); break; case 'V': S_Patch (B_Mis(++n)); break; case 'W': DrawZ (); break; default : break; } gr_sync (); MissionCodes(plr,MisType,Pad); TRACE1("<-Missions()"); } // end function missions #ifdef DEAD_CODE /** Draws stuff about choosing a program and having < 2 groups available * * \deprecated This function appears to be deprecated. */ char FutBad(void) { char i; grSetColor(0); ShBox(84,41,232,128); InBox(91,47,225,103); IOBox(91,107,225,123); grSetColor(1); PrintAt(150,117,"EXIT"); grSetColor(11); PrintAt(96,60,"YOU HAVE SELECTED A"); PrintAt(96,70,"PROGRAM WITH LESS THAN"); PrintAt(96,80,"TWO GROUPS AVAILABLE."); WaitForMouseUp(); i=0; while(i==0) { GetMouse(); if (mousebuttons!=0) { if (x>=93 && y>=109 && x<=223 && y<=121) { InBox(93,109,223,123);i=3; delay(50); }; }; }; /* End while */ return (i); } #endif /* vim: set noet ts=4 sw=4 tw=77: */
# SSClusterViewer/app This folder contains the javascript files for the application. # SSClusterViewer/resources This folder contains static resources (typically an `"images"` folder as well). # SSClusterViewer/overrides This folder contains override classes. All overrides in this folder will be automatically included in application builds if the target class of the override is loaded. # SSClusterViewer/sass/etc This folder contains misc. support code for sass builds (global functions, mixins, etc.) # SSClusterViewer/sass/src This folder contains sass files defining css rules corresponding to classes included in the application's javascript code build. By default, files in this folder are mapped to the application's root namespace, 'SSClusterViewer'. The namespace to which files in this directory are matched is controlled by the app.sass.namespace property in SSClusterViewer/.sencha/app/sencha.cfg. # SSClusterViewer/sass/var This folder contains sass files defining sass variables corresponding to classes included in the application's javascript code build. By default, files in this folder are mapped to the application's root namespace, 'SSClusterViewer'. The namespace to which files in this directory are matched is controlled by the app.sass.namespace property in SSClusterViewer/.sencha/app/sencha.cfg.
layout: post title: Objectify and strange errors with GWT serializations date: '2013-04-04T09:15:00.003-07:00' author: David Hatanian tags: modified_time: '2013-04-04T09:15:34.396-07:00' blogger_id: tag:blogger.com,1999:<API key>.<API key> blogger_orig_url: http://david-codes.blogspot.com/2013/04/<API key>.html <div style="text-align: justify;">OK, so it turns out Objectify returns non-serializable lists when using the <i>list()</i>&nbsp;method. Using the following method : </div> <div style="text-align: justify;"><br/></div> <div style="text-align: justify;"><br/></div><br/> <pre style="background-color: white; font-size: 12px; max-width: 80em; padding-left: 0.7em; text-align: start; white-space: pre-wrap;">ofy.load().type(Plant.class).list();<br/></pre> <pre style="background-color: white; font-size: 12px; max-width: 80em; padding-left: 0.7em; text-align: start; white-space: pre-wrap;"><br/></pre> <pre style="background-color: white; font-size: 12px; max-width: 80em; padding-left: 0.7em; text-align: start; white-space: pre-wrap;"><br/></pre>And directly returning the value to GWT client side throws a cryptic serialization exception, where the class that raises the problem is called <i>Proxy$XX </i>where XX are digits.<br/> <br/>That problem is going to be fixed in GWT next version, but meanwhile we have to use the workaround provided in the <a href="https://code.google.com/p/objectify-appengine/issues/detail?id=120">bug report</a>.
TARGET = rlm_utf8 SRCS = rlm_utf8.c HEADERS = RLM_CFLAGS = RLM_LIBS = include ../rules.mak $(STATIC_OBJS): $(HEADERS) $(DYNAMIC_OBJS): $(HEADERS)
<div class="tx-test-extension"> <f:render section="main" /> </div>
#include <iostream> #include <fstream> #include <algorithm> #include "calibrate.h" #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <math.h> #include <sys/types.h> #include <dirent.h> #include "../parameters/parameters.h" extern "C" { #include "../tuning/iw.h" } #include <map> #include <vector> #include <string> using namespace std; static vector<string> usb_devices; static vector<string> rfkill_devices; static vector<string> backlight_devices; static vector<string> scsi_link_devices; static int blmax; static map<string, string> saved_sysfs; static volatile int stop_measurement; static int wireless_PS; static void save_sysfs(const char *filename) { char line[4096]; ifstream file; file.open(filename, ios::in); if (!file) return; file.getline(line, 4096); file.close(); saved_sysfs[filename] = line; } static void restore_all_sysfs(void) { map<string, string>::iterator it; for (it = saved_sysfs.begin(); it != saved_sysfs.end(); it++) write_sysfs(it->first, it->second); <API key>("wlan0", wireless_PS); } static void find_all_usb(void) { struct dirent *entry; DIR *dir; char filename[4096]; dir = opendir("/sys/bus/usb/devices/"); if (!dir) return; while (1) { ifstream file; entry = readdir(dir); if (!entry) break; if (entry->d_name[0] == '.') continue; sprintf(filename, "/sys/bus/usb/devices/%s/power/active_duration", entry->d_name); if (access(filename, R_OK)!=0) continue; sprintf(filename, "/sys/bus/usb/devices/%s/power/idVendor", entry->d_name); file.open(filename, ios::in); if (file) { file.getline(filename, 4096); file.close(); if (strcmp(filename, "1d6b")==0) continue; } sprintf(filename, "/sys/bus/usb/devices/%s/power/control", entry->d_name); save_sysfs(filename); usb_devices.push_back(filename); } closedir(dir); } static void <API key>(void) { unsigned int i; for (i = 0; i < usb_devices.size(); i++) write_sysfs(usb_devices[i], "auto\n"); } static void find_all_rfkill(void) { struct dirent *entry; DIR *dir; char filename[4096]; dir = opendir("/sys/class/rfkill/"); if (!dir) return; while (1) { ifstream file; entry = readdir(dir); if (!entry) break; if (entry->d_name[0] == '.') continue; sprintf(filename, "/sys/class/rfkill/%s/soft", entry->d_name); if (access(filename, R_OK)!=0) continue; save_sysfs(filename); rfkill_devices.push_back(filename); } closedir(dir); } static void rfkill_all_radios(void) { unsigned int i; for (i = 0; i < rfkill_devices.size(); i++) write_sysfs(rfkill_devices[i], "1\n"); } static void unrfkill_all_radios(void) { unsigned int i; for (i = 0; i < rfkill_devices.size(); i++) write_sysfs(rfkill_devices[i], "0\n"); } static void find_backlight(void) { struct dirent *entry; DIR *dir; char filename[4096]; dir = opendir("/sys/class/backlight/"); if (!dir) return; while (1) { ifstream file; entry = readdir(dir); if (!entry) break; if (entry->d_name[0] == '.') continue; sprintf(filename, "/sys/class/backlight/%s/brightness", entry->d_name); if (access(filename, R_OK)!=0) continue; save_sysfs(filename); backlight_devices.push_back(filename); sprintf(filename, "/sys/class/backlight/%s/max_brightness", entry->d_name); blmax = read_sysfs(filename); } closedir(dir); } static void lower_backlight(void) { unsigned int i; for (i = 0; i < backlight_devices.size(); i++) write_sysfs(backlight_devices[i], "0\n"); } static void find_scsi_link(void) { struct dirent *entry; DIR *dir; char filename[4096]; dir = opendir("/sys/class/scsi_host/"); if (!dir) return; while (1) { ifstream file; entry = readdir(dir); if (!entry) break; if (entry->d_name[0] == '.') continue; sprintf(filename, "/sys/class/scsi_host/%s/<API key>", entry->d_name); if (access(filename, R_OK)!=0) continue; save_sysfs(filename); scsi_link_devices.push_back(filename); } closedir(dir); } static void set_scsi_link(const char *state) { unsigned int i; for (i = 0; i < scsi_link_devices.size(); i++) write_sysfs(scsi_link_devices[i], state); } static void *burn_cpu(void *dummy) { volatile double d = 1.1; while (!stop_measurement) { d = pow(d, 1.0001); } return NULL; } static void *burn_cpu_wakeups(void *dummy) { struct timespec tm; while (!stop_measurement) { tm.tv_sec = 0; tm.tv_nsec = (unsigned long)dummy; nanosleep(&tm, NULL); } return NULL; } static void *burn_disk(void *dummy) { int fd; char buffer[64*1024]; char filename[256]; strcpy(filename ,"/tmp/powertop.XXXXXX"); fd = mkstemp(filename); if (fd < 0) { printf(_("Cannot create temp file\n")); return NULL; } while (!stop_measurement) { lseek(fd, 0, SEEK_SET); write(fd, buffer, 64*1024); fdatasync(fd); } close(fd); return NULL; } static void cpu_calibration(int threads) { int i; pthread_t thr; printf(_("Calibrating: CPU usage on %i threads\n"), threads); stop_measurement = 0; for (i = 0; i < threads; i++) pthread_create(&thr, NULL, burn_cpu, NULL); one_measurement(15); stop_measurement = 1; sleep(1); } static void wakeup_calibration(unsigned long interval) { pthread_t thr; printf(_("Calibrating: CPU wakeup power consumption\n")); stop_measurement = 0; pthread_create(&thr, NULL, burn_cpu_wakeups, (void *)interval); one_measurement(15); stop_measurement = 1; sleep(1); } static void usb_calibration(void) { unsigned int i; /* chances are one of the USB devices is bluetooth; unrfkill first */ unrfkill_all_radios(); printf(_("Calibrating USB devices\n")); for (i = 0; i < usb_devices.size(); i++) { printf(_(".... device %s \n"), usb_devices[i].c_str()); <API key>(); write_sysfs(usb_devices[i], "on\n"); one_measurement(15); <API key>(); sleep(3); } rfkill_all_radios(); sleep(4); } static void rfkill_calibration(void) { unsigned int i; printf(_("Calibrating radio devices\n")); for (i = 0; i < rfkill_devices.size(); i++) { printf(_(".... device %s \n"), rfkill_devices[i].c_str()); rfkill_all_radios(); write_sysfs(rfkill_devices[i], "0\n"); one_measurement(15); rfkill_all_radios(); sleep(3); } for (i = 0; i < rfkill_devices.size(); i++) { printf(_(".... device %s \n"), rfkill_devices[i].c_str()); unrfkill_all_radios(); write_sysfs(rfkill_devices[i], "1\n"); one_measurement(15); unrfkill_all_radios(); sleep(3); } rfkill_all_radios(); } static void <API key>(void) { unsigned int i; printf(_("Calibrating backlight\n")); for (i = 0; i < backlight_devices.size(); i++) { char str[4096]; printf(_(".... device %s \n"), backlight_devices[i].c_str()); lower_backlight(); one_measurement(15); sprintf(str, "%i\n", blmax / 4); write_sysfs(backlight_devices[i], str); one_measurement(15); sprintf(str, "%i\n", blmax / 2); write_sysfs(backlight_devices[i], str); one_measurement(15); sprintf(str, "%i\n", 3 * blmax / 4 ); write_sysfs(backlight_devices[i], str); one_measurement(15); sprintf(str, "%i\n", blmax); write_sysfs(backlight_devices[i], str); one_measurement(15); lower_backlight(); sleep(1); } printf(_("Calibrating idle\n")); system("DISPLAY=:0 /usr/bin/xset dpms force off"); one_measurement(15); system("DISPLAY=:0 /usr/bin/xset dpms force on"); } static void idle_calibration(void) { printf(_("Calibrating idle\n")); system("DISPLAY=:0 /usr/bin/xset dpms force off"); one_measurement(15); system("DISPLAY=:0 /usr/bin/xset dpms force on"); } static void disk_calibration(void) { pthread_t thr; printf(_("Calibrating: disk usage \n")); set_scsi_link("min_power"); stop_measurement = 0; pthread_create(&thr, NULL, burn_disk, NULL); one_measurement(15); stop_measurement = 1; sleep(1); } void calibrate(void) { find_all_usb(); find_all_rfkill(); find_backlight(); find_scsi_link(); wireless_PS = <API key>("wlan0"); save_sysfs("/sys/module/snd_hda_intel/parameters/power_save"); cout << _("Starting PowerTOP power estimate calibration \n"); <API key>(); rfkill_all_radios(); lower_backlight(); <API key>("wlan0", 1); sleep(4); idle_calibration(); disk_calibration(); <API key>(); write_sysfs("/sys/module/snd_hda_intel/parameters/power_save", "1\n"); cpu_calibration(1); cpu_calibration(4); wakeup_calibration(10000); wakeup_calibration(100000); wakeup_calibration(1000000); <API key>("wlan0", 0); usb_calibration(); rfkill_calibration(); cout << _("Finishing PowerTOP power estimate calibration \n"); restore_all_sysfs(); learn_parameters(300, 1); printf(_("Parameters after calibration:\n")); <API key>(); save_parameters("saved_parameters.powertop"); save_all_results("saved_results.powertop"); }
#include "kptdocumentseditor.h" #include "kptcommand.h" #include "kptitemmodelbase.h" #include "kptduration.h" #include "kptnode.h" #include "kptproject.h" #include "kpttask.h" #include "kptdocuments.h" #include "kptdatetime.h" #include "kptitemviewsettup.h" #include "kptdebug.h" #include <QMenu> #include <QList> #include <QVBoxLayout> #include <kaction.h> #include <kicon.h> #include <kglobal.h> #include <klocale.h> #include <kactioncollection.h> #include <kdebug.h> #include <KoDocument.h> namespace KPlato { DocumentTreeView::DocumentTreeView( QWidget *parent ) : TreeViewBase( parent ) { // header()-><API key>( Qt::CustomContextMenu ); <API key>( true ); DocumentItemModel *m = new DocumentItemModel(); setModel( m ); setRootIsDecorated ( false ); <API key>( QAbstractItemView::SelectRows ); setSelectionMode( QAbstractItemView::SingleSelection ); createItemDelegates( m ); setAcceptDrops( true ); <API key>( true ); connect( selectionModel(), SIGNAL( selectionChanged ( const QItemSelection&, const QItemSelection& ) ), SLOT( <API key>( const QItemSelection& ) ) ); setColumnHidden( DocumentModel::Property_Status, true ); // not used atm } Document *DocumentTreeView::currentDocument() const { return model()->document( selectionModel()->currentIndex() ); } QModelIndexList DocumentTreeView::selectedRows() const { return selectionModel()->selectedRows(); } void DocumentTreeView::<API key>( const QItemSelection &selected ) { emit selectionChanged( selected.indexes() ); } QList<Document*> DocumentTreeView::selectedDocuments() const { QList<Document*> lst; foreach ( const QModelIndex &i, selectionModel()->selectedRows() ) { Document *doc = model()->document( i ); if ( doc ) { lst << doc; } } return lst; } DocumentsEditor::DocumentsEditor( KoDocument *part, QWidget *parent ) : ViewBase( part, parent ) { setupGui(); QVBoxLayout * l = new QVBoxLayout( this ); l->setMargin( 0 ); m_view = new DocumentTreeView( this ); l->addWidget( m_view ); m_view->setEditTriggers( m_view->editTriggers() | QAbstractItemView::EditKeyPressed ); connect( model(), SIGNAL( executeCommand( KUndo2Command* ) ), part, SLOT( addCommand( KUndo2Command* ) ) ); connect( m_view, SIGNAL( currentChanged( const QModelIndex &, const QModelIndex & ) ), this, SLOT( slotCurrentChanged( const QModelIndex & ) ) ); connect( m_view, SIGNAL( selectionChanged( const QModelIndexList ) ), this, SLOT( <API key>( const QModelIndexList ) ) ); connect( m_view, SIGNAL( <API key>( QModelIndex, const QPoint& ) ), this, SLOT( <API key>( QModelIndex, const QPoint& ) ) ); connect( m_view, SIGNAL( <API key>( const QPoint& ) ), SLOT( <API key>( const QPoint& ) ) ); } void DocumentsEditor::updateReadWrite( bool readwrite ) { kDebug(planDbg())<<isReadWrite()<<"->"<<readwrite; ViewBase::updateReadWrite( readwrite ); m_view->setReadWrite( readwrite ); <API key>( readwrite ); } void DocumentsEditor::draw( Documents &docs ) { m_view->setDocuments( &docs ); } void DocumentsEditor::draw() { } void DocumentsEditor::setGuiActive( bool activate ) { kDebug(planDbg())<<activate; <API key>( true ); ViewBase::setGuiActive( activate ); if ( activate && !m_view->selectionModel()->currentIndex().isValid() ) { m_view->selectionModel()->setCurrentIndex(m_view->model()->index( 0, 0 ), QItemSelectionModel::NoUpdate); } } void DocumentsEditor::<API key>( QModelIndex index, const QPoint& pos ) { //kDebug(planDbg())<<index.row()<<","<<index.column()<<":"<<pos; QString name; if ( index.isValid() ) { Document *obj = m_view->model()->document( index ); if ( obj ) { name = "<API key>"; } } emit requestPopupMenu( name, pos ); } void DocumentsEditor::<API key>( const QPoint &pos ) { kDebug(planDbg()); QList<QAction*> lst = contextActionList(); if ( ! lst.isEmpty() ) { QMenu::exec( lst, pos, lst.first() ); } } Document *DocumentsEditor::currentDocument() const { return m_view->currentDocument(); } void DocumentsEditor::slotCurrentChanged( const QModelIndex & ) { //kDebug(planDbg())<<curr.row()<<","<<curr.column(); // slotEnableActions(); } void DocumentsEditor::<API key>( const QModelIndexList list ) { kDebug(planDbg())<<list.count(); <API key>( true ); } void DocumentsEditor::slotEnableActions( bool on ) { <API key>( on ); } void DocumentsEditor::<API key>( bool on ) { QList<Document*> lst = m_view->selectedDocuments(); if ( lst.isEmpty() || lst.count() > 1 ) { actionEditDocument->setEnabled( false ); actionViewDocument->setEnabled( false ); return; } Document *doc = lst.first(); actionViewDocument->setEnabled( on ); actionEditDocument->setEnabled( on && doc->type() == Document::Type_Product && isReadWrite() ); } void DocumentsEditor::setupGui() { QString name = "<API key>"; actionEditDocument = new KAction(KIcon( "document-properties" ), i18n("Edit..."), this); actionCollection()->addAction("edit_documents", actionEditDocument ); // actionEditDocument->setShortcut( KShortcut( Qt::CTRL + Qt::SHIFT + Qt::Key_I ) ); connect( actionEditDocument, SIGNAL( triggered( bool ) ), SLOT( slotEditDocument() ) ); addAction( name, actionEditDocument ); actionViewDocument = new KAction(KIcon( "document-preview" ), i18nc("@action View a document", "View..."), this); actionCollection()->addAction("view_documents", actionViewDocument ); // actionViewDocument->setShortcut( KShortcut( Qt::CTRL + Qt::SHIFT + Qt::Key_I ) ); connect( actionViewDocument, SIGNAL( triggered( bool ) ), SLOT( slotViewDocument() ) ); addAction( name, actionViewDocument ); /* <API key> = new KAction(KIcon( "edit-delete" ), i18n("Delete"), this); actionCollection()->addAction("delete_selection", <API key> ); <API key>->setShortcut( KShortcut( Qt::Key_Delete ) ); connect( <API key>, SIGNAL( triggered( bool ) ), SLOT( slotDeleteSelection() ) ); addAction( name, <API key> );*/ // Add the context menu actions for the view options createOptionAction(); } void DocumentsEditor::slotOptions() { kDebug(planDbg()); <API key> dlg( this, m_view/*->masterView()*/ ); dlg.exec(); } void DocumentsEditor::slotEditDocument() { QList<Document*> dl = m_view->selectedDocuments(); if ( dl.isEmpty() ) { return; } kDebug(planDbg())<<dl; emit editDocument( dl.first() ); } void DocumentsEditor::slotViewDocument() { QList<Document*> dl = m_view->selectedDocuments(); if ( dl.isEmpty() ) { return; } kDebug(planDbg())<<dl; emit viewDocument( dl.first() ); } void DocumentsEditor::slotAddDocument() { //kDebug(planDbg()); QList<Document*> dl = m_view->selectedDocuments(); Document *after = 0; if ( dl.count() > 0 ) { after = dl.last(); } Document *doc = new Document(); QModelIndex i = m_view->model()->insertDocument( doc, after ); if ( i.isValid() ) { m_view->selectionModel()->setCurrentIndex( i, QItemSelectionModel::NoUpdate ); m_view->edit( i ); } } void DocumentsEditor::slotDeleteSelection() { QList<Document*> lst = m_view->selectedDocuments(); //kDebug(planDbg())<<lst.count()<<" objects"; if ( ! lst.isEmpty() ) { emit deleteDocumentList( lst ); } } bool DocumentsEditor::loadContext( const KoXmlElement &context ) { return m_view->loadContext( m_view->model()->columnMap(), context ); } void DocumentsEditor::saveContext( QDomElement &context ) const { m_view->saveContext( m_view->model()->columnMap(), context ); } } // namespace KPlato #include "kptdocumentseditor.moc"
#ifndef GRAPHICS_FX_H #define GRAPHICS_FX_H #include "video/video.h" // PlayerVisual #include "game/game_data.h" // Player #include "game/camera.h" // Camera #include "video/nebu_video_types.h" // Visual void drawImpact(int player); void drawGlow(PlayerVisual *pV, Player *pTarget, float dim); #endif
package bbcodeeditor.control.actions; import bbcodeeditor.control.Controller; import bbcodeeditor.control.SecImage; import bbcodeeditor.control.SecSmiley; /** * @author Assi Nilsmussen * */ public final class AddImageAction extends HistoryAction { /** * the image to add */ private final SecImage _image; /** * constructor * * @param con the controller of the text-field * @param start the start-position of this action * @param end the end-position of this action * @param image the image */ public AddImageAction(Controller con,int start,int end,SecImage image) { super(con,start,end); _image = image; } public void performAction() { switch(_actionType) { case UNDO: _con.removeText(_start,_end,false); _actionType = REDO; break; case REDO: _con.addImage(_image,_start); _con.goToPosition(_start + 1); _actionType = UNDO; break; } } public String getName() { String imgName; if(_image instanceof SecSmiley) imgName = "smiley '" + ((SecSmiley)_image).getPrimaryCode() + "'"; else imgName = "image"; String res; if(_actionType == UNDO) res = "Remove " + imgName; else res = "Add " + imgName; return res + " [" + _start + "," + _end + "]"; } public String toString() { return getName(); } }
<?php # Define namespace namespace WCFE\Modules\Editor\View\Editor\Templates\Tabs\Tabs; # Imports use WCFE\Modules\Editor\View\Editor\Templates\Tabs\FieldsTab; class MultiSiteOptionsTab extends FieldsTab { /** * put your comment there... * * @var mixed */ protected $<API key> = \WCFE\Hooks::<API key>; /** * put your comment there... * * @var mixed */ protected $fields = array ( 'WCFE\Modules\Editor\View\Editor\Templates\Fields' => array ( 'MultiSiteAllow', 'MultiSite', '<API key>', '<API key>', '<API key>', 'MultiSiteSiteId', 'MultiSiteBlogId', '<API key>', ) ); /** * put your comment there... * */ protected function initialize() { $this->title = $this->_( 'Multi Sites' ); $this->fields = $this->bcCreateFieldsList( $this->fields ); } }
<?php define('INCHARBROWSER', true); include_once(__DIR__ . "/include/common.php"); include_once(__DIR__ . "/include/profile.php"); include_once(__DIR__ . "/include/db.php"); //converts faction values into a the string from the language file. function FactionToString($character_value) { global $language; if($character_value >= 1101) return $language['FACTION_ALLY']; if($character_value >= 701 && $character_value <= 1100) return $language['FACTION_WARMLY']; if($character_value >= 401 && $character_value <= 700) return $language['FACTION_KINDLY']; if($character_value >= 101 && $character_value <= 400) return $language['FACTION_AMIABLE']; if($character_value >= 0 && $character_value <= 100) return $language['FACTION_INDIFF']; if($character_value >= -100 && $character_value <= -1) return $language['FACTION_APPR']; if($character_value >= -700 && $character_value <= -101) return $language['FACTION_DUBIOUS']; if($character_value >= -999 && $character_value <= -701) return $language['FACTION_THREAT']; if($character_value <= -1000) return $language['FACTION_SCOWLS']; return $language['FACTION_INDIFF']; } if(!$_GET['char']) cb_message_die($language['MESSAGE_ERROR'],$language['MESSAGE_NO_CHAR']); else $charName = $_GET['char']; //character initializations $char = new profile($charName, $cbsql, $cbsql_content, $language, $showsoftdelete, $<API key>); //the profile class will sanitize the character name $charID = $char->char_id(); $name = $char->GetValue('name'); $mypermission = GetPermissions($char->GetValue('gm'), $char->GetValue('anon'), $char->char_id()); if ($mypermission['factions']) cb_message_die($language['MESSAGE_ERROR'],$language['<API key>']); //get content factions from the content db $tpl = <<<TPL SELECT fl.id, fl.name, IFNULL(fl.base, 0) AS base, IFNULL(flmc.mod, 0) AS classmod, IFNULL(flmr.mod, 0) AS racemod, IFNULL(flmd.mod, 0) AS deitymod FROM faction_list AS fl LEFT JOIN faction_list_mod AS flmc ON fl.id = flmc.faction_id AND (flmc.mod_name = 'c%d') LEFT JOIN faction_list_mod AS flmr ON fl.id = flmr.faction_id AND (flmr.mod_name = 'r%d') LEFT JOIN faction_list_mod AS flmd ON fl.id = flmd.faction_id AND (flmd.mod_name = 'd%d') ORDER BY name ASC TPL; $query = sprintf( $tpl, $char->GetValue('class'), $char->GetValue('race'), ($char->GetValue('deity') == 396) ? "140" : $char->GetValue('deity') ); $result = $cbsql_content->query($query); $content_factions = $cbsql_content->fetch_all($result); //get the characters factions from the player db $tpl = <<<TPL SELECT current_value, faction_ID FROM faction_values WHERE char_id = '%s' TPL; $query = sprintf($tpl, $charID); $result = $cbsql->query($query); $character_factions = $cbsql->fetch_all($result); //DO A MANUAL JOIN OF THE RESULTS $joined_factions = manual_join($content_factions, 'id', $character_factions, 'faction_ID', 'left'); $d_title = " - ".$name.$language['<API key>']; include(__DIR__ . "/include/header.php"); output_profile_menu($name, 'factions'); if (!$mypermission['advfactions']) { $cb_template->set_filenames(array( 'factions' => '<API key>.tpl') ); } else { $cb_template->set_filenames(array( 'factions' => 'factions_basic_body.tpl') ); } $cb_template->assign_both_vars(array( 'NAME' => $name) ); $cb_template->assign_vars(array( 'L_FACTIONS' => $language['FACTION_FACTIONS'], 'L_NAME' => $language['FACTION_NAME'], 'L_FACTION' => $language['FACTION_FACTION'], 'L_BASE' => $language['FACTION_BASE'], 'L_CHAR' => $language['FACTION_CHAR'], 'L_CLASS' => $language['FACTION_CLASS'], 'L_RACE' => $language['FACTION_RACE'], 'L_DEITY' => $language['FACTION_DEITY'], 'L_TOTAL' => $language['FACTION_TOTAL'], 'L_DONE' => $language['BUTTON_DONE']) ); foreach($joined_factions as $faction) { $charmod = intval($faction['current_value']); $total = $faction['base'] + $charmod + $faction['classmod'] + $faction['racemod'] + $faction['deitymod']; $cb_template-><API key>("factions", array( 'ID' => $faction['id'], 'LINK' => QuickTemplate($link_faction, array('FACTION_ID' => $faction['id'])), 'NAME' => $faction['name'], 'FACTION' => FactionToString($total), 'BASE' => $faction['base'], 'CHAR' => $charmod, 'CLASS' => $faction['classmod'], 'RACE' => $faction['racemod'], 'DEITY' => $faction['deitymod'], 'TOTAL' => $total) ); } $cb_template->pparse('factions'); $cb_template->destroy; include(__DIR__ . "/include/footer.php"); ?>
var elixir = require('laravel-elixir'); var gulp = require("gulp"); require('<API key>'); var bowerDir = "public/vendor/"; var lessPaths = [ bowerDir + "bootstrap/less/" ] var templatePaths = [ "resources/assets/js/app/components/*/*.html", ]; elixir.extend("templates", function(src, base, dest) { gulp.task("templates", function () { // the base option sets the relative root for the set of files, // preserving the folder structure gulp.src(src, {base: base}) .pipe(gulp.dest(dest)); }); // Watch each glob in src for (idx in src){ var glob = src[idx]; this.registerWatcher("templates", glob); } return this.queueTask("templates"); }); elixir(function(mix) { // Complile LESS into CSS mix.less("main.less", "public/css/", {paths: lessPaths}); // Inject dependencies into layout (except bootstrap css, since that is compiled into main css) mix.wiredep({src: "master.blade.php"}, {exclude: "vendor/bootstrap/dist/css/bootstrap.css"}); // Combine app js into one file mix.scriptsIn("resources/assets/js/", "public/js/main.js"); // Copy angular templates to public folder mix.templates(templatePaths, "resources/assets/js/app/components/", "public"); });
package com.onkiup.minedroid; import com.onkiup.minedroid.gui.resources.*; import com.onkiup.minedroid.gui.MineDroid; /** * This class is auto generated. * Manually made changes will be discarded. **/ public final class R { final static String MODID = "minedroid"; public final static class id { public final static int message = 268435456; public final static int hint = 268435457; public final static int test = 268435458; public final static int text = 268435459; public final static int debug = 268435460; public final static int close = 268435461; public final static int edit = 268435462; public final static int edit_multiline = 268435463; public final static int progress = 268435464; public final static int list = 268435465; } public final static class string { public final static ValueLink cancel = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "Cancel") }); public final static ValueLink test_window = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "Minedroid Test") }); public final static ValueLink test = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "test") }); public final static ValueLink alert_hint = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "click or press Y to dismiss") }); public final static ValueLink confirm_hint = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "press Y/N to respond") }); public final static ValueLink ok = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "Ok") }); public final static ValueLink close = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "close") }); } public final static class layout { public final static ResourceLink minedroid_test = new ResourceLink(MODID, "layouts", "minedroid_test.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink alert = new ResourceLink(MODID, "layouts", "alert.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink holder_string = new ResourceLink(MODID, "layouts", "holder_string.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink config_main = new ResourceLink(MODID, "layouts", "config_main.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink confirm = new ResourceLink(MODID, "layouts", "confirm.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); } public final static class drawable { public final static ResourceLink shadow = new ResourceLink(MODID, "drawables", "shadow.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink check = new ResourceLink(MODID, "drawables", "check.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink scroll = new ResourceLink(MODID, "drawables", "scroll.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink bg_overlay = new ResourceLink(MODID, "drawables", "bg_overlay.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink bg_checkbox = new ResourceLink(MODID, "drawables", "bg_checkbox.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink fg_progress_view = new ResourceLink(MODID, "drawables", "fg_progress_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink bg_edit_text = new ResourceLink(MODID, "drawables", "bg_edit_text.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink overlay = new ResourceLink(MODID, "drawables", "overlay.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink bg_button = new ResourceLink(MODID, "drawables", "bg_button.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink bg_progress_view = new ResourceLink(MODID, "drawables", "bg_progress_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); } public final static class ninepatch { public final static ResourceLink panel = new ResourceLink(MODID, "ninepatches", "panel", new EnvParams[] { new EnvParams(null, null, null, null)}); } public final static class style { public final static Style focus = new Style(new ResourceLink(MODID, "styles", "focus.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/linear_layout"); public final static Style content_view = new Style(new ResourceLink(MODID, "styles", "content_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/view"); public final static Style relative_layout = new Style(new ResourceLink(MODID, "styles", "relative_layout.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/view_group"); public final static Style checkbox = new Style(new ResourceLink(MODID, "styles", "checkbox.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view"); public final static Style entity_view = new Style(new ResourceLink(MODID, "styles", "entity_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view"); public final static Style edit_text = new Style(new ResourceLink(MODID, "styles", "edit_text.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/text_view"); public final static Style view_group = new Style(new ResourceLink(MODID, "styles", "view_group.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view"); public final static Style scroll_view = new Style(new ResourceLink(MODID, "styles", "scroll_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view"); public final static Style overlay = new Style(new ResourceLink(MODID, "styles", "overlay.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class); public final static Style progress_view = new Style(new ResourceLink(MODID, "styles", "progress_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view"); public final static Style text = new Style(new ResourceLink(MODID, "styles", "text.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class); public final static Style theme = new Style(new ResourceLink(MODID, "styles", "theme.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class); public final static Style text_view = new Style(new ResourceLink(MODID, "styles", "text_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view"); public final static Style list_view = new Style(new ResourceLink(MODID, "styles", "list_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/linear_layout"); public final static Style button = new Style(new ResourceLink(MODID, "styles", "button.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/text_view"); public final static Style view = new Style(new ResourceLink(MODID, "styles", "view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class); public final static Style linear_layout = new Style(new ResourceLink(MODID, "styles", "linear_layout.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/view_group"); } }
package thesis; import java.io.File; import java.io.<API key>; import java.io.PrintWriter; import java.io.<API key>; import termo.component.Compound; import termo.eos.Cubic; import termo.eos.EquationsOfState; import termo.eos.alpha.Alphas; import termo.matter.Mixture; import termo.matter.Substance; import termo.phase.Phase; import compounds.CompoundReader; public class CubicFileGenerator extends FileGenerator { Substance substance; public CubicFileGenerator(){ CompoundReader reader = new CompoundReader(); Compound heptane = reader.<API key>("N-heptane"); substance = new Substance(EquationsOfState.vanDerWaals() ,Alphas.<API key>() ,heptane,Phase.VAPOR); } public void <API key>(String fileName) throws <API key>, <API key>{ PrintWriter writer = new PrintWriter(fileName, "UTF-8"); writer.println(" Volumen Presion Temperatura"); double min_volume = 0.245; double max_volume = 1.2; int n = 60; double pass = (max_volume- min_volume)/n; int nt =20; double min_temperature = 150; double max_temperature = 400; double tempPass = (max_temperature - min_temperature)/nt; for(int j = 0; j < nt; j++){ double temperature = min_temperature + tempPass *j ; for(int i=0;i < n; i++){ double volume = min_volume + pass*i; double pressure = calculatePressure(volume, temperature); writer.println(" "+ volume + " " + temperature + " " + pressure); } writer.println(); } writer.close(); } public double calculatePressure(double volume, double temperature){ return substance.calculatePressure(temperature,volume); //parametros de van der waals para el heptano // double a = 3107000.0; //double b = 0.2049; // return cubic.calculatePressure(temperature, volume,a,b); } public void <API key>(String fileName) throws <API key>, <API key>{ PrintWriter writer = new PrintWriter(fileName, "UTF-8"); writer.println(" Volumen Presion"); double min_volume = 0.245; double max_volume = 1.2; int n = 100; double pass = (max_volume- min_volume)/n; for(int i=0;i < n; i++){ double volume = min_volume + pass*i; double pressure =calculatePressure(volume, 300); writer.println(" "+ volume + " " + pressure); } writer.close(); } public void <API key>(String folderName) throws <API key>, <API key>{ File directory = new File(folderName); if(!directory.exists()){ directory.mkdir(); } Cubic cubic = EquationsOfState.vanDerWaals(); double min_reducedPressure = 0.1; double max_reducedPressure= 7; double pressurepass =( max_reducedPressure- min_reducedPressure)/ 100; double <API key>= 1 ; double <API key>=2; double criticalTemperature = 540.2; double criticalPressure = 2.74000E+06; double a = 3107000.0; double b = 0.2049; PrintWriter writer= new PrintWriter(folderName + "pz_temp.dat", "UTF-8"); writer.println(" p z rt"); for(double reducedTemperature = <API key>; reducedTemperature <= <API key>; reducedTemperature +=0.1){ for(double reducedPressure = min_reducedPressure ; reducedPressure <= max_reducedPressure; reducedPressure+= pressurepass){ double temperature = criticalTemperature * reducedTemperature; double pressure = criticalPressure * reducedPressure; // double A =cubic.get_A(temperature, pressure, a); // double B = cubic.get_B(temperature, pressure, b); substance.setPressure(pressure); substance.setTemperature(temperature); double z = substance.<API key>(); //double z =cubic.<API key>(A, B, Phase.LIQUID); writer.println(" " + reducedPressure + " " + z + " " + reducedTemperature); } writer.println(); } writer.close(); } }
#include <QHBoxLayout> #include <QKeyEvent> #include <QLineEdit> #include <QMenu> #include <QPushButton> #include <QMdiArea> #include <QMdiSubWindow> #include "FileBrowser.h" #include "BBTrackContainer.h" #include "ConfigManager.h" #include "debug.h" #include "embed.h" #include "Engine.h" #include "gui_templates.h" #include "ImportFilter.h" #include "Instrument.h" #include "InstrumentTrack.h" #include "MainWindow.h" #include "DataFile.h" #include "<API key>.h" #include "SamplePlayHandle.h" #include "Song.h" #include "StringPairDrag.h" #include "TextFloat.h" enum TreeWidgetItemTypes { TypeFileItem = QTreeWidgetItem::UserType, TypeDirectoryItem } ; FileBrowser::FileBrowser(const QString & directories, const QString & filter, const QString & title, const QPixmap & pm, QWidget * parent, bool dirs_as_items ) : SideBarWidget( title, pm, parent ), m_directories( directories ), m_filter( filter ), m_dirsAsItems( dirs_as_items ) { setWindowTitle( tr( "Browser" ) ); m_l = new <API key>( contentParent() ); addContentWidget( m_l ); QWidget * ops = new QWidget( contentParent() ); ops->setFixedHeight( 24 ); QHBoxLayout * opl = new QHBoxLayout( ops ); opl->setMargin( 0 ); opl->setSpacing( 0 ); m_filterEdit = new QLineEdit( ops ); connect( m_filterEdit, SIGNAL( textEdited( const QString & ) ), this, SLOT( filterItems( const QString & ) ) ); QPushButton * reload_btn = new QPushButton( embed::getIconPixmap( "reload" ), QString::null, ops ); connect( reload_btn, SIGNAL( clicked() ), this, SLOT( reloadTree() ) ); opl->addWidget( m_filterEdit ); opl->addSpacing( 5 ); opl->addWidget( reload_btn ); addContentWidget( ops ); reloadTree(); show(); } FileBrowser::~FileBrowser() { } void FileBrowser::filterItems( const QString & filter ) { const bool show_all = filter.isEmpty(); for( int i = 0; i < m_l->topLevelItemCount(); ++i ) { QTreeWidgetItem * it = m_l->topLevelItem( i ); // show all items if filter is empty if( show_all ) { it->setHidden( false ); if( it->childCount() ) { filterItems( it, filter ); } } // is directory? else if( it->childCount() ) { // matches filter? if( it->text( 0 ). contains( filter, Qt::CaseInsensitive ) ) { // yes, then show everything below it->setHidden( false ); filterItems( it, QString::null ); } else { // only show if item below matches filter it->setHidden( !filterItems( it, filter ) ); } } // a standard item (i.e. no file or directory item?) else if( it->type() == QTreeWidgetItem::Type ) { // hide in every case when filtering it->setHidden( true ); } else { // file matches filter? it->setHidden( !it->text( 0 ). contains( filter, Qt::CaseInsensitive ) ); } } } bool FileBrowser::filterItems(QTreeWidgetItem * item, const QString & filter ) { const bool show_all = filter.isEmpty(); bool matched = false; for( int i = 0; i < item->childCount(); ++i ) { QTreeWidgetItem * it = item->child( i ); bool cm = false; // whether current item matched // show all items if filter is empty if( show_all ) { it->setHidden( false ); if( it->childCount() ) { filterItems( it, filter ); } } // is directory? else if( it->childCount() ) { // matches filter? if( it->text( 0 ). contains( filter, Qt::CaseInsensitive ) ) { // yes, then show everything below it->setHidden( false ); filterItems( it, QString::null ); cm = true; } else { // only show if item below matches filter cm = filterItems( it, filter ); it->setHidden( !cm ); } } // a standard item (i.e. no file or directory item?) else if( it->type() == QTreeWidgetItem::Type ) { // hide in every case when filtering it->setHidden( true ); } else { // file matches filter? cm = it->text( 0 ). contains( filter, Qt::CaseInsensitive ); it->setHidden( !cm ); } if( cm ) { matched = true; } } return matched; } void FileBrowser::reloadTree( void ) { const QString text = m_filterEdit->text(); m_filterEdit->clear(); m_l->clear(); QStringList paths = m_directories.split( '*' ); for( QStringList::iterator it = paths.begin(); it != paths.end(); ++it ) { addItems( *it ); } m_filterEdit->setText( text ); filterItems( text ); } void FileBrowser::addItems(const QString & path ) { if( m_dirsAsItems ) { m_l->addTopLevelItem( new Directory( path, QString::null, m_filter ) ); return; } QDir cdir( path ); QStringList files = cdir.entryList( QDir::Dirs, QDir::Name ); for( QStringList::const_iterator it = files.constBegin(); it != files.constEnd(); ++it ) { QString cur_file = *it; if( cur_file[0] != '.' ) { bool orphan = true; for( int i = 0; i < m_l->topLevelItemCount(); ++i ) { Directory * d = dynamic_cast<Directory *>( m_l->topLevelItem( i ) ); if( d == NULL || cur_file < d->text( 0 ) ) { m_l->insertTopLevelItem( i, new Directory( cur_file, path, m_filter ) ); orphan = false; break; } else if( cur_file == d->text( 0 ) ) { d->addDirectory( path ); orphan = false; break; } } if( orphan ) { m_l->addTopLevelItem( new Directory( cur_file, path, m_filter ) ); } } } files = cdir.entryList( QDir::Files, QDir::Name ); for( QStringList::const_iterator it = files.constBegin(); it != files.constEnd(); ++it ) { QString cur_file = *it; if( cur_file[0] != '.' ) { // TODO: don't insert instead of removing, order changed // remove existing file-items QList<QTreeWidgetItem *> existing = m_l->findItems( cur_file, Qt::MatchFixedString ); if( !existing.empty() ) { delete existing.front(); } (void) new FileItem( m_l, cur_file, path ); } } } void FileBrowser::keyPressEvent(QKeyEvent * ke ) { if( ke->key() == Qt::Key_F5 ) { reloadTree(); } else { ke->ignore(); } } <API key>::<API key>(QWidget * parent ) : QTreeWidget( parent ), m_mousePressed( false ), m_pressPos(), m_previewPlayHandle( NULL ), m_pphMutex( QMutex::Recursive ), m_contextMenuItem( NULL ) { setColumnCount( 1 ); headerItem()->setHidden( true ); setSortingEnabled( false ); setFont( pointSizeF( font(), 7.5f ) ); connect( this, SIGNAL( itemDoubleClicked( QTreeWidgetItem *, int ) ), SLOT( activateListItem( QTreeWidgetItem *, int ) ) ); connect( this, SIGNAL( itemCollapsed( QTreeWidgetItem * ) ), SLOT( updateDirectory( QTreeWidgetItem * ) ) ); connect( this, SIGNAL( itemExpanded( QTreeWidgetItem * ) ), SLOT( updateDirectory( QTreeWidgetItem * ) ) ); } <API key>::~<API key>() { } void <API key>::contextMenuEvent(QContextMenuEvent * e ) { FileItem * f = dynamic_cast<FileItem *>( itemAt( e->pos() ) ); if( f != NULL && ( f->handling() == FileItem::LoadAsPreset || f->handling() == FileItem::LoadByPlugin ) ) { m_contextMenuItem = f; QMenu contextMenu( this ); contextMenu.addAction( tr( "Send to active instrument-track" ), this, SLOT( <API key>() ) ); contextMenu.addAction( tr( "Open in new instrument-track/" "Song-Editor" ), this, SLOT( <API key>() ) ); contextMenu.addAction( tr( "Open in new instrument-track/" "B+B Editor" ), this, SLOT( <API key>() ) ); contextMenu.exec( e->globalPos() ); m_contextMenuItem = NULL; } } void <API key>::mousePressEvent(QMouseEvent * me ) { QTreeWidget::mousePressEvent( me ); if( me->button() != Qt::LeftButton ) { return; } QTreeWidgetItem * i = itemAt( me->pos() ); if ( i ) { // TODO: Restrict to visible selection // if ( _me->x() > header()->cellPos( header()->mapToActual( 0 ) ) // + treeStepSize() * ( i->depth() + ( rootIsDecorated() ? // 1 : 0 ) ) + itemMargin() || // _me->x() < header()->cellPos( // header()->mapToActual( 0 ) ) ) m_pressPos = me->pos(); m_mousePressed = true; } FileItem * f = dynamic_cast<FileItem *>( i ); if( f != NULL ) { m_pphMutex.lock(); if( m_previewPlayHandle != NULL ) { Engine::mixer()->removePlayHandle( m_previewPlayHandle ); m_previewPlayHandle = NULL; } // in special case of sample-files we do not care about // handling() rather than directly creating a SamplePlayHandle if( f->type() == FileItem::SampleFile ) { TextFloat * tf = TextFloat::displayMessage( tr( "Loading sample" ), tr( "Please wait, loading sample for " "preview..." ), embed::getIconPixmap( "sample_file", 24, 24 ), 0 ); qApp->processEvents( QEventLoop::<API key> ); SamplePlayHandle * s = new SamplePlayHandle( f->fullName() ); s-><API key>( false ); m_previewPlayHandle = s; delete tf; } else if( f->type() != FileItem::VstPluginFile && ( f->handling() == FileItem::LoadAsPreset || f->handling() == FileItem::LoadByPlugin ) ) { m_previewPlayHandle = new <API key>( f->fullName(), f->handling() == FileItem::LoadByPlugin ); } if( m_previewPlayHandle != NULL ) { if( !Engine::mixer()->addPlayHandle( m_previewPlayHandle ) ) { m_previewPlayHandle = NULL; } } m_pphMutex.unlock(); } } void <API key>::mouseMoveEvent( QMouseEvent * me ) { if( m_mousePressed == true && ( m_pressPos - me->pos() ).manhattanLength() > QApplication::startDragDistance() ) { // make sure any playback is stopped mouseReleaseEvent( NULL ); FileItem * f = dynamic_cast<FileItem *>( itemAt( m_pressPos ) ); if( f != NULL ) { switch( f->type() ) { case FileItem::PresetFile: new StringPairDrag( f->handling() == FileItem::LoadAsPreset ? "presetfile" : "pluginpresetfile", f->fullName(), embed::getIconPixmap( "preset_file" ), this ); break; case FileItem::SampleFile: new StringPairDrag( "samplefile", f->fullName(), embed::getIconPixmap( "sample_file" ), this ); break; case FileItem::SoundFontFile: new StringPairDrag( "soundfontfile", f->fullName(), embed::getIconPixmap( "soundfont_file" ), this ); break; case FileItem::VstPluginFile: new StringPairDrag( "vstpluginfile", f->fullName(), embed::getIconPixmap( "vst_plugin_file" ), this ); break; case FileItem::MidiFile: // don't allow dragging FLP-files as FLP import filter clears project // without asking // case fileItem::FlpFile: new StringPairDrag( "importedproject", f->fullName(), embed::getIconPixmap( "midi_file" ), this ); break; default: break; } } } } void <API key>::mouseReleaseEvent(QMouseEvent * me ) { m_mousePressed = false; m_pphMutex.lock(); if( m_previewPlayHandle != NULL ) { // if there're samples shorter than 3 seconds, we don't // stop them if the user releases mouse-button... if( m_previewPlayHandle->type() == PlayHandle::<API key> ) { SamplePlayHandle * s = dynamic_cast<SamplePlayHandle *>( m_previewPlayHandle ); if( s && s->totalFrames() - s->framesDone() <= static_cast<f_cnt_t>( Engine::mixer()-> <API key>() * 3 ) ) { s-><API key>( true ); m_previewPlayHandle = NULL; m_pphMutex.unlock(); return; } } Engine::mixer()->removePlayHandle( m_previewPlayHandle ); m_previewPlayHandle = NULL; } m_pphMutex.unlock(); } void <API key>::handleFile(FileItem * f, InstrumentTrack * it ) { Engine::mixer()->lock(); switch( f->handling() ) { case FileItem::LoadAsProject: if( Engine::mainWindow()->mayChangeProject() ) { Engine::getSong()->loadProject( f->fullName() ); } break; case FileItem::LoadByPlugin: { const QString e = f->extension(); Instrument * i = it->instrument(); if( i == NULL || !i->descriptor()->supportsFileType( e ) ) { i = it->loadInstrument( Engine::pluginFileHandling()[e] ); } i->loadFile( f->fullName() ); break; } case FileItem::LoadAsPreset: { DataFile dataFile( f->fullName() ); InstrumentTrack::removeMidiPortNode( dataFile ); it-><API key>(); it->loadSettings( dataFile.content().toElement() ); break; } case FileItem::ImportAsProject: if( f->type() == FileItem::FlpFile && !Engine::mainWindow()->mayChangeProject() ) { break; } ImportFilter::import( f->fullName(), Engine::getSong() ); break; case FileItem::NotSupported: default: break; } Engine::mixer()->unlock(); } void <API key>::activateListItem(QTreeWidgetItem * item, int column ) { FileItem * f = dynamic_cast<FileItem *>( item ); if( f == NULL ) { return; } if( f->handling() == FileItem::LoadAsProject || f->handling() == FileItem::ImportAsProject ) { handleFile( f, NULL ); } else if( f->handling() != FileItem::NotSupported ) { // engine::mixer()->lock(); InstrumentTrack * it = dynamic_cast<InstrumentTrack *>( Track::create( Track::InstrumentTrack, Engine::getBBTrackContainer() ) ); handleFile( f, it ); // engine::mixer()->unlock(); } } void <API key>::<API key>( TrackContainer* tc ) { if( m_contextMenuItem->handling() == FileItem::LoadAsPreset || m_contextMenuItem->handling() == FileItem::LoadByPlugin ) { // engine::mixer()->lock(); InstrumentTrack * it = dynamic_cast<InstrumentTrack *>( Track::create( Track::InstrumentTrack, tc ) ); handleFile( m_contextMenuItem, it ); // engine::mixer()->unlock(); } } void <API key>::<API key>( void ) { <API key>( Engine::getBBTrackContainer() ); } void <API key>::<API key>( void ) { <API key>( Engine::getSong() ); } void <API key>::<API key>( void ) { // get all windows opened in the workspace QList<QMdiSubWindow*> pl = Engine::mainWindow()->workspace()-> subWindowList( QMdiArea::StackingOrder ); QListIterator<QMdiSubWindow *> w( pl ); w.toBack(); // now we travel through the window-list until we find an // instrument-track while( w.hasPrevious() ) { <API key> * itw = dynamic_cast<<API key> *>( w.previous()->widget() ); if( itw != NULL && itw->isHidden() == false ) { handleFile( m_contextMenuItem, itw->model() ); break; } } } void <API key>::updateDirectory(QTreeWidgetItem * item ) { Directory * dir = dynamic_cast<Directory *>( item ); if( dir != NULL ) { dir->update(); } } QPixmap * Directory::s_folderPixmap = NULL; QPixmap * Directory::<API key> = NULL; QPixmap * Directory::<API key> = NULL; Directory::Directory(const QString & filename, const QString & path, const QString & filter ) : QTreeWidgetItem( QStringList( filename ), TypeDirectoryItem ), m_directories( path ), m_filter( filter ) { initPixmaps(); <API key>( QTreeWidgetItem::ShowIndicator ); if( !QDir( fullName() ).isReadable() ) { setIcon( 0, *<API key> ); } else { setIcon( 0, *s_folderPixmap ); } } void Directory::initPixmaps( void ) { if( s_folderPixmap == NULL ) { s_folderPixmap = new QPixmap( embed::getIconPixmap( "folder" ) ); } if( <API key> == NULL ) { <API key> = new QPixmap( embed::getIconPixmap( "folder_opened" ) ); } if( <API key> == NULL ) { <API key> = new QPixmap( embed::getIconPixmap( "folder_locked" ) ); } } void Directory::update( void ) { if( !isExpanded() ) { setIcon( 0, *s_folderPixmap ); return; } setIcon( 0, *<API key> ); if( !childCount() ) { for( QStringList::iterator it = m_directories.begin(); it != m_directories.end(); ++it ) { int top_index = childCount(); if( addItems( fullName( *it ) ) && ( *it ).contains( ConfigManager::inst()->dataDir() ) ) { QTreeWidgetItem * sep = new QTreeWidgetItem; sep->setText( 0, <API key>::tr( " sep->setIcon( 0, embed::getIconPixmap( "factory_files" ) ); insertChild( top_index, sep ); } } } } bool Directory::addItems(const QString & path ) { QDir thisDir( path ); if( !thisDir.isReadable() ) { return false; } treeWidget()->setUpdatesEnabled( false ); bool added_something = false; QStringList files = thisDir.entryList( QDir::Dirs, QDir::Name ); for( QStringList::const_iterator it = files.constBegin(); it != files.constEnd(); ++it ) { QString cur_file = *it; if( cur_file[0] != '.' ) { bool orphan = true; for( int i = 0; i < childCount(); ++i ) { Directory * d = dynamic_cast<Directory *>( child( i ) ); if( d == NULL || cur_file < d->text( 0 ) ) { insertChild( i, new Directory( cur_file, path, m_filter ) ); orphan = false; break; } else if( cur_file == d->text( 0 ) ) { d->addDirectory( path ); orphan = false; break; } } if( orphan ) { addChild( new Directory( cur_file, path, m_filter ) ); } added_something = true; } } QList<QTreeWidgetItem*> items; files = thisDir.entryList( QDir::Files, QDir::Name ); for( QStringList::const_iterator it = files.constBegin(); it != files.constEnd(); ++it ) { QString cur_file = *it; if( cur_file[0] != '.' && thisDir.match( m_filter, cur_file.toLower() ) ) { items << new FileItem( cur_file, path ); added_something = true; } } addChildren( items ); treeWidget()->setUpdatesEnabled( true ); return added_something; } QPixmap * FileItem::s_projectFilePixmap = NULL; QPixmap * FileItem::s_presetFilePixmap = NULL; QPixmap * FileItem::s_sampleFilePixmap = NULL; QPixmap * FileItem::<API key> = NULL; QPixmap * FileItem::<API key> = NULL; QPixmap * FileItem::s_midiFilePixmap = NULL; QPixmap * FileItem::s_flpFilePixmap = NULL; QPixmap * FileItem::s_unknownFilePixmap = NULL; FileItem::FileItem(QTreeWidget * parent, const QString & name, const QString & path ) : QTreeWidgetItem( parent, QStringList( name) , TypeFileItem ), m_path( path ) { determineFileType(); initPixmaps(); } FileItem::FileItem(const QString & name, const QString & path ) : QTreeWidgetItem( QStringList( name ), TypeFileItem ), m_path( path ) { determineFileType(); initPixmaps(); } void FileItem::initPixmaps( void ) { if( s_projectFilePixmap == NULL ) { s_projectFilePixmap = new QPixmap( embed::getIconPixmap( "project_file", 16, 16 ) ); } if( s_presetFilePixmap == NULL ) { s_presetFilePixmap = new QPixmap( embed::getIconPixmap( "preset_file", 16, 16 ) ); } if( s_sampleFilePixmap == NULL ) { s_sampleFilePixmap = new QPixmap( embed::getIconPixmap( "sample_file", 16, 16 ) ); } if ( <API key> == NULL ) { <API key> = new QPixmap( embed::getIconPixmap( "soundfont_file", 16, 16 ) ); } if ( <API key> == NULL ) { <API key> = new QPixmap( embed::getIconPixmap( "vst_plugin_file", 16, 16 ) ); } if( s_midiFilePixmap == NULL ) { s_midiFilePixmap = new QPixmap( embed::getIconPixmap( "midi_file", 16, 16 ) ); } if( s_flpFilePixmap == NULL ) { s_flpFilePixmap = new QPixmap( embed::getIconPixmap( "midi_file", 16, 16 ) ); } if( s_unknownFilePixmap == NULL ) { s_unknownFilePixmap = new QPixmap( embed::getIconPixmap( "unknown_file" ) ); } switch( m_type ) { case ProjectFile: setIcon( 0, *s_projectFilePixmap ); break; case PresetFile: setIcon( 0, *s_presetFilePixmap ); break; case SoundFontFile: setIcon( 0, *<API key> ); break; case VstPluginFile: setIcon( 0, *<API key> ); break; case SampleFile: case PatchFile: // TODO setIcon( 0, *s_sampleFilePixmap ); break; case MidiFile: setIcon( 0, *s_midiFilePixmap ); break; case FlpFile: setIcon( 0, *s_flpFilePixmap ); break; case UnknownFile: default: setIcon( 0, *s_unknownFilePixmap ); break; } } void FileItem::determineFileType( void ) { m_handling = NotSupported; const QString ext = extension(); if( ext == "mmp" || ext == "mpt" || ext == "mmpz" ) { m_type = ProjectFile; m_handling = LoadAsProject; } else if( ext == "xpf" || ext == "xml" ) { m_type = PresetFile; m_handling = LoadAsPreset; } else if( ext == "xiz" && Engine::pluginFileHandling().contains( ext ) ) { m_type = PresetFile; m_handling = LoadByPlugin; } else if( ext == "sf2" ) { m_type = SoundFontFile; } else if( ext == "pat" ) { m_type = PatchFile; } else if( ext == "mid" ) { m_type = MidiFile; m_handling = ImportAsProject; } else if( ext == "flp" ) { m_type = FlpFile; m_handling = ImportAsProject; } else if( ext == "dll" ) { m_type = VstPluginFile; m_handling = LoadByPlugin; } else { m_type = UnknownFile; } if( m_handling == NotSupported && !ext.isEmpty() && Engine::pluginFileHandling().contains( ext ) ) { m_handling = LoadByPlugin; // classify as sample if not classified by anything yet but can // be handled by a certain plugin if( m_type == UnknownFile ) { m_type = SampleFile; } } } QString FileItem::extension( void ) { return extension( fullName() ); } QString FileItem::extension(const QString & file ) { return QFileInfo( file ).suffix().toLower(); }
#include "gprocess.h" #include "misc.h" #include "messages.h" #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <time.h> #include <sys/resource.h> #include <sys/wait.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> #include <signal.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <pwd.h> #include <grp.h> #if ENABLE_LINUX_CAPS # include <sys/capability.h> # include <sys/prctl.h> #endif /* * NOTES: * * * pidfile is created and removed by the daemon (e.g. the child) itself, * the parent does not touch that * * * we communicate with the user using stderr (using fprintf) as long as it * is available and using syslog() afterwards * * * there are 3 processes involved in safe_background mode (e.g. auto-restart) * - startup process which was started by the user (zorpctl) * - supervisor process which automatically restarts the daemon when it exits abnormally * - daemon processes which perform the actual task at hand * * The startup process delivers the result of the first startup to its * caller, if we can deliver a failure in this case then restarts will not * be performed (e.g. if the first startup fails, the daemon will not be * restarted even if auto-restart was enabled). After the first successful * start, the startup process exits (delivering that startup was * successful) and the supervisor process wait()s for the daemon processes * to exit. If they exit prematurely (e.g. they crash) they will be * restarted, if the startup is not successful in this case the restart * will be attempted again just as if they crashed. * * The processes communicate with two pairs of pipes, startup_result_pipe * is used to indicate success/failure to the startup process, * init_result_pipe (as in "initialization") is used to deliver success * reports from the daemon to the supervisor. */ typedef enum { G_PK_STARTUP, G_PK_SUPERVISOR, G_PK_DAEMON, } GProcessKind; #define <API key> 64 #define <API key> PATH_PREFIX "/sbin/syslog-ng-failure" /* pipe used to deliver the initialization result to the calling process */ static gint startup_result_pipe[2] = { -1, -1 }; /* pipe used to deliver initialization result to the supervisor */ static gint init_result_pipe[2] = { -1, -1 }; static GProcessKind process_kind = G_PK_STARTUP; static gboolean stderr_present = TRUE; /* global variables */ static struct { GProcessMode mode; const gchar *name; const gchar *user; gint uid; const gchar *group; gint gid; const gchar *chroot_dir; const gchar *pidfile; const gchar *pidfile_dir; const gchar *cwd; const gchar *caps; gint argc; gchar **argv; gchar *argv_start; size_t argv_env_len; gchar *argv_orig; gboolean core; gint fd_limit_min; gint check_period; gboolean (*check_fn)(void); } process_opts = { .mode = <API key>, .argc = 0, .argv = NULL, .argv_start = NULL, .argv_env_len = 0, #ifdef __CYGWIN__ .fd_limit_min = 256, #else .fd_limit_min = 4096, #endif .check_period = -1, .check_fn = NULL, .uid = -1, .gid = -1 }; #if ENABLE_LINUX_CAPS /** * <API key>: * @capability: capability to turn off or on * @onoff: specifies whether the capability should be enabled or disabled * * This function modifies the current permitted set of capabilities by * enabling or disabling the capability specified in @capability. * * Returns: whether the operation was successful. **/ gboolean <API key>(int capability, int onoff) { cap_t caps; if (!process_opts.caps) return TRUE; caps = cap_get_proc(); if (!caps) return FALSE; if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &capability, onoff) == -1) { msg_error("Error managing capability set, cap_set_flag returned an error", evt_tag_errno("error", errno), NULL); cap_free(caps); return FALSE; } if (cap_set_proc(caps) == -1) { gchar *cap_text; cap_text = cap_to_text(caps, NULL); msg_error("Error managing capability set, cap_set_proc returned an error", evt_tag_str("caps", cap_text), evt_tag_errno("error", errno), NULL); cap_free(cap_text); cap_free(caps); return FALSE; } cap_free(caps); return TRUE; } /** * g_process_cap_save: * * Save the set of current capabilities and return it. The caller might * restore the saved set of capabilities by using cap_restore(). * * Returns: the current set of capabilities **/ cap_t g_process_cap_save(void) { if (!process_opts.caps) return NULL; return cap_get_proc(); } /** * cap_restore: * @r: capability set saved by cap_save() * * Restore the set of current capabilities specified by @r. * * Returns: whether the operation was successful. **/ void <API key>(cap_t r) { gboolean rc; if (!process_opts.caps) return; rc = cap_set_proc(r) != -1; cap_free(r); if (!rc) { gchar *cap_text; cap_text = cap_to_text(r, NULL); msg_error("Error managing capability set, cap_set_proc returned an error", evt_tag_str("caps", cap_text), evt_tag_errno("error", errno), NULL); cap_free(cap_text); return; } return; } #endif /** * g_process_set_mode: * @mode: an element from ZProcessMode * * This function should be called by the daemon to set the processing mode * as specified by @mode. **/ void g_process_set_mode(GProcessMode mode) { process_opts.mode = mode; } /** * g_process_set_name: * @name: the name of the process to be reported as program name * * This function should be called by the daemon to set the program name * which is present in various error message and might influence the PID * file if not overridden by <API key>(). **/ void g_process_set_name(const gchar *name) { process_opts.name = name; } /** * g_process_set_user: * @user: the name of the user the process should switch to during startup * * This function should be called by the daemon to set the user name. **/ void g_process_set_user(const gchar *user) { if (!process_opts.user) process_opts.user = user; } /** * g_process_set_group: * @group: the name of the group the process should switch to during startup * * This function should be called by the daemon to set the group name. **/ void g_process_set_group(const gchar *group) { if (!process_opts.group) process_opts.group = group; } /** * <API key>: * @chroot_dir: the name of the chroot directory the process should switch to during startup * * This function should be called by the daemon to set the chroot directory **/ void <API key>(const gchar *chroot_dir) { if (!process_opts.chroot_dir) process_opts.chroot_dir = chroot_dir; } /** * <API key>: * @pidfile: the name of the complete pid file with full path * * This function should be called by the daemon to set the PID file name to * store the pid of the process. This value will be used as the pidfile * directly, neither name nor pidfile_dir influences the pidfile location if * this is set. **/ void <API key>(const gchar *pidfile) { if (!process_opts.pidfile) process_opts.pidfile = pidfile; } /** * <API key>: * @pidfile_dir: name of the pidfile directory * * This function should be called by the daemon to set the PID file * directory. This value is not used if set_pidfile() was called. **/ void <API key>(const gchar *pidfile_dir) { if (!process_opts.pidfile_dir) process_opts.pidfile_dir = pidfile_dir; } /** * <API key>: * @working_dir: name of the working directory * * This function should be called by the daemon to set the working * directory. The process will change its current directory to this value or * to pidfile_dir if it is unset. **/ void <API key>(const gchar *cwd) { if (!process_opts.cwd) process_opts.cwd = cwd; } void g_process_set_caps(const gchar *caps) { if (!process_opts.caps) process_opts.caps = caps; } /** * <API key>: * @argc: Original argc, as received by the main function in it's first parameter * @argv: Original argv, as received by the main function in it's second parameter * * This function should be called by the daemon if it wants to enable * process title manipulation in the supervisor process. **/ void <API key>(gint argc, gchar **argv) { extern char **environ; gchar *lastargv = NULL; gchar **envp = environ; gint i; if (process_opts.argv) return; process_opts.argv = argv; process_opts.argc = argc; for (i = 0; envp[i] != NULL; i++) ; environ = g_new(char *, i + 1); /* * Find the last argv string or environment variable within * our process memory area. */ for (i = 0; i < process_opts.argc; i++) { if (lastargv == NULL || lastargv + 1 == process_opts.argv[i]) lastargv = process_opts.argv[i] + strlen(process_opts.argv[i]); } for (i = 0; envp[i] != NULL; i++) { if (lastargv + 1 == envp[i]) lastargv = envp[i] + strlen(envp[i]); } process_opts.argv_start = process_opts.argv[0]; process_opts.argv_env_len = lastargv - process_opts.argv[0] - 1; process_opts.argv_orig = malloc(sizeof(gchar) * process_opts.argv_env_len); memcpy(process_opts.argv_orig, process_opts.argv_start, process_opts.argv_env_len); /* * Copy environment * XXX - will truncate env on strdup fail */ for (i = 0; envp[i] != NULL; i++) environ[i] = g_strdup(envp[i]); environ[i] = NULL; } /** * g_process_set_check: * @check_period: check period in seconds * @check_fn: checker function * * Installs a checker function that is called at the specified rate. * The checked process is allowed to run as long as this function * returns TRUE. */ void g_process_set_check(gint check_period, gboolean (*check_fn)(void)) { process_opts.check_period = check_period; process_opts.check_fn = check_fn; } /** * g_process_message: * @fmt: format string * @...: arguments to @fmt * * This function sends a message to the client preferring to use the stderr * channel as long as it is available and switching to using syslog() if it * isn't. Generally the stderr channell will be available in the startup * process and in the beginning of the first startup in the * supervisor/daemon processes. Later on the stderr fd will be closed and we * have to fall back to using the system log. **/ void g_process_message(const gchar *fmt, ...) { gchar buf[2048]; va_list ap; va_start(ap, fmt); g_vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); if (stderr_present) fprintf(stderr, "%s: %s\n", process_opts.name, buf); else { gchar name[32]; g_snprintf(name, sizeof(name), "%s/%s", process_kind == G_PK_SUPERVISOR ? "supervise" : "daemon", process_opts.name); openlog(name, LOG_PID, LOG_DAEMON); syslog(LOG_CRIT, "%s\n", buf); closelog(); } } /** * <API key>: * * This function is called from g_process_start() to detach from the * controlling tty. **/ static void <API key>(void) { if (process_opts.mode != G_PM_FOREGROUND) { /* detach ourselves from the tty when not staying in the foreground */ if (isatty(STDIN_FILENO)) { #ifdef TIOCNOTTY ioctl(STDIN_FILENO, TIOCNOTTY, 0); #endif setsid(); } } } /** * <API key>: * * Set fd limit. * **/ static void <API key>(void) { struct rlimit limit; limit.rlim_cur = limit.rlim_max = process_opts.fd_limit_min; if (setrlimit(RLIMIT_NOFILE, &limit) < 0) g_process_message("Error setting file number limit; limit='%d'; error='%s'", process_opts.fd_limit_min, g_strerror(errno)); } /** * <API key>: * * Use /dev/null as input/output/error. This function is idempotent, can be * called any number of times without harm. **/ static void <API key>(void) { gint devnull_fd; if (process_opts.mode != G_PM_FOREGROUND && stderr_present) { devnull_fd = open("/dev/null", O_RDONLY); if (devnull_fd >= 0) { dup2(devnull_fd, STDIN_FILENO); close(devnull_fd); } devnull_fd = open("/dev/null", O_WRONLY); if (devnull_fd >= 0) { dup2(devnull_fd, STDOUT_FILENO); dup2(devnull_fd, STDERR_FILENO); close(devnull_fd); } stderr_present = FALSE; } } /** * <API key>: * * Enable core file dumping by setting PR_DUMPABLE and changing the core * file limit to infinity. **/ static void <API key>(void) { struct rlimit limit; if (process_opts.core) { #if ENABLE_LINUX_CAPS if (!prctl(PR_GET_DUMPABLE, 0, 0, 0, 0)) { gint rc; rc = prctl(PR_SET_DUMPABLE, 1, 0, 0, 0); if (rc < 0) g_process_message("Cannot set process to be dumpable; error='%s'", g_strerror(errno)); } #endif limit.rlim_cur = limit.rlim_max = RLIM_INFINITY; if (setrlimit(RLIMIT_CORE, &limit) < 0) g_process_message("Error setting core limit to infinity; error='%s'", g_strerror(errno)); } } /** * <API key>: * @buf: buffer to store the pidfile name * @buflen: size of @buf * * Format the pid file name according to the settings specified by the * process. **/ static const gchar * <API key>(gchar *buf, gsize buflen) { const gchar *pidfile = process_opts.pidfile; if (pidfile == NULL) { g_snprintf(buf, buflen, "%s/%s.pid", process_opts.pidfile_dir ? process_opts.pidfile_dir : PATH_PIDFILEDIR, process_opts.name); pidfile = buf; } else if (pidfile[0] != '/') { /* complete path to pidfile not specified, assume it is a relative path to pidfile_dir */ g_snprintf(buf, buflen, "%s/%s", process_opts.pidfile_dir ? process_opts.pidfile_dir : PATH_PIDFILEDIR, pidfile); pidfile = buf; } return pidfile; } /** * <API key>: * @pid: pid to write into the pidfile * * Write the pid to the pidfile. **/ static void <API key>(pid_t pid) { gchar buf[256]; const gchar *pidfile; FILE *fd; pidfile = <API key>(buf, sizeof(buf)); fd = fopen(pidfile, "w"); if (fd != NULL) { fprintf(fd, "%d\n", (int) pid); fclose(fd); } else { g_process_message("Error creating pid file; file='%s', error='%s'", pidfile, g_strerror(errno)); } } /** * <API key>: * * Remove the pidfile. **/ static void <API key>(void) { gchar buf[256]; const gchar *pidfile; pidfile = <API key>(buf, sizeof(buf)); if (unlink(pidfile) < 0) { g_process_message("Error removing pid file; file='%s', error='%s'", pidfile, g_strerror(errno)); } } /** * <API key>: * * Change the current root to the value specified by the user, causes the * startup process to fail if this function returns FALSE. (e.g. the user * specified a chroot but we could not change to that directory) * * Returns: TRUE to indicate success **/ static gboolean <API key>(void) { if (process_opts.chroot_dir) { if (chroot(process_opts.chroot_dir) < 0) { g_process_message("Error in chroot(); chroot='%s', error='%s'\n", process_opts.chroot_dir, g_strerror(errno)); return FALSE; } if (chdir("/") < 0) { g_process_message("Error in chdir() after chroot; chroot='%s', error='%s'\n", process_opts.chroot_dir, g_strerror(errno)); return FALSE; } } return TRUE; } /** * <API key>: * * Change the current user/group/groups to the value specified by the user. * causes the startup process to fail if this function returns FALSE. (e.g. * the user requested the uid/gid to change we could not change to that uid) * * Returns: TRUE to indicate success **/ static gboolean <API key>(void) { #if ENABLE_LINUX_CAPS if (process_opts.caps) prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0); #endif if (process_opts.gid >= 0) { if (setgid((gid_t) process_opts.gid) < 0) { g_process_message("Error in setgid(); group='%s', gid='%d', error='%s'", process_opts.group, process_opts.gid, g_strerror(errno)); if (getuid() == 0) return FALSE; } if (process_opts.user && initgroups(process_opts.user, (gid_t) process_opts.gid) < 0) { g_process_message("Error in initgroups(); user='%s', error='%s'", process_opts.user, g_strerror(errno)); if (getuid() == 0) return FALSE; } } if (process_opts.uid >= 0) { if (setuid((uid_t) process_opts.uid) < 0) { g_process_message("Error in setuid(); user='%s', uid='%d', error='%s'", process_opts.user, process_opts.uid, g_strerror(errno)); if (getuid() == 0) return FALSE; } } return TRUE; } #if ENABLE_LINUX_CAPS /** * <API key>: * * Change the current capset to the value specified by the user. causes the * startup process to fail if this function returns FALSE, but we only do * this if the capset cannot be parsed, otherwise a failure changing the * capabilities will not result in failure * * Returns: TRUE to indicate success **/ static gboolean <API key>(void) { if (process_opts.caps) { cap_t cap = cap_from_text(process_opts.caps); if (cap == NULL) { g_process_message("Error parsing capabilities: %s", process_opts.caps); process_opts.caps = NULL; return FALSE; } else { if (cap_set_proc(cap) == -1) { g_process_message("Error setting capabilities, capability management disabled; error='%s'", g_strerror(errno)); process_opts.caps = NULL; } cap_free(cap); } } return TRUE; } #else static gboolean <API key>(void) { return TRUE; } #endif static void <API key>(void) { if (process_opts.user && !resolve_user(process_opts.user, &process_opts.uid)) { g_process_message("Error resolving user; user='%s'", process_opts.user); process_opts.uid = -1; } if (process_opts.group && !resolve_group(process_opts.group, &process_opts.gid)) { g_process_message("Error resolving group; group='%s'", process_opts.group); process_opts.gid = -1; } } /** * <API key>: * * Change the current working directory to the value specified by the user * and verify that the daemon would be able to dump core to that directory * if that is requested. **/ static void <API key>(void) { const gchar *cwd = NULL; if (process_opts.mode != G_PM_FOREGROUND) { if (process_opts.cwd) cwd = process_opts.cwd; else if (process_opts.pidfile_dir) cwd = process_opts.pidfile_dir; if (!cwd) cwd = PATH_PIDFILEDIR; if (cwd) chdir(cwd); } /* this check is here to avoid having to change directory early in the startup process */ if ((process_opts.core) && access(".", W_OK) < 0) { gchar buf[256]; getcwd(buf, sizeof(buf)); g_process_message("Unable to write to current directory, core dumps will not be generated; dir='%s', error='%s'", buf, g_strerror(errno)); } } /** * <API key>: * @ret_num: exit code of the process * * This function is called to notify our parent process (which is the same * executable process but separated with a fork()) about the result of the * process startup phase. Specifying ret_num == 0 means that everything was * dandy, all other values mean that the initialization failed and the * parent should exit using ret_num as the exit code. The function behaves * differently depending on which process it was called from, determined by * the value of the process_kind global variable. In the daemon process it * writes to init_result_pipe, in the startup process it writes to the * startup_result_pipe. * * This function can only be called once, further invocations will do nothing. **/ static void <API key>(guint ret_num) { gchar buf[10]; guint buf_len; gint *fd; if (process_kind == G_PK_SUPERVISOR) fd = &startup_result_pipe[1]; else if (process_kind == G_PK_DAEMON) fd = &init_result_pipe[1]; else <API key>(); if (*fd != -1) { buf_len = g_snprintf(buf, sizeof(buf), "%d\n", ret_num); write(*fd, buf, buf_len); close(*fd); *fd = -1; } } /** * <API key>: * * Retrieves an exit code value from one of the result pipes depending on * which process the function was called from. This function can be called * only once, further invocations will return non-zero result code. **/ static gint <API key>(void) { gchar ret_buf[6]; gint ret_num = 1; gint *fd; /* FIXME: use a timer */ if (process_kind == G_PK_SUPERVISOR) fd = &init_result_pipe[0]; else if (process_kind == G_PK_STARTUP) fd = &startup_result_pipe[0]; else <API key>(); if (*fd != -1) { memset(ret_buf, 0, sizeof(ret_buf)); if (read(*fd, ret_buf, sizeof(ret_buf)) > 0) { ret_num = atoi(ret_buf); } else { /* the process probably crashed without telling a proper exit code */ ret_num = 1; } close(*fd); *fd = -1; } return ret_num; } /** * <API key>: * * This function is the startup process, never returns, the startup process exits here. **/ static void <API key>(void) { /* startup process */ exit(<API key>()); } #define SPT_PADCHAR '\0' static void <API key>(const gchar* proc_title) { size_t len; g_assert(process_opts.argv_start != NULL); len = g_strlcpy(process_opts.argv_start, proc_title, process_opts.argv_env_len); for (; len < process_opts.argv_env_len; ++len) process_opts.argv_start[len] = SPT_PADCHAR; } #define PROC_TITLE_SPACE 1024 /** * <API key>: * * Supervise process, returns only in the context of the daemon process, the * supervisor process exits here. **/ static void <API key>(void) { pid_t pid; gboolean first = TRUE, exited = FALSE; gchar proc_title[PROC_TITLE_SPACE]; g_snprintf(proc_title, PROC_TITLE_SPACE, "supervising %s", process_opts.name); <API key>(proc_title); while (1) { if (pipe(init_result_pipe) != 0) { g_process_message("Error daemonizing process, cannot open pipe; error='%s'", g_strerror(errno)); <API key>(1, TRUE); } /* fork off a child process */ if ((pid = fork()) < 0) { g_process_message("Error forking child process; error='%s'", g_strerror(errno)); <API key>(1, TRUE); } else if (pid != 0) { gint rc; gboolean deadlock = FALSE; /* this is the supervisor process */ /* shut down init_result_pipe write side */ close(init_result_pipe[1]); init_result_pipe[1] = -1; rc = <API key>(); if (first) { /* first time encounter, we have a chance to report back, do it */ <API key>(rc); if (rc != 0) break; <API key>(); } first = FALSE; if (rc != 0) { gint i = 0; /* initialization failed in daemon, it will probably exit soon, wait and restart */ while (i < 6 && waitpid(pid, &rc, WNOHANG) == 0) { if (i > 3) kill(pid, i > 4 ? SIGKILL : SIGTERM); sleep(1); i++; } if (i == 6) g_process_message("Initialization failed but the daemon did not exit, even when forced to, trying to recover; pid='%d'", pid); continue; } if (process_opts.check_fn && (process_opts.check_period >= 0)) { gint i = 1; while (!(exited = waitpid(pid, &rc, WNOHANG))) { if (i >= process_opts.check_period) { if (!process_opts.check_fn()) break; i = 0; } sleep(1); i++; } if (!exited) { gint j = 0; g_process_message("Daemon deadlock detected, killing process;"); deadlock = TRUE; while (j < 6 && waitpid(pid, &rc, WNOHANG) == 0) { if (j > 3) kill(pid, j > 4 ? SIGKILL : SIGABRT); sleep(1); j++; } if (j == 6) g_process_message("The daemon did not exit after deadlock, even when forced to, trying to recover; pid='%d'", pid); } } else { waitpid(pid, &rc, 0); } if (deadlock || WIFSIGNALED(rc) || (WIFEXITED(rc) && WEXITSTATUS(rc) != 0)) { gchar argbuf[64]; if (!access(<API key>, R_OK | X_OK)) { const gchar *notify_reason; pid_t npid = fork(); gint nrc; switch (npid) { case -1: g_process_message("Could not fork for external notification; reason='%s'", strerror(errno)); break; case 0: switch(fork()) { case -1: g_process_message("Could not fork for external notification; reason='%s'", strerror(errno)); exit(1); break; case 0: if (deadlock) { notify_reason = "deadlock detected"; argbuf[0] = 0; } else { snprintf(argbuf, sizeof(argbuf), "%d", WIFSIGNALED(rc) ? WTERMSIG(rc) : WEXITSTATUS(rc)); if (WIFSIGNALED(rc)) notify_reason = "signalled"; else notify_reason = "non-zero exit code"; } execlp(<API key>, <API key>, SAFE_STRING(process_opts.name), SAFE_STRING(process_opts.chroot_dir), SAFE_STRING(process_opts.pidfile_dir), SAFE_STRING(process_opts.pidfile), SAFE_STRING(process_opts.cwd), SAFE_STRING(process_opts.caps), notify_reason, argbuf, (deadlock || !WIFSIGNALED(rc) || WTERMSIG(rc) != SIGKILL) ? "restarting" : "not-restarting", (gchar*) NULL); g_process_message("Could not execute external notification; reason='%s'", strerror(errno)); break; default: exit(0); break; } /* child process */ default: waitpid(npid, &nrc, 0); break; } } if (deadlock || !WIFSIGNALED(rc) || WTERMSIG(rc) != SIGKILL) { g_process_message("Daemon exited due to a deadlock/signal/failure, restarting; exitcode='%d'", rc); sleep(1); } else { g_process_message("Daemon was killed, not restarting; exitcode='%d'", rc); break; } } else { g_process_message("Daemon exited gracefully, not restarting; exitcode='%d'", rc); break; } } else { /* this is the daemon process, thus we should return to the caller of g_process_start() */ /* shut down init_result_pipe read side */ process_kind = G_PK_DAEMON; close(init_result_pipe[0]); init_result_pipe[0] = -1; memcpy(process_opts.argv_start, process_opts.argv_orig, process_opts.argv_env_len); return; } } exit(0); } /** * g_process_start: * * Start the process as directed by the options set by various * g_process_set_*() functions. **/ void g_process_start(void) { pid_t pid; <API key>(); <API key>(); <API key>(); if (process_opts.mode == G_PM_BACKGROUND) { /* no supervisor, sends result to startup process directly */ if (pipe(init_result_pipe) != 0) { g_process_message("Error daemonizing process, cannot open pipe; error='%s'", g_strerror(errno)); exit(1); } if ((pid = fork()) < 0) { g_process_message("Error forking child process; error='%s'", g_strerror(errno)); exit(1); } else if (pid != 0) { /* shut down init_result_pipe write side */ close(init_result_pipe[1]); /* connect startup_result_pipe with init_result_pipe */ startup_result_pipe[0] = init_result_pipe[0]; init_result_pipe[0] = -1; <API key>(); /* NOTE: never returns */ <API key>(); } process_kind = G_PK_DAEMON; /* shut down init_result_pipe read side */ close(init_result_pipe[0]); init_result_pipe[0] = -1; } else if (process_opts.mode == <API key>) { /* full blown startup/supervisor/daemon */ if (pipe(startup_result_pipe) != 0) { g_process_message("Error daemonizing process, cannot open pipe; error='%s'", g_strerror(errno)); exit(1); } /* first fork off supervisor process */ if ((pid = fork()) < 0) { g_process_message("Error forking child process; error='%s'", g_strerror(errno)); exit(1); } else if (pid != 0) { /* this is the startup process */ /* shut down startup_result_pipe write side */ close(startup_result_pipe[1]); startup_result_pipe[1] = -1; /* NOTE: never returns */ <API key>(); <API key>(); } /* this is the supervisor process */ /* shut down startup_result_pipe read side */ close(startup_result_pipe[0]); startup_result_pipe[0] = -1; process_kind = G_PK_SUPERVISOR; <API key>(); /* we only return in the daamon process here */ } else if (process_opts.mode == G_PM_FOREGROUND) { process_kind = G_PK_DAEMON; } else { <API key>(); } /* daemon process, we should return to the caller to perform work */ setsid(); /* NOTE: we need to signal the parent in case of errors from this point. * This is accomplished by writing the appropriate exit code to * init_result_pipe, the easiest way doing so is calling <API key>. * */ if (!<API key>() || !<API key>() || !<API key>()) { <API key>(1, TRUE); } <API key>(); <API key>(); } /** * <API key>: * @ret_num: exit code * @may_exit: whether to exit the process * * This is a public API function to be called by the user code when * initialization failed. **/ void <API key>(guint ret_num, gboolean may_exit) { if (process_kind != G_PK_STARTUP) <API key>(ret_num); if (may_exit) { exit(ret_num); } else { <API key>(); } } /** * <API key>: * * This is a public API function to be called by the user code when * initialization was successful, we can report back to the user. **/ void <API key>(void) { <API key>(getpid()); <API key>(0); <API key>(); } /** * g_process_finish: * * This is a public API function to be called by the user code when the * daemon exits after properly initialized (e.g. when it terminates because * of SIGTERM). This function currently only removes the PID file. **/ void g_process_finish(void) { <API key>(); } static gboolean <API key>(const gchar *option_name G_GNUC_UNUSED, const gchar *value, gpointer data G_GNUC_UNUSED, GError **error) { if (strcmp(value, "foreground") == 0) { process_opts.mode = G_PM_FOREGROUND; } else if (strcmp(value, "background") == 0) { process_opts.mode = G_PM_BACKGROUND; } else if (strcmp(value, "safe-background") == 0) { process_opts.mode = <API key>; } else { g_set_error(error, G_OPTION_ERROR, <API key>, "Error parsing process-mode argument"); return FALSE; } return TRUE; } static GOptionEntry <API key>[] = { { "foreground", 'F', <API key>, G_OPTION_ARG_NONE, &process_opts.mode, "Do not go into the background after initialization", NULL }, { "process-mode", 0, 0, <API key>, <API key> , "Set process running mode", "<foreground|background|safe-background>" }, { "user", 'u', 0, G_OPTION_ARG_STRING, &process_opts.user, "Set the user to run as", "<user>" }, { "uid", 0, <API key>, G_OPTION_ARG_STRING, &process_opts.user, NULL, NULL }, { "group", 'g', 0, G_OPTION_ARG_STRING, &process_opts.group, "Set the group to run as", "<group>" }, { "gid", 0, <API key>, G_OPTION_ARG_STRING, &process_opts.group, NULL, NULL }, { "chroot", 'C', 0, G_OPTION_ARG_STRING, &process_opts.chroot_dir, "Chroot to this directory", "<dir>" }, { "caps", 0, 0, G_OPTION_ARG_STRING, &process_opts.caps, "Set default capability set", "<capspec>" }, { "no-caps", 0, <API key>, G_OPTION_ARG_NONE, &process_opts.caps, "Disable managing Linux capabilities", NULL }, { "pidfile", 'p', 0, G_OPTION_ARG_STRING, &process_opts.pidfile, "Set path to pid file", "<pidfile>" }, { "enable-core", 0, 0, G_OPTION_ARG_NONE, &process_opts.core, "Enable dumping core files", NULL }, { "fd-limit", 0, 0, G_OPTION_ARG_INT, &process_opts.fd_limit_min, "The minimum required number of fds", NULL }, { NULL, 0, 0, 0, NULL, NULL, NULL }, }; void <API key>(GOptionContext *ctx) { GOptionGroup *group; group = g_option_group_new("process", "Process options", "Process options", NULL, NULL); <API key>(group, <API key>); <API key>(ctx, group); }
<div id="<API key>"> <fieldset> <legend>{{ lang('<API key>') }}</legend> <p>{{ lang('<API key>') }}</p> <dl> <dt><label>{{ lang('FORUM_PERTOPIC') }}{{ lang('COLON') }}</label><br/><span>{{ lang('<API key>') }}</span> </dt> <dd><input type="text" id="forum_pertopic" maxlength="6" size="5" name="forum_pertopic" value="{{ FORUM_PERTOPIC }}"/></dd> </dl> <dl> <dt><label>{{ lang('FORUM_PERPOST') }}{{ lang('COLON') }}</label><br/><span>{{ lang('<API key>') }}</span> </dt> <dd><input type="text" id="forum_perpost" maxlength="6" size="5" name="forum_perpost" value="{{ FORUM_PERPOST }}"/></dd> </dl> <dl> <dt><label>{{ lang('FORUM_PEREDIT') }}{{ lang('COLON') }}</label><br/><span>{{ lang('<API key>') }}</span> </dt> <dd><input type="text" id="forum_peredit" maxlength="6" size="5" name="forum_peredit" value="{{ FORUM_PEREDIT }}"/></dd> </dl> <dl> <dt><label>{{ lang('FORUM_COST') }}{{ lang('COLON') }}</label><br/><span>{{ lang('FORUM_COST_EXPLAIN') }}</span></dt> <dd><input type="text" id="forum_cost" maxlength="6" size="5" name="forum_cost" value="{{ FORUM_COST }}"/> </dd> </dl> <dl> <dt><label>{{ lang('FORUM_COST_TOPIC') }}{{ lang('COLON') }}</label><br/><span>{{ lang('<API key>') }}</span> </dt> <dd><input type="text" id="forum_cost_topic" maxlength="6" size="5" name="forum_cost_topic" value="{{ FORUM_COST_TOPIC }}"/></dd> </dl> <dl> <dt><label>{{ lang('FORUM_COST_POST') }}{{ lang('COLON') }}</label><br/><span>{{ lang('<API key>') }}</span> </dt> <dd><input type="text" id="forum_cost_post" maxlength="6" size="5" name="forum_cost_post" value="{{ FORUM_COST_POST }}"/></dd> </dl> </fieldset> </div>
# -*- coding: utf-8 -*- def mayaxes(title_string='VOID', xlabel='VOID', ylabel='VOID', zlabel='VOID', handle='VOID', \ title_size=25, ticks=7, font_scaling=0.7, background='w'): if type(title_string) != str or type(xlabel) != str or type(ylabel) != str or type(zlabel) != str: print('ERROR: label inputs must all be strings') return elif type(ticks) != int: print('ERROR: number of ticks must be an integer') return elif type(font_scaling) != float and type(font_scaling) != int: print('Error: font scaling factor must be an integer or a float') return from mayavi.mlab import axes,title,gcf,outline # Create axes object ax = axes() # Font factor globally adjusts figure text size ax.axes.font_factor = font_scaling # Number of ticks along each axis ax.axes.number_of_labels = ticks # Set axis labels to input strings # (spaces are included for padding so that labels do not intersect with axes) if xlabel=='void' or xlabel=='Void' or xlabel=='VOID': print 'X axis label title disabled' else: ax.axes.x_label = ' ' + xlabel if ylabel=='void' or ylabel=='Void' or ylabel=='VOID': print 'Y axis label disabled' else: ax.axes.y_label = ylabel + ' ' if zlabel=='void' or zlabel=='Void' or zlabel=='VOID': print 'Z axis label disabled' else: ax.axes.z_label = zlabel + ' ' # Create figure title if title_string=='void' or title_string=='Void' or title_string=='VOID': print 'Figure title disabled' else: text_title = title(title_string) text_title.x_position = 0.5 text_title.y_position = 0.9 text_title.property.color = (0.0, 0.0, 0.0) text_title.actor.text_scale_mode = 'none' text_title.property.font_size = title_size text_title.property.justification = 'centered' # Create bounding box if handle=='void' or handle=='Void' or handle=='VOID': print 'Bounding box disabled' else: if background == 'w': bounding_box = outline(handle, color=(0.0, 0.0, 0.0), opacity=0.2) elif background == 'b': bounding_box = outline(handle, color=(1.0, 1.0, 1.0), opacity=0.2) # Set axis, labels and titles to neat black text #ax.property.color = (0.0, 0.0, 0.0) #ax.title_text_property.color = (0.0, 0.0, 0.0) #ax.label_text_property.color = (0.0, 0.0, 0.0) ax.label_text_property.bold = False ax.label_text_property.italic = False ax.title_text_property.italic = False ax.title_text_property.bold = False # Reset axis range ax.axes.use_ranges = True # Set scene background, axis and text colours fig = gcf() if background == 'w': fig.scene.background = (1.0, 1.0, 1.0) ax.label_text_property.color = (0.0, 0.0, 0.0) ax.property.color = (0.0, 0.0, 0.0) ax.title_text_property.color = (0.0, 0.0, 0.0) elif background == 'b': fig.scene.background = (0.0, 0.0, 0.0) ax.label_text_property.color = (1.0, 1.0, 1.0) ax.property.color = (1.0, 1.0, 1.0) ax.title_text_property.color = (1.0, 1.0, 1.0) fig.scene.parallel_projection = True def test_mayaxes(): from mayaxes import mayaxes from scipy import sqrt,sin,meshgrid,linspace,pi import mayavi.mlab as mlab resolution = 200 lambda_var = 3 theta = linspace(-lambda_var*2*pi,lambda_var*2*pi,resolution) x, y = meshgrid(theta, theta) r = sqrt(x**2 + y**2) z = sin(r)/r fig = mlab.figure(size=(1024,768)) surf = mlab.surf(theta,theta,z,colormap='jet',opacity=1.0,warp_scale='auto') mayaxes(title_string='Figure 1: Diminishing polar cosine series', \ xlabel='X data',ylabel='Y data',zlabel='Z data',handle=surf) fig.scene.camera.position = [435.4093863309094, 434.1268937227623, 315.90311468125287] fig.scene.camera.focal_point = [94.434632665253829, 93.152140057106593, -25.071638984402856] fig.scene.camera.view_angle = 30.0 fig.scene.camera.view_up = [0.0, 0.0, 1.0] fig.scene.camera.clipping_range = [287.45231734040635, 973.59247058049255] fig.scene.camera.<API key>() fig.scene.render() mlab.show()
#include <QGuiApplication> #include <QQuickView> #include <sailfishapp.h> int main(int argc, char *argv[]) { QScopedPointer<QGuiApplication> application(SailfishApp::application(argc, argv)); application->setApplicationName(QStringLiteral("depecher")); application-><API key>(QStringLiteral("Depecher")); QScopedPointer<QQuickView> view(SailfishApp::createView()); view->setSource(SailfishApp::pathTo(QStringLiteral("qml/main.qml"))); view->setTitle(application-><API key>()); view->setResizeMode(QQuickView::<API key>); view->show(); return application->exec(); }
<?php // No direct access. defined('_JEXEC') or die; /** * Items list controller class. */ class <API key> extends FarmappController { /** * Constructor. * * @param array $config An optional associative array of configuration settings. * @see JController * @since 1.6 */ public function __construct($config = array()) { parent::__construct($config); } function display() { $model=$this->getModel('crops'); $items=$model->getItems(); $pagination = $model->getPagination(); $state = $model->getState(); $view=$this->getView('crops','html'); $view->assign('items',$items); $view->assign('pagination',$pagination); $view->assign('state',$state); $view->display(); } function edit() { $id = JRequest::getVar('cid','0'); $model=$this->getModel('crop'); // get the Data $item = $model->getItem($id[0]); $form = $model->getForm($id[0]); $view=$this->getView('crop','html'); $view->assign('form',$form); $view->assign('item',$item); $view->setLayout('edit'); $view->display(); } /* * Method for save data from farm-form...... * */ function save() { $task = $this->getTask(); $data=JRequest::get('post'); $bed_ids = $data['bed_id']; $bed_id = implode(',',$bed_ids); $data['bed_id'] = $bed_id; $model=$this->getModel('crop'); $id=$model->save($data); if($id!=='') { switch ( $task ) { case 'save2new': $link = 'index.php?option=com_farmapp&view=crops&task=add'; $this->setRedirect($link, $msg); break; case 'save': $msg = JText::_( 'Crop save successfully' ); $link = 'index.php?option=com_farmapp&view=crops'; $this->setRedirect($link, $msg); break; case 'apply': $msg = JText::_( 'Crop save successfully' ); $link = 'index.php?option=com_farmapp&view=crops&task=edit&cid[]='.$id; $this->setRedirect($link, $msg); break; } } } /* * Method for deleting single/multiple crops...... * */ function delete() { $model = $this->getModel('crops'); if(!$model->delete()) { $msg = JText::_( 'Error: One or More crop Could not be Deleted' ); }else{ $msg = JText::_( 'crop(s) Deleted' ); } $link = 'index.php?option=com_farmapp&view=crops'; $this->setRedirect($link, $msg); } /* * Method for publish single/multiple farms...... * */ function multiplepublish() { $model = $this->getModel('crops'); if(!$model->multiplepublish()) { $msg = JText::_( 'Error: One or More crops Could not be published' ); } else { $msg = JText::_( 'crop(s) Published.' ); } $link = 'index.php?option=com_farmapp&view=crops'; $this->setRedirect($link, $msg); } /* * Method for unpublish single/multiple farms...... * */ function multipleunpublish() { $model = $this->getModel('crops'); if(!$model->multipleunpublish()){ $msg = JText::_( 'Error: One or More crop Could not be unpublished' ); }else{ $msg = JText::_( 'crop(s) UnPublished.' ); } $link = 'index.php?option=com_farmapp&view=crops'; $this->setRedirect($link, $msg); } /*method single row publish and unpublish on click on tick mark*/ function publish(){ // Initialise variables. $ids = JRequest::getVar('cid', array(), '', 'array'); $values = array('publish' => 1, 'unpublish' => 0); $task = $this->getTask(); $value = JArrayHelper::getValue($values, $task, 0, 'int'); if (empty($ids)) { JError::raiseWarning(500, JText::_('<API key>')); } else { // Get the model. $model = $this->getModel('crops'); // Publish the items. if (!$model->publish($ids, $value)) { JError::raiseWarning(500, $model->getError()); } } $this->setRedirect('index.php?option=com_farmapp&view=crops'); } /* * * Method to get the beds according to the farm/zones........ */ function findbeds() { $model=$this->getModel('crops'); $farmzoneid = JRequest::getVar('val'); $cropid = JRequest::getVar('cropid'); $bedslist = $model->getbedslist($farmzoneid, $cropid); echo $bedslist; } }
<?php namespace Drupal\<API key>\Suggestion; use Drupal\Core\Render\RenderableInterface; /** * Defines a single autocompletion suggestion. */ interface SuggestionInterface extends RenderableInterface { /** * Retrieves the keywords this suggestion will autocomplete to. * * @return string|null * The suggested keywords, or NULL if the suggestion should direct to a URL * instead. */ public function getSuggestedKeys(); /** * Retrieves the URL to which the suggestion should redirect. * * A URL to which the suggestion should redirect instead of completing the * user input in the text field. This overrides the normal behavior and thus * makes the suggested keys obsolete. * * @return \Drupal\Core\Url|null * The URL to which the suggestion should redirect to, or NULL if none was * set. */ public function getUrl(); /** * Retrieves the prefix for the suggestion. * * For special kinds of suggestions, this will contain some kind of prefix * describing them. * * @return string|null * The prefix, if set. */ public function getPrefix(); /** * Retrieves the label to use for the suggestion. * * Should only be used if the other fields that will be displayed (suggestion * prefix/suffix and user input) are empty. * * @return string * The suggestion's label. */ public function getLabel(); /** * Retrieves the prefix suggested for the entered keys. * * @return string|null * The suggested prefix, if any. */ public function getSuggestionPrefix(); /** * The input entered by the user, if it should be included in the label. * * @return string|null * The input provided by the user. */ public function getUserInput(); /** * A suggested suffix for the entered input. * * @return string|null * A suffix. */ public function getSuggestionSuffix(); /** * Returns the estimated number of results for this suggestion. * * @return int|null * The estimated number of results, or NULL if no estimate is available. */ public function getResultsCount(); /** * Returns the render array set for this suggestion. * * This should be displayed to the user for this suggestion. If missing, the * suggestion is instead rendered with the * "<API key>" theme. * * @return array|null * A renderable array of the suggestion results, or NULL if none was set. */ public function getRender(); /** * Sets the keys. * * @param string|null $keys * The keys. * * @return $this */ public function setSuggestedKeys($keys); /** * Sets the URL. * * @param \Drupal\Core\Url|null $url * The URL. * * @return $this */ public function setUrl($url); /** * Sets the prefix. * * @param string|null $prefix * The prefix. * * @return $this */ public function setPrefix($prefix); /** * Sets the label. * * @param string|null $label * The new label. * * @return $this */ public function setLabel($label); /** * Sets the suggestion prefix. * * @param string|null $suggestion_prefix * The suggestion prefix. * * @return $this */ public function setSuggestionPrefix($suggestion_prefix); /** * Sets the user input. * * @param string|null $user_input * The user input. * * @return $this */ public function setUserInput($user_input); /** * Sets the suggestion suffix. * * @param string|null $suggestion_suffix * The suggestion suffix. * * @return $this */ public function setSuggestionSuffix($suggestion_suffix); /** * Sets the result count. * * @param string|null $results * The result count. * * @return $this */ public function setResultsCount($results); /** * Sets the render array. * * @param array|null $render * The render array. * * @return $this */ public function setRender($render); }
#include "precomp.h" #define LCDTIMING0_PPL(x) ((((x) / 16 - 1) & 0x3f) << 2) #define LCDTIMING1_LPP(x) (((x) & 0x3ff) - 1) #define LCDCONTROL_LCDPWR (1 << 11) #define LCDCONTROL_LCDEN (1) #define LCDCONTROL_LCDBPP(x) (((x) & 7) << 1) #define LCDCONTROL_LCDTFT (1 << 5) #define PL110_LCDTIMING0 (PVOID)0x10120000 #define PL110_LCDTIMING1 (PVOID)0x10120004 #define PL110_LCDTIMING2 (PVOID)0x10120008 #define PL110_LCDUPBASE (PVOID)0x10120010 #define PL110_LCDLPBASE (PVOID)0x10120014 #define PL110_LCDCONTROL (PVOID)0x10120018 PUSHORT LlbHwVideoBuffer; VOID NTAPI <API key>(VOID) { /* Set framebuffer address */ <API key>(PL110_LCDUPBASE, (ULONG)LlbHwGetFrameBuffer()); <API key>(PL110_LCDLPBASE, (ULONG)LlbHwGetFrameBuffer()); /* Initialize timings to 720x400 */ <API key>(PL110_LCDTIMING0, LCDTIMING0_PPL(LlbHwGetScreenWidth())); <API key>(PL110_LCDTIMING1, LCDTIMING1_LPP(<API key>())); /* Enable the TFT/LCD Display */ <API key>(PL110_LCDCONTROL, LCDCONTROL_LCDEN | LCDCONTROL_LCDTFT | LCDCONTROL_LCDPWR | LCDCONTROL_LCDBPP(4)); } ULONG NTAPI LlbHwGetScreenWidth(VOID) { return 720; } ULONG NTAPI <API key>(VOID) { return 400; } PVOID NTAPI LlbHwGetFrameBuffer(VOID) { return (PVOID)0x000A0000; } ULONG NTAPI <API key>(IN ULONG Red, IN ULONG Green, IN ULONG Blue) { return (((Blue >> 3) << 11)| ((Green >> 2) << 5)| ((Red >> 3) << 0)); } /* EOF */
<?php // Protect from unauthorized access defined('FOF_INCLUDED') or die; /** * Query Building Class. * * @package Joomla.Platform * @subpackage Database * @since 3.4 */ class <API key> extends <API key> { }
#include <linux/i2c.h> #include <linux/leds.h> #include <linux/slab.h> #include <linux/platform_device.h> #include <linux/input.h> #include <linux/led-lm3530.h> #include <linux/types.h> #include <linux/regulator/consumer.h> #include <linux/module.h> #define LM3530_LED_DEV "lcd-backlight" #define LM3530_NAME "lm3530-led" #define LM3530_GEN_CONFIG 0x10 #define LM3530_ALS_CONFIG 0x20 #define <API key> 0x30 #define <API key> 0x41 #define LM3530_BRT_CTRL_REG 0xA0 #define LM3530_ALS_ZB0_REG 0x60 #define LM3530_ALS_ZB1_REG 0x61 #define LM3530_ALS_ZB2_REG 0x62 #define LM3530_ALS_ZB3_REG 0x63 #define LM3530_ALS_Z0T_REG 0x70 #define LM3530_ALS_Z1T_REG 0x71 #define LM3530_ALS_Z2T_REG 0x72 #define LM3530_ALS_Z3T_REG 0x73 #define LM3530_ALS_Z4T_REG 0x74 #define LM3530_REG_MAX 14 /* General Control Register */ #define LM3530_EN_I2C_SHIFT (0) #define <API key> (1) #define <API key> (2) #define LM3530_EN_PWM_SHIFT (5) #define <API key> (6) #define <API key> (7) #define LM3530_ENABLE_I2C (1 << LM3530_EN_I2C_SHIFT) #define LM3530_ENABLE_PWM (1 << LM3530_EN_PWM_SHIFT) #define LM3530_POL_LOW (1 << <API key>) #define <API key> (1 << <API key>) /* ALS Config Register Options */ #define <API key> (0) #define LM3530_EN_ALS_SHIFT (3) #define <API key> (5) #define LM3530_ENABLE_ALS (3 << LM3530_EN_ALS_SHIFT) /* Brightness Ramp Rate Register */ #define <API key> (0) #define <API key> (3) /* ALS Resistor Select */ #define <API key> (0) #define <API key> (4) /* Zone Boundary Register defaults */ #define LM3530_ALS_ZB_MAX (4) #define <API key> (1000) #define <API key> (4) /* Zone Target Register defaults */ #define LM3530_DEF_ZT_0 (0x7F) #define LM3530_DEF_ZT_1 (0x66) #define LM3530_DEF_ZT_2 (0x4C) #define LM3530_DEF_ZT_3 (0x33) #define LM3530_DEF_ZT_4 (0x19) /* 7 bits are used for the brightness : LM3530_BRT_CTRL_REG */ #define MAX_BRIGHTNESS (127) struct lm3530_mode_map { const char *mode; enum lm3530_mode mode_val; }; static struct lm3530_mode_map mode_map[] = { { "man", <API key> }, { "als", LM3530_BL_MODE_ALS }, { "pwm", LM3530_BL_MODE_PWM }, }; /** * struct lm3530_data * @led_dev: led class device * @client: i2c client * @pdata: LM3530 platform data * @mode: mode of operation - manual, ALS, PWM * @regulator: regulator * @brighness: previous brightness value * @enable: regulator is enabled */ struct lm3530_data { struct led_classdev led_dev; struct i2c_client *client; struct <API key> *pdata; enum lm3530_mode mode; struct regulator *regulator; enum led_brightness brightness; bool enable; }; static const u8 lm3530_reg[LM3530_REG_MAX] = { LM3530_GEN_CONFIG, LM3530_ALS_CONFIG, <API key>, <API key>, LM3530_BRT_CTRL_REG, LM3530_ALS_ZB0_REG, LM3530_ALS_ZB1_REG, LM3530_ALS_ZB2_REG, LM3530_ALS_ZB3_REG, LM3530_ALS_Z0T_REG, LM3530_ALS_Z1T_REG, LM3530_ALS_Z2T_REG, LM3530_ALS_Z3T_REG, LM3530_ALS_Z4T_REG, }; static int <API key>(const char *str) { int i; for (i = 0; i < ARRAY_SIZE(mode_map); i++) if (sysfs_streq(str, mode_map[i].mode)) return mode_map[i].mode_val; return -1; } static int <API key>(struct lm3530_data *drvdata) { int ret = 0; int i; u8 gen_config; u8 als_config = 0; u8 brt_ramp; u8 als_imp_sel = 0; u8 brightness; u8 reg_val[LM3530_REG_MAX]; u8 zones[LM3530_ALS_ZB_MAX]; u32 als_vmin, als_vmax, als_vstep; struct <API key> *pdata = drvdata->pdata; struct i2c_client *client = drvdata->client; struct lm3530_pwm_data *pwm = &pdata->pwm_data; gen_config = (pdata->brt_ramp_law << <API key>) | ((pdata->max_current & 7) << <API key>); switch (drvdata->mode) { case <API key>: case LM3530_BL_MODE_ALS: gen_config |= LM3530_ENABLE_I2C; break; case LM3530_BL_MODE_PWM: gen_config |= LM3530_ENABLE_PWM | <API key> | (pdata->pwm_pol_hi << <API key>); break; } if (drvdata->mode == LM3530_BL_MODE_ALS) { if (pdata->als_vmax == 0) { pdata->als_vmin = 0; pdata->als_vmax = <API key>; } als_vmin = pdata->als_vmin; als_vmax = pdata->als_vmax; if ((als_vmax - als_vmin) > <API key>) pdata->als_vmax = als_vmax = als_vmin + <API key>; /* n zone boundary makes n+1 zones */ als_vstep = (als_vmax - als_vmin) / (LM3530_ALS_ZB_MAX + 1); for (i = 0; i < LM3530_ALS_ZB_MAX; i++) zones[i] = (((als_vmin + <API key>) + als_vstep + (i * als_vstep)) * LED_FULL) / 1000; als_config = (pdata->als_avrg_time << <API key>) | (LM3530_ENABLE_ALS) | (pdata->als_input_mode << <API key>); als_imp_sel = (pdata->als1_resistor_sel << <API key>) | (pdata->als2_resistor_sel << <API key>); } brt_ramp = (pdata->brt_ramp_fall << <API key>) | (pdata->brt_ramp_rise << <API key>); if (drvdata->brightness) brightness = drvdata->brightness; else brightness = drvdata->brightness = pdata->brt_val; if (brightness > drvdata->led_dev.max_brightness) brightness = drvdata->led_dev.max_brightness; reg_val[0] = gen_config; /* LM3530_GEN_CONFIG */ reg_val[1] = als_config; /* LM3530_ALS_CONFIG */ reg_val[2] = brt_ramp; /* <API key> */ reg_val[3] = als_imp_sel; /* <API key> */ reg_val[4] = brightness; /* LM3530_BRT_CTRL_REG */ reg_val[5] = zones[0]; /* LM3530_ALS_ZB0_REG */ reg_val[6] = zones[1]; /* LM3530_ALS_ZB1_REG */ reg_val[7] = zones[2]; /* LM3530_ALS_ZB2_REG */ reg_val[8] = zones[3]; /* LM3530_ALS_ZB3_REG */ reg_val[9] = LM3530_DEF_ZT_0; /* LM3530_ALS_Z0T_REG */ reg_val[10] = LM3530_DEF_ZT_1; /* LM3530_ALS_Z1T_REG */ reg_val[11] = LM3530_DEF_ZT_2; /* LM3530_ALS_Z2T_REG */ reg_val[12] = LM3530_DEF_ZT_3; /* LM3530_ALS_Z3T_REG */ reg_val[13] = LM3530_DEF_ZT_4; /* LM3530_ALS_Z4T_REG */ if (!drvdata->enable) { ret = regulator_enable(drvdata->regulator); if (ret) { dev_err(&drvdata->client->dev, "Enable regulator failed\n"); return ret; } drvdata->enable = true; } for (i = 0; i < LM3530_REG_MAX; i++) { /* do not update brightness register when pwm mode */ if (lm3530_reg[i] == LM3530_BRT_CTRL_REG && drvdata->mode == LM3530_BL_MODE_PWM) { if (pwm->pwm_set_intensity) pwm->pwm_set_intensity(reg_val[i], drvdata->led_dev.max_brightness); continue; } ret = <API key>(client, lm3530_reg[i], reg_val[i]); if (ret) break; } return ret; } static void <API key>(struct led_classdev *led_cdev, enum led_brightness brt_val) { int err; struct lm3530_data *drvdata = container_of(led_cdev, struct lm3530_data, led_dev); struct <API key> *pdata = drvdata->pdata; struct lm3530_pwm_data *pwm = &pdata->pwm_data; u8 max_brightness = led_cdev->max_brightness; switch (drvdata->mode) { case <API key>: if (!drvdata->enable) { err = <API key>(drvdata); if (err) { dev_err(&drvdata->client->dev, "Register Init failed: %d\n", err); break; } } /* set the brightness in brightness control register*/ err = <API key>(drvdata->client, LM3530_BRT_CTRL_REG, brt_val); if (err) dev_err(&drvdata->client->dev, "Unable to set brightness: %d\n", err); else drvdata->brightness = brt_val; if (brt_val == 0) { err = regulator_disable(drvdata->regulator); if (err) dev_err(&drvdata->client->dev, "Disable regulator failed\n"); drvdata->enable = false; } break; case LM3530_BL_MODE_ALS: break; case LM3530_BL_MODE_PWM: if (pwm->pwm_set_intensity) pwm->pwm_set_intensity(brt_val, max_brightness); break; default: break; } } static ssize_t lm3530_mode_get(struct device *dev, struct device_attribute *attr, char *buf) { struct led_classdev *led_cdev = dev_get_drvdata(dev); struct lm3530_data *drvdata; int i, len = 0; drvdata = container_of(led_cdev, struct lm3530_data, led_dev); for (i = 0; i < ARRAY_SIZE(mode_map); i++) if (drvdata->mode == mode_map[i].mode_val) len += sprintf(buf + len, "[%s] ", mode_map[i].mode); else len += sprintf(buf + len, "%s ", mode_map[i].mode); len += sprintf(buf + len, "\n"); return len; } static ssize_t lm3530_mode_set(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { struct led_classdev *led_cdev = dev_get_drvdata(dev); struct lm3530_data *drvdata; struct lm3530_pwm_data *pwm; u8 max_brightness; int mode, err; drvdata = container_of(led_cdev, struct lm3530_data, led_dev); pwm = &drvdata->pdata->pwm_data; max_brightness = led_cdev->max_brightness; mode = <API key>(buf); if (mode < 0) { dev_err(dev, "Invalid mode\n"); return -EINVAL; } drvdata->mode = mode; /* set pwm to low if unnecessary */ if (mode != LM3530_BL_MODE_PWM && pwm->pwm_set_intensity) pwm->pwm_set_intensity(0, max_brightness); err = <API key>(drvdata); if (err) { dev_err(dev, "Setting %s Mode failed :%d\n", buf, err); return err; } return sizeof(drvdata->mode); } static DEVICE_ATTR(mode, 0644, lm3530_mode_get, lm3530_mode_set); static int __devinit lm3530_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct <API key> *pdata = client->dev.platform_data; struct lm3530_data *drvdata; int err = 0; if (pdata == NULL) { dev_err(&client->dev, "platform data required\n"); err = -ENODEV; goto err_out; } /* BL mode */ if (pdata->mode > LM3530_BL_MODE_PWM) { dev_err(&client->dev, "Illegal Mode request\n"); err = -EINVAL; goto err_out; } if (!<API key>(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "I2C_FUNC_I2C not supported\n"); err = -EIO; goto err_out; } drvdata = kzalloc(sizeof(struct lm3530_data), GFP_KERNEL); if (drvdata == NULL) { err = -ENOMEM; goto err_out; } drvdata->mode = pdata->mode; drvdata->client = client; drvdata->pdata = pdata; drvdata->brightness = LED_OFF; drvdata->enable = false; drvdata->led_dev.name = LM3530_LED_DEV; drvdata->led_dev.brightness_set = <API key>; drvdata->led_dev.max_brightness = MAX_BRIGHTNESS; i2c_set_clientdata(client, drvdata); drvdata->regulator = regulator_get(&client->dev, "vin"); if (IS_ERR(drvdata->regulator)) { dev_err(&client->dev, "regulator get failed\n"); err = PTR_ERR(drvdata->regulator); drvdata->regulator = NULL; goto err_regulator_get; } if (drvdata->pdata->brt_val) { err = <API key>(drvdata); if (err < 0) { dev_err(&client->dev, "Register Init failed: %d\n", err); err = -ENODEV; goto err_reg_init; } } err = <API key>(&client->dev, &drvdata->led_dev); if (err < 0) { dev_err(&client->dev, "Register led class failed: %d\n", err); err = -ENODEV; goto err_class_register; } err = device_create_file(drvdata->led_dev.dev, &dev_attr_mode); if (err < 0) { dev_err(&client->dev, "File device creation failed: %d\n", err); err = -ENODEV; goto err_create_file; } return 0; err_create_file: <API key>(&drvdata->led_dev); err_class_register: err_reg_init: regulator_put(drvdata->regulator); err_regulator_get: kfree(drvdata); err_out: return err; } static int __devexit lm3530_remove(struct i2c_client *client) { struct lm3530_data *drvdata = i2c_get_clientdata(client); device_remove_file(drvdata->led_dev.dev, &dev_attr_mode); if (drvdata->enable) regulator_disable(drvdata->regulator); regulator_put(drvdata->regulator); <API key>(&drvdata->led_dev); kfree(drvdata); return 0; } static const struct i2c_device_id lm3530_id[] = { {LM3530_NAME, 0}, {} }; MODULE_DEVICE_TABLE(i2c, lm3530_id); static struct i2c_driver lm3530_i2c_driver = { .probe = lm3530_probe, .remove = __devexit_p(lm3530_remove), .id_table = lm3530_id, .driver = { .name = LM3530_NAME, .owner = THIS_MODULE, }, }; module_i2c_driver(lm3530_i2c_driver); MODULE_DESCRIPTION("Back Light driver for LM3530"); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Shreshtha Kumar SAHU <shreshthakumar.sahu@stericsson.com>");
package sergio; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Calendar; import java.util.GregorianCalendar; //Ejercicio Metodos 18 //Realiza una clase llamada milibreria que contenga al menos cinco de los metodos realizados. //Usalas de 3 formas diferentes //Autor: Sergio Tobal //Fecha: 12-02-2012 public class EjerMetods18 { /** * @param args * @throws IOException * @throws <API key> */ public static void main(String[] args) throws <API key>, IOException { BufferedReader lectura = new BufferedReader(new InputStreamReader(System.in)); int numsend=10,edad; char nombre; boolean nombreceive; String msgname = null; System.out.println("Dame tu inicial:"); nombre=lectura.readLine().charAt(0); nombreceive=EsMayus(nombre); if (nombreceive==true) { msgname="MAYUSCULAS"; } else if (nombreceive==false) { msgname="minusculas"; } EsPerfecto(numsend); System.out.println("Tu primer numero perfecto es "+numsend+" porque tienes "+(edad=ObtenerEdad())+" años, y tu inicial esta escrita en "+msgname); } private static boolean EsPerfecto(int numsend) { int perfect=0; for (int i = 1; i < numsend; i++) { if (numsend % i == 0) { perfect += i; } } if (perfect == numsend) { return true; }else { return false; } } private static int ObtenerEdad()throws <API key>, IOException{ BufferedReader lectura = new BufferedReader(new InputStreamReader(System.in)); int year,month,day; System.out.println("Dime tu dia de nacimiento: "); day=Integer.parseInt(lectura.readLine()); System.out.println("Dime tu mes de nacimiento: "); month=Integer.parseInt(lectura.readLine()); System.out.println("Dime tu año de nacimiento: "); year=Integer.parseInt(lectura.readLine()); Calendar cal = new GregorianCalendar(year, month, day); Calendar now = new GregorianCalendar(); int edad = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR); if ((cal.get(Calendar.MONTH) > now.get(Calendar.MONTH)) || (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH) && cal.get(Calendar.DAY_OF_MONTH) > now.get(Calendar.DAY_OF_MONTH))) { edad } return edad; } private static int Factorial(int num) { int factorial=1; // Va multiplicando el numero del usuario por 1 hasta que el numero llega ha cero y retorna // la multiplicacion de todos los numeros while (num!=0) { factorial=factorial*num; num } return factorial; } private static boolean ValFecha(int day, int month) { if ((day>=1 && day<=31) && (month>=1 && month<=12)) { return true; }else { return false; } } private static boolean EsMayus(char nombre) { boolean opt=true; // La funcion isUpperCase comprueba que el contenido de num sea mayuscula if (Character.isUpperCase(nombre) == true) { opt=true; // La funcion isLowerCase comprueba que el contenido de num sea minuscula } else if(Character.isLowerCase(nombre) == true){ opt=false; } return opt; } }
@import judgels.fs.FileInfo @import org.iatoki.judgels.sandalphon.problem.programming.grading.blackbox.<API key> @import play.api.mvc.Call @(<API key>: Form[<API key>], <API key>: Call, testDataFiles: List[FileInfo], helperFiles: List[FileInfo]) @<API key> = @{ b3.horizontal.fieldConstructor("col-md-3", "col-md-9") } <script type="text/javascript" src="@controllers.routes.Assets.at("lib/jquery/jquery.min.js")"></script> <script type="text/javascript"> $(document).ready(function() { var <API key> = $('#<API key>'); var <API key> = $('#sample-test-data'); var sampleTestData = { container: <API key>, newSampleTestCase: { inSelect: <API key>.find('select').first(), outSelect: <API key>.find('select').last(), addButton: <API key>.find('a').last() }, sampleTestCases: [] }; var testCaseTemplate = $('#test-case-template'); var testDataContainer = $('#test-data'); var testData = { container: testDataContainer, newTestCase: { inSelect: testDataContainer.find('select').first(), outSelect: testDataContainer.find('select').last(), addButton: testDataContainer.find('a').last() }, testCases: [] }; function <API key>(inputVal, outputVal) { if (!inputVal || !outputVal) { alert("You don't have any test data files"); return; } var container = <API key>.clone().removeAttr('id'); var inInput = container.find('input').first(); var outInput = container.find('input').last(); var removeButton = container.find('a').last(); var caseNo = sampleTestData.sampleTestCases.length; // Update input values inInput .prop('name', '<API key>[' + caseNo + ']') .val(inputVal); outInput .prop('name', '<API key>[' + caseNo + ']') .val(outputVal); // Update remove test case button removeButton.on('click', function() { <API key>(caseNo); return false; }); var sampleTestCase = { container: container, inInput: inInput, outInput: outInput, removeButton: removeButton }; sampleTestData.sampleTestCases.push(sampleTestCase); // Append this sample test case container.insertBefore(sampleTestData.container.find('tr').last()); <API key>(); container.show(); } function <API key>(caseNo) { sampleTestData.sampleTestCases[caseNo].container.remove(); sampleTestData.sampleTestCases.splice(caseNo, 1); <API key>(); } function <API key>() { var <API key> = sampleTestData.sampleTestCases.length; for (var caseNo = 0; caseNo < <API key>; caseNo++) { var sampleTestCase = sampleTestData.sampleTestCases[caseNo]; sampleTestCase.inInput.prop('name', '<API key>[' + caseNo + ']'); sampleTestCase.outInput.prop('name', '<API key>[' + caseNo + ']'); (function(caseNo) { sampleTestCase.removeButton.off('click').on('click', function() { <API key>(caseNo); return false ; }); })(caseNo); } } function addNewTestCase(inputVal, outputVal) { if (!inputVal || !outputVal) { alert("You don't have any test data files"); return; } var container = testCaseTemplate.clone().removeAttr('id'); var inInput = container.find('input').first(); var outInput = container.find('input').last(); var removeButton = container.find('a').last(); var caseNo = testData.testCases.length; // Update input values inInput .prop('name', 'testCaseInputs[0][' + caseNo + ']') .val(inputVal); outInput .prop('name', 'testCaseOutputs[0][' + caseNo + ']') .val(outputVal); // Update remove test case button removeButton.on('click', function() { removeTestCase(caseNo); return false; }); var testCase = { container: container, inInput: inInput, outInput: outInput, removeButton: removeButton }; testData.testCases.push(testCase); // Append this test case container.insertBefore(testData.container.find('tr').last()); refreshTestData(); container.show(); } function removeTestCase(caseNo) { testData.testCases[caseNo].container.remove(); testData.testCases.splice(caseNo, 1); refreshTestData(); } function refreshTestData() { var testCasesCount = testData.testCases.length; for (var caseNo = 0; caseNo < testCasesCount; caseNo++) { var testCase = testData.testCases[caseNo]; testCase.inInput.prop('name', 'testCaseInputs[0][' + caseNo + ']'); testCase.outInput.prop('name', 'testCaseOutputs[0][' + caseNo + ']'); (function(caseNo) { testCase.removeButton.off('click').on('click', function() { removeTestCase(caseNo) ; return false ; }); })(caseNo); } } sampleTestData.newSampleTestCase.addButton.on('click', function() { <API key>(sampleTestData.newSampleTestCase.inSelect.val(), sampleTestData.newSampleTestCase.outSelect.val()); return false; }); testData.newTestCase.addButton.on('click', function() { addNewTestCase(testData.newTestCase.inSelect.val(), testData.newTestCase.outSelect.val()); return false; }); @for(i <- 0 until <API key>.get.<API key>.size) { <API key>('@<API key>.get.<API key>.get(i)', '@<API key>.get.<API key>.get(i)'); } @for(i <- 0 until <API key>.get.testCaseInputs.size) { @for(j <- 0 until <API key>.get.testCaseInputs.get(i).size) { addNewTestCase('@<API key>.get.testCaseInputs.get(i).get(j)', '@<API key>.get.testCaseOutputs.get(i).get(j)'); } } }); </script> @b3.form(<API key>) { @helper.CSRF.formField @b3.inputWrapped("timeLimit", <API key>("timeLimit"), '_label -> "Time Limit") { input => <div class="input-group"> @input <div class="input-group-addon">milliseconds</div> </div> } @b3.inputWrapped("memoryLimit", <API key>("memoryLimit"), '_label -> "Memory Limit") { input => <div class="input-group"> @input <div class="input-group-addon">kilobytes</div> </div> } <div class="row" style="margin-bottom: 10px;"> <div class="col-md-3"> <label class="control-label">Sample Test Data</label> </div> <div class="col-md-9"> <div class="panel panel-default"> <div class="panel-body"> <table class="table table-condensed"> <thead> <tr> <th>Sample Input</th> <th>Sample Output</th> <th></th> </tr> </thead> <tbody id="sample-test-data"> <tr id="<API key>" style="display: none"> <td> <input class="form-control input-sm" type="text" readonly="readonly" value="file_0_0.in" /> </td> <td> <input class="form-control input-sm" type="text" readonly="readonly" value="file_0_0.out" /> </td> <td class="text-center"> <a href="#"><span class="glyphicon glyphicon-remove"></span></a> </td> </tr> <tr class="active"> <td> <select> @for(file <- testDataFiles) { <option value="@file.getName">@file.getName</option> } </select> </td> <td> <select> @for(file <- testDataFiles) { <option value="@file.getName">@file.getName</option> } </select> </td> <td class="text-center"> <a href=""><span class="glyphicon glyphicon-plus"></span></a> </td> </tr> </tbody> </table> </div> </div> </div> </div> <div class="row" style="margin-bottom: 10px;"> <div class="col-md-3"> <label class="control-label">Test Data</label> </div> <div class="col-md-9"> <div class="panel panel-default"> <div class="panel-body"> <table class="table table-condensed"> <thead> <tr> <th>Input</th> <th>Output</th> <th></th> </tr> </thead> <tbody id="test-data"> <tr id="test-case-template" style="display: none"> <td> <input class="form-control input-sm" type="text" readonly="readonly" value="file_0_0.in" /> </td> <td> <input class="form-control input-sm" type="text" readonly="readonly" value="file_0_0.out" /> </td> <td class="text-center"> <a href="#"><span class="glyphicon glyphicon-remove"></span></a> </td> </tr> <tr class="active"> <td> <select> @for(file <- testDataFiles) { <option value="@file.getName">@file.getName</option> } </select> </td> <td> <select> @for(file <- testDataFiles) { <option value="@file.getName">@file.getName</option> } </select> </td> <td class="text-center"> <a href=""><span class="glyphicon glyphicon-plus"></span></a> </td> </tr> </tbody> </table> </div> </div> </div> </div> @b3.select(<API key>("customScorer"), helperFiles.map(f => f.getName -> f.getName).toSeq ++ Seq("(none)" -> "(None)"), '_label -> "Custom Scorer") @b3.submit('class -> "btn btn-primary") { Update } }
#!/bin/sh # Support routines for hand-crafting weird or malicious packs. # You can make a complete pack like: # pack_header 2 >foo.pack && # pack_obj <SHA1-like> >>foo.pack && # pack_obj <SHA1-like> >>foo.pack && # pack_trailer foo.pack # Print the big-endian 4-byte octal representation of $1 uint32_octal () { n=$1 printf '\%o' $(($n / 16777216)); n=$((n % 16777216)) printf '\%o' $(($n / 65536)); n=$((n % 65536)) printf '\%o' $(($n / 256)); n=$((n % 256)) printf '\%o' $(($n )); } # Print the big-endian 4-byte binary representation of $1 uint32_binary () { printf "$(uint32_octal "$1")" } # Print a pack header, version 2, for a pack with $1 objects pack_header () { printf 'PACK' && printf '\0\0\0\2' && uint32_binary "$1" } # Print the pack data for object $1, as a delta against object $2 (or as a full # object if $2 is missing or empty). The output is suitable for including # directly in the packfile, and represents the entirety of the object entry. # Doing this on the fly (especially picking your deltas) is quite tricky, so we # have hardcoded some well-known objects. See the case statements below for the # complete list. pack_obj () { case "$1" in # empty blob <SHA1-like>) case "$2" in '') printf '\060\170\234\003\0\0\0\0\1' return ;; esac ;; # blob containing "\7\76" <SHA1-like>) case "$2" in '') printf '\062\170\234\143\267\3\0\0\116\0\106' return ;; <SHA1-like>) printf '\165\1\327\161\66\146\364\336\202\47\166' && printf '\307\142\54\20\361\260\175\342\200\334\170' && printf '\234\143\142\142\142\267\003\0\0\151\0\114' return ;; esac ;; # blob containing "\7\0" <SHA1-like>) case "$2" in '') printf '\062\170\234\143\147\0\0\0\20\0\10' return ;; <SHA1-like>) printf '\165\346\217\350\22\233\124\153\20\32\356' && printf '\225\20\305\62\216\177\41\312\35\30\170\234' && printf '\143\142\142\142\147\0\0\0\53\0\16' return ;; esac ;; esac echo >&2 "BUG: don't know how to print $1${2:+ (from $2)}" return 1 } # Compute and append pack trailer to "$1" pack_trailer () { test-sha1 -b <"$1" >trailer.tmp && cat trailer.tmp >>"$1" && rm -f trailer.tmp } # Remove any existing packs to make sure that # whatever we index next will be the pack that we # actually use. clear_packs () {
#region using System.Collections.Generic; using System.Data; using Albian.Persistence.Model; #endregion namespace Albian.Persistence.Context { public interface IStorageContext { string StorageName { get; set; } IList<<API key>> FakeCommand { get; set; } IDbConnection Connection { get; set; } IDbTransaction Transaction { get; set; } IList<IDbCommand> Command { get; set; } IStorageAttribute Storage { get; set; } } }
#include <esc/proto/socket.h> #include <esc/stream/fstream.h> #include <esc/stream/istringstream.h> #include <esc/stream/ostream.h> #include <esc/dns.h> #include <sys/common.h> #include <sys/endian.h> #include <sys/proc.h> #include <sys/thread.h> #include <signal.h> namespace esc { #define <API key> 0x100 #define DNS_PORT 53 #define BUF_SIZE 512 uint16_t DNS::_nextId = 0; esc::Net::IPv4Addr DNS::_nameserver; enum Type { TYPE_A = 1, /* a host address */ TYPE_NS = 2, /* an authoritative name server */ TYPE_CNAME = 5, /* the canonical name for an alias */ TYPE_HINFO = 13, /* host information */ TYPE_MX = 15, /* mail exchange */ }; enum Class { CLASS_IN = 1 /* the Internet */ }; struct DNSHeader { uint16_t id; uint16_t flags; uint16_t qdCount; uint16_t anCount; uint16_t nsCount; uint16_t arCount; } A_PACKED; struct DNSQuestionEnd { uint16_t type; uint16_t cls; } A_PACKED; struct DNSAnswer { uint16_t name; uint16_t type; uint16_t cls; uint32_t ttl; uint16_t length; } A_PACKED; esc::Net::IPv4Addr DNS::getHost(const char *name,uint timeout) { if(isIPAddress(name)) { esc::Net::IPv4Addr addr; IStringStream is(name); is >> addr; return addr; } return resolve(name,timeout); } bool DNS::isIPAddress(const char *name) { int dots = 0; int len = 0; // ignore whitespace at the beginning while(isspace(*name)) name++; while(dots < 4 && len < 4 && *name) { if(*name == '.') { dots++; len = 0; } else if(isdigit(*name)) len++; else break; name++; } // ignore whitespace at the end while(isspace(*name)) name++; return dots == 3 && len > 0 && len < 4; } esc::Net::IPv4Addr DNS::resolve(const char *name,uint timeout) { uint8_t buffer[BUF_SIZE]; if(_nameserver.value() == 0) { FStream in(getResolveFile(),"r"); in >> _nameserver; if(_nameserver.value() == 0) VTHROWE("No nameserver",-EHOSTNOTFOUND); } size_t nameLen = strlen(name); size_t total = sizeof(DNSHeader) + nameLen + 2 + sizeof(DNSQuestionEnd); if(total > sizeof(buffer)) VTHROWE("Hostname too long",-EINVAL); // generate a unique uint16_t txid = (getpid() << 16) | _nextId; // build DNS request message DNSHeader *h = reinterpret_cast<DNSHeader*>(buffer); h->id = cputobe16(txid); h->flags = cputobe16(<API key>); h->qdCount = cputobe16(1); h->anCount = 0; h->nsCount = 0; h->arCount = 0; convertHostname(reinterpret_cast<char*>(h + 1),name,nameLen); DNSQuestionEnd *qend = reinterpret_cast<DNSQuestionEnd*>(buffer + sizeof(*h) + nameLen + 2); qend->type = cputobe16(TYPE_A); qend->cls = cputobe16(CLASS_IN); // create socket esc::Socket sock(esc::Socket::SOCK_DGRAM,esc::Socket::PROTO_UDP); // send over socket esc::Socket::Addr addr; addr.family = esc::Socket::AF_INET; addr.d.ipv4.addr = _nameserver.value(); addr.d.ipv4.port = DNS_PORT; sock.sendto(addr,buffer,total); sighandler_t oldhandler; if((oldhandler = signal(SIGALRM,sigalarm)) == SIG_ERR) VTHROW("Unable to set SIGALRM handler"); int res; if((res = ualarm(timeout * 1000)) < 0) VTHROWE("ualarm(" << (timeout * 1000) << ")",res); try { // receive response sock.recvfrom(addr,buffer,sizeof(buffer)); } catch(const esc::default_error &e) { if(e.error() == -EINTR) VTHROWE("Received no response from DNS server " << _nameserver,-ETIMEOUT); // ignore errors here if(signal(SIGALRM,oldhandler) == SIG_ERR) {} throw; } // ignore errors here if(signal(SIGALRM,oldhandler) == SIG_ERR) {} if(be16tocpu(h->id) != txid) VTHROWE("Received DNS response with wrong transaction id",-EHOSTNOTFOUND); int questions = be16tocpu(h->qdCount); int answers = be16tocpu(h->anCount); // skip questions uint8_t *data = reinterpret_cast<uint8_t*>(h + 1); for(int i = 0; i < questions; ++i) { size_t len = questionLength(data); data += len + sizeof(DNSQuestionEnd); } // parse answers for(int i = 0; i < answers; ++i) { DNSAnswer *ans = reinterpret_cast<DNSAnswer*>(data); if(be16tocpu(ans->type) == TYPE_A && be16tocpu(ans->length) == esc::Net::IPv4Addr::LEN) return esc::Net::IPv4Addr(data + sizeof(DNSAnswer)); } VTHROWE("Unable to find IP address in DNS response",-EHOSTNOTFOUND); } void DNS::convertHostname(char *dst,const char *src,size_t len) { // leave one byte space for the length of the first part const char *from = src + len++; char *to = dst + len; // we start with the \0 at the end int partLen = -1; for(size_t i = 0; i < len; i++, to--, from--) { if(*from == '.') { *to = partLen; partLen = 0; } else { *to = *from; partLen++; } } *to = partLen; } size_t DNS::questionLength(const uint8_t *data) { size_t total = 0; while(*data != 0) { uint8_t len = *data; // skip this name-part total += len + 1; data += len + 1; } // skip zero ending, too return total + 1; } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1"> <title>PushReceiver</title> <link rel="stylesheet" href="style.css"/> <!-- Inline scripts are forbidden in Firefox OS apps (CSP restrictions), so we use a script file. <script src="app.js" defer></script> </head> <body> <!-- This code is in the public domain. Enjoy! --> <h1>PushReceiver</h1> <div class="row control"><button id="go">Register</button></div> <div id="status"> Not Connected. <div> </body> </html>
<?php /* included from <API key>::<API key> */?> <p><?php if ($docs_sent) printf(__('%d documents sent to translation.<br />%d are complete, %d waiting for translation.', '<API key>'), $docs_sent, $docs_completed, $docs_waiting); ?></p> <p><a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php" class="button secondary"><strong><?php _e('Translate content', '<API key>'); ?></strong></a></p> <?php if(!defined('ICL_DONT_PROMOTE') || !ICL_DONT_PROMOTE):?> <h5 style="margin: 15px 0 0 0;"><?php _e('Need translation work?', '<API key>'); ?></h5> <p><?php printf(__('%s offers affordable professional translation via a streamlined process.','<API key>'), '<a target="_blank" href="http: <p><a href="<?php echo admin_url('index.php?icl_ajx_action=quote-get'); ?>" class="button secondary thickbox"><strong><?php _e('Get quote','<API key>') ?></strong></a> <a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php&amp;sm=translators&amp;service=icanlocalize" class="button secondary"><strong><?php _e('Get translators','<API key>') ?></strong></a> </p> <?php endif;?> <?php // shows only when translation polling is on and there are translations in progress $ICL_Pro_Translation-><API key>('icl_cyan_box'); ?> <?php if (count($active_languages = $sitepress-><API key>()) > 1): ?> <div><a href="javascript:void(0)" onclick="jQuery(this).parent().next('.wrapper').slideToggle();" style="display:block; padding:5px; border: 1px solid #eee; margin-bottom:2px; background-color: #F7F7F7;"><?php _e('Content translation', '<API key>') ?></a> </div> <div class="wrapper" style="display:none; padding: 5px 10px; border: 1px solid #eee; border-top: 0px; margin:-11px 0 2px 0;"> <?php $your_translators = <API key>::<API key>(); $<API key> = <API key>::<API key>(); if (!empty($your_translators) || !empty($<API key>)) { echo '<p><strong>' . __('Your translators', '<API key>') . '</strong></p><ul>'; if (!empty($your_translators)) foreach ($your_translators as $your_translator) { echo '<li>'; if ($current_user->ID == $your_translator->ID) { $edit_link = 'profile.php'; } else { $edit_link = esc_url(add_query_arg('wp_http_referer', urlencode(esc_url(stripslashes($_SERVER['REQUEST_URI']))), "user-edit.php?user_id=$your_translator->ID")); } echo '<a href="' . $edit_link . '"><strong>' . $your_translator->display_name . '</strong></a> - '; foreach ($your_translator->language_pairs as $from => $lp) { $tos = array(); foreach ($lp as $to => $null) { $tos[] = $active_languages[$to]['display_name']; } printf(__('%s to %s', '<API key>'), $active_languages[$from]['display_name'], join(', ', $tos)); } echo '</li>'; } if (!empty($<API key>)){ $langs = $sitepress-><API key>(); foreach ($<API key> as $rows){ foreach($rows['langs'] as $from => $lp){ $from = isset($langs[$from]['display_name']) ? $langs[$from]['display_name'] : $from; $tos = array(); foreach($lp as $to){ $tos[] = isset($langs[$to]['display_name']) ? $langs[$to]['display_name'] : $to; } } echo '<li>'; echo '<strong>' . $rows['name'] . '</strong> | ' . sprintf(__('%s to %s', '<API key>'), $from, join(', ', $tos)) . ' | ' . $rows['action']; echo '</li>'; } } echo '</ul><hr />'; } ?> <?php if(!defined('ICL_DONT_PROMOTE') || !ICL_DONT_PROMOTE):?> <p><a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php&amp;sm=translators&amp;service=icanlocalize"><strong><?php _e('Add translators from ICanLocalize &raquo;', '<API key>'); ?></strong></a></p> <?php endif; ?> <p><a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php&amp;sm=translators&amp;service=local"><strong><?php _e('Add your own translators &raquo;', '<API key>'); ?></strong></a></p> <p><a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php"><strong><?php _e('Translate contents &raquo;', '<API key>'); ?></strong></a></p> </div> <?php endif; ?>
<HEAD><TITLE>rle.sp</TITLE></HEAD> <BODY> <HR><DIV ALIGN="center"><H1> File : rle.sp </H1></DIV><HR> <DIV ALIGN="center"> <TABLE CELLSPACING="0" CELLPADDING="3" WIDTH="80%" SUMMARY=""> <TR> <TD BGCOLOR="black"><SPAN STYLE="color: #00CC00"> <PRE> $ spar rle 12W1B12W3B24W1B14W <API key> </PRE> </SPAN> </TD> </TR> </TABLE> </DIV> <HR> <PRE> #!/usr/local/bin/spar <b>pragma</b> <b>is</b> annotate( summary, "rle" ); annotate( description, "Given a string containing uppercase characters (A-Z)," ); annotate( description, "compress repeated 'runs' of the same character by" ); annotate( description, "storing the length of that run, and provide a function to" ); annotate( description, "reverse the compression. The output can be anything, as" ); annotate( description, "long as you can recreate the input with it." ); annotate( description, "" ); annotate( description, "Example:" ); annotate( description, "Input: <API key>" ); annotate( description, "Output: 12W1B12W3B24W1B14W" ); annotate( see_also, "http://rosettacode.org/wiki/Run-length_encoding" ); annotate( author, "Ken O. Burtch" ); license( unrestricted ); restriction( <API key> ); <b>end</b> <b>pragma</b>; <b>procedure</b> rle <b>is</b> <b>function</b> to_rle( s : string ) <b>return</b> string <b>is</b> <b>begin</b> <b>if</b> strings.length( s ) = 0 <b>then</b> <b>return</b> ""; <b>end</b> <b>if</b>; <b>declare</b> result : string; code : character; prefix : string; first : natural := 1; index : natural := 1; <b>begin</b> <b>while</b> index &lt;= strings.length( s ) <b>loop</b> first := index; index := @+1; code := strings.element( s, positive(first) ); <b>while</b> index &lt;= strings.length( s ) <b>loop</b> <b>exit</b> <b>when</b> code /= strings.element( s, positive(index) ); index := @+1; <b>exit</b> <b>when</b> index-first = 99; <b>end</b> <b>loop</b>; prefix := strings.trim( strings.image( index - first ), trim_end.left ); result := @ &amp; prefix &amp; code; <b>end</b> <b>loop</b>; <b>return</b> result; <b>end</b>; <b>end</b> to_rle; <b>function</b> from_rle( s : string ) <b>return</b> string <b>is</b> <b>begin</b> <b>if</b> strings.length( s ) = 0 <b>then</b> <b>return</b> ""; <b>end</b> <b>if</b>; <b>declare</b> result : string; index : positive := 1; prefix : string; code : character; <b>begin</b> <b>loop</b> prefix := "" &amp; strings.element( s, index ); index := @+1; <b>if</b> strings.is_digit( strings.element( s, index ) ) <b>then</b> prefix := @ &amp; strings.element( s, index ); index := @+1; <b>end</b> <b>if</b>; code := strings.element( s, index ); index := @+1; result := @ &amp; ( numerics.value( prefix ) * code ); <b>exit</b> <b>when</b> natural(index) &gt; strings.length( s ); <b>end</b> <b>loop</b>; <b>return</b> result; <b>end</b>; <b>end</b> from_rle; <b>begin</b> ? to_rle( "<API key>" ); ? from_rle( "12W1B12W3B24W1B14W"); <b>end</b> rle; <FONT COLOR=green><EM>-- VIM editor formatting instructions</EM></FONT> <FONT COLOR=green><EM>-- vim: ft=spar</EM></FONT> </PRE></BODY></HTML>
# Install script for directory: /home/parallels/new-pi/utils # Set the install prefix IF(NOT DEFINED <API key>) SET(<API key> "/usr/local") ENDIF(NOT DEFINED <API key>) STRING(REGEX REPLACE "/$" "" <API key> "${<API key>}") # Set the install configuration name. IF(NOT DEFINED <API key>) IF(BUILD_TYPE) STRING(REGEX REPLACE "^[^A-Za-z0-9_]+" "" <API key> "${BUILD_TYPE}") ELSE(BUILD_TYPE) SET(<API key> "DEBUG") ENDIF(BUILD_TYPE) MESSAGE(STATUS "Install configuration: \"${<API key>}\"") ENDIF(NOT DEFINED <API key>) # Set the component getting installed. IF(NOT <API key>) IF(COMPONENT) MESSAGE(STATUS "Install component: \"${COMPONENT}\"") SET(<API key> "${COMPONENT}") ELSE(COMPONENT) SET(<API key>) ENDIF(COMPONENT) ENDIF(NOT <API key>) IF(NOT DEFINED <API key>) SET(<API key> "1") ENDIF(NOT DEFINED <API key>)
#include <cstdio> #include <cstdlib> #include <cstdarg> #include <cstring> #include "../../Port.h" #include "../../NLS.h" #include "../GBA.h" #include "../GBAGlobals.h" #include "../GBAinline.h" #include "../GBACheats.h" #include "GBACpu.h" #include "../GBAGfx.h" #include "../GBASound.h" #include "../EEprom.h" #include "../Flash.h" #include "../Sram.h" #include "../bios.h" #include "../elf.h" #include "../RTC.h" #include "../agbprint.h" #include "../../common/System.h" #include "../../common/SystemGlobals.h" #include "../../common/Util.h" #include "../../common/movie.h" #include "../../common/vbalua.h" #ifdef PROFILING #include "../prof/prof.h" #endif #ifdef __GNUC__ #define _stricmp strcasecmp #endif static inline void interp_rate() { /* empty for now */ } int32 SWITicks = 0; int32 IRQTicks = 0; u32 mastercode = 0; int32 layerEnableDelay = 0; bool8 busPrefetch = false; bool8 busPrefetchEnable = false; u32 busPrefetchCount = 0; u32 cpuPrefetch[2]; int32 cpuDmaTicksToUpdate = 0; int32 cpuDmaCount = 0; bool8 cpuDmaHack = 0; u32 cpuDmaLast = 0; int32 dummyAddress = 0; int32 gbaSaveType = 0; // used to remember the save type on reset bool8 intState = false; bool8 stopState = false; bool8 holdState = false; int32 holdType = 0; bool8 cpuSramEnabled = true; bool8 cpuFlashEnabled = true; bool8 cpuEEPROMEnabled = true; bool8 <API key> = false; #ifdef SDL bool8 cpuBreakLoop = false; #endif // These don't seem to affect determinism int32 cpuNextEvent = 0; int32 cpuTotalTicks = 0; #ifdef PROFILING int profilingTicks = 0; int <API key> = 0; static profile_segment *profilSegment = NULL; #endif #ifdef BKPT_SUPPORT u8 freezeWorkRAM[0x40000]; u8 freezeInternalRAM[0x8000]; u8 freezeVRAM[0x18000]; u8 freezePRAM[0x400]; u8 freezeOAM[0x400]; bool debugger_last; #endif int32 lcdTicks = (useBios && !skipBios) ? 1008 : 208; u8 timerOnOffDelay = 0; u16 timer0Value = 0; bool8 timer0On = false; int32 timer0Ticks = 0; int32 timer0Reload = 0; int32 timer0ClockReload = 0; u16 timer1Value = 0; bool8 timer1On = false; int32 timer1Ticks = 0; int32 timer1Reload = 0; int32 timer1ClockReload = 0; u16 timer2Value = 0; bool8 timer2On = false; int32 timer2Ticks = 0; int32 timer2Reload = 0; int32 timer2ClockReload = 0; u16 timer3Value = 0; bool8 timer3On = false; int32 timer3Ticks = 0; int32 timer3Reload = 0; int32 timer3ClockReload = 0; u32 dma0Source = 0; u32 dma0Dest = 0; u32 dma1Source = 0; u32 dma1Dest = 0; u32 dma2Source = 0; u32 dma2Dest = 0; u32 dma3Source = 0; u32 dma3Dest = 0; void (*cpuSaveGameFunc)(u32, u8) = flashSaveDecide; void (*renderLine)() = mode0RenderLine; bool8 fxOn = false; bool8 windowOn = false; char buffer[1024]; FILE *out = NULL; const int32 TIMER_TICKS[4] = { 0, 6, 8, 10 }; extern bool8 cpuIsMultiBoot; extern const u32 objTilesAddress[3] = { 0x010000, 0x014000, 0x014000 }; const u8 gamepakRamWaitState[4] = { 4, 3, 2, 8 }; const u8 gamepakWaitState[4] = { 4, 3, 2, 8 }; const u8 gamepakWaitState0[2] = { 2, 1 }; const u8 gamepakWaitState1[2] = { 4, 1 }; const u8 gamepakWaitState2[2] = { 8, 1 }; const bool8 isInRom[16] = { false, false, false, false, false, false, false, false, true, true, true, true, true, true, false, false }; u8 memoryWait[16] = { 0, 0, 2, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 0 }; u8 memoryWait32[16] = { 0, 0, 5, 0, 0, 1, 1, 0, 7, 7, 9, 9, 13, 13, 4, 0 }; u8 memoryWaitSeq[16] = { 0, 0, 2, 0, 0, 0, 0, 0, 2, 2, 4, 4, 8, 8, 4, 0 }; u8 memoryWaitSeq32[16] = { 0, 0, 5, 0, 0, 1, 1, 0, 5, 5, 9, 9, 17, 17, 4, 0 }; // The videoMemoryWait constants are used to add some waitstates // if the opcode access video memory data outside of vblank/hblank // It seems to happen on only one ticks for each pixel. // Not used for now (too problematic with current code). //const u8 videoMemoryWait[16] = // {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}; static int32 romSize = 0x2000000; u8 biosProtected[4]; u8 cpuBitsSet[256]; u8 cpuLowestBitSet[256]; #ifdef WORDS_BIGENDIAN bool8 cpuBiosSwapped = false; #endif u32 myROM[] = { 0xEA000006, 0xEA000093, 0xEA000006, 0x00000000, 0x00000000, 0x00000000, 0xEA000088, 0x00000000, 0xE3A00302, 0xE1A0F000, 0xE92D5800, 0xE55EC002, 0xE28FB03C, 0xE79BC10C, 0xE14FB000, 0xE92D0800, 0xE20BB080, 0xE38BB01F, 0xE129F00B, 0xE92D4004, 0xE1A0E00F, 0xE12FFF1C, 0xE8BD4004, 0xE3A0C0D3, 0xE129F00C, 0xE8BD0800, 0xE169F00B, 0xE8BD5800, 0xE1B0F00E, 0x0000009C, 0x0000009C, 0x0000009C, 0x0000009C, 0x000001F8, 0x000001F0, 0x000000AC, 0x000000A0, 0x000000FC, 0x00000168, 0xE12FFF1E, 0xE1A03000, 0xE1A00001, 0xE1A01003, 0xE2113102, 0x42611000, 0xE033C040, 0x22600000, 0xE1B02001, 0xE15200A0, 0x91A02082, 0x3AFFFFFC, 0xE1500002, 0xE0A33003, 0x20400002, 0xE1320001, 0x11A020A2, 0x1AFFFFF9, 0xE1A01000, 0xE1A00003, 0xE1B0C08C, 0x22600000, 0x42611000, 0xE12FFF1E, 0xE92D0010, 0xE1A0C000, 0xE3A01001, 0xE1500001, 0x81A000A0, 0x81A01081, 0x8AFFFFFB, 0xE1A0000C, 0xE1A04001, 0xE3A03000, 0xE1A02001, 0xE15200A0, 0x91A02082, 0x3AFFFFFC, 0xE1500002, 0xE0A33003, 0x20400002, 0xE1320001, 0x11A020A2, 0x1AFFFFF9, 0xE0811003, 0xE1B010A1, 0xE1510004, 0x3AFFFFEE, 0xE1A00004, 0xE8BD0010, 0xE12FFF1E, 0xE0010090, 0xE1A01741, 0xE2611000, 0xE3A030A9, 0xE0030391, 0xE1A03743, 0xE2833E39, 0xE0030391, 0xE1A03743, 0xE2833C09, 0xE283301C, 0xE0030391, 0xE1A03743, 0xE2833C0F, 0xE28330B6, 0xE0030391, 0xE1A03743, 0xE2833C16, 0xE28330AA, 0xE0030391, 0xE1A03743, 0xE2833A02, 0xE2833081, 0xE0030391, 0xE1A03743, 0xE2833C36, 0xE2833051, 0xE0030391, 0xE1A03743, 0xE2833CA2, 0xE28330F9, 0xE0000093, 0xE1A00840, 0xE12FFF1E, 0xE3A00001, 0xE3A01001, 0xE92D4010, 0xE3A03000, 0xE3A04001, 0xE3500000, 0x1B000004, 0xE5CC3301, 0xEB000002, 0x0AFFFFFC, 0xE8BD4010, 0xE12FFF1E, 0xE3A0C301, 0xE5CC3208, 0xE15C20B8, 0xE0110002, 0x10222000, 0x114C20B8, 0xE5CC4208, 0xE12FFF1E, 0xE92D500F, 0xE3A00301, 0xE1A0E00F, 0xE510F004, 0xE8BD500F, 0xE25EF004, 0xE59FD044, 0xE92D5000, 0xE14FC000, 0xE10FE000, 0xE92D5000, 0xE3A0C302, 0xE5DCE09C, 0xE35E00A5, 0x1A000004, 0x05DCE0B4, 0x021EE080, 0xE28FE004, 0x159FF018, 0x059FF018, 0xE59FD018, 0xE8BD5000, 0xE169F00C, 0xE8BD5000, 0xE25EF004, 0x03007FF0, 0x09FE2000, 0x09FFC000, 0x03007FE0 }; variable_desc saveGameStruct[] = { { &DISPCNT, sizeof(u16) }, { &DISPSTAT, sizeof(u16) }, { &VCOUNT, sizeof(u16) }, { &BG0CNT, sizeof(u16) }, { &BG1CNT, sizeof(u16) }, { &BG2CNT, sizeof(u16) }, { &BG3CNT, sizeof(u16) }, { &BG0HOFS, sizeof(u16) }, { &BG0VOFS, sizeof(u16) }, { &BG1HOFS, sizeof(u16) }, { &BG1VOFS, sizeof(u16) }, { &BG2HOFS, sizeof(u16) }, { &BG2VOFS, sizeof(u16) }, { &BG3HOFS, sizeof(u16) }, { &BG3VOFS, sizeof(u16) }, { &BG2PA, sizeof(u16) }, { &BG2PB, sizeof(u16) }, { &BG2PC, sizeof(u16) }, { &BG2PD, sizeof(u16) }, { &BG2X_L, sizeof(u16) }, { &BG2X_H, sizeof(u16) }, { &BG2Y_L, sizeof(u16) }, { &BG2Y_H, sizeof(u16) }, { &BG3PA, sizeof(u16) }, { &BG3PB, sizeof(u16) }, { &BG3PC, sizeof(u16) }, { &BG3PD, sizeof(u16) }, { &BG3X_L, sizeof(u16) }, { &BG3X_H, sizeof(u16) }, { &BG3Y_L, sizeof(u16) }, { &BG3Y_H, sizeof(u16) }, { &WIN0H, sizeof(u16) }, { &WIN1H, sizeof(u16) }, { &WIN0V, sizeof(u16) }, { &WIN1V, sizeof(u16) }, { &WININ, sizeof(u16) }, { &WINOUT, sizeof(u16) }, { &MOSAIC, sizeof(u16) }, { &BLDMOD, sizeof(u16) }, { &COLEV, sizeof(u16) }, { &COLY, sizeof(u16) }, { &DM0SAD_L, sizeof(u16) }, { &DM0SAD_H, sizeof(u16) }, { &DM0DAD_L, sizeof(u16) }, { &DM0DAD_H, sizeof(u16) }, { &DM0CNT_L, sizeof(u16) }, { &DM0CNT_H, sizeof(u16) }, { &DM1SAD_L, sizeof(u16) }, { &DM1SAD_H, sizeof(u16) }, { &DM1DAD_L, sizeof(u16) }, { &DM1DAD_H, sizeof(u16) }, { &DM1CNT_L, sizeof(u16) }, { &DM1CNT_H, sizeof(u16) }, { &DM2SAD_L, sizeof(u16) }, { &DM2SAD_H, sizeof(u16) }, { &DM2DAD_L, sizeof(u16) }, { &DM2DAD_H, sizeof(u16) }, { &DM2CNT_L, sizeof(u16) }, { &DM2CNT_H, sizeof(u16) }, { &DM3SAD_L, sizeof(u16) }, { &DM3SAD_H, sizeof(u16) }, { &DM3DAD_L, sizeof(u16) }, { &DM3DAD_H, sizeof(u16) }, { &DM3CNT_L, sizeof(u16) }, { &DM3CNT_H, sizeof(u16) }, { &TM0D, sizeof(u16) }, { &TM0CNT, sizeof(u16) }, { &TM1D, sizeof(u16) }, { &TM1CNT, sizeof(u16) }, { &TM2D, sizeof(u16) }, { &TM2CNT, sizeof(u16) }, { &TM3D, sizeof(u16) }, { &TM3CNT, sizeof(u16) }, { &P1, sizeof(u16) }, { &IE, sizeof(u16) }, { &IF, sizeof(u16) }, { &IME, sizeof(u16) }, { &holdState, sizeof(bool8) }, { &holdType, sizeof(int32) }, { &lcdTicks, sizeof(int32) }, { &timer0On, sizeof(bool8) }, { &timer0Ticks, sizeof(int32) }, { &timer0Reload, sizeof(int32) }, { &timer0ClockReload, sizeof(int32) }, { &timer1On, sizeof(bool8) }, { &timer1Ticks, sizeof(int32) }, { &timer1Reload, sizeof(int32) }, { &timer1ClockReload, sizeof(int32) }, { &timer2On, sizeof(bool8) }, { &timer2Ticks, sizeof(int32) }, { &timer2Reload, sizeof(int32) }, { &timer2ClockReload, sizeof(int32) }, { &timer3On, sizeof(bool8) }, { &timer3Ticks, sizeof(int32) }, { &timer3Reload, sizeof(int32) }, { &timer3ClockReload, sizeof(int32) }, { &dma0Source, sizeof(u32) }, { &dma0Dest, sizeof(u32) }, { &dma1Source, sizeof(u32) }, { &dma1Dest, sizeof(u32) }, { &dma2Source, sizeof(u32) }, { &dma2Dest, sizeof(u32) }, { &dma3Source, sizeof(u32) }, { &dma3Dest, sizeof(u32) }, { &fxOn, sizeof(bool8) }, { &windowOn, sizeof(bool8) }, { &N_FLAG, sizeof(bool8) }, { &C_FLAG, sizeof(bool8) }, { &Z_FLAG, sizeof(bool8) }, { &V_FLAG, sizeof(bool8) }, { &armState, sizeof(bool8) }, { &armIrqEnable, sizeof(bool8) }, { &armNextPC, sizeof(u32) }, { &armMode, sizeof(int32) }, { &saveType, sizeof(int32) }, { NULL, 0 } }; #ifdef PROFILING void cpuProfil(profile_segment *seg) { profilSegment = seg; } void cpuEnableProfiling(int hz) { if (hz == 0) hz = 100; profilingTicks = <API key> = 16777216 / hz; profSetHertz(hz); } #endif inline int CPUUpdateTicks() { int cpuLoopTicks = lcdTicks; if (soundTicks < cpuLoopTicks) cpuLoopTicks = soundTicks; if (timer0On && (timer0Ticks < cpuLoopTicks)) { cpuLoopTicks = timer0Ticks; } if (timer1On && !(TM1CNT & 4) && (timer1Ticks < cpuLoopTicks)) { cpuLoopTicks = timer1Ticks; } if (timer2On && !(TM2CNT & 4) && (timer2Ticks < cpuLoopTicks)) { cpuLoopTicks = timer2Ticks; } if (timer3On && !(TM3CNT & 4) && (timer3Ticks < cpuLoopTicks)) { cpuLoopTicks = timer3Ticks; } #ifdef PROFILING if (<API key> != 0) { if (profilingTicks < cpuLoopTicks) { cpuLoopTicks = profilingTicks; } } #endif if (SWITicks) { if (SWITicks < cpuLoopTicks) cpuLoopTicks = SWITicks; } if (IRQTicks) { if (IRQTicks < cpuLoopTicks) cpuLoopTicks = IRQTicks; } return cpuLoopTicks; } void CPUUpdateWindow0() { int x00 = WIN0H >> 8; int x01 = WIN0H & 255; if (x00 <= x01) { for (int i = 0; i < 240; i++) { gfxInWin0[i] = (i >= x00 && i < x01); } } else { for (int i = 0; i < 240; i++) { gfxInWin0[i] = (i >= x00 || i < x01); } } } void CPUUpdateWindow1() { int x00 = WIN1H >> 8; int x01 = WIN1H & 255; if (x00 <= x01) { for (int i = 0; i < 240; i++) { gfxInWin1[i] = (i >= x00 && i < x01); } } else { for (int i = 0; i < 240; i++) { gfxInWin1[i] = (i >= x00 || i < x01); } } } #define CLEAR_ARRAY(a) \ { \ u32 *array = (a); \ for (int i = 0; i < 240; i++) { \ *array++ = 0x80000000; \ } \ } \ void <API key>(bool force) { if (!(layerEnable & 0x0100) || force) { CLEAR_ARRAY(line0); } if (!(layerEnable & 0x0200) || force) { CLEAR_ARRAY(line1); } if (!(layerEnable & 0x0400) || force) { CLEAR_ARRAY(line2); } if (!(layerEnable & 0x0800) || force) { CLEAR_ARRAY(line3); } } #undef CLEAR_ARRAY bool <API key>(gzFile gzFile) { utilWriteInt(gzFile, SAVE_GAME_VERSION); utilGzWrite(gzFile, &rom[0xa0], 16); utilWriteInt(gzFile, useBios); utilGzWrite(gzFile, &reg[0], sizeof(reg)); utilWriteData(gzFile, saveGameStruct); // new to version 0.7.1 utilWriteInt(gzFile, stopState); // new to version 0.8 utilWriteInt(gzFile, intState); utilGzWrite(gzFile, internalRAM, 0x8000); utilGzWrite(gzFile, paletteRAM, 0x400); utilGzWrite(gzFile, workRAM, 0x40000); utilGzWrite(gzFile, vram, 0x20000); utilGzWrite(gzFile, oam, 0x400); utilGzWrite(gzFile, pix, 4 * 241 * 162); utilGzWrite(gzFile, ioMem, 0x400); eepromSaveGame(gzFile); flashSaveGame(gzFile); soundSaveGame(gzFile); cheatsSaveGame(gzFile); // version 1.5 rtcSaveGame(gzFile); // SAVE_GAME_VERSION_9 (new to re-recording version which is based on 1.72) { utilGzWrite(gzFile, &sensorX, sizeof(sensorX)); utilGzWrite(gzFile, &sensorY, sizeof(sensorY)); bool8 movieActive = VBAMovieIsActive(); utilGzWrite(gzFile, &movieActive, sizeof(movieActive)); if (movieActive) { uint8 *movie_freeze_buf = NULL; uint32 movie_freeze_size = 0; int code = VBAMovieFreeze(&movie_freeze_buf, &movie_freeze_size); if (movie_freeze_buf) { utilGzWrite(gzFile, &movie_freeze_size, sizeof(movie_freeze_size)); utilGzWrite(gzFile, movie_freeze_buf, movie_freeze_size); delete [] movie_freeze_buf; } else { if (code == <API key>) { systemMessage(0, N_("Cannot make a movie snapshot as long as there are unrecorded input changes.")); } else { systemMessage(0, N_("Failed to save movie snapshot.")); } return false; } } utilGzWrite(gzFile, &systemCounters.frameCount, sizeof(systemCounters.frameCount)); } // <API key> { utilGzWrite(gzFile, &systemCounters.lagCount, sizeof(systemCounters.lagCount)); utilGzWrite(gzFile, &systemCounters.lagged, sizeof(systemCounters.lagged)); utilGzWrite(gzFile, &systemCounters.laggedLast, sizeof(systemCounters.laggedLast)); } // <API key> { utilGzWrite(gzFile, memoryWait, 16 * sizeof(u8)); utilGzWrite(gzFile, memoryWait32, 16 * sizeof(u8)); utilGzWrite(gzFile, memoryWaitSeq, 16 * sizeof(u8)); utilGzWrite(gzFile, memoryWaitSeq32, 16 * sizeof(u8)); utilGzWrite(gzFile, &speedHack, sizeof(bool8)); // just in case it's ever used... } return true; } bool CPUWriteState(const char *file) { gzFile gzFile = utilGzOpen(file, "wb"); if (gzFile == NULL) { systemMessage(<API key>, N_("Error creating file %s"), file); return false; } bool res = <API key>(gzFile); utilGzClose(gzFile); return res; } bool CPUWriteMemState(char *memory, int available) { gzFile gzFile = utilMemGzOpen(memory, available, "w"); if (gzFile == NULL) { return false; } bool res = <API key>(gzFile); long pos = utilGzTell(gzFile) + 8; if (pos >= (available)) res = false; utilGzClose(gzFile); return res; } bool <API key>(gzFile gzFile) { char tempBackupName[128]; if (tempSaveSafe) { sprintf(tempBackupName, "gbatempsave%d.sav", tempSaveID++); CPUWriteState(tempBackupName); } int version = utilReadInt(gzFile); if (version > SAVE_GAME_VERSION || version < SAVE_GAME_VERSION_1) { systemMessage(<API key>, N_("Unsupported VisualBoyAdvance save game version %d"), version); goto failedLoad; } u8 romname[17]; utilGzRead(gzFile, romname, 16); if (memcmp(&rom[0xa0], romname, 16) != 0) { romname[16] = 0; for (int i = 0; i < 16; i++) if (romname[i] < 32) romname[i] = 32; systemMessage(MSG_CANNOT_LOAD_SGM, N_("Cannot load save game for %s"), romname); goto failedLoad; } bool8 ub = utilReadInt(gzFile) ? true : false; if (ub != useBios) { if (useBios) systemMessage(<API key>, N_("Save game is not using the BIOS files")); else systemMessage(<API key>, N_("Save game is using the BIOS file")); goto failedLoad; } utilGzRead(gzFile, &reg[0], sizeof(reg)); utilReadData(gzFile, saveGameStruct); if (version < SAVE_GAME_VERSION_3) stopState = false; else stopState = utilReadInt(gzFile) ? true : false; if (version < SAVE_GAME_VERSION_4) intState = false; else intState = utilReadInt(gzFile) ? true : false; utilGzRead(gzFile, internalRAM, 0x8000); utilGzRead(gzFile, paletteRAM, 0x400); utilGzRead(gzFile, workRAM, 0x40000); utilGzRead(gzFile, vram, 0x20000); utilGzRead(gzFile, oam, 0x400); if (version < SAVE_GAME_VERSION_6) utilGzRead(gzFile, pix, 4 * 240 * 160); else utilGzRead(gzFile, pix, 4 * 241 * 162); utilGzRead(gzFile, ioMem, 0x400); if (skipSaveGameBattery) { // skip eeprom data eepromReadGameSkip(gzFile, version); // skip flash data flashReadGameSkip(gzFile, version); } else { eepromReadGame(gzFile, version); flashReadGame(gzFile, version); } soundReadGame(gzFile, version); if (version > SAVE_GAME_VERSION_1) { if (skipSaveGameCheats) { // skip cheats list data cheatsReadGameSkip(gzFile, version); } else { cheatsReadGame(gzFile, version); } } if (version > SAVE_GAME_VERSION_6) { rtcReadGame(gzFile); } if (version <= SAVE_GAME_VERSION_7) { u32 temp; #define SWAP(a, b, c) \ temp = (a); \ (a) = (b) << 16 | (c); \ (b) = (temp) >> 16; \ (c) = (temp) & 0xFFFF; SWAP(dma0Source, DM0SAD_H, DM0SAD_L); SWAP(dma0Dest, DM0DAD_H, DM0DAD_L); SWAP(dma1Source, DM1SAD_H, DM1SAD_L); SWAP(dma1Dest, DM1DAD_H, DM1DAD_L); SWAP(dma2Source, DM2SAD_H, DM2SAD_L); SWAP(dma2Dest, DM2DAD_H, DM2DAD_L); SWAP(dma3Source, DM3SAD_H, DM3SAD_L); SWAP(dma3Dest, DM3DAD_H, DM3DAD_L); } #undef SWAP if (version <= SAVE_GAME_VERSION_8) { timer0ClockReload = TIMER_TICKS[TM0CNT & 3]; timer1ClockReload = TIMER_TICKS[TM1CNT & 3]; timer2ClockReload = TIMER_TICKS[TM2CNT & 3]; timer3ClockReload = TIMER_TICKS[TM3CNT & 3]; timer0Ticks = ((0x10000 - TM0D) << timer0ClockReload) - timer0Ticks; timer1Ticks = ((0x10000 - TM1D) << timer1ClockReload) - timer1Ticks; timer2Ticks = ((0x10000 - TM2D) << timer2ClockReload) - timer2Ticks; timer3Ticks = ((0x10000 - TM3D) << timer3ClockReload) - timer3Ticks; interp_rate(); } // set pointers! layerEnable = layerSettings & DISPCNT; CPUUpdateRender(); <API key>(true); CPUUpdateWindow0(); CPUUpdateWindow1(); gbaSaveType = 0; switch (saveType) { case 0: cpuSaveGameFunc = flashSaveDecide; break; case 1: cpuSaveGameFunc = sramWrite; gbaSaveType = 1; break; case 2: cpuSaveGameFunc = flashWrite; gbaSaveType = 2; break; case 3: break; case 5: gbaSaveType = 5; break; default: systemMessage(<API key>, N_("Unsupported save type %d"), saveType); break; } if (eepromInUse) gbaSaveType = 3; <API key> = <API key>; bool wasPlayingMovie = VBAMovieIsActive() && VBAMovieIsPlaying(); if (version >= SAVE_GAME_VERSION_9) { utilGzRead(gzFile, &sensorX, sizeof(sensorX)); utilGzRead(gzFile, &sensorY, sizeof(sensorY)); bool8 movieSnapshot; utilGzRead(gzFile, &movieSnapshot, sizeof(movieSnapshot)); if (VBAMovieIsActive() && !movieSnapshot) { systemMessage(0, N_("Can't load a non-movie snapshot while a movie is active.")); goto failedLoad; } if (movieSnapshot) // even if a movie isn't active we still want to parse through this // because we have already got stuff added in this save format { uint32 movieInputDataSize = 0; utilGzRead(gzFile, &movieInputDataSize, sizeof(movieInputDataSize)); uint8 *local_movie_data = new uint8[movieInputDataSize]; int readBytes = utilGzRead(gzFile, local_movie_data, movieInputDataSize); if (readBytes != movieInputDataSize) { systemMessage(0, N_("Corrupt movie snapshot.")); delete [] local_movie_data; goto failedLoad; } int code = VBAMovieUnfreeze(local_movie_data, movieInputDataSize); delete [] local_movie_data; if (code != MOVIE_SUCCESS && VBAMovieIsActive()) { char errStr [1024]; strcpy(errStr, "Failed to load movie snapshot"); switch (code) { case <API key>: strcat(errStr, ";\nSnapshot not from this movie"); break; case <API key>: strcat(errStr, ";\nNot a movie snapshot"); break; // shouldn't get here... case <API key>: sprintf(errStr, "%s;\nSnapshot unverifiable with movie after End Frame %u", errStr, <API key>()); break; case <API key>: sprintf(errStr, "%s;\nSnapshot inconsistent with movie at Frame %u", errStr, <API key>()); break; case MOVIE_WRONG_FORMAT: strcat(errStr, ";\nWrong format"); break; } strcat(errStr, "."); systemMessage(0, N_(errStr)); goto failedLoad; } } utilGzRead(gzFile, &systemCounters.frameCount, sizeof(systemCounters.frameCount)); } if (version < <API key>) { if (version >= <API key>) { utilGzSeek(gzFile, 16 * sizeof(int32) * 6, SEEK_CUR); } if (version >= <API key>) { utilGzSeek(gzFile, sizeof(bool8) * 3, SEEK_CUR); } if (version >= <API key>) { utilGzSeek(gzFile, sizeof(bool8) * 2, SEEK_CUR); } } if (version >= <API key>) { utilGzRead(gzFile, &systemCounters.lagCount, sizeof(systemCounters.lagCount)); utilGzRead(gzFile, &systemCounters.lagged, sizeof(systemCounters.lagged)); utilGzRead(gzFile, &systemCounters.laggedLast, sizeof(systemCounters.laggedLast)); } if (version >= <API key>) { utilGzRead(gzFile, memoryWait, 16 * sizeof(u8)); utilGzRead(gzFile, memoryWait32, 16 * sizeof(u8)); utilGzRead(gzFile, memoryWaitSeq, 16 * sizeof(u8)); utilGzRead(gzFile, memoryWaitSeq32, 16 * sizeof(u8)); utilGzRead(gzFile, &speedHack, sizeof(bool8)); // just in case it's ever used... } if (armState) { ARM_PREFETCH; } else { THUMB_PREFETCH; } CPUUpdateRegister(0x204, <API key>(0x4000204)); systemSetJoypad(0, ~P1 & 0x3FF); <API key>(); <API key>(); systemRefreshScreen(); if (tempSaveSafe) { remove(tempBackupName); tempSaveAttempts = 0; } return true; failedLoad: if (tempSaveSafe) { tempSaveAttempts++; if (tempSaveAttempts < 3) // fail no more than 2 times in a row CPUReadState(tempBackupName); remove(tempBackupName); } if (wasPlayingMovie && VBAMovieIsRecording()) { <API key>(); } return false; } bool CPUReadMemState(char *memory, int available) { gzFile gzFile = utilMemGzOpen(memory, available, "r"); tempSaveSafe = false; bool res = <API key>(gzFile); tempSaveSafe = true; utilGzClose(gzFile); return res; } bool CPUReadState(const char *file) { gzFile gzFile = utilGzOpen(file, "rb"); if (gzFile == NULL) return false; bool res = <API key>(gzFile); utilGzClose(gzFile); return res; } bool CPUExportEepromFile(const char *fileName) { if (eepromInUse) { FILE *file = fopen(fileName, "wb"); if (!file) { systemMessage(<API key>, N_("Error creating file %s"), fileName); return false; } for (int i = 0; i < eepromSize; ) { for (int j = 0; j < 8; j++) { if (fwrite(&eepromData[i + 7 - j], 1, 1, file) != 1) { fclose(file); return false; } } i += 8; } fclose(file); } return true; } bool <API key>(gzFile gzFile) { if (!gzFile) return false; utilWriteInt(gzFile, SAVE_GAME_VERSION); // for simplicity, we put both types of battery files should be in the stream, even if one's empty eepromSaveGame(gzFile); flashSaveGame(gzFile); return true; } bool CPUWriteBatteryFile(const char *fileName) { if (gbaSaveType == 0) { if (eepromInUse) gbaSaveType = 3; else switch (saveType) { case 1: gbaSaveType = 1; break; case 2: gbaSaveType = 2; break; } } if ((gbaSaveType != 0) && (gbaSaveType != 5)) { FILE *file = fopen(fileName, "wb"); if (!file) { systemMessage(<API key>, N_("Error creating file %s"), fileName); return false; } // only save if Flash/Sram in use or EEprom in use if (gbaSaveType != 3) { if (gbaSaveType == 2) { if (fwrite(flashSaveMemory, 1, flashSize, file) != (size_t)flashSize) { fclose(file); return false; } } else { if (fwrite(flashSaveMemory, 1, 0x10000, file) != 0x10000) { fclose(file); return false; } } } else { if (fwrite(eepromData, 1, eepromSize, file) != (size_t)eepromSize) { fclose(file); return false; } } fclose(file); } return true; } bool CPUReadGSASnapshot(const char *fileName) { int i; FILE *file = fopen(fileName, "rb"); if (!file) { systemMessage(<API key>, N_("Cannot open file %s"), fileName); return false; } // check file size to know what we should read fseek(file, 0, SEEK_END); // long size = ftell(file); fseek(file, 0x0, SEEK_SET); fread(&i, 1, 4, file); fseek(file, i, SEEK_CUR); // Skip SharkPortSave fseek(file, 4, SEEK_CUR); // skip some sort of flag fread(&i, 1, 4, file); // name length fseek(file, i, SEEK_CUR); // skip name fread(&i, 1, 4, file); // desc length fseek(file, i, SEEK_CUR); // skip desc fread(&i, 1, 4, file); // notes length fseek(file, i, SEEK_CUR); // skip notes int saveSize; fread(&saveSize, 1, 4, file); // read length saveSize -= 0x1c; // remove header size char buffer[17]; char buffer2[17]; fread(buffer, 1, 16, file); buffer[16] = 0; for (i = 0; i < 16; i++) if (buffer[i] < 32) buffer[i] = 32; memcpy(buffer2, &rom[0xa0], 16); buffer2[16] = 0; for (i = 0; i < 16; i++) if (buffer2[i] < 32) buffer2[i] = 32; if (memcmp(buffer, buffer2, 16)) { systemMessage(<API key>, N_("Cannot import snapshot for %s. Current game is %s"), buffer, buffer2); fclose(file); return false; } fseek(file, 12, SEEK_CUR); // skip some flags if (saveSize >= 65536) { if (fread(flashSaveMemory, 1, saveSize, file) != (size_t)saveSize) { fclose(file); return false; } } else { systemMessage(<API key>, N_("Unsupported snapshot file %s"), fileName); fclose(file); return false; } fclose(file); CPUReset(); return true; } bool CPUWriteGSASnapshot(const char *fileName, const char *title, const char *desc, const char *notes) { FILE *file = fopen(fileName, "wb"); if (!file) { systemMessage(<API key>, N_("Cannot open file %s"), fileName); return false; } u8 buffer[17]; utilPutDword(buffer, 0x0d); // SharkPortSave length fwrite(buffer, 1, 4, file); fwrite("SharkPortSave", 1, 0x0d, file); utilPutDword(buffer, 0x000f0000); fwrite(buffer, 1, 4, file); // save type 0x000f0000 = GBA save utilPutDword(buffer, (u32)strlen(title)); fwrite(buffer, 1, 4, file); // title length fwrite(title, 1, strlen(title), file); utilPutDword(buffer, (u32)strlen(desc)); fwrite(buffer, 1, 4, file); // desc length fwrite(desc, 1, strlen(desc), file); utilPutDword(buffer, (u32)strlen(notes)); fwrite(buffer, 1, 4, file); // notes length fwrite(notes, 1, strlen(notes), file); int saveSize = 0x10000; if (gbaSaveType == 2) saveSize = flashSize; int totalSize = saveSize + 0x1c; utilPutDword(buffer, totalSize); // length of remainder of save - CRC fwrite(buffer, 1, 4, file); char *temp = new char[0x2001c]; memset(temp, 0, 28); memcpy(temp, &rom[0xa0], 16); // copy internal name temp[0x10] = rom[0xbe]; // reserved area (old checksum) temp[0x11] = rom[0xbf]; // reserved area (old checksum) temp[0x12] = rom[0xbd]; // complement check temp[0x13] = rom[0xb0]; // maker temp[0x14] = 1; // 1 save ? memcpy(&temp[0x1c], flashSaveMemory, saveSize); // copy save fwrite(temp, 1, totalSize, file); // write save + header u32 crc = 0; for (int i = 0; i < totalSize; i++) { crc += ((u32)temp[i] << (crc % 0x18)); } utilPutDword(buffer, crc); fwrite(buffer, 1, 4, file); // CRC? fclose(file); delete [] temp; return true; } bool CPUImportEepromFile(const char *fileName) { FILE *file = fopen(fileName, "rb"); if (!file) return false; // check file size to know what we should read fseek(file, 0, SEEK_END); long size = ftell(file); fseek(file, 0, SEEK_SET); if (size == 512 || size == 0x2000) { if (fread(eepromData, 1, size, file) != (size_t)size) { fclose(file); return false; } for (int i = 0; i < size; ) { u8 tmp = eepromData[i]; eepromData[i] = eepromData[7 - i]; eepromData[7 - i] = tmp; i++; tmp = eepromData[i]; eepromData[i] = eepromData[7 - i]; eepromData[7 - i] = tmp; i++; tmp = eepromData[i]; eepromData[i] = eepromData[7 - i]; eepromData[7 - i] = tmp; i++; tmp = eepromData[i]; eepromData[i] = eepromData[7 - i]; eepromData[7 - i] = tmp; i++; i += 4; } } else { fclose(file); return false; } fclose(file); return true; } bool <API key>(gzFile gzFile) { if (!gzFile) return false; int version = utilReadInt(gzFile); // for simplicity, we put both types of battery files should be in the stream, even if one's empty eepromReadGame(gzFile, version); flashReadGame(gzFile, version); return true; } bool CPUReadBatteryFile(const char *fileName) { FILE *file = fopen(fileName, "rb"); if (!file) return false; // check file size to know what we should read fseek(file, 0, SEEK_END); long size = ftell(file); fseek(file, 0, SEEK_SET); <API key> = <API key>; if (size == 512 || size == 0x2000) { if (fread(eepromData, 1, size, file) != (size_t)size) { fclose(file); return false; } } else { if (size == 0x20000) { if (fread(flashSaveMemory, 1, 0x20000, file) != 0x20000) { fclose(file); return false; } flashSetSize(0x20000); } else { if (fread(flashSaveMemory, 1, 0x10000, file) != 0x10000) { fclose(file); return false; } flashSetSize(0x10000); } } fclose(file); return true; } bool CPUWritePNGFile(const char *fileName) { return utilWritePNGFile(fileName, 240, 160, pix); } bool CPUWriteBMPFile(const char *fileName) { return utilWriteBMPFile(fileName, 240, 160, pix); } void CPUCleanUp() { #ifdef PROFILING if (<API key>) { profCleanup(); } #endif PIX_FREE(pix); pix = NULL; free(bios); bios = NULL; free(rom); rom = NULL; free(internalRAM); internalRAM = NULL; free(workRAM); workRAM = NULL; free(paletteRAM); paletteRAM = NULL; free(vram); vram = NULL; free(oam); oam = NULL; free(ioMem); ioMem = NULL; #if 0 eepromErase(); flashErase(); #endif #ifndef NO_DEBUGGER elfCleanUp(); #endif systemCleanUp(); systemRefreshScreen(); } int CPULoadRom(const char *szFile) { int size = 0x2000000; if (rom != NULL) { CPUCleanUp(); } <API key> = <API key>; rom = (u8 *)malloc(0x2000000); if (rom == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "ROM"); return 0; } // FIXME: size+4 is so RAM search and watch are safe to read any byte in the allocated region as a 4-byte int workRAM = (u8 *)RAM_CALLOC(0x40000); if (workRAM == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "WRAM"); return 0; } u8 *whereToLoad = cpuIsMultiBoot ? workRAM : rom; #ifndef NO_DEBUGGER if (utilIsELF(szFile)) { FILE *f = fopen(szFile, "rb"); if (!f) { systemMessage(<API key>, N_("Error opening image %s"), szFile); CPUCleanUp(); return 0; } bool res = elfRead(szFile, size, f); if (!res || size == 0) { CPUCleanUp(); elfCleanUp(); return 0; } } else #endif //NO_DEBUGGER if (szFile != NULL) { if (!utilLoad(szFile, utilIsGBAImage, whereToLoad, size)) { CPUCleanUp(); return 0; } } u16 *temp = (u16 *)(rom + ((size + 1) & ~1)); for (int i = (size + 1) & ~1; i < 0x2000000; i += 2) { WRITE16LE(temp, (i >> 1) & 0xFFFF); temp++; } pix = (u8 *)PIX_CALLOC(4 * 241 * 162); if (pix == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "PIX"); CPUCleanUp(); return 0; } bios = (u8 *)RAM_CALLOC(0x4000); if (bios == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "BIOS"); CPUCleanUp(); return 0; } internalRAM = (u8 *)RAM_CALLOC(0x8000); if (internalRAM == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "IRAM"); CPUCleanUp(); return 0; } paletteRAM = (u8 *)RAM_CALLOC(0x400); if (paletteRAM == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "PRAM"); CPUCleanUp(); return 0; } vram = (u8 *)RAM_CALLOC(0x20000); if (vram == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "VRAM"); CPUCleanUp(); return 0; } oam = (u8 *)RAM_CALLOC(0x400); if (oam == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "OAM"); CPUCleanUp(); return 0; } ioMem = (u8 *)RAM_CALLOC(0x400); if (ioMem == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "IO"); CPUCleanUp(); return 0; } flashInit(); eepromInit(); <API key>(true); romSize = size; return size; } void CPUDoMirroring(bool b) { u32 mirroredRomSize = (((romSize) >> 20) & 0x3F) << 20; u32 mirroredRomAddress = romSize; if ((mirroredRomSize <= 0x800000) && (b)) { mirroredRomAddress = mirroredRomSize; if (mirroredRomSize == 0) mirroredRomSize = 0x100000; while (mirroredRomAddress < 0x01000000) { memcpy((u16 *)(rom + mirroredRomAddress), (u16 *)(rom), mirroredRomSize); mirroredRomAddress += mirroredRomSize; } } } // Emulates the Cheat System (m) code void CPUMasterCodeCheck() { if (cheatsEnabled) { if ((mastercode) && (mastercode == armNextPC)) { u32 joy = 0; if (systemReadJoypads()) joy = systemGetJoypad(0, <API key>); u32 ext = (joy >> 10); cpuTotalTicks += cheatsCheckKeys(P1 ^ 0x3FF, ext); } } } void CPUUpdateRender() { switch (DISPCNT & 7) { case 0: if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) || cpuDisableSfx) renderLine = mode0RenderLine; else if (fxOn && !windowOn && !(layerEnable & 0x8000)) renderLine = <API key>; else renderLine = mode0RenderLineAll; break; case 1: if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) || cpuDisableSfx) renderLine = mode1RenderLine; else if (fxOn && !windowOn && !(layerEnable & 0x8000)) renderLine = <API key>; else renderLine = mode1RenderLineAll; break; case 2: if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) || cpuDisableSfx) renderLine = mode2RenderLine; else if (fxOn && !windowOn && !(layerEnable & 0x8000)) renderLine = <API key>; else renderLine = mode2RenderLineAll; break; case 3: if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) || cpuDisableSfx) renderLine = mode3RenderLine; else if (fxOn && !windowOn && !(layerEnable & 0x8000)) renderLine = <API key>; else renderLine = mode3RenderLineAll; break; case 4: if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) || cpuDisableSfx) renderLine = mode4RenderLine; else if (fxOn && !windowOn && !(layerEnable & 0x8000)) renderLine = <API key>; else renderLine = mode4RenderLineAll; break; case 5: if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) || cpuDisableSfx) renderLine = mode5RenderLine; else if (fxOn && !windowOn && !(layerEnable & 0x8000)) renderLine = <API key>; else renderLine = mode5RenderLineAll; default: break; } } void CPUUpdateCPSR() { u32 CPSR = reg[16].I & 0x40; if (N_FLAG) CPSR |= 0x80000000; if (Z_FLAG) CPSR |= 0x40000000; if (C_FLAG) CPSR |= 0x20000000; if (V_FLAG) CPSR |= 0x10000000; if (!armState) CPSR |= 0x00000020; if (!armIrqEnable) CPSR |= 0x80; CPSR |= (armMode & 0x1F); reg[16].I = CPSR; } void CPUUpdateFlags(bool breakLoop) { u32 CPSR = reg[16].I; N_FLAG = (CPSR & 0x80000000) ? true : false; Z_FLAG = (CPSR & 0x40000000) ? true : false; C_FLAG = (CPSR & 0x20000000) ? true : false; V_FLAG = (CPSR & 0x10000000) ? true : false; armState = (CPSR & 0x20) ? false : true; armIrqEnable = (CPSR & 0x80) ? false : true; if (breakLoop) { if (armIrqEnable && (IF & IE) && (IME & 1)) cpuNextEvent = cpuTotalTicks; } } void CPUUpdateFlags() { CPUUpdateFlags(true); } #ifdef WORDS_BIGENDIAN static void CPUSwap(volatile u32 *a, volatile u32 *b) { volatile u32 c = *b; *b = *a; *a = c; } #else static void CPUSwap(u32 *a, u32 *b) { u32 c = *b; *b = *a; *a = c; } #endif void CPUSwitchMode(int mode, bool saveState, bool breakLoop) { // if(armMode == mode) // return; CPUUpdateCPSR(); switch (armMode) { case 0x10: case 0x1F: reg[R13_USR].I = reg[13].I; reg[R14_USR].I = reg[14].I; reg[17].I = reg[16].I; break; case 0x11: CPUSwap(&reg[R8_FIQ].I, &reg[8].I); CPUSwap(&reg[R9_FIQ].I, &reg[9].I); CPUSwap(&reg[R10_FIQ].I, &reg[10].I); CPUSwap(&reg[R11_FIQ].I, &reg[11].I); CPUSwap(&reg[R12_FIQ].I, &reg[12].I); reg[R13_FIQ].I = reg[13].I; reg[R14_FIQ].I = reg[14].I; reg[SPSR_FIQ].I = reg[17].I; break; case 0x12: reg[R13_IRQ].I = reg[13].I; reg[R14_IRQ].I = reg[14].I; reg[SPSR_IRQ].I = reg[17].I; break; case 0x13: reg[R13_SVC].I = reg[13].I; reg[R14_SVC].I = reg[14].I; reg[SPSR_SVC].I = reg[17].I; break; case 0x17: reg[R13_ABT].I = reg[13].I; reg[R14_ABT].I = reg[14].I; reg[SPSR_ABT].I = reg[17].I; break; case 0x1b: reg[R13_UND].I = reg[13].I; reg[R14_UND].I = reg[14].I; reg[SPSR_UND].I = reg[17].I; break; } u32 CPSR = reg[16].I; u32 SPSR = reg[17].I; switch (mode) { case 0x10: case 0x1F: reg[13].I = reg[R13_USR].I; reg[14].I = reg[R14_USR].I; reg[16].I = SPSR; break; case 0x11: CPUSwap(&reg[8].I, &reg[R8_FIQ].I); CPUSwap(&reg[9].I, &reg[R9_FIQ].I); CPUSwap(&reg[10].I, &reg[R10_FIQ].I); CPUSwap(&reg[11].I, &reg[R11_FIQ].I); CPUSwap(&reg[12].I, &reg[R12_FIQ].I); reg[13].I = reg[R13_FIQ].I; reg[14].I = reg[R14_FIQ].I; if (saveState) reg[17].I = CPSR; else reg[17].I = reg[SPSR_FIQ].I; break; case 0x12: reg[13].I = reg[R13_IRQ].I; reg[14].I = reg[R14_IRQ].I; reg[16].I = SPSR; if (saveState) reg[17].I = CPSR; else reg[17].I = reg[SPSR_IRQ].I; break; case 0x13: reg[13].I = reg[R13_SVC].I; reg[14].I = reg[R14_SVC].I; reg[16].I = SPSR; if (saveState) reg[17].I = CPSR; else reg[17].I = reg[SPSR_SVC].I; break; case 0x17: reg[13].I = reg[R13_ABT].I; reg[14].I = reg[R14_ABT].I; reg[16].I = SPSR; if (saveState) reg[17].I = CPSR; else reg[17].I = reg[SPSR_ABT].I; break; case 0x1b: reg[13].I = reg[R13_UND].I; reg[14].I = reg[R14_UND].I; reg[16].I = SPSR; if (saveState) reg[17].I = CPSR; else reg[17].I = reg[SPSR_UND].I; break; default: systemMessage(<API key>, N_("Unsupported ARM mode %02x"), mode); break; } armMode = mode; CPUUpdateFlags(breakLoop); CPUUpdateCPSR(); } void CPUSwitchMode(int mode, bool saveState) { CPUSwitchMode(mode, saveState, true); } void <API key>() { u32 PC = reg[15].I; bool savedArmState = armState; CPUSwitchMode(0x1b, true, false); reg[14].I = PC - (savedArmState ? 4 : 2); reg[15].I = 0x04; armState = true; armIrqEnable = false; armNextPC = 0x04; ARM_PREFETCH; reg[15].I += 4; } void <API key>() { u32 PC = reg[15].I; bool savedArmState = armState; CPUSwitchMode(0x13, true, false); reg[14].I = PC - (savedArmState ? 4 : 2); reg[15].I = 0x08; armState = true; armIrqEnable = false; armNextPC = 0x08; ARM_PREFETCH; reg[15].I += 4; } void <API key>(int comment) { static bool disableMessage = false; if (armState) comment >>= 16; #ifdef BKPT_SUPPORT if (comment == 0xff) { dbgOutput(NULL, reg[0].I); return; } #endif #ifdef PROFILING if (comment == 0xfe) { profStartup(reg[0].I, reg[1].I); return; } if (comment == 0xfd) { profControl(reg[0].I); return; } if (comment == 0xfc) { profCleanup(); return; } if (comment == 0xfb) { profCount(); return; } #endif if (comment == 0xfa) { agbPrintFlush(); return; } #ifdef SDL if (comment == 0xf9) { emulating = 0; cpuNextEvent = cpuTotalTicks; cpuBreakLoop = true; return; } #endif if (useBios) { #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_SWI) { log("SWI: %08x at %08x (0x%08x,0x%08x,0x%08x,VCOUNT = %2d)\n", comment, armState ? armNextPC - 4 : armNextPC - 2, reg[0].I, reg[1].I, reg[2].I, VCOUNT); } #endif <API key>(); return; } // This would be correct, but it causes problems if uncommented // else { // biosProtected = 0xe3a02004; switch (comment) { case 0x00: BIOS_SoftReset(); ARM_PREFETCH; break; case 0x01: <API key>(); break; case 0x02: #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_SWI) { log("Halt: (VCOUNT = %2d)\n", VCOUNT); } #endif holdState = true; holdType = -1; cpuNextEvent = cpuTotalTicks; break; case 0x03: #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_SWI) { log("Stop: (VCOUNT = %2d)\n", VCOUNT); } #endif holdState = true; holdType = -1; stopState = true; cpuNextEvent = cpuTotalTicks; break; case 0x04: #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_SWI) { log("IntrWait: 0x%08x,0x%08x (VCOUNT = %2d)\n", reg[0].I, reg[1].I, VCOUNT); } #endif <API key>(); break; case 0x05: #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_SWI) { log("VBlankIntrWait: (VCOUNT = %2d)\n", VCOUNT); } #endif <API key>(); break; case 0x06: <API key>(); break; case 0x07: <API key>(); break; case 0x08: BIOS_Sqrt(); break; case 0x09: BIOS_ArcTan(); break; case 0x0A: BIOS_ArcTan2(); break; case 0x0B: { int len = (reg[2].I & 0x1FFFFF) >> 1; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + len) & 0xe000000) == 0)) { if ((reg[2].I >> 24) & 1) { if ((reg[2].I >> 26) & 1) SWITicks = (7 + memoryWait32[(reg[1].I >> 24) & 0xF]) * (len >> 1); else SWITicks = (8 + memoryWait[(reg[1].I >> 24) & 0xF]) * (len); } else { if ((reg[2].I >> 26) & 1) SWITicks = (10 + memoryWait32[(reg[0].I >> 24) & 0xF] + memoryWait32[(reg[1].I >> 24) & 0xF]) * (len >> 1); else SWITicks = (11 + memoryWait[(reg[0].I >> 24) & 0xF] + memoryWait[(reg[1].I >> 24) & 0xF]) * len; } } } BIOS_CpuSet(); break; case 0x0C: { int len = (reg[2].I & 0x1FFFFF) >> 5; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + len) & 0xe000000) == 0)) { if ((reg[2].I >> 24) & 1) SWITicks = (6 + memoryWait32[(reg[1].I >> 24) & 0xF] + 7 * (memoryWaitSeq32[(reg[1].I >> 24) & 0xF] + 1)) * len; else SWITicks = (9 + memoryWait32[(reg[0].I >> 24) & 0xF] + memoryWait32[(reg[1].I >> 24) & 0xF] + 7 * (memoryWaitSeq32[(reg[0].I >> 24) & 0xF] + memoryWaitSeq32[(reg[1].I >> 24) & 0xF] + 2)) * len; } } BIOS_CpuFastSet(); break; case 0x0D: <API key>(); break; case 0x0E: BIOS_BgAffineSet(); break; case 0x0F: BIOS_ObjAffineSet(); break; case 0x10: { int len = CPUReadHalfWord(reg[2].I); if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + len) & 0xe000000) == 0)) SWITicks = (32 + memoryWait[(reg[0].I >> 24) & 0xF]) * len; } BIOS_BitUnPack(); break; case 0x11: { u32 len = CPUReadMemory(reg[0].I) >> 8; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0)) SWITicks = (9 + memoryWait[(reg[1].I >> 24) & 0xF]) * len; } BIOS_LZ77UnCompWram(); break; case 0x12: { u32 len = CPUReadMemory(reg[0].I) >> 8; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0)) SWITicks = (19 + memoryWait[(reg[1].I >> 24) & 0xF]) * len; } BIOS_LZ77UnCompVram(); break; case 0x13: { u32 len = CPUReadMemory(reg[0].I) >> 8; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0)) SWITicks = (29 + (memoryWait[(reg[0].I >> 24) & 0xF] << 1)) * len; } BIOS_HuffUnComp(); break; case 0x14: { u32 len = CPUReadMemory(reg[0].I) >> 8; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0)) SWITicks = (11 + memoryWait[(reg[0].I >> 24) & 0xF] + memoryWait[(reg[1].I >> 24) & 0xF]) * len; } BIOS_RLUnCompWram(); break; case 0x15: { u32 len = CPUReadMemory(reg[0].I) >> 9; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0)) SWITicks = (34 + (memoryWait[(reg[0].I >> 24) & 0xF] << 1) + memoryWait[(reg[1].I >> 24) & 0xF]) * len; } BIOS_RLUnCompVram(); break; case 0x16: { u32 len = CPUReadMemory(reg[0].I) >> 8; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0)) SWITicks = (13 + memoryWait[(reg[0].I >> 24) & 0xF] + memoryWait[(reg[1].I >> 24) & 0xF]) * len; } <API key>(); break; case 0x17: { u32 len = CPUReadMemory(reg[0].I) >> 9; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0)) SWITicks = (39 + (memoryWait[(reg[0].I >> 24) & 0xF] << 1) + memoryWait[(reg[1].I >> 24) & 0xF]) * len; } <API key>(); break; case 0x18: { u32 len = CPUReadMemory(reg[0].I) >> 9; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0)) SWITicks = (13 + memoryWait[(reg[0].I >> 24) & 0xF] + memoryWait[(reg[1].I >> 24) & 0xF]) * len; } <API key>(); break; case 0x19: #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_SWI) { log("SoundBiasSet: 0x%08x (VCOUNT = %2d)\n", reg[0].I, VCOUNT); } #endif if (reg[0].I) systemSoundPause(); else systemSoundResume(); break; case 0x1F: BIOS_MidiKey2Freq(); break; case 0x2A: <API key>(); // let it go, because we don't really emulate this function // FIXME (?) default: #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_SWI) { log("SWI: %08x at %08x (0x%08x,0x%08x,0x%08x,VCOUNT = %2d)\n", comment, armState ? armNextPC - 4 : armNextPC - 2, reg[0].I, reg[1].I, reg[2].I, VCOUNT); } #endif if (!disableMessage) { systemMessage(<API key>, N_("Unsupported BIOS function %02x called from %08x. A BIOS file is needed in order to get correct behaviour."), comment, armMode ? armNextPC - 4 : armNextPC - 2); disableMessage = true; } break; } } void CPUCompareVCOUNT() { if (VCOUNT == (DISPSTAT >> 8)) { DISPSTAT |= 4; UPDATE_REG(0x04, DISPSTAT); if (DISPSTAT & 0x20) { IF |= 4; UPDATE_REG(0x202, IF); } } else { DISPSTAT &= 0xFFFB; UPDATE_REG(0x4, DISPSTAT); } if (layerEnableDelay > 0) { --layerEnableDelay; if (layerEnableDelay == 1) layerEnable = layerSettings & DISPCNT; } } static void doDMA(u32 &s, u32 &d, u32 si, u32 di, u32 c, int transfer32) { int sm = s >> 24; int dm = d >> 24; int sw = 0; int dw = 0; int sc = c; cpuDmaCount = c; // This is done to get the correct waitstates. if (sm > 15) sm = 15; if (dm > 15) dm = 15; //if ((sm>=0x05) && (sm<=0x07) || (dm>=0x05) && (dm <=0x07)) // blank = (((DISPSTAT | ((DISPSTAT>>1)&1))==1) ? true : false); if (transfer32) { s &= 0xFFFFFFFC; if (s < 0x02000000 && (reg[15].I >> 24)) { while (c != 0) { CPUWriteMemory(d, 0); d += di; c } } else { while (c != 0) { cpuDmaLast = CPUReadMemory(s); CPUWriteMemory(d, cpuDmaLast); d += di; s += si; c } } } else { s &= 0xFFFFFFFE; si = (int)si >> 1; di = (int)di >> 1; if (s < 0x02000000 && (reg[15].I >> 24)) { while (c != 0) { CPUWriteHalfWord(d, 0); d += di; c } } else { while (c != 0) { cpuDmaLast = CPUReadHalfWord(s); CPUWriteHalfWord(d, cpuDmaLast); cpuDmaLast |= (cpuDmaLast << 16); d += di; s += si; c } } } cpuDmaCount = 0; int totalTicks = 0; if (transfer32) { sw = 1 + memoryWaitSeq32[sm & 15]; dw = 1 + memoryWaitSeq32[dm & 15]; totalTicks = (sw + dw) * (sc - 1) + 6 + memoryWait32[sm & 15] + memoryWaitSeq32[dm & 15]; } else { sw = 1 + memoryWaitSeq[sm & 15]; dw = 1 + memoryWaitSeq[dm & 15]; totalTicks = (sw + dw) * (sc - 1) + 6 + memoryWait[sm & 15] + memoryWaitSeq[dm & 15]; } cpuDmaTicksToUpdate += totalTicks; } void CPUCheckDMA(int reason, int dmamask) { // DMA 0 if ((DM0CNT_H & 0x8000) && (dmamask & 1)) { if (((DM0CNT_H >> 12) & 3) == reason) { u32 sourceIncrement = 4; u32 destIncrement = 4; switch ((DM0CNT_H >> 7) & 3) { case 0: break; case 1: sourceIncrement = (u32) - 4; break; case 2: sourceIncrement = 0; break; } switch ((DM0CNT_H >> 5) & 3) { case 0: break; case 1: destIncrement = (u32) - 4; break; case 2: destIncrement = 0; break; } #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_DMA0) { int count = (DM0CNT_L ? DM0CNT_L : 0x4000) << 1; if (DM0CNT_H & 0x0400) count <<= 1; log("DMA0: s=%08x d=%08x c=%04x count=%08x\n", dma0Source, dma0Dest, DM0CNT_H, count); } #endif doDMA(dma0Source, dma0Dest, sourceIncrement, destIncrement, DM0CNT_L ? DM0CNT_L : 0x4000, DM0CNT_H & 0x0400); cpuDmaHack = true; if (DM0CNT_H & 0x4000) { IF |= 0x0100; UPDATE_REG(0x202, IF); cpuNextEvent = cpuTotalTicks; } if (((DM0CNT_H >> 5) & 3) == 3) { dma0Dest = DM0DAD_L | (DM0DAD_H << 16); } if (!(DM0CNT_H & 0x0200) || (reason == 0)) { DM0CNT_H &= 0x7FFF; UPDATE_REG(0xBA, DM0CNT_H); } } } // DMA 1 if ((DM1CNT_H & 0x8000) && (dmamask & 2)) { if (((DM1CNT_H >> 12) & 3) == reason) { u32 sourceIncrement = 4; u32 destIncrement = 4; switch ((DM1CNT_H >> 7) & 3) { case 0: break; case 1: sourceIncrement = (u32) - 4; break; case 2: sourceIncrement = 0; break; } switch ((DM1CNT_H >> 5) & 3) { case 0: break; case 1: destIncrement = (u32) - 4; break; case 2: destIncrement = 0; break; } if (reason == 3) { #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_DMA1) { log("DMA1: s=%08x d=%08x c=%04x count=%08x\n", dma1Source, dma1Dest, DM1CNT_H, 16); } #endif doDMA(dma1Source, dma1Dest, sourceIncrement, 0, 4, 0x0400); } else { #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_DMA1) { int count = (DM1CNT_L ? DM1CNT_L : 0x4000) << 1; if (DM1CNT_H & 0x0400) count <<= 1; log("DMA1: s=%08x d=%08x c=%04x count=%08x\n", dma1Source, dma1Dest, DM1CNT_H, count); } #endif doDMA(dma1Source, dma1Dest, sourceIncrement, destIncrement, DM1CNT_L ? DM1CNT_L : 0x4000, DM1CNT_H & 0x0400); } cpuDmaHack = true; if (DM1CNT_H & 0x4000) { IF |= 0x0200; UPDATE_REG(0x202, IF); cpuNextEvent = cpuTotalTicks; } if (((DM1CNT_H >> 5) & 3) == 3) { dma1Dest = DM1DAD_L | (DM1DAD_H << 16); } if (!(DM1CNT_H & 0x0200) || (reason == 0)) { DM1CNT_H &= 0x7FFF; UPDATE_REG(0xC6, DM1CNT_H); } } } // DMA 2 if ((DM2CNT_H & 0x8000) && (dmamask & 4)) { if (((DM2CNT_H >> 12) & 3) == reason) { u32 sourceIncrement = 4; u32 destIncrement = 4; switch ((DM2CNT_H >> 7) & 3) { case 0: break; case 1: sourceIncrement = (u32) - 4; break; case 2: sourceIncrement = 0; break; } switch ((DM2CNT_H >> 5) & 3) { case 0: break; case 1: destIncrement = (u32) - 4; break; case 2: destIncrement = 0; break; } if (reason == 3) { #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_DMA2) { int count = (4) << 2; log("DMA2: s=%08x d=%08x c=%04x count=%08x\n", dma2Source, dma2Dest, DM2CNT_H, count); } #endif doDMA(dma2Source, dma2Dest, sourceIncrement, 0, 4, 0x0400); } else { #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_DMA2) { int count = (DM2CNT_L ? DM2CNT_L : 0x4000) << 1; if (DM2CNT_H & 0x0400) count <<= 1; log("DMA2: s=%08x d=%08x c=%04x count=%08x\n", dma2Source, dma2Dest, DM2CNT_H, count); } #endif doDMA(dma2Source, dma2Dest, sourceIncrement, destIncrement, DM2CNT_L ? DM2CNT_L : 0x4000, DM2CNT_H & 0x0400); } cpuDmaHack = true; if (DM2CNT_H & 0x4000) { IF |= 0x0400; UPDATE_REG(0x202, IF); cpuNextEvent = cpuTotalTicks; } if (((DM2CNT_H >> 5) & 3) == 3) { dma2Dest = DM2DAD_L | (DM2DAD_H << 16); } if (!(DM2CNT_H & 0x0200) || (reason == 0)) { DM2CNT_H &= 0x7FFF; UPDATE_REG(0xD2, DM2CNT_H); } } } // DMA 3 if ((DM3CNT_H & 0x8000) && (dmamask & 8)) { if (((DM3CNT_H >> 12) & 3) == reason) { u32 sourceIncrement = 4; u32 destIncrement = 4; switch ((DM3CNT_H >> 7) & 3) { case 0: break; case 1: sourceIncrement = (u32) - 4; break; case 2: sourceIncrement = 0; break; } switch ((DM3CNT_H >> 5) & 3) { case 0: break; case 1: destIncrement = (u32) - 4; break; case 2: destIncrement = 0; break; } #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_DMA3) { int count = (DM3CNT_L ? DM3CNT_L : 0x10000) << 1; if (DM3CNT_H & 0x0400) count <<= 1; log("DMA3: s=%08x d=%08x c=%04x count=%08x\n", dma3Source, dma3Dest, DM3CNT_H, count); } #endif doDMA(dma3Source, dma3Dest, sourceIncrement, destIncrement, DM3CNT_L ? DM3CNT_L : 0x10000, DM3CNT_H & 0x0400); if (DM3CNT_H & 0x4000) { IF |= 0x0800; UPDATE_REG(0x202, IF); cpuNextEvent = cpuTotalTicks; } if (((DM3CNT_H >> 5) & 3) == 3) { dma3Dest = DM3DAD_L | (DM3DAD_H << 16); } if (!(DM3CNT_H & 0x0200) || (reason == 0)) { DM3CNT_H &= 0x7FFF; UPDATE_REG(0xDE, DM3CNT_H); } } } } void CPUUpdateRegister(u32 address, u16 value) { switch (address) { case 0x00: { if ((value & 7) > 5) { // display modes above 0-5 are prohibited DISPCNT = (value & 7); } bool change = (0 != ((DISPCNT ^ value) & 0x80)); bool changeBG = (0 != ((DISPCNT ^ value) & 0x0F00)); u16 changeBGon = ((~DISPCNT) & value) & 0x0F00; // these layers are being activated DISPCNT = (value & 0xFFF7); // bit 3 can only be accessed by the BIOS to enable GBC mode UPDATE_REG(0x00, DISPCNT); if (changeBGon) { layerEnableDelay = 4; layerEnable = layerSettings & value & (~changeBGon); } else { layerEnable = layerSettings & value; // CPUUpdateTicks(); // what does this do? } windowOn = (layerEnable & 0x6000) ? true : false; if (change && !((value & 0x80))) { if (!(DISPSTAT & 1)) { lcdTicks = 1008; // VCOUNT = 0; // UPDATE_REG(0x06, VCOUNT); DISPSTAT &= 0xFFFC; UPDATE_REG(0x04, DISPSTAT); CPUCompareVCOUNT(); } // (*renderLine)(); } CPUUpdateRender(); // we only care about changes in BG0-BG3 if (changeBG) { <API key>(false); } break; } case 0x04: DISPSTAT = (value & 0xFF38) | (DISPSTAT & 7); UPDATE_REG(0x04, DISPSTAT); break; case 0x06: // not writable break; case 0x08: BG0CNT = (value & 0xDFCF); UPDATE_REG(0x08, BG0CNT); break; case 0x0A: BG1CNT = (value & 0xDFCF); UPDATE_REG(0x0A, BG1CNT); break; case 0x0C: BG2CNT = (value & 0xFFCF); UPDATE_REG(0x0C, BG2CNT); break; case 0x0E: BG3CNT = (value & 0xFFCF); UPDATE_REG(0x0E, BG3CNT); break; case 0x10: BG0HOFS = value & 511; UPDATE_REG(0x10, BG0HOFS); break; case 0x12: BG0VOFS = value & 511; UPDATE_REG(0x12, BG0VOFS); break; case 0x14: BG1HOFS = value & 511; UPDATE_REG(0x14, BG1HOFS); break; case 0x16: BG1VOFS = value & 511; UPDATE_REG(0x16, BG1VOFS); break; case 0x18: BG2HOFS = value & 511; UPDATE_REG(0x18, BG2HOFS); break; case 0x1A: BG2VOFS = value & 511; UPDATE_REG(0x1A, BG2VOFS); break; case 0x1C: BG3HOFS = value & 511; UPDATE_REG(0x1C, BG3HOFS); break; case 0x1E: BG3VOFS = value & 511; UPDATE_REG(0x1E, BG3VOFS); break; case 0x20: BG2PA = value; UPDATE_REG(0x20, BG2PA); break; case 0x22: BG2PB = value; UPDATE_REG(0x22, BG2PB); break; case 0x24: BG2PC = value; UPDATE_REG(0x24, BG2PC); break; case 0x26: BG2PD = value; UPDATE_REG(0x26, BG2PD); break; case 0x28: BG2X_L = value; UPDATE_REG(0x28, BG2X_L); gfxBG2Changed |= 1; break; case 0x2A: BG2X_H = (value & 0xFFF); UPDATE_REG(0x2A, BG2X_H); gfxBG2Changed |= 1; break; case 0x2C: BG2Y_L = value; UPDATE_REG(0x2C, BG2Y_L); gfxBG2Changed |= 2; break; case 0x2E: BG2Y_H = value & 0xFFF; UPDATE_REG(0x2E, BG2Y_H); gfxBG2Changed |= 2; break; case 0x30: BG3PA = value; UPDATE_REG(0x30, BG3PA); break; case 0x32: BG3PB = value; UPDATE_REG(0x32, BG3PB); break; case 0x34: BG3PC = value; UPDATE_REG(0x34, BG3PC); break; case 0x36: BG3PD = value; UPDATE_REG(0x36, BG3PD); break; case 0x38: BG3X_L = value; UPDATE_REG(0x38, BG3X_L); gfxBG3Changed |= 1; break; case 0x3A: BG3X_H = value & 0xFFF; UPDATE_REG(0x3A, BG3X_H); gfxBG3Changed |= 1; break; case 0x3C: BG3Y_L = value; UPDATE_REG(0x3C, BG3Y_L); gfxBG3Changed |= 2; break; case 0x3E: BG3Y_H = value & 0xFFF; UPDATE_REG(0x3E, BG3Y_H); gfxBG3Changed |= 2; break; case 0x40: WIN0H = value; UPDATE_REG(0x40, WIN0H); CPUUpdateWindow0(); break; case 0x42: WIN1H = value; UPDATE_REG(0x42, WIN1H); CPUUpdateWindow1(); break; case 0x44: WIN0V = value; UPDATE_REG(0x44, WIN0V); break; case 0x46: WIN1V = value; UPDATE_REG(0x46, WIN1V); break; case 0x48: WININ = value & 0x3F3F; UPDATE_REG(0x48, WININ); break; case 0x4A: WINOUT = value & 0x3F3F; UPDATE_REG(0x4A, WINOUT); break; case 0x4C: MOSAIC = value; UPDATE_REG(0x4C, MOSAIC); break; case 0x50: BLDMOD = value & 0x3FFF; UPDATE_REG(0x50, BLDMOD); fxOn = ((BLDMOD >> 6) & 3) != 0; CPUUpdateRender(); break; case 0x52: COLEV = value & 0x1F1F; UPDATE_REG(0x52, COLEV); break; case 0x54: COLY = value & 0x1F; UPDATE_REG(0x54, COLY); break; case 0x60: case 0x62: case 0x64: case 0x68: case 0x6c: case 0x70: case 0x72: case 0x74: case 0x78: case 0x7c: case 0x80: case 0x84: soundEvent(address & 0xFF, (u8)(value & 0xFF)); soundEvent((address & 0xFF) + 1, (u8)(value >> 8)); break; case 0x82: case 0x88: case 0xa0: case 0xa2: case 0xa4: case 0xa6: case 0x90: case 0x92: case 0x94: case 0x96: case 0x98: case 0x9a: case 0x9c: case 0x9e: soundEvent(address & 0xFF, value); break; case 0xB0: DM0SAD_L = value; UPDATE_REG(0xB0, DM0SAD_L); break; case 0xB2: DM0SAD_H = value & 0x07FF; UPDATE_REG(0xB2, DM0SAD_H); break; case 0xB4: DM0DAD_L = value; UPDATE_REG(0xB4, DM0DAD_L); break; case 0xB6: DM0DAD_H = value & 0x07FF; UPDATE_REG(0xB6, DM0DAD_H); break; case 0xB8: DM0CNT_L = value & 0x3FFF; UPDATE_REG(0xB8, 0); break; case 0xBA: { bool start = ((DM0CNT_H ^ value) & 0x8000) ? true : false; value &= 0xF7E0; DM0CNT_H = value; UPDATE_REG(0xBA, DM0CNT_H); if (start && (value & 0x8000)) { dma0Source = DM0SAD_L | (DM0SAD_H << 16); dma0Dest = DM0DAD_L | (DM0DAD_H << 16); CPUCheckDMA(0, 1); } break; } case 0xBC: DM1SAD_L = value; UPDATE_REG(0xBC, DM1SAD_L); break; case 0xBE: DM1SAD_H = value & 0x0FFF; UPDATE_REG(0xBE, DM1SAD_H); break; case 0xC0: DM1DAD_L = value; UPDATE_REG(0xC0, DM1DAD_L); break; case 0xC2: DM1DAD_H = value & 0x07FF; UPDATE_REG(0xC2, DM1DAD_H); break; case 0xC4: DM1CNT_L = value & 0x3FFF; UPDATE_REG(0xC4, 0); break; case 0xC6: { bool start = ((DM1CNT_H ^ value) & 0x8000) ? true : false; value &= 0xF7E0; DM1CNT_H = value; UPDATE_REG(0xC6, DM1CNT_H); if (start && (value & 0x8000)) { dma1Source = DM1SAD_L | (DM1SAD_H << 16); dma1Dest = DM1DAD_L | (DM1DAD_H << 16); CPUCheckDMA(0, 2); } break; } case 0xC8: DM2SAD_L = value; UPDATE_REG(0xC8, DM2SAD_L); break; case 0xCA: DM2SAD_H = value & 0x0FFF; UPDATE_REG(0xCA, DM2SAD_H); break; case 0xCC: DM2DAD_L = value; UPDATE_REG(0xCC, DM2DAD_L); break; case 0xCE: DM2DAD_H = value & 0x07FF; UPDATE_REG(0xCE, DM2DAD_H); break; case 0xD0: DM2CNT_L = value & 0x3FFF; UPDATE_REG(0xD0, 0); break; case 0xD2: { bool start = ((DM2CNT_H ^ value) & 0x8000) ? true : false; value &= 0xF7E0; DM2CNT_H = value; UPDATE_REG(0xD2, DM2CNT_H); if (start && (value & 0x8000)) { dma2Source = DM2SAD_L | (DM2SAD_H << 16); dma2Dest = DM2DAD_L | (DM2DAD_H << 16); CPUCheckDMA(0, 4); } break; } case 0xD4: DM3SAD_L = value; UPDATE_REG(0xD4, DM3SAD_L); break; case 0xD6: DM3SAD_H = value & 0x0FFF; UPDATE_REG(0xD6, DM3SAD_H); break; case 0xD8: DM3DAD_L = value; UPDATE_REG(0xD8, DM3DAD_L); break; case 0xDA: DM3DAD_H = value & 0x0FFF; UPDATE_REG(0xDA, DM3DAD_H); break; case 0xDC: DM3CNT_L = value; UPDATE_REG(0xDC, 0); break; case 0xDE: { bool start = ((DM3CNT_H ^ value) & 0x8000) ? true : false; value &= 0xFFE0; DM3CNT_H = value; UPDATE_REG(0xDE, DM3CNT_H); if (start && (value & 0x8000)) { dma3Source = DM3SAD_L | (DM3SAD_H << 16); dma3Dest = DM3DAD_L | (DM3DAD_H << 16); CPUCheckDMA(0, 8); } break; } case 0x100: timer0Reload = value; interp_rate(); break; case 0x102: timer0Value = value; timerOnOffDelay |= 1; cpuNextEvent = cpuTotalTicks; break; case 0x104: timer1Reload = value; interp_rate(); break; case 0x106: timer1Value = value; timerOnOffDelay |= 2; cpuNextEvent = cpuTotalTicks; break; case 0x108: timer2Reload = value; break; case 0x10A: timer2Value = value; timerOnOffDelay |= 4; cpuNextEvent = cpuTotalTicks; break; case 0x10C: timer3Reload = value; break; case 0x10E: timer3Value = value; timerOnOffDelay |= 8; cpuNextEvent = cpuTotalTicks; break; case 0x128: if (value & 0x80) { value &= 0xff7f; if (value & 1 && (value & 0x4000)) { UPDATE_REG(0x12a, 0xFF); IF |= 0x80; UPDATE_REG(0x202, IF); value &= 0x7f7f; } } UPDATE_REG(0x128, value); break; case 0x130: P1 |= (value & 0x3FF); UPDATE_REG(0x130, P1); break; case 0x132: UPDATE_REG(0x132, value & 0xC3FF); break; case 0x200: IE = value & 0x3FFF; UPDATE_REG(0x200, IE); if ((IME & 1) && (IF & IE) && armIrqEnable) cpuNextEvent = cpuTotalTicks; break; case 0x202: IF ^= (value & IF); UPDATE_REG(0x202, IF); break; case 0x204: { memoryWait[0x0e] = memoryWaitSeq[0x0e] = gamepakRamWaitState[value & 3]; if (!speedHack) { memoryWait[0x08] = memoryWait[0x09] = gamepakWaitState[(value >> 2) & 3]; memoryWaitSeq[0x08] = memoryWaitSeq[0x09] = gamepakWaitState0[(value >> 4) & 1]; memoryWait[0x0a] = memoryWait[0x0b] = gamepakWaitState[(value >> 5) & 3]; memoryWaitSeq[0x0a] = memoryWaitSeq[0x0b] = gamepakWaitState1[(value >> 7) & 1]; memoryWait[0x0c] = memoryWait[0x0d] = gamepakWaitState[(value >> 8) & 3]; memoryWaitSeq[0x0c] = memoryWaitSeq[0x0d] = gamepakWaitState2[(value >> 10) & 1]; } else { memoryWait[0x08] = memoryWait[0x09] = 3; memoryWaitSeq[0x08] = memoryWaitSeq[0x09] = 1; memoryWait[0x0a] = memoryWait[0x0b] = 3; memoryWaitSeq[0x0a] = memoryWaitSeq[0x0b] = 1; memoryWait[0x0c] = memoryWait[0x0d] = 3; memoryWaitSeq[0x0c] = memoryWaitSeq[0x0d] = 1; } for (int i = 8; i < 15; i++) { memoryWait32[i] = memoryWait[i] + memoryWaitSeq[i] + 1; memoryWaitSeq32[i] = memoryWaitSeq[i] * 2 + 1; } if ((value & 0x4000) == 0x4000) { busPrefetchEnable = true; busPrefetch = false; busPrefetchCount = 0; } else { busPrefetchEnable = false; busPrefetch = false; busPrefetchCount = 0; } UPDATE_REG(0x204, value & 0x7FFF); } break; case 0x208: IME = value & 1; UPDATE_REG(0x208, IME); if ((IME & 1) && (IF & IE) && armIrqEnable) cpuNextEvent = cpuTotalTicks; break; case 0x300: if (value != 0) value &= 0xFFFE; UPDATE_REG(0x300, value); break; default: UPDATE_REG(address & 0x3FE, value); break; } } void applyTimer() { if (timerOnOffDelay & 1) { timer0ClockReload = TIMER_TICKS[timer0Value & 3]; if (!timer0On && (timer0Value & 0x80)) { // reload the counter TM0D = timer0Reload; timer0Ticks = (0x10000 - TM0D) << timer0ClockReload; UPDATE_REG(0x100, TM0D); } timer0On = timer0Value & 0x80 ? true : false; TM0CNT = timer0Value & 0xC7; interp_rate(); UPDATE_REG(0x102, TM0CNT); // CPUUpdateTicks(); } if (timerOnOffDelay & 2) { timer1ClockReload = TIMER_TICKS[timer1Value & 3]; if (!timer1On && (timer1Value & 0x80)) { // reload the counter TM1D = timer1Reload; timer1Ticks = (0x10000 - TM1D) << timer1ClockReload; UPDATE_REG(0x104, TM1D); } timer1On = timer1Value & 0x80 ? true : false; TM1CNT = timer1Value & 0xC7; interp_rate(); UPDATE_REG(0x106, TM1CNT); } if (timerOnOffDelay & 4) { timer2ClockReload = TIMER_TICKS[timer2Value & 3]; if (!timer2On && (timer2Value & 0x80)) { // reload the counter TM2D = timer2Reload; timer2Ticks = (0x10000 - TM2D) << timer2ClockReload; UPDATE_REG(0x108, TM2D); } timer2On = timer2Value & 0x80 ? true : false; TM2CNT = timer2Value & 0xC7; UPDATE_REG(0x10A, TM2CNT); } if (timerOnOffDelay & 8) { timer3ClockReload = TIMER_TICKS[timer3Value & 3]; if (!timer3On && (timer3Value & 0x80)) { // reload the counter TM3D = timer3Reload; timer3Ticks = (0x10000 - TM3D) << timer3ClockReload; UPDATE_REG(0x10C, TM3D); } timer3On = timer3Value & 0x80 ? true : false; TM3CNT = timer3Value & 0xC7; UPDATE_REG(0x10E, TM3CNT); } cpuNextEvent = CPUUpdateTicks(); timerOnOffDelay = 0; } void CPULoadInternalBios() { // load internal BIOS #ifdef WORDS_BIGENDIAN for (size_t i = 0; i < sizeof(myROM) / 4; ++i) { WRITE32LE(&bios[i], myROM[i]); } #else memcpy(bios, myROM, sizeof(myROM)); #endif } void CPUInit() { biosProtected[0] = 0x00; biosProtected[1] = 0xf0; biosProtected[2] = 0x29; biosProtected[3] = 0xe1; int i = 0; for (i = 0; i < 256; i++) { int cpuBitSetCount = 0; int j; for (j = 0; j < 8; j++) if (i & (1 << j)) cpuBitSetCount++; cpuBitsSet[i] = cpuBitSetCount; for (j = 0; j < 8; j++) if (i & (1 << j)) break; cpuLowestBitSet[i] = j; } for (i = 0; i < 0x400; i++) ioReadable[i] = true; for (i = 0x10; i < 0x48; i++) ioReadable[i] = false; for (i = 0x4c; i < 0x50; i++) ioReadable[i] = false; for (i = 0x54; i < 0x60; i++) ioReadable[i] = false; for (i = 0x8c; i < 0x90; i++) ioReadable[i] = false; for (i = 0xa0; i < 0xb8; i++) ioReadable[i] = false; for (i = 0xbc; i < 0xc4; i++) ioReadable[i] = false; for (i = 0xc8; i < 0xd0; i++) ioReadable[i] = false; for (i = 0xd4; i < 0xdc; i++) ioReadable[i] = false; for (i = 0xe0; i < 0x100; i++) ioReadable[i] = false; for (i = 0x110; i < 0x120; i++) ioReadable[i] = false; for (i = 0x12c; i < 0x130; i++) ioReadable[i] = false; for (i = 0x138; i < 0x140; i++) ioReadable[i] = false; for (i = 0x144; i < 0x150; i++) ioReadable[i] = false; for (i = 0x15c; i < 0x200; i++) ioReadable[i] = false; for (i = 0x20c; i < 0x300; i++) ioReadable[i] = false; for (i = 0x304; i < 0x400; i++) ioReadable[i] = false; if (romSize < 0x1fe2000) { *((u16 *)&rom[0x1fe209c]) = 0xdffa; // SWI 0xFA *((u16 *)&rom[0x1fe209e]) = 0x4770; // BX LR } else { agbPrintEnable(false); } gbaSaveType = 0; eepromInUse = 0; saveType = 0; } void CPUReset() { systemReset(); if (gbaSaveType == 0) { if (eepromInUse) gbaSaveType = 3; else switch (saveType) { case 1: gbaSaveType = 1; break; case 2: gbaSaveType = 2; break; } } // clean picture memset(pix, 0, 4 * 241 * 162); // clean registers memset(&reg[0], 0, sizeof(reg)); // clean OAM memset(oam, 0, 0x400); // clean palette memset(paletteRAM, 0, 0x400); // clean vram memset(vram, 0, 0x20000); // clean io memory memset(ioMem, 0, 0x400); DISPCNT = 0x0080; DISPSTAT = 0x0000; VCOUNT = (useBios && !skipBios) ? 0 : 0x007E; BG0CNT = 0x0000; BG1CNT = 0x0000; BG2CNT = 0x0000; BG3CNT = 0x0000; BG0HOFS = 0x0000; BG0VOFS = 0x0000; BG1HOFS = 0x0000; BG1VOFS = 0x0000; BG2HOFS = 0x0000; BG2VOFS = 0x0000; BG3HOFS = 0x0000; BG3VOFS = 0x0000; BG2PA = 0x0100; BG2PB = 0x0000; BG2PC = 0x0000; BG2PD = 0x0100; BG2X_L = 0x0000; BG2X_H = 0x0000; BG2Y_L = 0x0000; BG2Y_H = 0x0000; BG3PA = 0x0100; BG3PB = 0x0000; BG3PC = 0x0000; BG3PD = 0x0100; BG3X_L = 0x0000; BG3X_H = 0x0000; BG3Y_L = 0x0000; BG3Y_H = 0x0000; WIN0H = 0x0000; WIN1H = 0x0000; WIN0V = 0x0000; WIN1V = 0x0000; WININ = 0x0000; WINOUT = 0x0000; MOSAIC = 0x0000; BLDMOD = 0x0000; COLEV = 0x0000; COLY = 0x0000; DM0SAD_L = 0x0000; DM0SAD_H = 0x0000; DM0DAD_L = 0x0000; DM0DAD_H = 0x0000; DM0CNT_L = 0x0000; DM0CNT_H = 0x0000; DM1SAD_L = 0x0000; DM1SAD_H = 0x0000; DM1DAD_L = 0x0000; DM1DAD_H = 0x0000; DM1CNT_L = 0x0000; DM1CNT_H = 0x0000; DM2SAD_L = 0x0000; DM2SAD_H = 0x0000; DM2DAD_L = 0x0000; DM2DAD_H = 0x0000; DM2CNT_L = 0x0000; DM2CNT_H = 0x0000; DM3SAD_L = 0x0000; DM3SAD_H = 0x0000; DM3DAD_L = 0x0000; DM3DAD_H = 0x0000; DM3CNT_L = 0x0000; DM3CNT_H = 0x0000; TM0D = 0x0000; TM0CNT = 0x0000; TM1D = 0x0000; TM1CNT = 0x0000; TM2D = 0x0000; TM2CNT = 0x0000; TM3D = 0x0000; TM3CNT = 0x0000; P1 = 0x03FF; IE = 0x0000; IF = 0x0000; IME = 0x0000; armMode = 0x1F; armState = true; if (cpuIsMultiBoot) { reg[13].I = 0x03007F00; reg[15].I = 0x02000000; reg[16].I = 0x00000000; reg[R13_IRQ].I = 0x03007FA0; reg[R13_SVC].I = 0x03007FE0; armIrqEnable = true; } else { if (useBios && !skipBios) { reg[15].I = 0x00000000; armMode = 0x13; armIrqEnable = false; } else { reg[13].I = 0x03007F00; reg[15].I = 0x08000000; reg[16].I = 0x00000000; reg[R13_IRQ].I = 0x03007FA0; reg[R13_SVC].I = 0x03007FE0; armIrqEnable = true; } } C_FLAG = V_FLAG = N_FLAG = Z_FLAG = false; UPDATE_REG(0x00, DISPCNT); UPDATE_REG(0x06, VCOUNT); UPDATE_REG(0x20, BG2PA); UPDATE_REG(0x26, BG2PD); UPDATE_REG(0x30, BG3PA); UPDATE_REG(0x36, BG3PD); UPDATE_REG(0x130, P1); UPDATE_REG(0x88, 0x200); // disable FIQ reg[16].I |= 0x40; CPUUpdateCPSR(); armNextPC = reg[15].I; reg[15].I += 4; // reset internal state intState = false; stopState = false; holdState = false; holdType = 0; biosProtected[0] = 0x00; biosProtected[1] = 0xf0; biosProtected[2] = 0x29; biosProtected[3] = 0xe1; lcdTicks = (useBios && !skipBios) ? 1008 : 208; timer0On = false; timer0Ticks = 0; timer0Reload = 0; timer0ClockReload = 0; timer1On = false; timer1Ticks = 0; timer1Reload = 0; timer1ClockReload = 0; timer2On = false; timer2Ticks = 0; timer2Reload = 0; timer2ClockReload = 0; timer3On = false; timer3Ticks = 0; timer3Reload = 0; timer3ClockReload = 0; dma0Source = 0; dma0Dest = 0; dma1Source = 0; dma1Dest = 0; dma2Source = 0; dma2Dest = 0; dma3Source = 0; dma3Dest = 0; cpuSaveGameFunc = flashSaveDecide; renderLine = mode0RenderLine; fxOn = false; windowOn = false; saveType = 0; layerEnable = DISPCNT & layerSettings; <API key>(true); for (int i = 0; i < 256; i++) { memoryMap[i].address = (u8 *)&dummyAddress; memoryMap[i].mask = 0; } memoryMap[0].address = bios; memoryMap[0].mask = 0x3FFF; memoryMap[2].address = workRAM; memoryMap[2].mask = 0x3FFFF; memoryMap[3].address = internalRAM; memoryMap[3].mask = 0x7FFF; memoryMap[4].address = ioMem; memoryMap[4].mask = 0x3FF; memoryMap[5].address = paletteRAM; memoryMap[5].mask = 0x3FF; memoryMap[6].address = vram; memoryMap[6].mask = 0x1FFFF; memoryMap[7].address = oam; memoryMap[7].mask = 0x3FF; memoryMap[8].address = rom; memoryMap[8].mask = 0x1FFFFFF; memoryMap[9].address = rom; memoryMap[9].mask = 0x1FFFFFF; memoryMap[10].address = rom; memoryMap[10].mask = 0x1FFFFFF; memoryMap[12].address = rom; memoryMap[12].mask = 0x1FFFFFF; memoryMap[14].address = flashSaveMemory; memoryMap[14].mask = 0xFFFF; eepromReset(); flashReset(); rtcReset(); CPUUpdateWindow0(); CPUUpdateWindow1(); // make sure registers are correctly initialized if not using BIOS if (!useBios) { if (cpuIsMultiBoot) <API key>(0xfe); else <API key>(0xff); } else { if (cpuIsMultiBoot) <API key>(0xfe); } switch (cpuSaveType) { case 0: // automatic cpuSramEnabled = true; cpuFlashEnabled = true; cpuEEPROMEnabled = true; <API key> = false; saveType = gbaSaveType = 0; break; case 1: // EEPROM cpuSramEnabled = false; cpuFlashEnabled = false; cpuEEPROMEnabled = true; <API key> = false; saveType = gbaSaveType = 3; // EEPROM usage is automatically detected break; case 2: // SRAM cpuSramEnabled = true; cpuFlashEnabled = false; cpuEEPROMEnabled = false; <API key> = false; cpuSaveGameFunc = sramDelayedWrite; // to insure we detect the write saveType = gbaSaveType = 1; break; case 3: // FLASH cpuSramEnabled = false; cpuFlashEnabled = true; cpuEEPROMEnabled = false; <API key> = false; cpuSaveGameFunc = flashDelayedWrite; // to insure we detect the write saveType = gbaSaveType = 2; break; case 4: // EEPROM+Sensor cpuSramEnabled = false; cpuFlashEnabled = false; cpuEEPROMEnabled = true; <API key> = true; // EEPROM usage is automatically detected saveType = gbaSaveType = 3; break; case 5: // NONE cpuSramEnabled = false; cpuFlashEnabled = false; cpuEEPROMEnabled = false; <API key> = false; // no save at all saveType = gbaSaveType = 5; break; } ARM_PREFETCH; cpuDmaHack = false; SWITicks = 0; IRQTicks = 0; soundReset(); systemRefreshScreen(); } void CPUInterrupt() { u32 PC = reg[15].I; bool savedState = armState; CPUSwitchMode(0x12, true, false); reg[14].I = PC; if (!savedState) reg[14].I += 2; reg[15].I = 0x18; armState = true; armIrqEnable = false; armNextPC = reg[15].I; reg[15].I += 4; ARM_PREFETCH; // if(!holdState) biosProtected[0] = 0x02; biosProtected[1] = 0xc0; biosProtected[2] = 0x5e; biosProtected[3] = 0xe5; } static inline void CPUDrawPixLine() { switch (systemColorDepth) { case 16: { u16 *dest = (u16 *)pix + 241 * (VCOUNT + 1); for (int x = 0; x < 240; ) { *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; } // for filters that read past the screen *dest++ = 0; break; } case 24: { u8 *dest = (u8 *)pix + 240 * VCOUNT * 3; for (int x = 0; x < 240; ) { *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; } break; } case 32: { u32 *dest = (u32 *)pix + 241 * (VCOUNT + 1); for (int x = 0; x < 240; ) { *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; } break; } } } static inline u32 CPUGetUserInput() { // update joystick information systemReadJoypads(); u32 joy = systemGetJoypad(0, <API key>); P1 = 0x03FF ^ (joy & 0x3FF); UPDATE_REG(0x130, P1); // HACK: some special "buttons" extButtons = (joy >> 18); speedup = (extButtons & 1) != 0; return joy; } static inline void CPUBeforeEmulation() { if (newFrame) { <API key>(<API key>); u32 joy = CPUGetUserInput(); // this seems wrong, but there are cases where the game // can enter the stop state without requesting an IRQ from // the joypad. // FIXME: where is the right place??? u16 P1CNT = READ16LE(((u16 *)&ioMem[0x132])); if ((P1CNT & 0x4000) || stopState) { u16 p1 = (0x3FF ^ P1) & 0x3FF; if (P1CNT & 0x8000) { if (p1 == (P1CNT & 0x3FF)) { IF |= 0x1000; UPDATE_REG(0x202, IF); } } else { if (p1 & P1CNT) { IF |= 0x1000; UPDATE_REG(0x202, IF); } } } //if (<API key>) //<API key>(0); <API key>(); newFrame = false; } } static inline void <API key>() { // HACK: some special "buttons" if (cheatsEnabled) cheatsCheckKeys(P1 ^ 0x3FF, extButtons); <API key>(); } void CPULoop(int _ticks) { CPUBeforeEmulation(); int32 ticks = _ticks; int32 clockTicks; int32 timerOverflow = 0; bool newVideoFrame = false; // variable used by the CPU core cpuTotalTicks = 0; cpuNextEvent = CPUUpdateTicks(); if (cpuNextEvent > ticks) cpuNextEvent = ticks; #ifdef SDL cpuBreakLoop = false; #endif for (;;) { #ifndef FINAL_VERSION if (systemDebug) { if (systemDebug >= 10 && !holdState) { CPUUpdateCPSR(); #ifdef BKPT_SUPPORT if (debugger_last) { sprintf( buffer, "R00=%08x R01=%08x R02=%08x R03=%08x R04=%08x R05=%08x R06=%08x R07=%08x R08=%08x R09=%08x R10=%08x R11=%08x R12=%08x R13=%08x R14=%08x R15=%08x R16=%08x R17=%08x\n", oldreg[0], oldreg[1], oldreg[2], oldreg[3], oldreg[4], oldreg[5], oldreg[6], oldreg[7], oldreg[8], oldreg[9], oldreg[10], oldreg[11], oldreg[12], oldreg[13], oldreg[14], oldreg[15], oldreg[16], oldreg[17]); } #endif sprintf( buffer, "R00=%08x R01=%08x R02=%08x R03=%08x R04=%08x R05=%08x R06=%08x R07=%08x R08=%08x" "R09=%08x R10=%08x R11=%08x R12=%08x R13=%08x R14=%08x R15=%08x R16=%08x R17=%08x\n", reg[0].I, reg[1].I, reg[2].I, reg[3].I, reg[4].I, reg[5].I, reg[6].I, reg[7].I, reg[8].I, reg[9].I, reg[10].I, reg[11].I, reg[12].I, reg[13].I, reg[14].I, reg[15].I, reg[16].I, reg[17].I); log(buffer); } else if (!holdState) { log("PC=%08x\n", armNextPC); } } #endif /* FINAL_VERSION */ if (!holdState && !SWITicks) { if (armState) { if (!armExecute()) return; } else { if (!thumbExecute()) return; } clockTicks = 0; } else clockTicks = CPUUpdateTicks(); cpuTotalTicks += clockTicks; if (cpuTotalTicks >= cpuNextEvent) { int32 remainingTicks = cpuTotalTicks - cpuNextEvent; if (SWITicks) { SWITicks -= clockTicks; if (SWITicks < 0) SWITicks = 0; } clockTicks = cpuNextEvent; cpuTotalTicks = 0; cpuDmaHack = false; updateLoop: if (IRQTicks) { IRQTicks -= clockTicks; if (IRQTicks < 0) IRQTicks = 0; } lcdTicks -= clockTicks; if (lcdTicks <= 0) { if (DISPSTAT & 1) // V-BLANK { // if in V-Blank mode, keep computing... if (DISPSTAT & 2) { lcdTicks += 1008; VCOUNT++; UPDATE_REG(0x06, VCOUNT); DISPSTAT &= 0xFFFD; UPDATE_REG(0x04, DISPSTAT); CPUCompareVCOUNT(); } else { lcdTicks += 224; DISPSTAT |= 2; UPDATE_REG(0x04, DISPSTAT); if (DISPSTAT & 16) { IF |= 2; UPDATE_REG(0x202, IF); } } if (VCOUNT >= 228) //Reaching last line { DISPSTAT &= 0xFFFC; UPDATE_REG(0x04, DISPSTAT); VCOUNT = 0; UPDATE_REG(0x06, VCOUNT); CPUCompareVCOUNT(); } } else { if (DISPSTAT & 2) { // if in H-Blank, leave it and move to drawing mode VCOUNT++; UPDATE_REG(0x06, VCOUNT); lcdTicks += 1008; DISPSTAT &= 0xFFFD; if (VCOUNT == 160) { DISPSTAT |= 1; DISPSTAT &= 0xFFFD; UPDATE_REG(0x04, DISPSTAT); if (DISPSTAT & 0x0008) { IF |= 1; UPDATE_REG(0x202, IF); } CPUCheckDMA(1, 0x0f); newVideoFrame = true; } UPDATE_REG(0x04, DISPSTAT); CPUCompareVCOUNT(); } else { if (<API key>()) { (*renderLine)(); CPUDrawPixLine(); } // entering H-Blank DISPSTAT |= 2; UPDATE_REG(0x04, DISPSTAT); lcdTicks += 224; CPUCheckDMA(2, 0x0f); if (DISPSTAT & 16) { IF |= 2; UPDATE_REG(0x202, IF); } } } } // we shouldn't be doing sound in stop state, but we lose synchronization // if sound is disabled, so in stop state, soundTick will just produce // mute sound soundTicks -= clockTicks; if (soundTicks <= 0) { soundTick(); soundTicks += soundTickStep; } if (!stopState) { if (timer0On) { timer0Ticks -= clockTicks; if (timer0Ticks <= 0) { timer0Ticks += (0x10000 - timer0Reload) << timer0ClockReload; timerOverflow |= 1; soundTimerOverflow(0); if (TM0CNT & 0x40) { IF |= 0x08; UPDATE_REG(0x202, IF); } } TM0D = 0xFFFF - (timer0Ticks >> timer0ClockReload) & 0xFFFF; UPDATE_REG(0x100, TM0D); } if (timer1On) { if (TM1CNT & 4) { if (timerOverflow & 1) { TM1D++; if (TM1D == 0) { TM1D += timer1Reload; timerOverflow |= 2; soundTimerOverflow(1); if (TM1CNT & 0x40) { IF |= 0x10; UPDATE_REG(0x202, IF); } } UPDATE_REG(0x104, TM1D); } } else { timer1Ticks -= clockTicks; if (timer1Ticks <= 0) { timer1Ticks += (0x10000 - timer1Reload) << timer1ClockReload; timerOverflow |= 2; soundTimerOverflow(1); if (TM1CNT & 0x40) { IF |= 0x10; UPDATE_REG(0x202, IF); } } TM1D = 0xFFFF - (timer1Ticks >> timer1ClockReload) & 0xFFFF; UPDATE_REG(0x104, TM1D); } } if (timer2On) { if (TM2CNT & 4) { if (timerOverflow & 2) { TM2D++; if (TM2D == 0) { TM2D += timer2Reload; timerOverflow |= 4; if (TM2CNT & 0x40) { IF |= 0x20; UPDATE_REG(0x202, IF); } } UPDATE_REG(0x108, TM2D); } } else { timer2Ticks -= clockTicks; if (timer2Ticks <= 0) { timer2Ticks += (0x10000 - timer2Reload) << timer2ClockReload; timerOverflow |= 4; if (TM2CNT & 0x40) { IF |= 0x20; UPDATE_REG(0x202, IF); } } TM2D = 0xFFFF - (timer2Ticks >> timer2ClockReload) & 0xFFFF; UPDATE_REG(0x108, TM2D); } } if (timer3On) { if (TM3CNT & 4) { if (timerOverflow & 4) { TM3D++; if (TM3D == 0) { TM3D += timer3Reload; if (TM3CNT & 0x40) { IF |= 0x40; UPDATE_REG(0x202, IF); } } UPDATE_REG(0x10C, TM3D); } } else { timer3Ticks -= clockTicks; if (timer3Ticks <= 0) { timer3Ticks += (0x10000 - timer3Reload) << timer3ClockReload; if (TM3CNT & 0x40) { IF |= 0x40; UPDATE_REG(0x202, IF); } } TM3D = 0xFFFF - (timer3Ticks >> timer3ClockReload) & 0xFFFF; UPDATE_REG(0x10C, TM3D); } } } timerOverflow = 0; #ifdef PROFILING profilingTicks -= clockTicks; if (profilingTicks <= 0) { profilingTicks += <API key>; if (profilSegment) { profile_segment *seg = profilSegment; do { u16 *b = (u16 *)seg->sbuf; int pc = ((reg[15].I - seg->s_lowpc) * seg->s_scale) / 0x10000; if (pc >= 0 && pc < seg->ssiz) { b[pc]++; break; } seg = seg->next; } while (seg); } } #endif if (newVideoFrame) { newVideoFrame = false; <API key>(); } ticks -= clockTicks; cpuNextEvent = CPUUpdateTicks(); if (cpuDmaTicksToUpdate > 0) { if (cpuDmaTicksToUpdate > cpuNextEvent) clockTicks = cpuNextEvent; else clockTicks = cpuDmaTicksToUpdate; cpuDmaTicksToUpdate -= clockTicks; cpuDmaHack = true; goto updateLoop; // this is evil } if (IF && (IME & 1) && armIrqEnable) { int res = IF & IE; if (stopState) res &= 0x3080; if (res) { if (intState) { if (!IRQTicks) { CPUInterrupt(); intState = false; holdState = false; stopState = false; holdType = 0; } } else { if (!holdState) { intState = true; IRQTicks = 7; if (cpuNextEvent > IRQTicks) cpuNextEvent = IRQTicks; } else { CPUInterrupt(); holdState = false; stopState = false; holdType = 0; } } // Stops the SWI Ticks emulation if an IRQ is executed //(to avoid problems with nested IRQ/SWI) if (SWITicks) SWITicks = 0; } } if (remainingTicks > 0) { if (remainingTicks > cpuNextEvent) clockTicks = cpuNextEvent; else clockTicks = remainingTicks; remainingTicks -= clockTicks; goto updateLoop; // this is evil, too } if (timerOnOffDelay) applyTimer(); //if (cpuNextEvent > ticks) // FIXME: can be negative and slow down // cpuNextEvent = ticks; #ifdef SDL if (newFrame || useOldFrameTiming && ticks <= 0 || cpuBreakLoop) #else if (newFrame || useOldFrameTiming && ticks <= 0) #endif { break; } } } } struct EmulatedSystem GBASystem = { // emuMain CPULoop, // emuReset CPUReset, // emuCleanUp CPUCleanUp, // emuReadBattery CPUReadBatteryFile, // emuWriteBattery CPUWriteBatteryFile, // <API key> <API key>, // <API key> <API key>, // emuReadState CPUReadState, // emuWriteState CPUWriteState, // <API key> <API key>, // <API key> <API key>, // emuReadMemState CPUReadMemState, // emuWriteMemState CPUWriteMemState, // emuWritePNG CPUWritePNGFile, // emuWriteBMP CPUWriteBMPFile, // emuUpdateCPSR CPUUpdateCPSR, // emuHasDebugger true, // emuCount #ifdef FINAL_VERSION 250000, #else 5000, #endif };
using UnityEngine; using System.Collections; [RequireComponent(typeof(SpriteRenderer))] public class SpriteRandomiser : MonoBehaviour { [System.Serializable] public class PossibleState { public Sprite texture = null; public Color color = Color.white; }; public PossibleState[] possibleStates = new PossibleState[0]; public void RandomiseSprite() { Random.seed = (int)Time.time; if(possibleStates.Length > 0) { PossibleState state = possibleStates[Random.Range(0,possibleStates.Length)]; SpriteRenderer spriteRenderer = GetComponent<Renderer>() as SpriteRenderer; spriteRenderer.sprite = state.texture; spriteRenderer.color = state.color; } } // Use this for initialization void Start () { RandomiseSprite(); } }
<!doctype html> <!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> <!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]--> <!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"><!--<![endif]--> <head> {% include head.html %} </head> <body id="post"> {% include navigation.html %} <div id="main" role="main"> <article class="hentry"> {% if page.image.feature %}<img src="{{ site.url }}/images/{{ page.image.feature }}" class="entry-feature-image" alt="{{ page.title }}">{% if page.image.credit %}<p class="image-credit">Photo Credit: <a href="{{ page.image.creditlink }}">{{ page.image.credit }}</a>{% endif %}{% endif %} <div class="entry-wrapper"> <header class="entry-header"> <span class="entry-tags">{% for tag in page.tags %}<a href="{{ site.url }}/tags.html#{{ tag | cgi_encode }}" title="Pages tagged {{ tag }}">{{ tag }}</a>{% unless forloop.last %}&nbsp;&bull;&nbsp;{% endunless %}{% endfor %}</span> {% if page.link %} <h1 class="entry-title"><a href="{{ page.link }}">{% if page.headline %}{{ page.headline }}{% else %}{{ page.title }}{% endif %} <span class="link-arrow">&rarr;</span></a></h1> {% else %} <h1 class="entry-title">{% if page.headline %}{{ page.headline }}{% else %}{{ page.title }}{% endif %}</h1> {% endif %} </header> <footer class="entry-meta"> <img src="{{ site.url }}/images/{{ site.owner.avatar }}" alt="{{ site.owner.name }} photo" class="author-photo"> <span class="author vcard">By <span class="fn"><a href="{{ site.url }}/about/" title="About {{ site.owner.name }}">{{ site.owner.name }}</a></span></span> <span class="entry-date date published"><time datetime="{{ page.date | date_to_xmlschema }}"><i class="icon-calendar-empty"></i> {{ page.date | date: "%B %d, %Y" }}</time></span> {% if page.modified %}<span class="entry-date date modified"><time datetime="{{ page.modified }}"><i class="icon-pencil"></i> {{ page.modified | date: "%B %d, %Y" }}</time></span>{% endif %} {% if site.disqus_shortname and page.comments %}<span class="entry-comments"><i class="icon-comment-alt"></i> <a href="#disqus_thread">Comment</a></span>{% endif %} <span><a href="{{ site.url }}{{ page.url }}" rel="bookmark" title="{{ page.title }}"><i class="icon-link"></i> Permalink</a></span> {% if page.share %} <span class="<API key>"> <a href="https: <span class="<API key>"> <a href="https://twitter.com/intent/tweet?text={{ site.url }}{{ page.url }}" title="Share on Twitter" itemprop="Twitter"><i class="icon-twitter-sign"></i> Tweet</a></span> <span class="<API key>"> <a href="https://plus.google.com/share?url={{ site.url }}{{ page.url }}" title="Share on Google Plus" itemprop="GooglePlus"><i class="<API key>"></i> +1</a></span> <!-- /.social-share -->{% endif %} </footer> <div class="entry-content"> {{ content }} {% if site.disqus_shortname and page.comments %}<div id="disqus_thread"></div><!-- /#disqus_thread -->{% endif %} </div><!-- /.entry-content --> </div><!-- /.entry-wrapper --> <nav class="pagination" role="navigation"> {% if page.previous %} <a href="{{ site.url }}{{ page.previous.url }}" class="btn" title="{{ page.previous.title }}">Previous article</a> {% endif %} {% if page.next %} <a href="{{ site.url }}{{ page.next.url }}" class="btn" title="{{ page.next.title }}">Next article</a> {% endif %} </nav><!-- /.pagination --> </article> </div><!-- /#main --> <div class="footer-wrapper"> <footer role="contentinfo"> {% include footer.html %} </footer> </div><!-- /.footer-wrapper --> {% include scripts.html %} </body> </html>
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Session; using System.Threading.Tasks; using MediaBrowser.Model.Services; namespace MediaBrowser.Controller.Net { public interface ISessionContext { Task<SessionInfo> GetSession(object requestContext); Task<User> GetUser(object requestContext); Task<SessionInfo> GetSession(IRequest requestContext); Task<User> GetUser(IRequest requestContext); } }
/* About Css */ body { -<API key>: none; /* prevent callout to copy image, etc when tap to hold */ -<API key>: none; /* prevent webkit from resizing text to fit */ -webkit-user-select: none; /* prevent copy paste, to allow, change 'none' to 'text' */ background: #333333; <API key>:fixed; font-family:'HelveticaNeue-Light', 'HelveticaNeue', Helvetica, Arial, sans-serif; font-size:12px; height:100%; margin:0px; padding:0px; width:100%; } /* Portrait layout (default) */ .app { height:250px; width:300px; margin:30px; } /* Landscape layout (with min-width) */ @media screen and (min-aspect-ratio: 1/1) and (min-width:400px) { .app { margin-left:160px; } } h1{ font-size:30px; font-weight:normal; margin:0px; overflow:visible; padding:0px; text-align:center; color:#FEFEFE; } .button{ background:#9f9f9f; border-radius:10px; margin:auto; text-align:center; text-decoration:none; border:#8f8f8f solid 1px; } .button p{ color:#fefefe; text-align:center; text-decoration:none; font-size:24px; padding:15px 0; margin:0; } .button:hover,.button:active{ background:#6f6f6f; color:#efefef; } .back{ margin-left:-25px; margin-right:15px; color:#fefefe; font-size:20px; padding:10px; background-color: #428bca; border-color: #357ebd; } .back:hover,.back:active{ background-color: #3071a9; border-color: #285e8e; }
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<math.h> #define MAX_SIZE 1010 int getarray(int a[]) { int i=0,count; scanf("%d",&count); for(; i<count ; i++) scanf("%d",&a[i]); return count; } int find(int a[], int n, int val) { int i,true=0; for(i=0; i<n; i++) { if(a[i]==val) { true=1; return i; } } if(true==0) return -1; } int main() { int cases, i; int arr[MAX_SIZE], size; int val, found = 0; scanf("%d", &cases); for(i = 1; i <= cases; i++) { size = getarray(arr); scanf("%d", &val); found = find(arr, size, val); if(found == -1) { printf("NOT FOUND\n"); continue; } printf("%d\n", found); } return 0; }
<section id="options"> <?php $terms = array(); $vid = NULL; $vid_machine_name = '<API key>'; $vocabulary = <API key>($vid_machine_name); if (!empty($vocabulary->vid)) { $vid = $vocabulary->vid; } if (!empty($vid)) { $terms = taxonomy_get_tree($vid); } ?> <ul id="filters" class="option-set right" data-option-key="filter"> <li><a href="#filter" data-option-value="*" class="button small selected"><?php print t('Show All'); ?></a></li> <?php if (!empty($terms)): ?> <?php foreach ($terms as $term): ?> <li><a href="#filter" data-option-value=".tid-<?php print $term->tid; ?>" class="button small"><?php print $term->name; ?></a></li> <?php endforeach; ?> <?php endif; ?> </ul> </section>
package com.<API key>.borZoi; import java.math.BigInteger; import java.security.SecureRandom; public class ECPrivKey { /** * The EC Domain Parameters */ public ECDomainParameters dp; /** * The Private Key */ public BigInteger s; /** * Generate a random private key with ECDomainParameters dp */ public ECPrivKey(ECDomainParameters dp) { this.dp = (ECDomainParameters) dp.clone(); SecureRandom rnd = new SecureRandom(); s = new BigInteger(dp.m, rnd); s = s.mod(dp.r); } /** * Generate a private key with ECDomainParameters dp * and private key s */ public ECPrivKey(ECDomainParameters dp, BigInteger s) { this.dp = dp; this.s = s; } public String toString() { String str = new String("dp: ").concat(dp.toString()).concat("\n"); str = str.concat("s: ").concat(s.toString()).concat("\n"); return str; } protected Object clone() { return new ECPrivKey(dp, s); } }
#include <sstream> #include <gdk/gdkkeysyms.h> #include <libgtkworkbook/workbook.h> #include <proactor/Proactor.hpp> #include <proactor/Event.hpp> #include <network/Tcp.hpp> #include "Realtime.hpp" using namespace realtime; /* @description: This method creates a filename with the prefix supplied and uses the pid of the process as its suffix. @pre: The prefix (should be a file path, obviously). */ static std::string AppendProcessId (const gchar * pre) { std::stringstream s; s << pre << getppid(); return s.str(); } static void <API key> (GtkWidget * w, gpointer data) { Realtime * rt = (Realtime *)data; OpenStreamDialog * dialog = rt->streamdialog(); if (dialog->widget == NULL) { dialog->rt = rt; dialog->widget = <API key> ("Open stream ", GTK_WINDOW (rt->app()->gtkwindow()), (GtkDialogFlags) (GTK_DIALOG_MODAL|<API key>), GTK_STOCK_OK, GTK_RESPONSE_OK, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); GtkWidget * gtk_frame = gtk_frame_new ("Connection Options"); GtkWidget * hbox = gtk_hbox_new(FALSE, 0); GtkWidget * box = GTK_DIALOG (dialog->widget)->vbox; dialog->host_entry = gtk_entry_new(); dialog->port_entry = gtk_entry_new(); <API key> (GTK_ENTRY (dialog->host_entry), 15); <API key> (GTK_ENTRY (dialog->port_entry), 5); <API key> (GTK_ENTRY (dialog->host_entry), 15); <API key> (GTK_ENTRY (dialog->port_entry), 5); gtk_box_pack_start (GTK_BOX (hbox), dialog->host_entry, FALSE, FALSE, 0); gtk_box_pack_end (GTK_BOX (hbox), dialog->port_entry, FALSE, FALSE, 0); gtk_container_add (GTK_CONTAINER (gtk_frame), hbox); gtk_box_pack_start (GTK_BOX (box), gtk_frame, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (dialog->widget), "delete-event", G_CALLBACK (<API key>), NULL); } gtk_widget_show_all ( dialog->widget ); if (gtk_dialog_run (GTK_DIALOG (dialog->widget)) == GTK_RESPONSE_OK) { const char * host_value = gtk_entry_get_text (GTK_ENTRY (dialog->host_entry)); const char * port_value = gtk_entry_get_text (GTK_ENTRY (dialog->port_entry)); Sheet * sheet = rt->workbook()->add_new_sheet (rt->workbook(), host_value, 100, 20); if (IS_NULLSTR (host_value) || IS_NULLSTR (port_value)) { g_warning ("One of requird values are empty"); } else if (sheet == NULL) { g_warning ("Cannot open connection to %s:%s because of failure to add sheet", host_value, port_value); } else if (rt->OpenTcpClient (sheet, host_value, atoi (port_value)) == false) { // STUB: Popup an alertbox about failing to connect? } else { // STUB: Success. Do we want to do anything else here? g_message ("Client connection opened on %s:%s on sheet %s", host_value, port_value, sheet->name); } } gtk_widget_hide_all ( dialog->widget ); } Realtime::Realtime (Application * appstate, Handle * platform) : Plugin (appstate, platform) { ConfigPair * logpath = appstate->config()->get_pair (appstate->config(), "realtime", "log", "path"); if (IS_NULL (logpath)) { g_critical ("Failed loading log->path from configuration file. Exiting application."); exit(1); } std::string logname = std::string (logpath->value).append("/"); logname.append (AppendProcessId("realtime.").append(".log")); if ((pktlog = fopen (logname.c_str(), "w")) == NULL) { g_critical ("Failed opening file '%s' for packet logging", logname.c_str()); } this->wb = workbook_open (appstate->gtkwindow(), "realtime"); this->packet_parser = NULL; this->tcp_server = NULL; } Realtime::~Realtime (void) { // Iterate through the list of active connections, and begin closing them. This should also // include deleting the pointers to all of the accepting threads. Eventually there should be // a boost::shared_ptr here so that we don't have to do the dirty work. ActiveThreads::iterator it = this->threads.begin(); while (it != this->threads.end()) { network::TcpSocket * socket = ((*it).first); concurrent::Thread * thread = ((*it).second); it = this->threads.erase (it); if (socket) delete socket; if (thread) { thread->stop(); delete thread; } } if (this->packet_parser) { this->packet_parser->stop(); delete this->packet_parser; } if (this->tcp_server) { this->tcp_server->stop(); delete this->tcp_server; } FCLOSE (this->pktlog); } bool Realtime::<API key> (network::TcpServerSocket * socket, AcceptThread * accept_thread) { this->threads.push_back ( ActiveThread (socket, accept_thread) ); if (this->tcp_server->addWorker (accept_thread) == false) { g_critical ("Failed starting accepting thread on socket %d", socket->getPort() ); return false; } return true; } bool Realtime::<API key> (network::TcpClientSocket * socket, CsvParser * csv, NetworkDispatcher * nd) { this->threads.push_back ( ActiveThread (socket, csv) ); this->threads.push_back ( ActiveThread (NULL, nd) ); // this is a hack ConnectionThread * reader = new ConnectionThread (socket); if (nd->addWorker (reader) == false) { g_critical ("Failed starting the client reader"); delete reader; return false; } this->threads.push_back ( ActiveThread (NULL, reader) ); // this is a hack return true; } bool Realtime::OpenTcpServer (int port) { // Has to be above the service ports. if (port < 1000) { g_warning ("Failed starting Tcp server: port (%d) must be above 1000", port); return false; } // The first time we attempt to create a port to receive input on we need to create a dispatcher, and // specify an event identifier so that we can communicate with it from workers. At this point the // Packet Parser is created as well. if (this->tcp_server == NULL) { int eventId = proactor::Event::uniqueEventId(); NetworkDispatcher * nd = new NetworkDispatcher (eventId); PacketParser * pp = new PacketParser (this->workbook(), this->pktlog, 0); if (nd->start() == false) { g_critical ("Failed starting network dispatcher for tcp server"); return false; } if (this->app()->proactor()->addWorker (eventId, pp) == false) { g_critical ("Failed starting packet parser for tcp server"); return false; } this->tcp_server = nd; this->packet_parser = pp; } network::TcpServerSocket * socket = new network::TcpServerSocket (port); if (socket->start(5) == false) { g_critical ("Failed starting network socket for tcp server on port %d", port); return false; } AcceptThread * accept_thread = new AcceptThread (socket->newAcceptor()); return this-><API key> (socket, accept_thread); } bool Realtime::OpenTcpClient (Sheet * sheet, const std::string & address, int port) { // Has to be above the service ports. if (port < 1000) { g_warning ("Failed starting Tcp client: port (%d) must be above 1000", port); return false; } // We need to create a network dispatcher for each one of these connections because of // the current limitation of the Proactor design. It really needs to be rewritten, but // that is a separate project in and of itself. For now a list of dispatchers must be // kept so that we do not lose track. int eventId = proactor::Event::uniqueEventId(); NetworkDispatcher * dispatcher = new NetworkDispatcher (eventId); if (dispatcher->start() == false) { g_critical ("Failed starting network dispatcher for %s:%d", address.c_str(), port); delete dispatcher; return false; } // Keeping this simple is the reason why we need multiple dispatchers. If I could come // up with a simple way to strap on the ability to have multiple sheets without the need // for an additioanl dispatcher/csv combo I would. It totally destroys the principle of // the proactor design. CsvParser * csv = new CsvParser (sheet, this->pktlog, 0); if (this->app()->proactor()->addWorker (eventId, csv) == false) { g_critical ("Failed starting csv parser and adding to proactor for %s:%d", address.c_str(), port); delete csv; delete dispatcher; return false; } network::TcpClientSocket * socket = new network::TcpClientSocket; if (socket->connect (address.c_str(), port) == false) { g_critical ("Failed making Tcp connection to %s:%d", address.c_str(), port); delete socket; delete csv; delete dispatcher; return false; } return this-><API key> (socket, csv, dispatcher); } void Realtime::Start(void) { Config * cfg = this->app()->config(); ConfigPair * servport = cfg->get_pair (cfg, "realtime", "tcp", "port"); int port = atoi (servport->value); if (this->OpenTcpServer (port) == true) { g_message ("Opened Tcp server on port %d", port); } } GtkWidget * Realtime::CreateMainMenu (void) { GtkWidget * rtmenu = gtk_menu_new(); GtkWidget * rtmenu_item = <API key> ("Realtime"); GtkWidget * rtmenu_open = <API key> ("Open Csv stream..."); <API key> (GTK_MENU_SHELL (rtmenu), rtmenu_open); g_signal_connect (G_OBJECT (rtmenu_open), "activate", G_CALLBACK (<API key>), this); <API key> (GTK_MENU_ITEM (rtmenu_item), rtmenu); return rtmenu_item; } GtkWidget * Realtime::BuildLayout (void) { GtkWidget * gtk_menu = this->app()->gtkmenu(); GtkWidget * box = gtk_vbox_new (FALSE, 0); GtkWidget * realtime_menu = this->CreateMainMenu(); // Append to the existing menu structure from the application. <API key> (GTK_MENU_SHELL (gtk_menu), realtime_menu); // Setup the workbook. wb->signals[<API key>] = this->app()->signals[Application::SHEET_CHANGED]; wb->gtk_box = box; // Pack all of the objects into a vertical box, and then pack that box into the application. gtk_box_pack_start (GTK_BOX (box), wb->gtk_notebook, TRUE, TRUE, 0); gtk_box_pack_start (GTK_BOX (this->app()->gtkvbox()), box, TRUE, TRUE, 0); return box; }
<?xml version="1.0" encoding="utf-8"?> <rss version="2.0" xml:base="http: <channel> <title>postmodernism - apathy</title> <link>http://machines.plannedobsolescence.net/149-2007/taxonomy/term/72/0</link> <description></description> <language>en</language> <item> <title>Postmodern Political Apathy</title> <link>http://machines.plannedobsolescence.net/149-2007/node/27</link> <description>&lt;p&gt;I identified with the some of Jameson&#039;s views on postmodern feelings, or lack thereof.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;http://machines.plannedobsolescence.net/149-2007/node/27&quot;&gt;read more&lt;/a&gt;&lt;/p&gt;</description> <comments>http://machines.plannedobsolescence.net/149-2007/node/27#comments</comments> <category domain="http://machines.plannedobsolescence.net/149-2007/taxonomy/term/72">apathy</category> <category domain="http://machines.plannedobsolescence.net/149-2007/taxonomy/term/73">feeling</category> <category domain="http://machines.plannedobsolescence.net/149-2007/taxonomy/term/55">Jameson</category> <category domain="http://machines.plannedobsolescence.net/149-2007/taxonomy/term/71">politics</category> <pubDate>Mon, 24 Sep 2007 02:42:00 +0000</pubDate> <dc:creator>blankman</dc:creator> <guid isPermaLink="false">27 at http://machines.plannedobsolescence.net/149-2007</guid> </item> </channel> </rss>
#ifndef __WS2SAN_H #define __WS2SAN_H #if __GNUC__ >=3 #pragma GCC system_header #endif #ifdef __cplusplus extern "C" { #endif #pragma pack(push,4) #include <winsock2.h> #include "ntddk.h" #define WSPAPI STDCALL /* FIXME: Unknown definitions */ typedef PVOID LPWSPDATA; typedef PDWORD LPWSATHREADID; typedef PVOID LPWSPPROC_TABLE; typedef struct _WSPUPCALLTABLEEX WSPUPCALLTABLEEX; typedef WSPUPCALLTABLEEX *LPWSPUPCALLTABLEEX; #define SO_MAX_RDMA_SIZE 0x700D #define <API key> 0x700E #define <API key> \ {0xC0B422F5, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}} #define <API key> \ {0xC0B422F6, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}} #define <API key> \ {0xC0B422F7, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}} #define <API key> \ {0xC0B422F8, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}} #define WSAID_RDMAWRITE \ {0xC0B422F9, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}} #define WSAID_RDMAREAD \ {0xC0B422FA, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}} #define <API key> \ {0xE5DA4AF8, 0xD824, 0x48CD, {0xA7, 0x99, 0x63, 0x37, 0xA9, 0x8E, 0xD2, 0xAF}} typedef struct _WSABUFEX { u_long len; char FAR *buf; HANDLE handle; } WSABUFEX, FAR * LPWSABUFEX; #if 0 typedef struct _WSPUPCALLTABLEEX { LPWPUCLOSEEVENT lpWPUCloseEvent; <API key> <API key>; LPWPUCREATEEVENT lpWPUCreateEvent; <API key> <API key>; LPWPUFDISSET lpWPUFDIsSet; <API key> <API key>; <API key> <API key>; LPWPUPOSTMESSAGE lpWPUPostMessage; <API key> <API key>; <API key> <API key>; LPWPUQUEUEAPC lpWPUQueueApc; LPWPURESETEVENT lpWPUResetEvent; LPWPUSETEVENT lpWPUSetEvent; <API key> <API key>; LPWPUCLOSETHREAD lpWPUCloseThread; <API key> <API key>; } WSPUPCALLTABLEEX, FAR * LPWSPUPCALLTABLEEX; #endif int WSPAPI WSPStartupEx( IN WORD wVersionRequested, OUT LPWSPDATA lpWSPData, IN LPWSAPROTOCOL_INFOW lpProtocolInfo, IN LPWSPUPCALLTABLEEX lpUpcallTable, OUT LPWSPPROC_TABLE lpProcTable); typedef int WSPAPI (*LPWSPSTARTUPEX)( IN WORD wVersionRequested, OUT LPWSPDATA lpWSPData, IN LPWSAPROTOCOL_INFOW lpProtocolInfo, IN LPWSPUPCALLTABLEEX lpUpcallTable, OUT LPWSPPROC_TABLE lpProcTable); #define MEM_READ 1 #define MEM_WRITE 2 #define MEM_READWRITE 3 int WSPAPI WSPDeregisterMemory( IN SOCKET s, IN HANDLE Handle, OUT LPINT lpErrno); typedef int WSPAPI (*<API key>)( IN SOCKET s, IN HANDLE Handle, OUT LPINT lpErrno); int WSPAPI <API key>( IN SOCKET s, IN LPVOID <API key>, IN DWORD dwDescriptorLength, OUT LPINT lpErrno); typedef int WSPAPI (*<API key>)( IN SOCKET s, IN LPVOID <API key>, IN DWORD dwDescriptorLength, OUT LPINT lpErrno); int WSPAPI <API key>( IN PVOID lpvAddress, IN SIZE_T Size, OUT LPINT lpErrno); typedef int WSPAPI (*<API key>)( IN PVOID lpvAddress, IN SIZE_T Size, OUT LPINT lpErrno); int WSPAPI WSPRdmaRead( IN SOCKET s, IN LPWSABUFEX lpBuffers, IN DWORD dwBufferCount, IN LPVOID <API key>, IN DWORD <API key>, IN DWORD <API key>, OUT LPDWORD <API key>, IN DWORD dwFlags, IN LPWSAOVERLAPPED lpOverlapped, IN <API key> lpCompletionRoutine, IN LPWSATHREADID lpThreadId, OUT LPINT lpErrno); typedef int WSPAPI (*LPFN_WSPRDMAREAD)( IN SOCKET s, IN LPWSABUFEX lpBuffers, IN DWORD dwBufferCount, IN LPVOID <API key>, IN DWORD <API key>, IN DWORD <API key>, OUT LPDWORD <API key>, IN DWORD dwFlags, IN LPWSAOVERLAPPED lpOverlapped, IN <API key> lpCompletionRoutine, IN LPWSATHREADID lpThreadId, OUT LPINT lpErrno); int WSPAPI WSPRdmaWrite( IN SOCKET s, IN LPWSABUFEX lpBuffers, IN DWORD dwBufferCount, IN LPVOID <API key>, IN DWORD <API key>, IN DWORD <API key>, OUT LPDWORD <API key>, IN DWORD dwFlags, IN LPWSAOVERLAPPED lpOverlapped, IN <API key> lpCompletionRoutine, IN LPWSATHREADID lpThreadId, OUT LPINT lpErrno); typedef int WSPAPI (*LPFN_WSPRDMAWRITE)( IN SOCKET s, IN LPWSABUFEX lpBuffers, IN DWORD dwBufferCount, IN LPVOID <API key>, IN DWORD <API key>, IN DWORD <API key>, OUT LPDWORD <API key>, IN DWORD dwFlags, IN LPWSAOVERLAPPED lpOverlapped, IN <API key> lpCompletionRoutine, IN LPWSATHREADID lpThreadId, OUT LPINT lpErrno); HANDLE WSPAPI WSPRegisterMemory( IN SOCKET s, IN PVOID lpBuffer, IN DWORD dwBufferLength, IN DWORD dwFlags, OUT LPINT lpErrno); int WSPAPI <API key>( IN SOCKET s, IN PVOID lpBuffer, IN DWORD dwBufferLength, IN DWORD dwFlags, OUT LPVOID <API key>, IN OUT LPDWORD <API key>, OUT LPINT lpErrno); typedef int WSPAPI (*<API key>)( IN SOCKET s, IN PVOID lpBuffer, IN DWORD dwBufferLength, IN DWORD dwFlags, OUT LPVOID <API key>, IN OUT LPDWORD <API key>, OUT LPINT lpErrno); #pragma pack(pop) #ifdef __cplusplus } #endif #endif /* __WS2SAN_H */
package java.util.concurrent.atomic; /** * An {@code <API key>} maintains an object reference * along with a mark bit, that can be updated atomically. * * <p>Implementation note: This implementation maintains markable * references by creating internal objects representing "boxed" * [reference, boolean] pairs. * * @since 1.5 * @author Doug Lea * @param <V> The type of object referred to by this reference */ public class <API key><V> { private static class Pair<T> { final T reference; final boolean mark; private Pair(T reference, boolean mark) { this.reference = reference; this.mark = mark; } static <T> Pair<T> of(T reference, boolean mark) { return new Pair<T>(reference, mark); } } private volatile Pair<V> pair; /** * Creates a new {@code <API key>} with the given * initial values. * * @param initialRef the initial reference * @param initialMark the initial mark */ public <API key>(V initialRef, boolean initialMark) { pair = Pair.of(initialRef, initialMark); } /** * Returns the current value of the reference. * * @return the current value of the reference */ public V getReference() { return pair.reference; } /** * Returns the current value of the mark. * * @return the current value of the mark */ public boolean isMarked() { return pair.mark; } /** * Returns the current values of both the reference and the mark. * Typical usage is {@code boolean[1] holder; ref = v.get(holder); }. * * @param markHolder an array of size of at least one. On return, * {@code markholder[0]} will hold the value of the mark. * @return the current value of the reference */ public V get(boolean[] markHolder) { Pair<V> pair = this.pair; markHolder[0] = pair.mark; return pair.reference; } /** * Atomically sets the value of both the reference and mark * to the given update values if the * current reference is {@code ==} to the expected reference * and the current mark is equal to the expected mark. * * <p><a href="package-summary.html#weakCompareAndSet">May fail * spuriously and does not provide ordering guarantees</a>, so is * only rarely an appropriate alternative to {@code compareAndSet}. * * @param expectedReference the expected value of the reference * @param newReference the new value for the reference * @param expectedMark the expected value of the mark * @param newMark the new value for the mark * @return {@code true} if successful */ public boolean weakCompareAndSet(V expectedReference, V newReference, boolean expectedMark, boolean newMark) { return compareAndSet(expectedReference, newReference, expectedMark, newMark); } /** * Atomically sets the value of both the reference and mark * to the given update values if the * current reference is {@code ==} to the expected reference * and the current mark is equal to the expected mark. * * @param expectedReference the expected value of the reference * @param newReference the new value for the reference * @param expectedMark the expected value of the mark * @param newMark the new value for the mark * @return {@code true} if successful */ public boolean compareAndSet(V expectedReference, V newReference, boolean expectedMark, boolean newMark) { Pair<V> current = pair; return expectedReference == current.reference && expectedMark == current.mark && ((newReference == current.reference && newMark == current.mark) || casPair(current, Pair.of(newReference, newMark))); } /** * Unconditionally sets the value of both the reference and mark. * * @param newReference the new value for the reference * @param newMark the new value for the mark */ public void set(V newReference, boolean newMark) { Pair<V> current = pair; if (newReference != current.reference || newMark != current.mark) this.pair = Pair.of(newReference, newMark); } /** * Atomically sets the value of the mark to the given update value * if the current reference is {@code ==} to the expected * reference. Any given invocation of this operation may fail * (return {@code false}) spuriously, but repeated invocation * when the current value holds the expected value and no other * thread is also attempting to set the value will eventually * succeed. * * @param expectedReference the expected value of the reference * @param newMark the new value for the mark * @return {@code true} if successful */ public boolean attemptMark(V expectedReference, boolean newMark) { Pair<V> current = pair; return expectedReference == current.reference && (newMark == current.mark || casPair(current, Pair.of(expectedReference, newMark))); } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe(); // private static final long pairOffset = // objectFieldOffset(UNSAFE, "pair", <API key>.class); private boolean casPair(Pair<V> cmp, Pair<V> val) { return UNSAFE.<API key>(this, pairOffset, cmp, val); } public static volatile long pairOffset; static { try { pairOffset = 0; UNSAFE.<API key>( <API key>.class.getDeclaredField("pairOffset"), <API key>.class.getDeclaredField("pair")); } catch (Exception ex) { throw new Error(ex); } } }
(function ($) { $(document).ready(function(){ $("#edit-title-0-value").change(update); $("#<API key>").click(update); $("#<API key>").change(update); $("#<API key>").change(update); $("#<API key>").change(update); $("#<API key>").change(update); $("#<API key>").change(update); $("#<API key>").change(update); $("#<API key>").change(update); $("#<API key>").change(update); $("#<API key>").change(update); var bgimagerecto = undefined; var bgimageverso = undefined; if($('span.file--image > a').length == 1) { if($('#<API key>')) { console.log("length11"); bgimagerecto = $("span.file--image > a:eq(0)").attr('href'); } else { console.log("length12"); bgimageverso = $("span.file--image > a:eq(0)").attr('href'); } } if($('span.file--image > a').length == 2) { console.log("length2"); bgimagerecto = $("span.file--image > a:eq(0)").attr('href'); bgimageverso = $("span.file--image > a:eq(1)").attr('href'); } if (bgimagerecto !== undefined) { console.log("imagerecto"); $('#gamecardrectolayout').css('background-image', 'url( ' + bgimagerecto + ')'); $('.<API key> .ajax-new-content').addClass('processed'); } if (bgimageverso !== undefined) { console.log("imageverso"); $('#gamecardversolayout').css('background-image', 'url( ' + bgimageverso + ')'); $('.<API key> .ajax-new-content').addClass('processed'); } $(document).ajaxComplete(function(event, xhr, settings) { //RECTO console.log(event.target); console.log("azer " + bgimagerecto); console.log("qsdf " + bgimageverso); if(~settings.url.indexOf("field_img_game_card")) { console.log('entering recto'); if ($('.<API key> .ajax-new-content').hasClass('processed')) { console.log("remove recto"); //$('.ajax-new-content').remove(); $('#gamecardrectolayout').removeAttr('style'); $('.<API key> .ajax-new-content').removeClass('processed'); return; } if(!$('#<API key>')) { console.log("remoooooove"); $('#gamecardrectolayout').removeAttr('style'); $('.<API key> .ajax-new-content').removeClass('processed'); return; } console.log("addingrecto"); $('.<API key> .ajax-new-content').addClass('processed'); bgimagerecto = $("span.file--image > a:eq(0)").attr('href'); //Manage here when single or double if (bgimagerecto !== undefined) { console.log("gorecto"); $('#gamecardrectolayout').css('background-image', 'url( ' + bgimagerecto + ')'); } return; } //VERSO if(~settings.url.indexOf("<API key>")) { if ($('.<API key> .ajax-new-content').hasClass('processed') || !$('#<API key>')) { console.log("remove verso"); //$('.ajax-new-content').remove(); $('#gamecardversolayout').removeAttr('style'); $('.<API key> .ajax-new-content').removeClass('processed'); return; } console.log("adding verso"); $('.<API key> .ajax-new-content').addClass('processed'); if($('span.file--image > a').length == 1) bgimageverso = $("span.file--image > a:eq(0)").attr('href'); if($('span.file--image > a').length == 2) bgimageverso = $("span.file--image > a:eq(1)").attr('href'); if (bgimageverso !== undefined) { console.log("Verso added"); $('#gamecardversolayout').css('background-image', 'url( ' + bgimageverso + ')'); } } }); }); function update(){ var cardname = (($("#edit-title-0-value").val() != "") ? $("#edit-title-0-value").val() : ""); var carac1 = (($("#<API key>").val() != "") ? $("#<API key>").val() : ""); var carac2 = (($("#<API key>").val() != "") ? $("#<API key>").val() : ""); var carac3 = (($("#<API key>").val() != "") ? $("#<API key>").val() : ""); var carac4 = (($("#<API key>").val() != "") ? $("#<API key>").val() : ""); var skill = (($("#<API key>").val() != "") ? $("#<API key>").val() : "") ; var question = (($("#<API key>").val() != "") ? $("#<API key>").val() : ""); var answer = (($("#<API key>").val() != "") ? $("#<API key>").val() : "") ; var rectoImg = (($("#<API key>").val() != "") ? $("#<API key>").val() : ""); var versoImg = (($("#<API key>").val() != "") ? $("#<API key>").val() : ""); if(rectoImg !== undefined) { if (rectoImg != null) { $('#gamecardrectolayout').css('background-image', 'url("' + rectoImg + '")'); } else { rectoImg = $("span.file--image > a:eq(0)").attr('href'); $('#gamecardrectolayout').css('background-image', 'url( ' + rectoImg + ')'); } } if(versoImg !== undefined) { if (versoImg != null) { $('#gamecardrectolayout').css('background-image', 'url("' + versoImg + '")'); } else { versoImg = $("span.file--image > a:eq(1)").attr('href'); $('#gamecardrectolayout').css('background-image', 'url( ' + versoImg + ')'); } } $('#displayCardname').html(cardname); $('#displayCarac1').html(carac1); $('#displayCarac2').html(carac2); $('#displayCarac3').html(carac3); $('#displayCarac4').html(carac4); $('#displaySkill').html(skill); $('#displayQuestion').html(question); $('#displayAnswer').html(answer); } })(jQuery);
<?php /** * @package WordPress * @subpackage <API key> * @since HTML5 Reset 2.0 Template Name: Groups */ get_header(); ?> <div class="content-background"> <div id="content-wrap"> <div class="grid"> <div class="col col-1-4"> <?php wp_nav_menu( array('menu' => 'Groups Menu', 'container_class' => 'side-menu-container', 'menu_class' => 'side-menu' )); ?> <div class="fb-like-box" data-href="https: <a href="https://twitter.com/SkiSnowstar" class="<TwitterConsumerkey>" data-width="90%" data-align="right" data-show-count="false" data-lang="en" data-size="large">Follow @twitter</a> <script>!function(d,s,id){var js,fjs=d.<API key>(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script> </div><!-- END COL-1-4 --> <div class="col col-3-4"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <article class="post" id="post-<?php the_ID(); ?>"> <!-- <h2><?php the_title(); ?></h2> --> <!-- <?php posted_on(); ?> --> <?php if ( has_post_thumbnail() ) {the_post_thumbnail('full', array('class' => 'content-img'));} ?> <div class="entry"> <?php the_content(); ?> <?php wp_link_pages(array('before' => __('Pages: '), 'next_or_number' => 'number')); ?> </div> <?php edit_post_link(__('Edit this entry.'), '<p>', '</p>'); ?> </article> <?php endwhile; endif; ?> </div><!-- END COL-3-4 --> </div><!-- END GRID --> </div> <!-- End Content Wrap --> <?php get_footer(); ?>
// <auto-generated> // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> namespace Caixa.Properties { <summary> A strongly-typed resource class, for looking up localized strings, etc. </summary> // This class was auto-generated by the <API key> // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.<API key>("System.Resources.Tools.<API key>", "4.0.0.0")] [global::System.Diagnostics.<API key>()] [global::System.Runtime.CompilerServices.<API key>()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.<API key>("Microsoft.Performance", "CA1811:<API key>")] internal Resources() { } <summary> Returns the cached ResourceManager instance used by this class. </summary> [global::System.ComponentModel.<API key>(global::System.ComponentModel.<API key>.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Caixa.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } <summary> Overrides the current thread's CurrentUICulture property for all resource lookups using this strongly typed resource class. </summary> [global::System.ComponentModel.<API key>(global::System.ComponentModel.<API key>.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
#ifndef <API key> #define <API key> #include "ardour/types.h" #include "ardour/<API key>.h" namespace ARDOUR { class LIBARDOUR_API TransportAPI { public: TransportAPI() {} virtual ~TransportAPI() {} private: friend struct TransportFSM; virtual void locate (samplepos_t, bool with_roll, bool with_flush, bool with_loop=false, bool force=false, bool with_mmc=true) = 0; virtual void stop_transport (bool abort = false, bool clear_state = false) = 0; virtual void start_transport () = 0; virtual void <API key> () = 0; virtual void <API key> () = 0; virtual bool <API key> () const = 0; virtual double speed() const = 0; virtual void set_transport_speed (double speed, bool abort_capture, bool clear_state, bool as_default) = 0; virtual samplepos_t position() const = 0; virtual bool <API key> () const = 0; }; } /* end namespace ARDOUR */ #endif
#ifndef <API key> #define <API key> #include "Define.h" #include <list> #include "Object.h" #include "GameObject.h" #include "CreatureAI.h" class GameObjectAI { protected: GameObject* const go; public: explicit GameObjectAI(GameObject* g) : go(g) {} virtual ~GameObjectAI() {} virtual void UpdateAI(uint32 /*diff*/) {} virtual void InitializeAI() { Reset(); } virtual void Reset() { } // Pass parameters between AI virtual void DoAction(const int32 /*param = 0 */) {} virtual void SetGUID(uint64 /*guid*/, int32 /*id = 0 */) {} virtual uint64 GetGUID(int32 /*id = 0 */) const { return 0; } static int Permissible(GameObject const* go); virtual bool GossipHello(Player* /*player*/) { return false; } virtual bool GossipSelect(Player* /*player*/, uint32 /*sender*/, uint32 /*action*/) { return false; } virtual bool GossipSelectCode(Player* /*player*/, uint32 /*sender*/, uint32 /*action*/, char const* /*code*/) { return false; } virtual bool QuestAccept(Player* /*player*/, Quest const* /*quest*/) { return false; } virtual bool QuestReward(Player* /*player*/, Quest const* /*quest*/, uint32 /*opt*/) { return false; } virtual uint32 GetDialogStatus(Player* /*player*/) { return 100; } virtual void Destroyed(Player* /*player*/, uint32 /*eventId*/) {} virtual uint32 GetData(uint32 ) const { return 0; } virtual void SetData64(uint32 , uint64 ) {} virtual uint64 GetData64(uint32 ) const { return 0; } virtual void SetData(uint32 , uint32 ) {} virtual void OnGameEvent(bool /*start*/, uint16 /*eventId*/) {} virtual void OnStateChanged(uint32 /*state*/, Unit* /*unit*/) {} virtual void EventInform(uint32 /*eventId*/) {} }; class NullGameObjectAI : public GameObjectAI { public: explicit NullGameObjectAI(GameObject* g); void UpdateAI(uint32 /*diff*/) {} static int Permissible(GameObject const* ) { return PERMIT_BASE_IDLE; } }; #endif
#ifndef BROWSER_H #define BROWSER_H #include <QList> #include <QMailAddress> #include <QMap> #include <QString> #include <QTextBrowser> #include <QUrl> #include <QVariant> class QWidget; class QMailMessage; class QMailMessagePart; class Browser: public QTextBrowser { Q_OBJECT public: Browser(QWidget *parent = 0); virtual ~Browser(); void setResource( const QUrl& name, QVariant var ); void clearResources(); void setMessage( const QMailMessage& mail, bool plainTextMode ); void scrollBy(int dx, int dy); virtual QVariant loadResource(int type, const QUrl& name); QList<QString> embeddedNumbers() const; signals: void finished(); public slots: virtual void setSource(const QUrl &name); protected: void keyPressEvent(QKeyEvent* event); private: void displayPlainText(const QMailMessage* mail); void displayHtml(const QMailMessage* mail); void setTextResource(const QUrl& name, const QString& textData); void setImageResource(const QUrl& name, const QByteArray& imageData); void setPartResource(const QMailMessagePart& part); QString renderPart(const QMailMessagePart& part); QString renderAttachment(const QMailMessagePart& part); QString describeMailSize(uint bytes) const; QString formatText(const QString& txt) const; QString smsBreakReplies(const QString& txt) const; QString noBreakReplies(const QString& txt) const; QString handleReplies(const QString& txt) const; QString buildParagraph(const QString& txt, const QString& prepend, bool preserveWs = false) const; QString encodeUrlAndMail(const QString& txt) const; QString listRefMailTo(const QList<QMailAddress>& list) const; QString refMailTo(const QMailAddress& address) const; QString refNumber(const QString& number) const; QMap<QUrl, QVariant> resourceMap; QString (Browser::*replySplitter)(const QString&) const; mutable QList<QString> numbers; }; #endif // BROWSER_H
#pragma once #ifndef TRACK_METADATA_HPP #define TRACK_METADATA_HPP #include "track_identifier.hpp" namespace ts { namespace resources { class Track_handle; struct Track_metadata { Track_identifier identifier; utf8_string gamemode; }; Track_metadata load_track_metadata(const resources::Track_handle& track_handle); } } #endif
package edu.stanford.nlp.time; import java.io.Serializable; import java.util.Calendar; import java.util.Map; import java.util.regex.Pattern; import edu.stanford.nlp.util.Pair; import org.w3c.dom.Element; public class Timex implements Serializable { private static final long serialVersionUID = 385847729549981302L; /** * XML representation of the TIMEX tag */ private String xml; /** * TIMEX3 value attribute - Time value (given in extended ISO 8601 format). */ private String val; /** * Alternate representation for time value (not part of TIMEX3 standard). * used when value of the time expression cannot be expressed as a standard TIMEX3 value. */ private String altVal; /** * Actual text that make up the time expression */ private String text; /** * TIMEX3 type attribute - Type of the time expression (DATE, TIME, DURATION, or SET) */ private String type; /** * TIMEX3 tid attribute - TimeID. ID to identify this time expression. * Should have the format of {@code t<integer>} */ private String tid; // TODO: maybe its easier if these are just strings... /** * TIMEX3 beginPoint attribute - integer indicating the TimeID of the begin time * that anchors this duration/range (-1 is not present). */ private int beginPoint; /** * TIMEX3 beginPoint attribute - integer indicating the TimeID of the end time * that anchors this duration/range (-1 is not present). */ private int endPoint; /** * Range begin/end/duration * (this is not part of the timex standard and is typically null, available if sutime.includeRange is true) */ private Range range; public static class Range implements Serializable { private static final long serialVersionUID = 1L; public String begin; public String end; public String duration; public Range(String begin, String end, String duration) { this.begin = begin; this.end = end; this.duration = duration; } } public String value() { return val; } public String altVal() { return altVal; } public String text() { return text; } public String timexType() { return type; } public String tid() { return tid; } public Range range() { return range; } public Timex() { } public Timex(Element element) { this.val = null; this.beginPoint = -1; this.endPoint = -1; /* * <API key> os = new <API key>(); Serializer ser = * new Serializer(os, "UTF-8"); ser.setIndent(2); // this is the default in * JDOM so let's keep the same ser.setMaxLength(0); // no line wrapping for * content ser.write(new Document(element)); */ init(element); } public Timex(String val) { this(null, val); } public Timex(String type, String val) { this.val = val; this.type = type; this.beginPoint = -1; this.endPoint = -1; this.xml = (val == null ? "<TIMEX3/>" : String.format("<TIMEX3 VAL=\"%s\" TYPE=\"%s\"/>", this.val, this.type)); } public Timex(String type, String val, String altVal, String tid, String text, int beginPoint, int endPoint) { this.type = type; this.val = val; this.altVal = altVal; this.tid = tid; this.text = text; this.beginPoint = beginPoint; this.endPoint = endPoint; } private void init(Element element) { init(XMLUtils.nodeToString(element, false), element); } private void init(String xml, Element element) { this.xml = xml; this.text = element.getTextContent(); // Mandatory attributes this.tid = XMLUtils.getAttribute(element, "tid"); this.val = XMLUtils.getAttribute(element, "VAL"); if (this.val == null) { this.val = XMLUtils.getAttribute(element, "value"); } this.altVal = XMLUtils.getAttribute(element, "alt_value"); this.type = XMLUtils.getAttribute(element, "type"); if (type == null) { this.type = XMLUtils.getAttribute(element, "TYPE"); } // if (this.type != null) { // this.type = this.type.intern(); // Optional attributes String beginPoint = XMLUtils.getAttribute(element, "beginPoint"); this.beginPoint = (beginPoint == null || beginPoint.length() == 0)? -1 : Integer.parseInt(beginPoint.substring(1)); String endPoint = XMLUtils.getAttribute(element, "endPoint"); this.endPoint = (endPoint == null || endPoint.length() == 0)? -1 : Integer.parseInt(endPoint.substring(1)); // Optional range String rangeStr = XMLUtils.getAttribute(element, "range"); if (rangeStr != null) { if (rangeStr.startsWith("(") && rangeStr.endsWith(")")) { rangeStr = rangeStr.substring(1, rangeStr.length()-1); } String[] parts = rangeStr.split(","); this.range = new Range(parts.length > 0? parts[0]:"", parts.length > 1? parts[1]:"", parts.length > 2? parts[2]:""); } } public int beginPoint() { return beginPoint; } public int endPoint() { return endPoint; } public String toString() { return (this.xml != null) ? this.xml : this.val; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Timex timex = (Timex) o; if (beginPoint != timex.beginPoint) { return false; } if (endPoint != timex.endPoint) { return false; } if (type != null ? !type.equals(timex.type) : timex.type != null) { return false; } if (val != null ? !val.equals(timex.val) : timex.val != null) { return false; } return true; } @Override public int hashCode() { int result = val != null ? val.hashCode() : 0; result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + beginPoint; result = 31 * result + endPoint; return result; } public Element toXmlElement() { Element element = XMLUtils.createElement("TIMEX3"); if (tid != null) { element.setAttribute("tid", tid); } if (value() != null) { element.setAttribute("value", val); } if (altVal != null) { element.setAttribute("altVal", altVal); } if (type != null) { element.setAttribute("type", type); } if (beginPoint != -1) { element.setAttribute("beginPoint", "t" + String.valueOf(beginPoint)); } if (endPoint != -1) { element.setAttribute("endPoint", "t" + String.valueOf(endPoint)); } if (text != null) { element.setTextContent(text); } return element; } // Used to create timex from XML (mainly for testing) public static Timex fromXml(String xml) { Element element = XMLUtils.parseElement(xml); if ("TIMEX3".equals(element.getNodeName())) { Timex t = new Timex(); // t.init(xml, element); // Doesn't preserve original input xml // Will reorder attributes of xml so can match xml of test timex and actual timex // (for which we can't control the order of the attributes now we don't use nu.xom...) t.init(element); return t; } else { throw new <API key>("Invalid timex xml: " + xml); } } public static Timex fromMap(String text, Map<String, String> map) { try { Element element = XMLUtils.createElement("TIMEX3"); for (Map.Entry<String, String> entry : map.entrySet()) { if (entry.getValue() != null) { element.setAttribute(entry.getKey(), entry.getValue()); } } element.setTextContent(text); return new Timex(element); } catch (Exception ex) { throw new RuntimeException(ex); } } /** * Gets the Calendar matching the year, month and day of this Timex. * * @return The matching Calendar. */ public Calendar getDate() { if (Pattern.matches("\\d\\d\\d\\d-\\d\\d-\\d\\d", this.val)) { int year = Integer.parseInt(this.val.substring(0, 4)); int month = Integer.parseInt(this.val.substring(5, 7)); int day = Integer.parseInt(this.val.substring(8, 10)); return makeCalendar(year, month, day); } else if (Pattern.matches("\\d\\d\\d\\d\\d\\d\\d\\d", this.val)) { int year = Integer.parseInt(this.val.substring(0, 4)); int month = Integer.parseInt(this.val.substring(4, 6)); int day = Integer.parseInt(this.val.substring(6, 8)); return makeCalendar(year, month, day); } throw new <API key>(String.format("%s is not a fully specified date", this)); } /** * Gets two Calendars, marking the beginning and ending of this Timex's range. * * @return The begin point and end point Calendars. */ public Pair<Calendar, Calendar> getRange() { return this.getRange(null); } /** * Gets two Calendars, marking the beginning and ending of this Timex's range. * * @param documentTime * The time the document containing this Timex was written. (Not * necessary for resolving all Timex expressions. This may be * {@code null}, but then relative time expressions cannot be * resolved.) * @return The begin point and end point Calendars. */ public Pair<Calendar, Calendar> getRange(Timex documentTime) { if (this.val == null) { throw new <API key>("no value specified for " + this); } // YYYYMMDD or YYYYMMDDT... where the time is concatenated directly with the // date else if (val.length() >= 8 && Pattern.matches("\\d\\d\\d\\d\\d\\d\\d\\d", this.val.substring(0, 8))) { int year = Integer.parseInt(this.val.substring(0, 4)); int month = Integer.parseInt(this.val.substring(4, 6)); int day = Integer.parseInt(this.val.substring(6, 8)); return new Pair<>(makeCalendar(year, month, day), makeCalendar(year, month, day)); } // YYYY-MM-DD or YYYY-MM-DDT... else if (val.length() >= 10 && Pattern.matches("\\d\\d\\d\\d-\\d\\d-\\d\\d", this.val.substring(0, 10))) { int year = Integer.parseInt(this.val.substring(0, 4)); int month = Integer.parseInt(this.val.substring(5, 7)); int day = Integer.parseInt(this.val.substring(8, 10)); return new Pair<>(makeCalendar(year, month, day), makeCalendar(year, month, day)); } // YYYYMMDDL+ else if (Pattern.matches("\\d\\d\\d\\d\\d\\d\\d\\d[A-Z]+", this.val)) { int year = Integer.parseInt(this.val.substring(0, 4)); int month = Integer.parseInt(this.val.substring(4, 6)); int day = Integer.parseInt(this.val.substring(6, 8)); return new Pair<>(makeCalendar(year, month, day), makeCalendar(year, month, day)); } // YYYYMM or YYYYMMT... else if (val.length() >= 6 && Pattern.matches("\\d\\d\\d\\d\\d\\d", this.val.substring(0, 6))) { int year = Integer.parseInt(this.val.substring(0, 4)); int month = Integer.parseInt(this.val.substring(4, 6)); Calendar begin = makeCalendar(year, month, 1); int lastDay = begin.getActualMaximum(Calendar.DATE); Calendar end = makeCalendar(year, month, lastDay); return new Pair<>(begin, end); } // YYYY-MM or YYYY-MMT... else if (val.length() >= 7 && Pattern.matches("\\d\\d\\d\\d-\\d\\d", this.val.substring(0, 7))) { int year = Integer.parseInt(this.val.substring(0, 4)); int month = Integer.parseInt(this.val.substring(5, 7)); Calendar begin = makeCalendar(year, month, 1); int lastDay = begin.getActualMaximum(Calendar.DATE); Calendar end = makeCalendar(year, month, lastDay); return new Pair<>(begin, end); } // YYYY or YYYYT... else if (val.length() >= 4 && Pattern.matches("\\d\\d\\d\\d", this.val.substring(0, 4))) { int year = Integer.parseInt(this.val.substring(0, 4)); return new Pair<>(makeCalendar(year, 1, 1), makeCalendar(year, 12, 31)); } // PDDY if (Pattern.matches("P\\d+Y", this.val) && documentTime != null) { Calendar rc = documentTime.getDate(); int yearRange = Integer.parseInt(this.val.substring(1, this.val.length() - 1)); // in the future if (this.beginPoint < this.endPoint) { Calendar start = copyCalendar(rc); Calendar end = copyCalendar(rc); end.add(Calendar.YEAR, yearRange); return new Pair<>(start, end); } // in the past else if (this.beginPoint > this.endPoint) { Calendar start = copyCalendar(rc); Calendar end = copyCalendar(rc); start.add(Calendar.YEAR, 0 - yearRange); return new Pair<>(start, end); } throw new RuntimeException("begin and end are equal " + this); } // PDDM if (Pattern.matches("P\\d+M", this.val) && documentTime != null) { Calendar rc = documentTime.getDate(); int monthRange = Integer.parseInt(this.val.substring(1, this.val.length() - 1)); // in the future if (this.beginPoint < this.endPoint) { Calendar start = copyCalendar(rc); Calendar end = copyCalendar(rc); end.add(Calendar.MONTH, monthRange); return new Pair<>(start, end); } // in the past if (this.beginPoint > this.endPoint) { Calendar start = copyCalendar(rc); Calendar end = copyCalendar(rc); start.add(Calendar.MONTH, 0 - monthRange); return new Pair<>(start, end); } throw new RuntimeException("begin and end are equal " + this); } // PDDD if (Pattern.matches("P\\d+D", this.val) && documentTime != null) { Calendar rc = documentTime.getDate(); int dayRange = Integer.parseInt(this.val.substring(1, this.val.length() - 1)); // in the future if (this.beginPoint < this.endPoint) { Calendar start = copyCalendar(rc); Calendar end = copyCalendar(rc); end.add(Calendar.DAY_OF_MONTH, dayRange); return new Pair<>(start, end); } // in the past if (this.beginPoint > this.endPoint) { Calendar start = copyCalendar(rc); Calendar end = copyCalendar(rc); start.add(Calendar.DAY_OF_MONTH, 0 - dayRange); return new Pair<>(start, end); } throw new RuntimeException("begin and end are equal " + this); } // YYYYSP if (Pattern.matches("\\d+SP", this.val)) { int year = Integer.parseInt(this.val.substring(0, 4)); Calendar start = makeCalendar(year, 2, 1); Calendar end = makeCalendar(year, 4, 31); return new Pair<>(start, end); } // YYYYSU if (Pattern.matches("\\d+SU", this.val)) { int year = Integer.parseInt(this.val.substring(0, 4)); Calendar start = makeCalendar(year, 5, 1); Calendar end = makeCalendar(year, 7, 31); return new Pair<>(start, end); } // YYYYFA if (Pattern.matches("\\d+FA", this.val)) { int year = Integer.parseInt(this.val.substring(0, 4)); Calendar start = makeCalendar(year, 8, 1); Calendar end = makeCalendar(year, 10, 31); return new Pair<>(start, end); } // YYYYWI if (Pattern.matches("\\d+WI", this.val)) { int year = Integer.parseInt(this.val.substring(0, 4)); Calendar start = makeCalendar(year, 11, 1); Calendar end = makeCalendar(year + 1, 1, 29); return new Pair<>(start, end); } // YYYYWDD if (Pattern.matches("\\d\\d\\d\\dW\\d+", this.val)) { int year = Integer.parseInt(this.val.substring(0, 4)); int week = Integer.parseInt(this.val.substring(5)); int startDay = (week - 1) * 7; int endDay = startDay + 6; Calendar start = makeCalendar(year, startDay); Calendar end = makeCalendar(year, endDay); return new Pair<>(start, end); } // PRESENT_REF if (this.val.equals("PRESENT_REF")) { Calendar rc = documentTime.getDate(); // todo: This case doesn't check for documentTime being null and will NPE Calendar start = copyCalendar(rc); Calendar end = copyCalendar(rc); return new Pair<>(start, end); } throw new RuntimeException(String.format("unknown value \"%s\" in %s", this.val, this)); } private static Calendar makeCalendar(int year, int month, int day) { Calendar date = Calendar.getInstance(); date.clear(); date.set(year, month - 1, day, 0, 0, 0); return date; } private static Calendar makeCalendar(int year, int dayOfYear) { Calendar date = Calendar.getInstance(); date.clear(); date.set(Calendar.YEAR, year); date.set(Calendar.DAY_OF_YEAR, dayOfYear); return date; } private static Calendar copyCalendar(Calendar c) { Calendar date = Calendar.getInstance(); date.clear(); date.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.HOUR_OF_DAY), c .get(Calendar.MINUTE), c.get(Calendar.SECOND)); return date; } }
#include "<API key>.h" #include "plugin/device.h" #include "devicemanager.h" #include <QDebug> #include <QJsonDocument> #include <QVariantMap> #include <QDateTime> DeviceClassId <API key> = DeviceClassId("<API key>"); ActionTypeId <API key> = ActionTypeId("<API key>"); StateTypeId <API key> = StateTypeId("<API key>"); StateTypeId <API key> = StateTypeId("<API key>"); StateTypeId <API key> = StateTypeId("<API key>"); StateTypeId <API key> = StateTypeId("<API key>"); StateTypeId humidityStateTypeId = StateTypeId("<API key>"); StateTypeId pressureStateTypeId = StateTypeId("<API key>"); StateTypeId <API key> = StateTypeId("<API key>"); StateTypeId <API key> = StateTypeId("<API key>"); StateTypeId <API key> = StateTypeId("<API key>"); StateTypeId <API key> = StateTypeId("<API key>"); StateTypeId sunriseStateTypeId = StateTypeId("<API key>"); StateTypeId sunsetStateTypeId = StateTypeId("<API key>"); <API key>::<API key>() { m_openweaher = new OpenWeatherMap(this); connect(m_openweaher, &OpenWeatherMap::searchResultReady, this, &<API key>::searchResultsReady); connect(m_openweaher, &OpenWeatherMap::weatherDataReady, this, &<API key>::weatherDataReady); } DeviceManager::DeviceError <API key>::discoverDevices(const DeviceClassId &deviceClassId, const ParamList &params) { if(deviceClassId != <API key>){ return DeviceManager::<API key>; } QString location; foreach (const Param &param, params) { if (param.name() == "location") { location = param.value().toString(); } } // if we have an empty search string, perform an autodetection of the location with the WAN ip... if (location.isEmpty()){ m_openweaher->searchAutodetect(); } else { m_openweaher->search(location); } // otherwise search the given string m_openweaher->search(location); return DeviceManager::DeviceErrorAsync; } DeviceManager::DeviceSetupStatus <API key>::setupDevice(Device *device) { foreach (Device *deviceListDevice, deviceManager()-><API key>(<API key>)) { if(deviceListDevice->paramValue("id").toString() == device->paramValue("id").toString()){ qWarning() << QString("Location " + device->paramValue("location").toString() + " already added."); return DeviceManager::<API key>; } } device->setName("Weather from OpenWeatherMap (" + device->paramValue("location").toString() + ")"); m_openweaher->update(device->paramValue("id").toString(), device->id()); return DeviceManager::<API key>; } DeviceManager::HardwareResources <API key>::requiredHardware() const { return DeviceManager::<API key>; } DeviceManager::DeviceError <API key>::executeAction(Device *device, const Action &action) { if(action.actionTypeId() == <API key>){ m_openweaher->update(device->paramValue("id").toString(), device->id()); } return DeviceManager::DeviceErrorNoError; } void <API key>::guhTimer() { foreach (Device *device, deviceManager()-><API key>(<API key>)) { m_openweaher->update(device->paramValue("id").toString(), device->id()); } } void <API key>::searchResultsReady(const QList<QVariantMap> &cityList) { QList<DeviceDescriptor> retList; foreach (QVariantMap elemant, cityList) { DeviceDescriptor descriptor(<API key>, elemant.value("name").toString(),elemant.value("country").toString()); ParamList params; Param locationParam("location", elemant.value("name")); params.append(locationParam); Param countryParam("country", elemant.value("country")); params.append(countryParam); Param idParam("id", elemant.value("id")); params.append(idParam); descriptor.setParams(params); retList.append(descriptor); } emit devicesDiscovered(<API key>,retList); } void <API key>::weatherDataReady(const QByteArray &data, const DeviceId &deviceId) { QJsonParseError error; QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &error); if(error.error != QJsonParseError::NoError) { qWarning() << "failed to parse data" << data << ":" << error.errorString(); return; } QVariantMap dataMap = jsonDoc.toVariant().toMap(); foreach (Device *device, deviceManager()-><API key>(<API key>)) { if(device->id() == deviceId){ if(dataMap.contains("clouds")){ int cloudiness = dataMap.value("clouds").toMap().value("all").toInt(); device->setStateValue(<API key>,cloudiness); } if(dataMap.contains("dt")){ uint lastUpdate = dataMap.value("dt").toUInt(); device->setStateValue(<API key>,lastUpdate); } if(dataMap.contains("main")){ double temperatur = dataMap.value("main").toMap().value("temp").toDouble(); double temperaturMax = dataMap.value("main").toMap().value("temp_max").toDouble(); double temperaturMin = dataMap.value("main").toMap().value("temp_min").toDouble(); double pressure = dataMap.value("main").toMap().value("pressure").toDouble(); int humidity = dataMap.value("main").toMap().value("humidity").toInt(); device->setStateValue(<API key>,temperatur); device->setStateValue(<API key>,temperaturMin); device->setStateValue(<API key>,temperaturMax); device->setStateValue(pressureStateTypeId,pressure); device->setStateValue(humidityStateTypeId,humidity); } if(dataMap.contains("sys")){ uint sunrise = dataMap.value("sys").toMap().value("sunrise").toUInt(); uint sunset = dataMap.value("sys").toMap().value("sunset").toUInt(); device->setStateValue(sunriseStateTypeId,sunrise); device->setStateValue(sunsetStateTypeId,sunset); } if(dataMap.contains("weather")){ QString description = dataMap.value("weather").toMap().value("description").toString(); device->setStateValue(<API key>,description); } if(dataMap.contains("wind")){ int windDirection = dataMap.value("wind").toMap().value("deg").toInt(); double windSpeed = dataMap.value("wind").toMap().value("speed").toDouble(); device->setStateValue(<API key>,windDirection); device->setStateValue(<API key>,windSpeed); } } } }