max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
335
{ "word": "Westward", "definitions": [ "Towards the west." ], "parts-of-speech": "Adjective" }
59
1,056
<reponame>timfel/netbeans /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.xml.tax.beans.editor; import java.util.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.*; import javax.swing.table.AbstractTableModel; import javax.swing.event.ListSelectionListener; import javax.swing.event.ListSelectionEvent; import org.openide.util.HelpCtx; import org.openide.explorer.propertysheet.editors.EnhancedCustomPropertyEditor; import org.netbeans.tax.*; import org.netbeans.tax.traversal.TreeNodeFilter; import org.netbeans.modules.xml.tax.util.TAXUtil; /** * * @author <NAME> * @version 0.1 */ public class TreeNodeFilterCustomEditor extends JPanel implements EnhancedCustomPropertyEditor { /** */ private static final long serialVersionUID = 1767193347881681541L; /** */ private static final Map<Class<?>, String> publicNodeTypeNamesMap = new HashMap(); // // Static initialization // static { publicNodeTypeNamesMap.put (TreeNode.class, Util.THIS.getString ("NAME_Any_Node_Type")); publicNodeTypeNamesMap.put (TreeParentNode.class, Util.THIS.getString ("NAME_Any_Parent_Node_Type")); publicNodeTypeNamesMap.put (TreeCharacterData.class, Util.THIS.getString ("NAME_Any_Character_Data_Node_Type")); publicNodeTypeNamesMap.put (TreeReference.class, Util.THIS.getString ("NAME_Any_Reference_Node_Type")); // publicNodeTypeNamesMap.put (TreeEntityReference.class, Util.THIS.getString ("NAME_Any_Entity_Reference_Node_Type")); publicNodeTypeNamesMap.put (TreeNodeDecl.class, Util.THIS.getString ("NAME_Any_Declaration_Node_Type")); publicNodeTypeNamesMap.put (TreeComment.class, Util.THIS.getString ("NAME_Comment_Node_Type")); publicNodeTypeNamesMap.put (TreeProcessingInstruction.class, Util.THIS.getString ("NAME_Processing_Instruction_Node_Type")); publicNodeTypeNamesMap.put (TreeText.class, Util.THIS.getString ("NAME_Text_Node_Type")); publicNodeTypeNamesMap.put (TreeCDATASection.class, Util.THIS.getString ("NAME_CDATA_Section_Node_Type")); publicNodeTypeNamesMap.put (TreeElement.class, Util.THIS.getString ("NAME_Element_Node_Type")); publicNodeTypeNamesMap.put (TreeAttribute.class, Util.THIS.getString ("NAME_Attribute_Node_Type")); // publicNodeTypeNamesMap.put (TreeDocument.class, Util.THIS.getString ("NAME_Document_Node_Type")); // publicNodeTypeNamesMap.put (TreeDTD.class, Util.THIS.getString ("NAME_DTD_Node_Type")); publicNodeTypeNamesMap.put (TreeConditionalSection.class, Util.THIS.getString ("NAME_Conditional_Section_Node_Type")); publicNodeTypeNamesMap.put (TreeDocumentType.class, Util.THIS.getString ("NAME_Document_Type_Node_Type")); publicNodeTypeNamesMap.put (TreeGeneralEntityReference.class, Util.THIS.getString ("NAME_General_Entity_Reference_Node_Type")); publicNodeTypeNamesMap.put (TreeParameterEntityReference.class, Util.THIS.getString ("NAME_Parameter_Entity_Reference_Node_Type")); publicNodeTypeNamesMap.put (TreeElementDecl.class, Util.THIS.getString ("NAME_Element_Declaration_Node_Type")); publicNodeTypeNamesMap.put (TreeEntityDecl.class, Util.THIS.getString ("NAME_Entity_Declaration_Node_Type")); publicNodeTypeNamesMap.put (TreeAttlistDecl.class, Util.THIS.getString ("NAME_Attlist_Declaration_Node_Type")); publicNodeTypeNamesMap.put (TreeNotationDecl.class, Util.THIS.getString ("NAME_Notation_Declaration_Node_Type")); } /** */ private final TreeNodeFilter filter; /** */ private final List<Class> nodeTypesList; /** */ private NodeTypesTableModel tableModel; // // init // /** Creates new TreeNodeFilterEditor */ public TreeNodeFilterCustomEditor (TreeNodeFilter filter) { this.filter = filter; this.nodeTypesList = new LinkedList<>(Arrays.asList(filter.getNodeTypes())); initComponents(); ownInitComponents(); initAccessibility(); HelpCtx.setHelpIDString (this, this.getClass().getName()); } /** */ private void ownInitComponents () { tableModel = (NodeTypesTableModel)nodeTypesTable.getModel(); ListSelectionModel selModel = nodeTypesTable.getSelectionModel(); selModel.addListSelectionListener (new ListSelectionListener () { public void valueChanged (ListSelectionEvent e) { if (e.getValueIsAdjusting()) return; ListSelectionModel lsm = (ListSelectionModel)e.getSource(); if (lsm.isSelectionEmpty()) { removeButton.setEnabled (false); } else { removeButton.setEnabled (true); } } }); // Object[] array = publicNodeTypeNamesMap.keySet().toArray(); // for (int i = 0; i < array.length; i++) { // array[i] = new NamedClass ((Class)array[i]); // } // Arrays.sort (array, new NamedClassComparator()); // JComboBox cb = new JComboBox (array); JComboBox cb = new JComboBox (getPublicNodeTypesInheritanceTree()); cb.setEditable (false); DefaultCellEditor dce = new DefaultCellEditor (cb); // dce.setClickCountToStart (2); nodeTypesTable.getColumnModel().getColumn (0).setCellEditor (dce); } /** * @return Returns the property value that is result of the CustomPropertyEditor. * @exception InvalidStateException when the custom property editor does not represent valid property value * (and thus it should not be set) */ public Object getPropertyValue () throws IllegalStateException { short acceptPolicy = acceptRadioButton.isSelected() ? TreeNodeFilter.ACCEPT_TYPES : TreeNodeFilter.REJECT_TYPES; Class[] nodeTypes = (Class[])nodeTypesList.toArray (new Class[0]); return new TreeNodeFilter (nodeTypes, acceptPolicy); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the FormEditor. */ private void initComponents() {//GEN-BEGIN:initComponents java.awt.GridBagConstraints gridBagConstraints; acceptPolicyGroup = new javax.swing.ButtonGroup(); acceptPolicyPanel = new javax.swing.JPanel(); acceptRejectLabel = new javax.swing.JLabel(); rbPanel = new javax.swing.JPanel(); acceptRadioButton = new javax.swing.JRadioButton(); acceptRadioButton.setSelected (filter.getAcceptPolicy() == TreeNodeFilter.ACCEPT_TYPES); rejectRadioButton = new javax.swing.JRadioButton(); rejectRadioButton.setSelected (filter.getAcceptPolicy() == TreeNodeFilter.REJECT_TYPES); tablePanel = new javax.swing.JPanel(); tableScrollPane = new javax.swing.JScrollPane(); nodeTypesTable = new javax.swing.JTable(); nodeTypesTable.setSelectionMode (ListSelectionModel.SINGLE_SELECTION); addButton = new javax.swing.JButton(); removeButton = new javax.swing.JButton(); setLayout(new java.awt.BorderLayout()); acceptPolicyPanel.setLayout(new java.awt.GridBagLayout()); acceptRejectLabel.setText(Util.THIS.getString ("LBL_acceptReject")); acceptRejectLabel.setLabelFor(rbPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(12, 12, 0, 0); acceptPolicyPanel.add(acceptRejectLabel, gridBagConstraints); rbPanel.setLayout(new java.awt.GridBagLayout()); acceptRadioButton.setText(Util.THIS.getString ("LBL_showItRadioButton")); acceptPolicyGroup.add(acceptRadioButton); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 12, 0, 0); rbPanel.add(acceptRadioButton, gridBagConstraints); rejectRadioButton.setText(Util.THIS.getString ("LBL_hideItRadioButton")); acceptPolicyGroup.add(rejectRadioButton); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 12, 0, 0); rbPanel.add(rejectRadioButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(12, 0, 0, 11); acceptPolicyPanel.add(rbPanel, gridBagConstraints); add(acceptPolicyPanel, java.awt.BorderLayout.NORTH); tablePanel.setLayout(new java.awt.GridBagLayout()); nodeTypesTable.setModel(new NodeTypesTableModel()); nodeTypesTable.setPreferredScrollableViewportSize(new java.awt.Dimension(300, 200)); tableScrollPane.setViewportView(nodeTypesTable); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(11, 12, 0, 0); tablePanel.add(tableScrollPane, gridBagConstraints); addButton.setText(Util.THIS.getString ("LBL_addButton")); addButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.insets = new java.awt.Insets(11, 11, 0, 11); tablePanel.add(addButton, gridBagConstraints); removeButton.setText(Util.THIS.getString ("LBL_removeButton")); removeButton.setEnabled(false); removeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.insets = new java.awt.Insets(5, 11, 11, 11); tablePanel.add(removeButton, gridBagConstraints); add(tablePanel, java.awt.BorderLayout.CENTER); }//GEN-END:initComponents private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed // Add your handling code here: int sel = nodeTypesTable.getSelectedRow(); if (sel != -1) { tableModel.removeRow (sel); int numRows = nodeTypesTable.getModel().getRowCount(); if (numRows > 0) { sel = Math.min (sel, numRows - 1); nodeTypesTable.getSelectionModel().setSelectionInterval (sel, sel); } } }//GEN-LAST:event_removeButtonActionPerformed private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed // Add your handling code here: nodeTypesList.add (TreeNode.class); tableModel.fireTableDataChanged(); }//GEN-LAST:event_addButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JRadioButton rejectRadioButton; private javax.swing.JPanel rbPanel; private javax.swing.JPanel acceptPolicyPanel; private javax.swing.JButton addButton; private javax.swing.JLabel acceptRejectLabel; private javax.swing.JScrollPane tableScrollPane; private javax.swing.JTable nodeTypesTable; private javax.swing.JRadioButton acceptRadioButton; private javax.swing.JPanel tablePanel; private javax.swing.ButtonGroup acceptPolicyGroup; private javax.swing.JButton removeButton; // End of variables declaration//GEN-END:variables // // class RowKeyListener // /** deletes whole row by pressing DELETE on row column. */ private class RowKeyListener extends KeyAdapter { /** */ private JTable table; // // init // public RowKeyListener (JTable table) { this.table = table; } // // itself // /** */ public void keyReleased (KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_DELETE) { tableModel.removeRow (table.getSelectedRow()); } } } // // class NodeTypesTableModel // /** * */ private class NodeTypesTableModel extends AbstractTableModel { private static final long serialVersionUID =-1438087942670592779L; /** */ public void removeRow (int row) { nodeTypesList.remove (row); fireTableDataChanged(); } /** Returns the number of rows in the model */ public int getRowCount () { return nodeTypesList.size(); } /** Returns the number of columns in the model */ public int getColumnCount () { return 1; } /** Returns the class for a model. */ public Class getColumnClass (int index) { return Class.class; } /** */ public Object getValueAt (int row, int column) { Object retVal = new Item (new NamedClass ((Class)nodeTypesList.get (row))); if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug ("<-- getValue: row = " + row); // NOI18N if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug ("<-- getValue: column = " + column); // NOI18N if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug ("<-- getValue: " + retVal.getClass().getName() + " -- '" + retVal + "'"); // NOI18N return retVal; } /** */ public void setValueAt (Object val, int row, int column) { if ( row >= nodeTypesList.size() ) { // fixed ArrayIndexOutOfBounds on nodeTypesList.set (row, type); // 1) select last row of multi row table // 2) try to edit -- show combo box // 3) remove this row // 4) click to another row // 5) exception occur return; } Class type = null; if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug ("--> setValue: " + val.getClass().getName() + " -- '" + val + "'"); // NOI18N if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug ("--> setValue: row = " + row); // NOI18N if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug ("--> setValue: column = " + column); // NOI18N if ( val instanceof String ) { try { type = Class.forName (val.toString()); } catch (ClassNotFoundException exc) { // DO NOTHING } } else if ( val instanceof Item ) { type = ((Item)val).clazz.clazz; } else if ( val instanceof NamedClass ) { type = ((NamedClass)val).clazz; } if ( ( type == null ) || ( TreeNodeFilter.isValidNodeType (type) == false ) ) { TAXUtil.notifyWarning (Util.THIS.getString ("MSG_invalidNodeType", val.toString())); return; } nodeTypesList.set (row, type); } /** */ public String getColumnName (int column) { return Util.THIS.getString ("LBL_nodeType"); } /** Returns true for all cells which are editable. For a * a new cell is editable only name field. */ public boolean isCellEditable (int rowIndex, int columnIndex) { return true; } } // end: class NodeTypesTableModel // // NamedClass // /** * */ private static class NamedClass { /** */ private final Class clazz; /** */ public NamedClass (Class clazz) { this.clazz = clazz; } /** */ public String toString () { String name = (String)publicNodeTypeNamesMap.get (clazz); if ( name == null ) { name = clazz.getName(); } return name; } /** */ public boolean equals (Object obj) { if ( (obj instanceof NamedClass) == false ) { return false; } NamedClass peer = (NamedClass)obj; return clazz.equals (peer.clazz); } } // end: class NamedClass // // NamedClassComparator // /** * */ private static class NamedClassComparator implements Comparator { /** */ public int compare (Object obj1, Object obj2) throws ClassCastException { return (obj1.toString().compareTo (obj2.toString())); } /** */ public boolean equals (Object obj) { return ( obj instanceof NamedClassComparator ); } } // end: class NamedClassComparator // // InheritanceTree // /** */ private static Vector<Item> publicNodeTypesInheritanceTree; /** */ private static Vector<Item> getPublicNodeTypesInheritanceTree () { if ( publicNodeTypesInheritanceTree == null ) { if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug ("Init Set"); // NOI18N Item rootItem = new Item(); Object[] array = publicNodeTypeNamesMap.keySet().toArray(); for (int i = 0; i < array.length; i++) { Class<?> clazz = (Class)array[i]; Item.insertItemIntoLayer (rootItem.layer, Item.getItem (clazz)); if ( clazz.isInterface() ) { for (int j = 0; j < i; j++) { Item.insertItemIntoLayer (rootItem.layer, Item.getItem ((Class)array[j])); } } } publicNodeTypesInheritanceTree = new Vector<>(); fillPublicNodeTypesInheritanceTree (rootItem.layer, ""); // NOI18N Item.itemMap.clear(); Item.itemMap = null; rootItem = null; } return publicNodeTypesInheritanceTree; } /** */ private static void fillPublicNodeTypesInheritanceTree (Set<Item> layer, String prefix) { Iterator<Item> it = layer.iterator(); while ( it.hasNext() ) { Item item = it.next(); String itemPrefix = ""; // NOI18N if ( prefix.length() != 0 ) { if ( it.hasNext() ) { itemPrefix = prefix + "|- "; // NOI18N } else { itemPrefix = prefix + "`- "; // NOI18N } } Item newItem = new Item (item, itemPrefix); if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug (">>" + newItem.toString() + "<<"); // NOI18N publicNodeTypesInheritanceTree.add (newItem); String newPrefix; if ( prefix.length() == 0 ) { newPrefix = " "; // NOI18N } else { if ( it.hasNext() ) { newPrefix = prefix + "| "; // NOI18N } else { newPrefix = prefix + " "; // NOI18N } } fillPublicNodeTypesInheritanceTree (item.layer, newPrefix); } } /** * */ private static class Item { /** */ private static Map<Class, Item> itemMap; /** */ private final NamedClass clazz; /** */ private final Set<Item> layer; /** */ private final String prefix; /** */ private Item (NamedClass clazz, Set layer, String prefix) { this.clazz = clazz; this.layer = layer; this.prefix = prefix; } /** */ private Item (Item item, String prefix) { this (item.clazz, null, prefix); } /** */ private Item (NamedClass clazz) { this (clazz, new TreeSet (new NamedClassComparator()), new String()); } /** */ private Item () { this (new NamedClass (null)); } /** */ public String toString () { return prefix + clazz.toString(); } /** */ public boolean equals (Object obj) { if ( (obj instanceof Item) == false ) { return false; } if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug ("___ Item::equals: this = " + this); // NOI18N if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug ("___ ::equals: obj = " + obj); // NOI18N Item peer = (Item)obj; return clazz.equals (peer.clazz); } /** */ private static Item getItem (Class clazz) { if ( itemMap == null ) { itemMap = new HashMap<>(); } Item item = itemMap.get(clazz); if ( item == null ) { itemMap.put(clazz, item = new Item (new NamedClass (clazz))); } return item; } /** */ private static void insertItemIntoLayer (Set<Item> layer, Item newItem) { if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug ("\n\nInsert newItem : " + newItem); // NOI18N if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug (" Item : set = " + layer); // NOI18N boolean inserted = false; Object[] array = layer.toArray(); for (int i = 0; i < array.length; i++) { Item item = (Item) array[i]; if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug (" Item : item [" + i + "] = " + item); // NOI18N if ( item.clazz.clazz == newItem.clazz.clazz ) { // previously inserted if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug (" Item : #1 -= [ ITEM.clazz.clazz == NEW_ITEM.clazz.clazz => IGNORE insert ]=-"); // NOI18N // DO NOTHING inserted = true; } else if ( item.clazz.clazz.isAssignableFrom (newItem.clazz.clazz) ) { // II. if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug (" Item : #2 -= [ NEW_ITEM is subclass of actual ITEM => insert to ITEM.LAYER ]=-"); // NOI18N insertItemIntoLayer (item.layer, newItem); inserted = true; } else if ( newItem.clazz.clazz.isAssignableFrom (item.clazz.clazz) ) { // I. if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug (" Item : #3 -= [ actual ITEM '" + item + "' is subclass of NEW_ITEM => item REMOVED & insert to NEW_ITEM.LAYER ]=-"); // NOI18N if ( newItem.clazz.clazz.isInterface() == false ) { layer.remove (item); insertItemIntoLayer (newItem.layer, item); } } } if ( inserted == false ) { // III. if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug (" Item : #4 -= [ item '" + newItem + "' INSERTED into " + layer + " ] =-"); // NOI18N layer.add (newItem); } } } /** Initialize accesibility */ public void initAccessibility(){ this.getAccessibleContext().setAccessibleDescription(Util.THIS.getString("ACSD_TreeNodeFilterCustomEditor")); acceptRadioButton.getAccessibleContext().setAccessibleDescription(Util.THIS.getString("ACSD_acceptRejectLabel")); acceptRadioButton.setMnemonic((Util.THIS.getString ("LBL_showItRadioButton_Mnem")).charAt(0)); rejectRadioButton.getAccessibleContext().setAccessibleDescription(Util.THIS.getString("ACSD_rejectRadioButton")); rejectRadioButton.setMnemonic((Util.THIS.getString ("LBL_hideItRadioButton_Mnem")).charAt(0)); addButton.getAccessibleContext().setAccessibleDescription(Util.THIS.getString("ACSD_addButton1")); addButton.setMnemonic((Util.THIS.getString ("LBL_addButton_Mnem")).charAt(0)); removeButton.getAccessibleContext().setAccessibleDescription(Util.THIS.getString("ACSD_removeButton1")); removeButton.setMnemonic((Util.THIS.getString ("LBL_removeButton_Mnem")).charAt(0)); nodeTypesTable.getAccessibleContext().setAccessibleDescription(Util.THIS.getString("ACSD_nodeTypesTable")); nodeTypesTable.getAccessibleContext().setAccessibleName(Util.THIS.getString("ACSN_nodeTypesTable")); } // debug public static final void main (String[] args) throws Exception { // Vector vector = getPublicNodeTypesInheritanceTree(); // Iterator it = vector.iterator(); // System.out.println ("+==================================="); // NOI18N // while (it.hasNext()) { // System.out.println ("-= [ " + it.next().toString() + " ] =-"); // NOI18N // } } }
12,628
335
<filename>H/Hail_noun.json<gh_stars>100-1000 { "word": "Hail", "definitions": [ "Pellets of frozen rain which fall in showers from cumulonimbus clouds.", "A large number of things hurled forcefully through the air." ], "parts-of-speech": "Noun" }
111
1,391
#include <u.h> #include <libc.h> #include <bin.h> #include <httpd.h> typedef struct Error Error; struct Error { char *num; char *concise; char *verbose; }; Error errormsg[] = { /* HInternal */ {"500 Internal Error", "Internal Error", "This server could not process your request due to an internal error."}, /* HTempFail */ {"500 Internal Error", "Temporary Failure", "The object %s is currently inaccessible.<p>Please try again later."}, /* HUnimp */ {"501 Not implemented", "Command not implemented", "This server does not implement the %s command."}, /* HBadReq */ {"400 Bad Request", "Strange Request", "Your client sent a query that this server could not understand."}, /* HBadSearch */ {"400 Bad Request", "Inapplicable Search", "Your client sent a search that cannot be applied to %s."}, /* HNotFound */ {"404 Not Found", "Object not found", "The object %s does not exist on this server."}, /* HUnauth */ {"403 Forbidden", "Forbidden", "You are not allowed to see the object %s."}, /* HSyntax */ {"400 Bad Request", "Garbled Syntax", "Your client sent a query with incoherent syntax."}, /* HNoSearch */ {"403 Forbidden", "Search not supported", "The object %s does not support the search command."}, /* HNoData */ {"403 Forbidden", "No data supplied", "Search or forms data must be supplied to %s."}, /* HExpectFail */ {"403 Expectation Failed", "Expectation Failed", "This server does not support some of your request's expectations."}, /* HUnkVers */ {"501 Not Implemented", "Unknown http version", "This server does not know how to respond to http version %s."}, /* HBadCont */ {"501 Not Implemented", "Impossible format", "This server cannot produce %s in any of the formats your client accepts."}, /* HOK */ {"200 OK", "everything is fine"}, }; /* * write a failure message to the net and exit */ int hfail(HConnect *c, int reason, ...) { Hio *hout; char makeup[HBufSize]; va_list arg; int n; hout = &c->hout; va_start(arg, reason); vseprint(makeup, makeup+HBufSize, errormsg[reason].verbose, arg); va_end(arg); n = snprint(c->xferbuf, HBufSize, "<head><title>%s</title></head>\n<body><h1>%s</h1>\n%s</body>\n", errormsg[reason].concise, errormsg[reason].concise, makeup); hprint(hout, "%s %s\r\n", hversion, errormsg[reason].num); hprint(hout, "Date: %D\r\n", time(nil)); hprint(hout, "Server: Plan9\r\n"); hprint(hout, "Content-Type: text/html\r\n"); hprint(hout, "Content-Length: %d\r\n", n); if(c->head.closeit) hprint(hout, "Connection: close\r\n"); else if(!http11(c)) hprint(hout, "Connection: Keep-Alive\r\n"); hprint(hout, "\r\n"); if(c->req.meth == nil || strcmp(c->req.meth, "HEAD") != 0) hwrite(hout, c->xferbuf, n); if(c->replog) c->replog(c, "Reply: %s\nReason: %s\n", errormsg[reason].num, errormsg[reason].concise); return hflush(hout); }
1,053
2,542
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace Api; // ******************************************************************************************************************** // ComStoreItemMetadataEnumerator::ComStoreItemMetadataEnumerator Implementation // ComStoreItemMetadataEnumerator::ComStoreItemMetadataEnumerator(IStoreItemMetadataEnumeratorPtr const & impl) : IFabricKeyValueStoreItemMetadataEnumerator2(), ComUnknownBase(), impl_(impl) { } ComStoreItemMetadataEnumerator::~ComStoreItemMetadataEnumerator() { } HRESULT ComStoreItemMetadataEnumerator::MoveNext(void) { return impl_->MoveNext().ToHResult(); } HRESULT ComStoreItemMetadataEnumerator::TryMoveNext(BOOLEAN * success) { bool hasNext = false; auto error = impl_->TryMoveNext(hasNext); if (error.IsSuccess()) { *success = (hasNext ? TRUE : FALSE); } return error.ToHResult(); } IFabricKeyValueStoreItemMetadataResult * ComStoreItemMetadataEnumerator::get_Current(void) { IStoreItemMetadataPtr ptr = impl_->GetCurrentItemMetadata(); auto resultWrapper = WrapperFactory::create_com_wrapper(ptr->ToKeyValueItemMetadata()); return resultWrapper.DetachNoRelease(); }
457
634
<filename>platform/lang-impl/src/com/intellij/openapi/roots/ui/componentsList/layout/OrientedDimensionSum.java /* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.roots.ui.componentsList.layout; import java.awt.*; public class OrientedDimensionSum { private final Orientation myOrientation; private final Dimension mySum = new Dimension(); public OrientedDimensionSum(Orientation orientation) { myOrientation = orientation; } public void add(Dimension size) { myOrientation.expandInline(mySum, size); } public void addInsets(Insets insets) { mySum.width += insets.left + insets.right; mySum.height += insets.top + insets.bottom; } public Dimension getSum() { return mySum; } public void grow(int length) { myOrientation.extend(mySum, length); } }
422
3,834
<reponame>cmarincia/enso package org.enso.interpreter.epb.runtime; import com.oracle.truffle.api.exception.AbstractTruffleException; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; /** * A wrapper for exceptions that cross the polyglot boundary. * * <p>It is responsible for proxying messages across the polyglot boundary specifically for the case * of exceptions. Without this, exceptions (as non-linear control flow) would bubble up into Enso * without their context. This would allow them to be caught, but Enso would have no means of * executing code on the guest-language exception. Instead, we wrap the exception into this proxy, * which holds onto the foreign exception, as well as the two contexts necessary for mediating calls * between Enso and the foreign language. * * <p>This is _separate_ to the {@link PolyglotProxy} as we did not want to make that proxy into an * {@link AbstractTruffleException}. This means that we have more control over when foreign objects * are represented as exceptions. */ @ExportLibrary(value = InteropLibrary.class, delegateTo = "delegate") public class PolyglotExceptionProxy extends AbstractTruffleException { final PolyglotProxy delegate; final AbstractTruffleException original; public PolyglotExceptionProxy( AbstractTruffleException prototype, GuardedTruffleContext origin, GuardedTruffleContext target) { super(prototype); this.original = prototype; this.delegate = new PolyglotProxy(prototype, origin, target); } @ExportMessage boolean isException() { return true; } @ExportMessage RuntimeException throwException() { throw this; } public AbstractTruffleException getOriginal() { return original; } public GuardedTruffleContext getOrigin() { return delegate.getOrigin(); } public GuardedTruffleContext getTarget() { return delegate.getTarget(); } }
578
5,937
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //+----------------------------------------------------------------------------- // // // $TAG ENGR // $Module: win_mil_graphics_media // $Keywords: // // $Description: // Provides support for the player state manager. This provides a separate // thread which starts up the Player OCX and also provides services for // // $ENDTAG // //------------------------------------------------------------------------------ #include "precomp.hpp" #include "WmpStateEngine.tmh" #define SEEK_GRANULARITY 0.001 MtDefine(CWmpStateEngine, Mem, "CWmpStateEngine"); MtDefine(SubArcMethodItem, Mem, "SubArcMethodItem"); // // Public methods // //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::Create // // Synopsis: // Creates a new object the performs state management for the WmpOcx. This // object waits for state transitions to be applied to it (from any thread, // and then dispatches them to the Ocx). It then in turns waits for the // Ocx to notify it that it has reached a particular state before allowing // a queued up "Target" transition to become the next transition. // //------------------------------------------------------------------------------ /*static*/ HRESULT CWmpStateEngine:: Create( __in MediaInstance *pMediaInstance, // per media globals __in bool canOpenAnyMedia, __in SharedState *pSharedState, __deref_out CWmpStateEngine **ppPlayerState ) { HRESULT hr = S_OK; CWmpStateEngine *pWmpStateEngine = NULL; TRACEFID(pMediaInstance->GetID(), &hr); pWmpStateEngine = new CWmpStateEngine(pMediaInstance, canOpenAnyMedia, pSharedState); IFCOOM(pWmpStateEngine); pWmpStateEngine->InternalAddRef(); IFC(pWmpStateEngine->Init()); *ppPlayerState = pWmpStateEngine; pWmpStateEngine = NULL; Cleanup: ReleaseInterface(pWmpStateEngine); EXPECT_SUCCESSID(pMediaInstance->GetID(), hr); RRETURN(hr); } void CWmpStateEngine:: SetHasAudio( __in bool hasAudio ) { Assert(m_stateThreadId == GetCurrentThreadId()); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "SetHasAudio(%d)", hasAudio); m_pSharedState->SetHasAudio(hasAudio); } void CWmpStateEngine:: SetHasVideo( __in bool hasVideo ) { Assert(m_stateThreadId == GetCurrentThreadId()); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "SetHasVideo(%d)", hasVideo); m_pSharedState->SetHasVideo(hasVideo); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::UpdatePosition // // Synopsis: // Updates the shared state position // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: UpdatePosition( void ) { HRESULT hr = S_OK; // // We need to get the player because we're in a different apartment // IWMPControls *pControls = NULL; double position = 0.0; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); if (m_targetState.m_seekTo.m_isValid) { position = m_targetState.m_seekTo.m_value; } else if (m_targetInternalState.m_seekTo.m_isValid) { position = m_targetInternalState.m_seekTo.m_value; } else { if (!m_isMediaEnded) { if (NULL != m_pIWMPPlayer) { IFC(m_pIWMPPlayer->get_controls(&pControls)); IFC(pControls->get_currentPosition(&position)); } else { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "OCX not yet available - returning position of 0"); position = 0; } } // // If we've reached the end of the media we report our position as being // the end of the media. We need to explicitly take care of this // condition because otherwise WMP will return 0 as the position. // else { position = m_mediaLength; } } // // we must return the position in 100 nanosecond ticks // m_pSharedState->SetPosition(SecondsToTicks(position)); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Updating position to %I64d (WMP format: %f)", m_pSharedState->GetPosition(), position); Cleanup: ReleaseInterface(pControls); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::UpdateDownloadProgress // // Synopsis: // Update the download progress of media. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: UpdateDownloadProgress( void ) { HRESULT hr = S_OK; IWMPNetwork *pNetwork = NULL; long lProgress = 0; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); // // WMP's download progress isn't valid if the user has requested a different // URL. // if ( NULL != m_pIWMPPlayer && m_targetState.m_url && AreStringsEqual(m_targetState.m_url, m_currentInternalState.m_url)) { IFC(m_pIWMPPlayer->get_network(&pNetwork)); IFC(pNetwork->get_downloadProgress(&lProgress)); } else { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "DownloadProgress not valid - returning progress of 0"); lProgress = 0; } SetDownloadProgress(double(lProgress) / 100.0); hr = S_OK; Cleanup: ReleaseInterface(pNetwork); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::UpdateBufferingProgress // // Synopsis: // Updates the buffering progress of media. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: UpdateBufferingProgress( void ) { HRESULT hr = S_OK; IWMPNetwork *pNetwork = NULL; long lProgress = 0; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); // // WMP's buffering progress isn't valid if the user has requested a // different URL. // if ( NULL != m_pIWMPPlayer && m_targetState.m_url && AreStringsEqual(m_targetState.m_url, m_currentInternalState.m_url)) { IFC(m_pIWMPPlayer->get_network(&pNetwork)); IFC(pNetwork->get_bufferingProgress(&lProgress)); } else { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "BufferingProgress not valid - returning progress of 0"); lProgress = 0; } SetBufferingProgress(double(lProgress) / 100.0); hr = S_OK; Cleanup: ReleaseInterface(pNetwork); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::UpdateMediaLength // // Synopsis: // Decide whether the given media can be seeked. Stores the result in // m_canSeek // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: UpdateMediaLength( void ) { HRESULT hr = S_OK; IWMPMedia *pMedia = NULL; double mediaLength = 0.0; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); IFC(m_pIWMPPlayer->get_currentMedia(&pMedia)); Assert(pMedia); // should have media by this point IFC(pMedia->get_duration(&mediaLength)); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "UpdateMediaLength: WMP format length of %.4f", mediaLength); SetMediaLength(mediaLength); hr = S_OK; Cleanup: ReleaseInterface(pMedia); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::SetMediaLength // // Synopsis: // Set the length of media // //------------------------------------------------------------------------------ void CWmpStateEngine:: SetMediaLength( __in double length ) { TRACEF(NULL); Assert(m_stateThreadId == GetCurrentThreadId()); m_mediaLength = length; // // duration gives us the number of seconds as a double // we must convert this to 100 nanosecond ticks // We add 0.5 to round up to the nearest integer // m_pSharedState->SetLength(SecondsToTicks(m_mediaLength)); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Setting length to %4f", m_mediaLength); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::UpdateNaturalHeight // // Synopsis: // Get the native height of the video. Returns 0 if the height is not yet // available. The height is not cached, in case it changes mid-stream (I // haven't encountered any videos that actually do this, but I'm not // certain that it's not possible) // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: UpdateNaturalHeight( void ) { UINT pixels = static_cast<UINT>(-1); TRACEF(NULL); Assert(m_stateThreadId == GetCurrentThreadId()); pixels = m_presenterWrapper.DisplayHeight(); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Updating height to %d", pixels); m_pSharedState->SetNaturalHeight(pixels); RRETURN(S_OK); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::UpdateNaturalWidth // // Synopsis: // Get the native width of the video, returns 0 if the width is not yet // available. The width is not cached, in case it changes mid-stream (I // haven't encountered any videos that actually do this, but I'm not // certain that it's not possible) // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: UpdateNaturalWidth( void ) { UINT pixels = static_cast<UINT>(-1); TRACEF(NULL); Assert(m_stateThreadId == GetCurrentThreadId()); pixels = m_presenterWrapper.DisplayWidth(); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Updating width to %d", pixels); m_pSharedState->SetNaturalWidth(pixels); RRETURN(S_OK); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::SetIsBuffering // // Synopsis: // Set whether or not we're currently buffering // //------------------------------------------------------------------------------ void CWmpStateEngine:: SetIsBuffering( __in bool isBuffering ) { TRACEF(NULL); Assert(m_stateThreadId == GetCurrentThreadId()); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "IsBuffering(%!bool!)", isBuffering); m_pSharedState->SetIsBuffering(isBuffering); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::SetCanPause // // Synopsis: // Set whether or not we can pause // //------------------------------------------------------------------------------ void CWmpStateEngine:: SetCanPause( __in bool canPause ) { TRACEF(NULL); Assert(m_stateThreadId == GetCurrentThreadId()); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "CanPause(%!bool!)", canPause); m_canPause = canPause; m_pSharedState->SetCanPause(canPause); } void CWmpStateEngine:: SetDownloadProgress( __in double downloadProgress ) { TRACEF(NULL); Assert(m_stateThreadId == GetCurrentThreadId()); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "SetDownloadProgress(%.4f)", downloadProgress); m_pSharedState->SetDownloadProgress(downloadProgress); } void CWmpStateEngine:: SetBufferingProgress( __in double bufferingProgress ) { TRACEF(NULL); Assert(m_stateThreadId == GetCurrentThreadId()); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "SetBufferingProgress(%.4f)", bufferingProgress); m_pSharedState->SetBufferingProgress(bufferingProgress); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::Close // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: Close( void ) { HRESULT hr = S_OK; Assert(m_stateThreadId == GetCurrentThreadId()); // // Our target state is to go back to the beginning. // We don't need to set the m_isOcxCreated field to false because // that is a side effect of Clear. We do need to set the target // volume to the default because Clear will set it to 0. // m_targetState.Clear(); m_targetState.m_volume = gc_defaultAvalonVolume; m_isScrubbingEnabled = false; m_didRaisePrerolled = false; IFC(SignalSelf()); Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::SetTargetOcx // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: SetTargetOcx( __in bool isOcxCreated ) { HRESULT hr = S_OK; Assert(m_stateThreadId == GetCurrentThreadId()); m_targetState.m_isOcxCreated = isOcxCreated; IFC(SignalSelf()); Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::SetTargetUrl // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: SetTargetUrl( __in LPCWSTR url ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); delete[] m_targetState.m_url; m_targetState.m_url = NULL; IFC(CopyHeapString(url, &m_targetState.m_url)); IFC(SignalSelf()); Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::SetTargetActionState // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: SetTargetActionState( __in ActionState::Enum actionState ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); m_targetState.m_actionState = actionState; IFC(SignalSelf()); Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::SetTargetVolume // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: SetTargetVolume( __in long volume ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); m_targetState.m_volume = volume; IFC(SignalSelf()); Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::SetTargetBalance // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: SetTargetBalance( __in long balance ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); m_targetState.m_balance = balance; IFC(SignalSelf()); Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::SetTargetRate // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: SetTargetRate( __in double rate ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); m_targetState.m_rate = rate; IFC(SignalSelf()); Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::SetTargetSeekTo // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: SetTargetSeekTo( __in Optional<double> seekTo ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); m_targetState.m_seekTo = seekTo; IFC(SignalSelf()); Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::SetTargetIsScrubbingEnabled // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: SetTargetIsScrubbingEnabled( __in bool isScrubbingEnabled ) { TRACEF(NULL); Assert(m_stateThreadId == GetCurrentThreadId()); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "SetTargetIsScrubbingEnabled(%d)", isScrubbingEnabled); // // We don't need to signal ourselves - the next time we do a seek while // paused we'll query this property and do the right thing // m_isScrubbingEnabled = isScrubbingEnabled; RRETURN(S_OK); } HRESULT CWmpStateEngine:: InvalidateDidRaisePrerolled( void ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); m_didRaisePrerolled = false; IFC(SignalSelf()); Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::UpdateHasVideoForWmp11 // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: UpdateHasVideoForWmp11( void ) { UINT height = static_cast<UINT>(-1); UINT width = static_cast<UINT>(-1); bool hasVideo = false; TRACEF(NULL); Assert(m_stateThreadId == GetCurrentThreadId()); // // If we are using render config, we can't use the graph to // determine whether we have video. // if (m_useRenderConfig) { width = m_presenterWrapper.DisplayWidth(); height = m_presenterWrapper.DisplayHeight(); hasVideo = width != 0 || height != 0; SetHasVideo(hasVideo); } RRETURN(S_OK); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::ErrorInTransition // // Synopsis: // Handle a failed transition. In the case of failures we // // 1. Raise an event to the caller (it might be a failure returned by the Ocx // but not raised as an asycnhronous error event). // 2. Abandon the previous state transition arc. // //------------------------------------------------------------------------------ void CWmpStateEngine:: ErrorInTransition( __in HRESULT failureHr // HRESULT of failure. ) { HRESULT hr = S_OK; TRACEF(&hr); LogAVDataM( AVTRACE_LEVEL_ERROR, AVCOMP_STATEENGINE, "Hit failure on state transition %x, abandoning arc", failureHr); // // Abandon all pending transitions // m_actualState.m_seekTo.m_isValid = false; IFC(m_actualState.Copy(&m_currentInternalState)); IFC(m_currentInternalState.Copy(&m_pendingInternalState)); IFC(m_currentInternalState.Copy(&m_targetInternalState)); IFC(m_nextSubArcMethodStack.Clear()); m_isMediaEnded = false; // // We might not have a video presenter if we don't have support on the platform. // for example, amd64 or WMP9. // m_presenterWrapper.EndScrub(); m_presenterWrapper.EndFakePause(); // // This is kind of nasty because it almost surely takes the // unmanaged/managed layers out of sync, but the alternative is to // repetitively try the same arc over and over again. I'm not sure which is // worse. // IFC(m_currentInternalState.Copy(&m_targetState)); m_volumeMask.m_isValid = false; IFC(RaiseEvent(AVMediaFailed, failureHr)); Cleanup: EXPECT_SUCCESS(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::PlayerReachedActionState // // Synopsis: // This call-back is called from the Wmp Ocx when certain play states are // reached. We translate into our own state and then finalize an arc (we // could also start moving to a new target state). We discard events that // don't map directly to a useable state for us. // //------------------------------------------------------------------------------ void CWmpStateEngine:: PlayerReachedActionState( __in WMPPlayState state // The WMP player state ) { TRACEF(NULL); bool runState = false; Optional<ActionState::Enum> ourState = MapWmpStateEngine(state); if (state == wmppsBuffering) { SetIsBuffering(true); } else { SetIsBuffering(false); } if (ourState.m_isValid) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "PlayerReachedActionState ours: %d, wmps: %d", ourState.m_value, state); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Notified of our player state %d", ourState.m_value); // // If the player hasn't changed states, we don't need to run the transition // if (m_actualState.m_actionState != ourState.m_value) { m_actualState.m_actionState = ourState.m_value; runState = true; } // // PlayerReachedActionStatePlay relies upon m_actualState.m_actionState // being set correctly, so we need to call the method after setting the // variable. // if (ourState.m_value == ActionState::Play) { PlayerReachedActionStatePlay(); } } else { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Notified of Ocx player state %d", state); if (state == wmppsMediaEnded) { THR(MediaFinished()); } } if (runState) { THR(SignalSelf()); } } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::PlayerReachedOpenState // // Synopsis: // This call-back is called from the Wmp Ocx (via CWmpEventHandler) when // open states are reached. This allows us to treat opening a new URL as an // asynchronous transition. // //------------------------------------------------------------------------------ void CWmpStateEngine:: PlayerReachedOpenState( __in WMPOpenState state ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); if (state == wmposPlaylistOpenNoMedia) { // The MSDN documentation says we're not allowed to call get_URL from an // event handler, so we just have to trust that the file that is open is // really the one we just opened. if (!AreStringsEqual(m_actualState.m_url, m_pendingInternalState.m_url)) { IFC(CopyHeapString(m_pendingInternalState.m_url, &m_actualState.m_url)); IFC(SignalSelf()); } } Cleanup: EXPECT_SUCCESS(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::PlayerReachedPosition // // Synopsis: // Called from the WMP OCX (via CWmpEventHandler) when the player reaches a // particular position. This allows us to treat seek as an asynchronous // transition. // //------------------------------------------------------------------------------ void CWmpStateEngine:: PlayerReachedPosition( __in double newPosition ) { TRACEF(NULL); Assert(m_stateThreadId == GetCurrentThreadId()); // // Should not receive duplicate reached position notifications // Assert(!m_actualState.m_seekTo.m_isValid); m_actualState.m_seekTo = newPosition; THR(SignalSelf()); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::EvrReachedState // // Synopsis: // Called from the EVR (via CEvrPresenter) when the EVR reaches a new // state. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: EvrReachedState( __in RenderState::Enum renderState ) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "EvrReachedState(%d)", renderState); m_isEvrClockRunning = EvrStateToIsEvrClockRunning(renderState); THR(SignalSelf()); RRETURN(S_OK); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::ScrubSampleComposited // // Synopsis: // Called from the EVR (via CEvrPresenter) when the EVR reaches a new // state. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: ScrubSampleComposited( __in int placeHolder ) { HRESULT hr = S_OK; TRACEF(&hr); m_didReceiveScrubSample = true; IFC(SignalSelf()); Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::NewPresenter // // Synopsis: // Creates a new presenter and sets it on the WmpStateEngine, we shutdown // the old presenter. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: NewPresenter( __deref_out EvrPresenterObj **ppNewPresenter ) { HRESULT hr = S_OK; TRACEF(&hr); IFC( EvrPresenter::Create( m_pMediaInstance, m_ResetToken, this, m_pDXVAManagerWrapper, ppNewPresenter)); m_presenterWrapper.SetPresenter(*ppNewPresenter); Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::GetSurfaceRenderer // // Synopsis: // Retrieves the surface renderer, this could either by a dummy renderer or // the surface renderer associated with the evr presenter. We don't // necessarily have a surface renderer if we haven't yet initialized the // Ocx, or if we have closed the Ocx. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: GetSurfaceRenderer( __deref_out IAVSurfaceRenderer **ppISurfaceRenderer ) { HRESULT hr = S_OK; TRACEF(&hr); IFC(m_presenterWrapper.GetSurfaceRenderer(ppISurfaceRenderer)); if (!*ppISurfaceRenderer) { SetInterface(*ppISurfaceRenderer, m_pDummyRenderer); } Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::NeedUIFrameUpdate // // Synopsis: // Indicates that we need a UI frame update. // //------------------------------------------------------------------------------ void CWmpStateEngine:: NeedUIFrameUpdate( void ) { m_pMediaInstance->GetCompositionNotifier().NeedUIFrameUpdate(); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::Shutdown // // Synopsis: // Shut down the wmp player from the UI thread. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: Shutdown( __in int placeholder ) { TRACEF(NULL); Assert(m_stateThreadId == GetCurrentThreadId()); m_isShutdown = true; m_targetState.m_isOcxCreated = false; IGNORE_HR(RemoveOcx()); ReleaseInterface(m_pDXVAManagerWrapper); // // Make sure no more items are added to the state thread through us. // if (!SetEvent(m_isShutdownEvent)) { RIP("The only way an event can fail to be signalled is if the handle has become invalid through a Close"); } // // Remove the apartment item from the apartment scheduler. // m_pStateThread->ReleaseItem(this); m_pStateThread->CancelAllItemsWithOwner(static_cast<IUnknown*>(static_cast<CMILCOMBase*>(this))); // // This should be released by RemoveOcx // Assert(m_pDXVAManagerWrapper == NULL); RRETURN(S_OK); } // // Protected methods // STDMETHODIMP CWmpStateEngine:: HrFindInterface( __in_ecount(1) REFIID riid, __deref_out void **ppv ) { // // IUnknown handled by CMILCOMBase // RRETURN(E_NOINTERFACE); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::Run, CStateThreadItem // // Synopsis: // This is called whenever we are run on the apartment thread side this // corresponds to an AddItem call on the appartment manager. // //------------------------------------------------------------------------------ __override void CWmpStateEngine:: Run( void ) { TRACEF(NULL); DBG_CODE(if (m_pStateThread) { m_stateThreadId = m_pStateThread->GetThreadId(); }); HandleStateChange(); } // // Private methods // CWmpStateEngine:: CWmpStateEngine( __in MediaInstance *pMediaInstance, __in bool canOpenAnyMedia, __in SharedState *pSharedState ) : m_uiID(pMediaInstance->GetID()), m_pDummyRenderer(NULL), m_pIWMPPlayer(NULL), m_pIConnectionPoint(NULL), m_connectionPointAdvise(0), m_isMediaEnded(false), m_didSeek(false), m_needFlushWhenEndingFreeze(false), m_canSeek(true), m_isShutdown(false), m_pStateThread(NULL), m_uiThreadId(0), m_pDXVAManagerWrapper(NULL), m_pWmpEventHandler(NULL), m_mediaLength(0.0), m_waitForActionState(ActionState::Stop), m_lastActionState(ActionState::Stop), m_useRenderConfig(false), m_lastRenderState(ActionState::Stop), m_isEvrClockRunning(false), m_nextSubArcMethodStack(pMediaInstance->GetID()), m_isScrubbingEnabled(false), m_canOpenAnyMedia(canOpenAnyMedia), m_didReceiveScrubSample(false), m_didPreroll(false), m_canPause(false), m_didRaisePrerolled(false), m_presenterWrapper(pMediaInstance->GetID()), m_pSharedState(pSharedState) // not ref-counted #if DBG , m_stateThreadId(static_cast<DWORD>(-1)) #endif { TRACEF(NULL); SetInterface(m_pMediaInstance, pMediaInstance); m_nextSubArcMethodStack.SetStateEngine(this); } /*virtual*/ CWmpStateEngine:: ~CWmpStateEngine( ) { TRACEF(NULL); ReleaseInterface(m_pIWMPPlayer); ReleaseInterface(m_pIConnectionPoint); ReleaseInterface(m_pStateThread); ReleaseInterface(m_pDXVAManagerWrapper); ReleaseInterface(m_pWmpEventHandler); ReleaseInterface(m_pDummyRenderer); ReleaseInterface(m_pMediaInstance); m_pSharedState = NULL; // not ref-counted if (m_isShutdownEvent) { CloseHandle(m_isShutdownEvent); m_isShutdownEvent = NULL; } // // This destructor is called from the garbage collector thread, so we // aren't allowed to block. However, we maintain a global reference on // the state thread that isn't given up until DLL Process Detach, so // we know that we won't release the last reference to the state // thread, and therefore we won't block. // ReleaseInterface(m_pStateThread); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::Init // // Synopsis: // Initialize any state that might fail. In this case, we have the apartment // tnread (could fail to initialize its synchronization events), an event // to signal when we are initialized and an an event to signal when we // are shutdown. We also tell the state thread to start instantiating the // WMP OCX. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: Init( void ) { HRESULT hr = S_OK; TRACEF(&hr); m_uiThreadId = GetCurrentThreadId(); IFC(m_presenterWrapper.Init()); IFC(CStateThreadItem::Init()); IFC(CStateThread::CreateApartmentThread(&m_pStateThread)); // // Create a dummy surface renderer so that if we are caught without // a surface renderer (because we are initializing), we can just // return the dummy. // IFC(DummySurfaceRenderer::Create(m_pMediaInstance, &m_pDummyRenderer)); // // We can't call the accessor methods because they assert that // we're on the state thread. Since the state thread hasn't run // yet, it's safe to initialize on the UI thread. // m_targetState.m_isOcxCreated = true; m_targetState.m_volume = gc_defaultAvalonVolume; m_isShutdownEvent = CreateEvent( NULL, // Security Attributes TRUE, // Manual Reset FALSE, // Initial State is not signalled NULL); // Name if (NULL == m_isShutdownEvent) { IFC(GetLastErrorAsFailHR()); IFC(E_UNEXPECTED); } IFC(SignalSelf()); Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::InitializeOcx // // Synopsis: // In the apartment thread, initialize the Ocx, if this fails, then the // failure can be returned to the UI thread through some asynchronous call // later. This should only fail in extremely low resource conditions or if // the wrong version of WMP is present. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: InitializeOcx( void ) { HRESULT hr = S_OK; IWMPSettings *pSettings = NULL; IOleObject *pOleObj = NULL; IConnectionPointContainer *pConnectionContainer = NULL; CWmpClientSite *pClientSite = NULL; Wmp11ClientSite *p11ClientSite = NULL; CWmpEventHandler *pEventHandler = NULL; IWMPPlayer *pIWmpPlayer = NULL; IConnectionPoint *pIConnectionPoint = NULL; IWMPVideoRenderConfig *pIWMPVideoRenderConfig = NULL; IWMPRenderConfig *pIWMPRenderConfig = NULL; MFActivateObj *pActivateObj = NULL; DWORD connectionPointAdvise = static_cast<DWORD>(-1); TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_targetState.m_isOcxCreated); Assert(!m_pendingInternalState.m_isOcxCreated); m_pendingInternalState.m_isOcxCreated = m_targetState.m_isOcxCreated; // // If we don't have a DXVA manager wrapper (the first time this call is made), // the create one. // if (NULL == m_pDXVAManagerWrapper) { IFC(CDXVAManagerWrapper::Create(m_uiID, &m_ResetToken, &m_pDXVAManagerWrapper)); } // // Create objects // THR(hr = CAVLoader::CreateWmpOcx(&pIWmpPlayer)); if (FAILED(hr) && hr != WGXERR_AV_WMPFACTORYNOTREGISTERED) { hr = WGXERR_AV_INVALIDWMPVERSION; } IFC(hr); IFC(pIWmpPlayer->QueryInterface(&pOleObj)); // // Creating the MFActivateObj will result in the m_pPresenter being initialized // through the call to NewPresenter, this will be returned to WMP10 through // the client site or it will be returned to WMP11 through the activation // object. // IFC( MFActivate::Create( m_uiID, this, &pActivateObj)); // // On Polaris (and with Vista), we insert our presenter // if (SUCCEEDED(pIWmpPlayer->QueryInterface(__uuidof(IWMPVideoRenderConfig), reinterpret_cast<void **>(&pIWMPVideoRenderConfig)))) { m_useRenderConfig = true; IFC(Wmp11ClientSite::Create( m_uiID, &p11ClientSite)); IFC(pOleObj->SetClientSite(p11ClientSite)); // // On Vista we want to make sure that they don't attempt to initialize us in another // process. // if (SUCCEEDED(pIWmpPlayer->QueryInterface(__uuidof(IWMPRenderConfig), reinterpret_cast<void **>(&pIWMPRenderConfig)))) { IFC(pIWMPRenderConfig->put_inProcOnly(TRUE)); } IFC(pIWMPVideoRenderConfig->put_presenterActivate(pActivateObj)); } else { m_useRenderConfig = false; IFC( CWmpClientSite::Create( m_uiID, &pClientSite, this)); // // Connect the objects to each other // IFC(pOleObj->SetClientSite(pClientSite)); } IFC(CheckPlayerVersion(pIWmpPlayer)); IFC(pIWmpPlayer->QueryInterface(&pSettings)); IFC(pIWmpPlayer->QueryInterface(&pConnectionContainer)); if (!m_canOpenAnyMedia) { IFC(SetSafeForScripting(pIWmpPlayer)); } // // We don't want the media to start until we explicitly say so // IFC(pSettings->put_autoStart(VARIANT_FALSE)); // // Don't show error dialogs // IFC(pSettings->put_enableErrorDialogs(VARIANT_FALSE)); // // don't invoke urls in browser // IFC(pSettings->put_invokeURLs(VARIANT_FALSE)); IFC(CWmpEventHandler::Create(m_pMediaInstance, this, &pEventHandler)); // // We try to connect to the IWMPEvents interface. // If that fails, we fall back to _WMPOCXEvents. // hr = pConnectionContainer->FindConnectionPoint(__uuidof(IWMPEvents), &pIConnectionPoint); if (FAILED(hr)) { // // If not, try the _WMPOCXEvents interface, which will use IDispatch // IFC(pConnectionContainer->FindConnectionPoint( __uuidof(_WMPOCXEvents), &pIConnectionPoint )); } // // IConnectionPoint::Advise takes an IUnknown. We have to cast here to // prevent an ambiguous conversion error // IFC(pIConnectionPoint->Advise( static_cast<IWMPEvents*>(pEventHandler), &connectionPointAdvise)); Assert(NULL == m_pIWMPPlayer); m_pIWMPPlayer = pIWmpPlayer; pIWmpPlayer = NULL; Assert(NULL == m_pIConnectionPoint); m_pIConnectionPoint = pIConnectionPoint; pIConnectionPoint = NULL; // // Save the event handler so that we can disconnect it later. // Assert(NULL == m_pWmpEventHandler); m_pWmpEventHandler = pEventHandler; pEventHandler = NULL; m_connectionPointAdvise = connectionPointAdvise; m_currentInternalState.m_isOcxCreated = true; // // The OCX is created - we make a note of that so we won't try to create it // again. // m_actualState.m_isOcxCreated = true; Cleanup: ReleaseInterface(pIConnectionPoint); ReleaseInterface(pIWmpPlayer); ReleaseInterface(pSettings); ReleaseInterface(pOleObj); ReleaseInterface(pConnectionContainer); ReleaseInterface(pClientSite); ReleaseInterface(p11ClientSite); ReleaseInterface(pEventHandler); ReleaseInterface(pIWMPVideoRenderConfig); ReleaseInterface(pIWMPRenderConfig); ReleaseInterface(pActivateObj); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::DiscardOcx // // Synopsis: // In the apartment thread, initialize the Ocx, if this fails, then the // failure can be returned to the UI thread through some asynchronous call // later. This should only fail in extremely low resource conditions or if // the wrong version of WMP is present. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: DiscardOcx( void ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(!m_targetState.m_isOcxCreated); Assert(m_pendingInternalState.m_isOcxCreated); IFC(RemoveOcx()); Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::RemoveOcx // // Synopsis: // Removes the Ocx from memory and sets our internal state to reflect this // correctly // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: RemoveOcx( void ) { TRACEF(NULL); // // I don't use IFC here because I want to continue shutting down as much as // possible, even if I get errors. // IWMPControls *pIControls = NULL; IOleObject *pOleObj = NULL; Assert(m_stateThreadId == GetCurrentThreadId()); // // Disconect the video presenter from the composition engine, update the // dummy presenter's size to match the video presenter, and force a // frame update // { DWORD width = m_presenterWrapper.DisplayWidth(); DWORD height = m_presenterWrapper.DisplayHeight(); if (width != 0 && height != 0) { // // Force the dummy surface renderer to do a frame update. // m_pDummyRenderer->ForceFrameUpdate(width, height); m_presenterWrapper.SetPresenter(NULL); // // Notify composition so that we'll display black. Since we've // released the video presenter, we'll hand out the dummy // surface renderer on the next composition pass. // m_pMediaInstance->GetCompositionNotifier().NotifyComposition(); } else { // // Even if a frame update wasn't necessary, we still have to // set the presenter to null to break circular dependencies // m_presenterWrapper.SetPresenter(NULL); } } // // Clear our state. We are about to throw everything away. // m_currentInternalState.Clear(); m_pendingInternalState.Clear(); m_actualState.Clear(); m_didPreroll = false; m_didRaisePrerolled = false; // // Disconnect the event handler from ourselves. This prevents spurious // run-down messages occuring while we are shutting down. // if (m_pWmpEventHandler) { m_pWmpEventHandler->DisconnectStateEngine(); } ReleaseInterface(m_pWmpEventHandler); // // Clear any action states that might have been floating around. This prevents // us getting surprised if we were in the middle of an arc when we closed media. // IGNORE_HR(m_nextSubArcMethodStack.Clear()); if (m_pIWMPPlayer) { if (SUCCEEDED(m_pIWMPPlayer->get_controls(&pIControls))) { THR(pIControls->stop()); ReleaseInterface(pIControls); } else { RIP("Couldn't get controls"); } if (SUCCEEDED(m_pIWMPPlayer->QueryInterface(&pOleObj))) { THR(pOleObj->SetClientSite(NULL)); THR(pOleObj->Close(OLECLOSE_NOSAVE)); ReleaseInterface(pOleObj); } else { RIP("QueryInterface failed."); } } ReleaseInterface(m_pIWMPPlayer); if (m_pIConnectionPoint) { m_pIConnectionPoint->Unadvise(m_connectionPointAdvise); } ReleaseInterface(m_pIConnectionPoint); m_connectionPointAdvise = 0; return S_OK; } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::CheckPlayerVersion // // Synopsis: // Checks to see whether the player version is what we expect it to be. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: CheckPlayerVersion( __in IWMPPlayer *pIWmpPlayer ) { HRESULT hr = S_OK; BSTR szVersion = NULL; UINT uiVersion = 0; UINT i = 0; TRACEFID(0, &hr); Assert(m_stateThreadId == GetCurrentThreadId()); IFC(pIWmpPlayer->get_versionInfo(&szVersion)); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Version is %ws", szVersion); while (szVersion[i] != NULL && szVersion[i] != '.') { uiVersion = (10 * uiVersion) + (szVersion[i] - '0'); i++; } if (uiVersion < 10) { // video needs at least version 10 IFC(WGXERR_AV_INVALIDWMPVERSION); } Cleanup: SysFreeString(szVersion); // it's okay to pass NULL here RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::HandleStateChange // // Synopsis: // This is the central function that is called whenever we hit a state // change in the apartment. // // NOTE: Like anything called by the apartment manager, this function could // be called more than once for the same transition in some race conditions // it must be written to handle the case. // //------------------------------------------------------------------------------ void CWmpStateEngine:: HandleStateChange( void ) { HRESULT hr = S_OK; int i = 0; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); m_targetState.DumpPlayerState(m_uiID, "Start of HSC: m_targetState"); m_targetInternalState.DumpPlayerState(m_uiID, "Start of HSC: m_targetInternalState"); m_pendingInternalState.DumpPlayerState(m_uiID, "Start of HSC: m_pendingInternalState"); m_currentInternalState.DumpPlayerState(m_uiID, "Start of HSC: m_currentInternalState"); m_actualState.DumpPlayerState(m_uiID, "Start of HSC: m_actualState"); IFC(DoPreemptiveTransitions()); // // If the OCX has been torn down, then the stack should have been emptied // Assert(m_currentInternalState.m_isOcxCreated || m_nextSubArcMethodStack.IsEmpty()); // // We may need to fire prerolled again. This can happen when: // 1. CWmpPlayer::Open("file1.wmv") // 2. CWmpPlayer::Open("file2.wmv") // 3. CWmpPlayer::Open("file1.wmv") // // If 2 and 3 occur in quick succession, then we won't have actually opened // file2, but we will have invalidated everything on SharedState. We need to // set all the state back and fire prerolled so that managed code will know // to call DrawVideo with a non-zero size. // IFC(RaisePrerolledIfNecessary()); // // If we have a transition to continue, continue it // IFC(m_nextSubArcMethodStack.PopAndCall()); // // We can't begin other transitions unless // a) the Ocx has not been torn down // b) the current URL is not null, and // c) we aren't waiting for a transition to complete // if ( m_currentInternalState.m_isOcxCreated && m_currentInternalState.m_url != NULL && m_nextSubArcMethodStack.IsEmpty()) { // // We resync the target internal state to the target state // before beginning new arcs // IFC(m_targetState.Copy(&m_targetInternalState)); m_targetInternalState.m_volume = m_volumeMask.ApplyAsMask(m_targetInternalState.m_volume); // // Start new transitions until we're told to wait for the stack to // unwind, or there are no new transitions to begin // while (m_nextSubArcMethodStack.IsEmpty() && m_currentInternalState != m_targetInternalState) { i++; AssertMsg(i < 20, "Infinite loop detected"); Assert(m_currentInternalState == m_pendingInternalState); IFC(BeginNewTransition()); } Assert(!m_nextSubArcMethodStack.IsEmpty() || m_targetInternalState == m_targetState || m_volumeMask.m_isValid); } m_targetState.DumpPlayerState(m_uiID, "End of HSC: m_targetState"); m_targetInternalState.DumpPlayerState(m_uiID, "End of HSC: m_targetInternalState"); m_pendingInternalState.DumpPlayerState(m_uiID, "End of HSC: m_pendingInternalState"); m_currentInternalState.DumpPlayerState(m_uiID, "End of HSC: m_currentInternalState"); m_actualState.DumpPlayerState(m_uiID, "End of HSC: m_actualState"); Cleanup: if (FAILED(hr)) { LogAVDataM( AVTRACE_LEVEL_ERROR, AVCOMP_STATEENGINE, "Couldn't handle state transition, hr = %x", hr); ErrorInTransition(hr); } EXPECT_SUCCESS(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::DoPreemptiveTransitions // // Synopsis: // Possibly pre-empt pending transitions to start really important // transitions. This is called by HandleStateChange // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: DoPreemptiveTransitions( void ) { HRESULT hr = S_OK; TRACEF(&hr); // // If we haven't created the OCX, we do that first // if (m_targetState.m_isOcxCreated != m_pendingInternalState.m_isOcxCreated) { if (m_targetState.m_isOcxCreated) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Preemptively chose to initialize the ocx"); IFC(InitializeOcx()); } else { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Preemptively chose to discard the ocx"); IFC(DiscardOcx()); } } // // Only do the other state transitions if we have an Ocx. // if (m_currentInternalState.m_isOcxCreated) { // // We pre-empt transitions for new urls, if the OCX has been created. We may have to stop this if WMP balks // if (!AreStringsEqual(m_targetState.m_url, m_pendingInternalState.m_url) && m_currentInternalState.m_isOcxCreated) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Preemptively chose to update the url"); IFC(BeginUrlArc()); } } Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::BeginNewTransition // // Synopsis: // Start a new transition (or do nothing if the target state is the same // as pending state). This is called by HandleStateChange when // m_currentInternalState != m_targetInternalState // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: BeginNewTransition( void ) { HRESULT hr = S_OK; TRACEF(&hr); // // We process target states. There is no need to process shutdown changes, // url changes or ocx changes since we do those in DoPreemptiveTransitions. // if (m_currentInternalState.m_volume != m_targetInternalState.m_volume) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Chose to update the volume"); IFC(DoVolumeArc()); } else if (m_currentInternalState.m_balance != m_targetInternalState.m_balance) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Chose to update the balance"); IFC(DoBalanceArc()); } else if (m_currentInternalState.m_seekTo != m_targetInternalState.m_seekTo && m_currentInternalState.m_actionState != ActionState::Play) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Chose to seek"); IFC(BeginSeekToAndScrubArc()); } else if (m_currentInternalState.m_actionState != m_targetInternalState.m_actionState) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Chose to update the playstate"); IFC(BeginActionStateArc()); } else if (m_currentInternalState.m_seekTo != m_targetInternalState.m_seekTo) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Chose to seek"); IFC(BeginSeekToAndScrubArc()); } else if (m_currentInternalState.m_rate != m_targetInternalState.m_rate) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Chose to update the rate"); IFC(DoRateArc()); } else { RIP("Didn't find anything to update even though target != current"); } Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::BeginActionStateArc // // Synopsis: // Start an action state transition. This method just dispatches to the // appropriate handler. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: BeginActionStateArc( void ) { static const struct { ActionState::Enum currentState; ActionState::Enum pendingState; SubArcMethod actionMethod; } sc_stateTransitionTable[] = { // // Current State Transitioning To Action to perform // { ActionState::Stop, ActionState::Pause, &CWmpStateEngine::BeginStopToPauseArc }, { ActionState::Stop, ActionState::Play, &CWmpStateEngine::BeginStopToPlayArc }, { ActionState::Pause, ActionState::Stop, &CWmpStateEngine::BeginPauseToStopArc }, { ActionState::Pause, ActionState::Play, &CWmpStateEngine::BeginPauseToPlayArc }, { ActionState::Play, ActionState::Stop, &CWmpStateEngine::BeginPlayToStopArc }, { ActionState::Play, ActionState::Pause, &CWmpStateEngine::BeginPlayToPauseArc }, }; HRESULT hr = S_OK; int i = 0; TRACEF(&hr); m_pendingInternalState.m_actionState = m_targetInternalState.m_actionState; Assert(m_pendingInternalState.m_actionState != m_currentInternalState.m_actionState); Assert(m_targetInternalState.m_actionState != m_currentInternalState.m_actionState); if (!m_isMediaEnded) { // // Keep track of the last ActionState so that we can make sure we don't hit a // state that we didn't expect. // m_lastActionState = m_actualState.m_actionState; for(i = 0; i < COUNTOF(sc_stateTransitionTable); i++) { if ( sc_stateTransitionTable[i].currentState == m_currentInternalState.m_actionState && sc_stateTransitionTable[i].pendingState == m_pendingInternalState.m_actionState) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Chose row i = %d, performing action", i); if (sc_stateTransitionTable[i].actionMethod != NULL) { IFC((this->*(sc_stateTransitionTable[i].actionMethod))()); } break; } } if (i >= COUNTOF(sc_stateTransitionTable)) { LogAVDataM( AVTRACE_LEVEL_ERROR, AVCOMP_STATEENGINE, "Unable to handle state arc [current = %!ActionState!, transition = %!ActionState!, player = %!ActionState!]", m_currentInternalState.m_actionState, m_pendingInternalState.m_actionState, m_actualState.m_actionState); RIP("Unable to handle state arc."); IFC(E_UNEXPECTED); } } // // If the media has finished, we just pretend that we've reached the state // we were trying for. We won't do anything until we're asked to seek back. // else { m_currentInternalState.m_actionState = m_pendingInternalState.m_actionState; } Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::Arc_WaitForActionState // // Synopsis: // Wait for an action state change // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: Arc_WaitForActionState( void ) { HRESULT hr = S_OK; TRACEF(&hr); if (m_isMediaEnded) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Media has ended, so we pretend to reach the requested action state"); m_pendingInternalState.m_actionState = m_targetInternalState.m_actionState; m_currentInternalState.m_actionState = m_targetInternalState.m_actionState; IFC(m_nextSubArcMethodStack.PopAndCall()); } // // If we haven't changed action states, even though we're waiting for a // change, then we reschedule ourselves // else if (m_actualState.m_actionState == m_lastActionState && m_lastActionState != m_waitForActionState) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Arc_WaitForActionState: current action state is %!ActionState!, but we're waiting for %!ActionState!.", m_actualState.m_actionState, m_waitForActionState); IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::Arc_WaitForActionState)); } // // If we haven't changed render states, even though we're waiting for a // change, then we reschedule ourselves // else if ( m_pSharedState->GetHasVideo() && ( (m_waitForActionState == ActionState::Play && !m_isEvrClockRunning) || (m_waitForActionState != ActionState::Play && m_isEvrClockRunning))) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Arc_WaitForActionState: m_isEvrClockRunning is %d, but we're waiting for state %d.", m_isEvrClockRunning, m_waitForActionState); IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::Arc_WaitForActionState)); } // // if WMP is currently buffering, we reschedule ourselves because we need // to wait until WMP is not buffering // else if (m_actualState.m_actionState == ActionState::Buffer) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Arc_WaitForActionState: we're buffering"); IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::Arc_WaitForActionState)); } // // If we're not at the action state we were waiting for, // then something is really wrong // else if (m_actualState.m_actionState != m_waitForActionState) { RIP("Unexpected actual action state"); IFC(E_UNEXPECTED); } // // Otherwise we process the next sub-arc. // else { m_lastActionState = m_actualState.m_actionState; IFC(m_nextSubArcMethodStack.PopAndCall()); } Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::PostSeek // // Synopsis: // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: PostSeek( void ) { TRACEF(NULL); // // We only reset the target seek to if it hasn't changed // if (m_targetState.m_seekTo == m_pendingInternalState.m_seekTo) { m_targetState.m_seekTo.m_isValid = false; } // // PostSeek may be called even though we didn't seek. For example, it // will be called if we ignore a seek request because we're already // within SEEK_GRANULARITY of the requested position. // If we've really done a seek, we're no longer finished playing media. // We set some properties to trigger media to restart // if (m_isMediaEnded && m_actualState.m_seekTo.m_isValid) { Assert(m_actualState.m_actionState == ActionState::Stop); m_isMediaEnded = false; m_currentInternalState.m_actionState = ActionState::Stop; } // // We indicate that we have finished our transition by resetting all seekto's to false. // seeking is special in that WMP doesn't (necessarily) remain at that position, so it // doesn't make sense to keep around the last seeked position // m_pendingInternalState.m_seekTo.m_isValid = false; m_currentInternalState.m_seekTo.m_isValid = false; m_targetInternalState.m_seekTo.m_isValid = false; m_actualState.m_seekTo.m_isValid = false; RRETURN(S_OK); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::BeginStopToPauseArc // // Synopsis: // This function handles the arc going from stop to pause, this must // transition through play. It is possible that this transition could cause // audio glitches so we mute the volume while we are playing. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: BeginStopToPauseArc( void ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_actualState.m_actionState == ActionState::Stop); Assert(m_pendingInternalState.m_actionState == ActionState::Pause); Assert(!m_pSharedState->GetHasVideo() || !m_isEvrClockRunning); if (m_isScrubbingEnabled) { // // Begin scrubbing or not and wait for it to complete. // StopToPauseArc_Done will be called at the end // IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::ContinueStopToPauseArc)); IFC(BeginScrubArc()); } else { IFC(BeginNoScrubStopToPauseArc()); } Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::BeginNoScrubStopToPauseArc // // Synopsis: // Handles the stop to pause arc for the case where no scrubbing is desired // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: BeginNoScrubStopToPauseArc( void ) { HRESULT hr = S_OK; IWMPControls *pIControls = NULL; TRACEF(&hr); // // Save the current position so that we can restore it when we // finally reach the pause state. // m_targetInternalState.m_seekTo = 0; // // Mute so no glitches will be heard // m_targetInternalState.m_volume = 0; IFC(DoVolumeArc()); // // Don't show frames to avoid visual glitches. We could show // a frame without any cost, but then we'd break the "not scrubbing" // m_presenterWrapper.EndScrub(); m_presenterWrapper.BeginStopToPauseFreeze(); m_needFlushWhenEndingFreeze = false; // // Wait until WMP has reached the play state, // then continue the scrubbing arc by calling ScrubArc_Pause // IFC(m_pIWMPPlayer->get_controls(&pIControls)); IFC(IsSupportedWmpReturn(pIControls->play())); m_waitForActionState = ActionState::Play; IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::NoScrubStopToPauseArc_Pause)); IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::Arc_WaitForActionState)); Cleanup: ReleaseInterface(pIControls); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::NoScrubStopToPauseArc_Pause // // Synopsis: // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: NoScrubStopToPauseArc_Pause( void ) { HRESULT hr = S_OK; IWMPControls *pIControls = NULL; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_pendingInternalState.m_actionState == ActionState::Pause); // // We may actually encounter media ended for very short media // if (m_isMediaEnded) { Assert(m_actualState.m_actionState == ActionState::Stop); // // The current action state will have been set to the pending action // state when the media finished. // Assert(m_currentInternalState.m_actionState == ActionState::Pause); // // We handle media ending by just pretending that we've // reached the pause state // IFC(StopToPauseArc_Done()); } else { Assert(m_actualState.m_actionState == ActionState::Play); Assert(!m_pSharedState->GetHasVideo() || m_isEvrClockRunning); if (m_pSharedState->GetCanPause()) { // // Wait for WMP to pause, // then continue the arc by calling NoScrubStopToPauseArc_Seek // IFC(m_pIWMPPlayer->get_controls(&pIControls)); IFC(IsSupportedWmpReturn(pIControls->pause())); m_waitForActionState = ActionState::Pause; IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::NoScrubStopToPauseArc_Seek)); IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::Arc_WaitForActionState)); } else { // // If we can't pause, then we're done // IFC(StopToPauseArc_Done()); } } Cleanup: ReleaseInterface(pIControls); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::NoScrubStopToPauseArc_Seek // // Synopsis: // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: NoScrubStopToPauseArc_Seek( void ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_actualState.m_actionState == ActionState::Pause); Assert(m_pendingInternalState.m_actionState == ActionState::Pause); Assert(!m_pSharedState->GetHasVideo() || !m_isEvrClockRunning); if (m_canSeek) { IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::StopToPauseArc_Done)); // // We seeking using BeginSeekToArc (not BeginSeekToAndScrubArc - // that would lead to infinite recursion). When the seek is complete // we'll be done // IFC(BeginSeekToArc()); } else { // // If we can't seek, then we can't scrub and we're finished our arc // IFC(StopToPauseArc_Done()); } Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::StopToPauseArc_Done // // Synopsis: // This function handles the end of the stop to pause arc // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: ContinueStopToPauseArc( void ) { HRESULT hr = S_OK; TRACEF(&hr); if (m_currentInternalState.m_actionState == ActionState::Stop) { IFC(BeginNoScrubStopToPauseArc()); } else { IFC(StopToPauseArc_Done()); } Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::StopToPauseArc_Done // // Synopsis: // This function handles the end of the stop to pause arc // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: StopToPauseArc_Done( void ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_pendingInternalState.m_actionState == ActionState::Pause); // // If we can pause, then this is normal media and we should be in a paused // state // if (m_isMediaEnded) { Assert(m_actualState.m_actionState == ActionState::Stop); // // The current internal action state will have been set to pause when // the media ended. // Assert(m_currentInternalState.m_actionState == ActionState::Pause); } else if (m_pSharedState->GetCanPause()) { Assert(m_actualState.m_actionState == ActionState::Pause); Assert(m_currentInternalState.m_actionState == ActionState::Stop); } // // If we can't pause, then this must be live streaming media. We are in a // fake pause state. // else { Assert(m_actualState.m_actionState == ActionState::Play); Assert(m_currentInternalState.m_actionState == ActionState::Stop); // // The volume is currently 0, but if we don't mask it to 0, // it will be restored // m_volumeMask = 0; // // tell the sample scheduler that we are now paused. // Scrubbing mode is incompatible with fake pause, so we end the // scrub (if there was one) // // m_presenterWrapper.EndScrub(); m_presenterWrapper.BeginFakePause(); } if (m_didSeek) { m_needFlushWhenEndingFreeze = true; } m_currentInternalState.m_actionState = ActionState::Pause; // // Tell the managed layer that we've finished prerolling // m_didPreroll = true; IFC(RaisePrerolledIfNecessary()); // // No one should be waiting for us to complete // Assert(m_nextSubArcMethodStack.IsEmpty()); Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::BeginStopToPlayArc // // Synopsis: // Start transitioning from the stop state to the play state // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: BeginStopToPlayArc( void ) { HRESULT hr = S_OK; IWMPControls *pIControls = NULL; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_actualState.m_actionState == ActionState::Stop); Assert(m_currentInternalState.m_actionState == ActionState::Stop); Assert(m_pendingInternalState.m_actionState == ActionState::Play); // // Since we're playing, we're no longer showing the cached scrub position, // so we need to invalidate it. // m_cachedScrubPosition.m_isValid = false; // // Tell the presenter to release any samples it may have been holding for // scrubbing purposes // m_presenterWrapper.EndScrub(); m_presenterWrapper.EndStopToPauseFreeze(m_needFlushWhenEndingFreeze); IFC(m_pIWMPPlayer->get_controls(&pIControls)); IFC(IsSupportedWmpReturn(pIControls->play())); // // Wait for WMP to play, then call StopToPlayArc_Done // m_waitForActionState = ActionState::Play; IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::StopToPlayArc_Done)); IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::Arc_WaitForActionState)); Cleanup: ReleaseInterface(pIControls); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::StopToPlayArc_Done // // Synopsis: // This function handles the end of the stop to play arc // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: StopToPlayArc_Done( void ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_pendingInternalState.m_actionState == ActionState::Play); if (!m_isMediaEnded) { Assert(m_actualState.m_actionState == ActionState::Play); Assert(m_currentInternalState.m_actionState == ActionState::Stop); } m_currentInternalState.m_actionState = ActionState::Play; m_didPreroll = true; IFC(RaisePrerolledIfNecessary()); // // No one should be waiting for us to complete // Assert(m_nextSubArcMethodStack.IsEmpty()); Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::BeginPauseToStopArc // // Synopsis: // Start transitioning from the pause state to the stop state // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: BeginPauseToStopArc( void ) { HRESULT hr = S_OK; IWMPControls *pIControls = NULL; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_currentInternalState.m_actionState == ActionState::Pause); Assert(m_pendingInternalState.m_actionState == ActionState::Stop); // // If we can pause than our actual action state is pause, otherwise // our actual action state is play // Assert( (m_pSharedState->GetCanPause() && m_actualState.m_actionState == ActionState::Pause) || (!m_pSharedState->GetCanPause() && m_actualState.m_actionState == ActionState::Play)); IFC(m_pIWMPPlayer->get_controls(&pIControls)); IFC(IsSupportedWmpReturn(pIControls->stop())); // // Wait for us to reach the stopped state, then call Arc_ActionStateComplete // m_waitForActionState = ActionState::Stop; IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::Arc_ActionStateComplete)); IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::Arc_WaitForActionState)); Cleanup: ReleaseInterface(pIControls); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::BeginPauseToPlayArc // // Synopsis: // Delegate to RealPauseToPlayArc_Play or FakePauseToPlayArc_Done // depending on whether or not this media can pause // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: BeginPauseToPlayArc( void ) { // // Since we're playing, we're no longer showing the cached scrub position, // so we need to invalidate it. // m_cachedScrubPosition.m_isValid = false; if (m_pSharedState->GetCanPause()) { RRETURN(RealPauseToPlayArc_Play()); } else { RRETURN(FakePauseToPlayArc_Done()); } } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::RealPauseToPlayArc_Play // // Synopsis: // Start transitioning from the pause state to the play state // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: RealPauseToPlayArc_Play( void ) { HRESULT hr = S_OK; IWMPControls *pIControls = NULL; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_actualState.m_actionState == ActionState::Pause); Assert(m_currentInternalState.m_actionState == ActionState::Pause); Assert(m_pendingInternalState.m_actionState == ActionState::Play); // // Tell the presenter to release any samples it may have been holding for // scrubbing purposes // m_presenterWrapper.EndScrub(); m_presenterWrapper.EndStopToPauseFreeze(m_needFlushWhenEndingFreeze); IFC(m_pIWMPPlayer->get_controls(&pIControls)); IFC(IsSupportedWmpReturn(pIControls->play())); // // Wait for WMP to reach the play state, then call Arc_ActionStateComplete // m_waitForActionState = ActionState::Play; IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::Arc_ActionStateComplete)); IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::Arc_WaitForActionState)); Cleanup: ReleaseInterface(pIControls); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::FakePauseToPlayArc_Done // // Synopsis: // Transition from fake pause to play. This means un-muting the volume and // telling the presenter to resume showing frames. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: FakePauseToPlayArc_Done( void ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_actualState.m_actionState == ActionState::Play); Assert(m_currentInternalState.m_actionState == ActionState::Pause); Assert(m_pendingInternalState.m_actionState == ActionState::Play); // // restore the previous volume // m_volumeMask.m_isValid = false; m_targetInternalState.m_volume = m_targetState.m_volume; IFC(DoVolumeArc()); // // Tell the presenter that we are out of frame freezing mode // m_presenterWrapper.EndScrub(); m_presenterWrapper.EndFakePause(); m_presenterWrapper.EndStopToPauseFreeze(m_needFlushWhenEndingFreeze); // // Indicate that we are done this arc // m_currentInternalState.m_actionState = ActionState::Play; Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } HRESULT CWmpStateEngine:: BeginScrubArc( void ) { HRESULT hr = S_OK; IWMPControls *pIControls = NULL; double position = 0; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_actualState.m_actionState == ActionState::Pause || m_actualState.m_actionState == ActionState::Stop); Assert(m_pendingInternalState.m_actionState == ActionState::Pause); // // We don't assert m_pSharedState->GetHasVideo because scrubbing may be invoked as the // initial transition, before we know whether or not we have video // Assert(!m_pSharedState->GetHasVideo() || !m_isEvrClockRunning); IFC(m_pIWMPPlayer->get_controls(&pIControls)); IFC(pIControls->get_currentPosition(&position)); if (m_cachedScrubPosition.m_isValid && fabs(m_cachedScrubPosition.m_value - position) < SEEK_GRANULARITY) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Not scrubbing because we're already showing the correct frame"); IFC(m_nextSubArcMethodStack.PopAndCall()); } else { // // Save the current position so that we can restore it when we // finally reach the pause state. // m_targetInternalState.m_seekTo = position; // // Cache the last position scrubbed so that we don't repeat a scrub twice // m_cachedScrubPosition = position; // // Mute so no glitches will be heard // m_targetInternalState.m_volume = 0; IFC(DoVolumeArc()); m_didReceiveScrubSample = false; // // Put the presenter in scrubbing mode, take it out of // show no samples mode, which it may have been in // m_presenterWrapper.EndStopToPauseFreeze(m_needFlushWhenEndingFreeze); m_presenterWrapper.BeginScrub(); IFC(IsSupportedWmpReturn(pIControls->play())); // // ScrubArc_Pause won't actually do anything until we have the scrub sample // IFC(CWmpStateEngine::ScrubArc_Pause()); } Cleanup: ReleaseInterface(pIControls); EXPECT_SUCCESS(hr); RRETURN(hr); } HRESULT CWmpStateEngine:: ScrubArc_Pause( void ) { HRESULT hr = S_OK; IWMPControls *pIControls = NULL; Assert(m_stateThreadId == GetCurrentThreadId()); TRACEF(&hr); if (m_isMediaEnded) { // // If the media ended then we're done scrubbing. // m_targetInternalState.m_seekTo is set so we can // resume our original playstate/position. We don't // attempt to play -> pause -> seek again because // that would likely throw us into an infinite loop. // IFC(ScrubArc_Seek()); } else if (!m_didReceiveScrubSample) { IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::ScrubArc_Pause)); } else if (m_actualState.m_actionState == ActionState::Buffer) { IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::ScrubArc_Pause)); } else { Assert(m_actualState.m_actionState == ActionState::Play); Assert(m_pendingInternalState.m_actionState == ActionState::Pause); if (m_pSharedState->GetCanPause()) { // // Wait for WMP to pause, // then continue scrubbing arc by calling ScrubArc_Seek // IFC(m_pIWMPPlayer->get_controls(&pIControls)); IFC(IsSupportedWmpReturn(pIControls->pause())); m_waitForActionState = ActionState::Pause; IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::ScrubArc_Seek)); IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::Arc_WaitForActionState)); } else { // // If we can't pause, then we're done scrubbing // IFC(m_nextSubArcMethodStack.PopAndCall()); } } Cleanup: ReleaseInterface(pIControls); RRETURN(hr); } HRESULT CWmpStateEngine:: ScrubArc_Seek( void ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_pendingInternalState.m_actionState == ActionState::Pause); Assert(m_actualState.m_actionState == (m_isMediaEnded? ActionState::Stop : ActionState::Pause )); // // We don't assert m_pSharedState->GetHasVideo because scrubbing may be invoked as the // initial transition, before we know whether or not we have video // Assert(!m_pSharedState->GetHasVideo() || !m_isEvrClockRunning); if (m_canSeek) { // // We seeking using BeginSeekToArc (not BeginSeekToAndScrubArc - // that would lead to infinite recursion). When the seek is complete // we'll be done scrubbing // IFC(BeginSeekToArc()); } else { // // If we can't seek, then we're done scrubbing. // If there is someone waiting for scrubbing to complete, call them. // IFC(m_nextSubArcMethodStack.PopAndCall()); } Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::BeginPlayToStopArc // // Synopsis: // Start transitioning from the play state to the stop state // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: BeginPlayToStopArc( void ) { HRESULT hr = S_OK; IWMPControls *pIControls = NULL; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_actualState.m_actionState == ActionState::Play); Assert(m_currentInternalState.m_actionState == ActionState::Play); Assert(m_pendingInternalState.m_actionState == ActionState::Stop); IFC(m_pIWMPPlayer->get_controls(&pIControls)); IFC(IsSupportedWmpReturn(pIControls->stop())); // // Wait for WMP to stop, then call Arc_ActionStateComplete // m_waitForActionState = ActionState::Stop; IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::Arc_ActionStateComplete)); IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::Arc_WaitForActionState)); Cleanup: ReleaseInterface(pIControls); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::BeginPlayToPauseArc // // Synopsis: // Start transitioning from the play state to the pause state. // Delegates to either PlayToRealPauseArc_Pause or PlayToFakePauseArc_Done // depending on whether or not this media can pause. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: BeginPlayToPauseArc( void ) { if (m_pSharedState->GetCanPause()) { RRETURN(PlayToRealPauseArc_Pause()); } else { RRETURN(PlayToFakePauseArc_Done()); } } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::PlayToRealPauseArc_Pause // // Synopsis: // Start transitioning from the play state to pause state. We tell WMP to // pause and wait for it to complete. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: PlayToRealPauseArc_Pause( void ) { HRESULT hr = S_OK; IWMPControls *pIControls = NULL; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_actualState.m_actionState == ActionState::Play); Assert(m_currentInternalState.m_actionState == ActionState::Play); Assert(m_pendingInternalState.m_actionState == ActionState::Pause); IFC(m_pIWMPPlayer->get_controls(&pIControls)); IFC(IsSupportedWmpReturn(pIControls->pause())); // // Wait for WMP to pause, then call PlayToRealPauseArc_Done // m_waitForActionState = ActionState::Pause; IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::PlayToRealPauseArc_Done)); IFC(Arc_WaitForActionState()); Cleanup: ReleaseInterface(pIControls); EXPECT_SUCCESS(hr); RRETURN(hr); } HRESULT CWmpStateEngine:: PlayToRealPauseArc_Done( void ) { HRESULT hr = S_OK; double position = 0.0; IWMPControls *pIControls = NULL; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_actualState.m_actionState == ActionState::Pause); Assert(m_currentInternalState.m_actionState == ActionState::Play); Assert(m_pendingInternalState.m_actionState == ActionState::Pause); IFC(m_pIWMPPlayer->get_controls(&pIControls)); IFC(pIControls->get_currentPosition(&position)); m_cachedScrubPosition = position; IFC(Arc_ActionStateComplete()); Cleanup: ReleaseInterface(pIControls); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::PlayToFakePauseArc_Done // // Synopsis: // Transition from play to fake pause. This just involves muting and // setting the pause time on the presenter, so this completes synchronously // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: PlayToFakePauseArc_Done( void ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_actualState.m_actionState == ActionState::Play); Assert(m_currentInternalState.m_actionState == ActionState::Play); Assert(m_pendingInternalState.m_actionState == ActionState::Pause); // // Fake pause is just masking the volume to 0 and telling the surface // renderer not to show new frames // Assert(!m_volumeMask.m_isValid); m_volumeMask = 0; m_targetInternalState.m_volume = 0; IFC(DoVolumeArc()); // // Scrubbing mode is incompatible with fake pause, so we end the // scrub (if there was one) // m_presenterWrapper.EndScrub(); m_presenterWrapper.BeginFakePause(); // // Indicate that we are done this arc // m_currentInternalState.m_actionState = ActionState::Pause; Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::Arc_ActionStateComplete // // Synopsis: // This function handles the arcs that don't need any special // post-processing // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: Arc_ActionStateComplete( void ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_waitForActionState == m_pendingInternalState.m_actionState); // // If we've been waiting for Play, then it's possible we've reached // Play, then immediately ended. This has been seen to happen sometimes // while attempting to play images. We handle this by pretending to // be in the play state. // if (m_waitForActionState == ActionState::Play && m_isMediaEnded) { Assert(m_actualState.m_actionState == ActionState::Stop); } else { Assert(m_actualState.m_actionState == m_waitForActionState); } m_currentInternalState.m_actionState = m_pendingInternalState.m_actionState; // // If anyone was waiting for the action state to complete, then we call them // IFC(m_nextSubArcMethodStack.PopAndCall()); Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::UpdateCanPause // // Synopsis: // Decide whether the given media can be paused. Stores the result in // m_pSharedState // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: UpdateCanPause( void ) { HRESULT hr = S_OK; IWMPControls *pControls = NULL; BSTR bstr = NULL; VARIANT_BOOL canPause = VARIANT_FALSE; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); // // m_canPause is only guaranteed to be valid if m_didPreroll is true. // Otherwise we need to update it here. We can only do that if our actual // state is Play // if (!m_didPreroll) { Assert(m_actualState.m_actionState == ActionState::Play); IFC(m_pIWMPPlayer->get_controls(&pControls)); bstr = SysAllocString(L"pause"); IFCOOM(bstr); IFC(pControls->get_isAvailable(bstr, &canPause)); SetCanPause(!!canPause); } else { SetCanPause(m_canPause); } LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "CanPause=%d", m_pSharedState->GetCanPause()); hr = S_OK; Cleanup: SysFreeString(bstr); ReleaseInterface(pControls); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::InternalCanSeek // // Synopsis: // Decide whether the given media can be seeked. Stores the result in // m_canSeek // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: InternalCanSeek( void ) { HRESULT hr = S_OK; IWMPControls *pControls = NULL; BSTR bstr = NULL; VARIANT_BOOL canSeek = VARIANT_FALSE; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); IFC(m_pIWMPPlayer->get_controls(&pControls)); bstr = SysAllocString(L"currentPosition"); IFCOOM(bstr); IFC(pControls->get_isAvailable(bstr, &canSeek)); m_canSeek = !!canSeek; LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "CanSeek=%d", m_canSeek); hr = S_OK; Cleanup: SysFreeString(bstr); ReleaseInterface(pControls); EXPECT_SUCCESS(hr); RRETURN(hr); } HRESULT CWmpStateEngine:: UpdateHasAudioForWmp11( void ) { HRESULT hr = S_OK; IWMPMedia *pMedia = NULL; IWMPMedia3 *pMedia3 = NULL; BSTR type = NULL; long items = 0 ; VARIANT var = { 0 }; bool hasAudio = false; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); VariantInit(&var); if (m_useRenderConfig) { IFC(m_pIWMPPlayer->get_currentMedia(&pMedia)); IFC(pMedia->QueryInterface(&pMedia3)); IFC(SysAllocStringCheck(L"Streams", &type)); IFC(pMedia3->getAttributeCountByType(type, NULL, &items)); for (long i = 0; i < items; i++) { IFC(VariantClear(&var)); IFC(pMedia3->getItemInfoByType(type, NULL, i, &var)); if (var.vt != VT_BSTR) { RIP("Expected bstr"); IFC(E_FAIL); } if (wcscmp(var.bstrVal, L"audio") == 0) { hasAudio = true; break; } } LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "HasAudio (as determined through IWMPMedia3) = %!bool!", hasAudio); SetHasAudio(hasAudio); } hr = S_OK; Cleanup: ReleaseInterface(pMedia); ReleaseInterface(pMedia3); IGNORE_HR(VariantClear(&var)); SysFreeString(type); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Function: // DoVolumeArc // // Synopsis: // Sets the player volume (internally) for real. We use WMP units to save // on conversions when the volume is stored. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: DoVolumeArc( void ) { HRESULT hr = S_OK; IWMPSettings *pISettings = NULL; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); m_pendingInternalState.m_volume = m_targetInternalState.m_volume; IFC( m_pIWMPPlayer->QueryInterface( __uuidof(IWMPSettings), reinterpret_cast<void**>(&pISettings))); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Setting volume to %d", m_pendingInternalState.m_volume); IFC(pISettings->put_volume(m_pendingInternalState.m_volume)); // // Indicate that we finished the arc // m_currentInternalState.m_volume = m_pendingInternalState.m_volume; m_actualState.m_volume = m_pendingInternalState.m_volume; hr = S_OK; Cleanup: ReleaseInterface(pISettings); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Function: // DoBalanceArc // // Synopsis: // Sets the player balance (internally) for real. We use WMP units to save // on conversions when the balance is stored. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: DoBalanceArc( void ) { HRESULT hr = S_OK; IWMPSettings *pISettings = NULL; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); m_pendingInternalState.m_balance = m_targetInternalState.m_balance; IFC( m_pIWMPPlayer->QueryInterface( __uuidof(IWMPSettings), reinterpret_cast<void**>(&pISettings))); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Setting balance to %f", m_pendingInternalState.m_balance); IFC(pISettings->put_balance(m_pendingInternalState.m_balance)); // // Indicate that we finished the arc // m_currentInternalState.m_balance = m_pendingInternalState.m_balance; m_actualState.m_balance = m_pendingInternalState.m_balance; hr = S_OK; Cleanup: ReleaseInterface(pISettings); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Function: // DoRateArc // // Synopsis: // Sets the player balance (internally) for real. We use WMP units to save // on conversions when the balance is stored. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: DoRateArc( void ) { HRESULT hr = S_OK; IWMPSettings *pISettings = NULL; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); m_pendingInternalState.m_rate = m_targetInternalState.m_rate; IFC( m_pIWMPPlayer->QueryInterface( __uuidof(IWMPSettings), reinterpret_cast<void**>(&pISettings))); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Setting rate to %f", m_pendingInternalState.m_rate); IFC(IsSupportedWmpReturn(pISettings->put_rate(m_pendingInternalState.m_rate))); // // Indicate that we finished the arc // m_currentInternalState.m_rate = m_pendingInternalState.m_rate; m_actualState.m_rate = m_pendingInternalState.m_rate; hr = S_OK; Cleanup: ReleaseInterface(pISettings); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Function: // BeginUrlArc // // Synopsis: // Updates the url. This does not complete synchronously. We assume that we // are finished when we receive the wmposPlaylistOpenNoMedia event. // However, we don't find about all properties of the media until we // actually start playing it. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: BeginUrlArc( void ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); BSTR bstrUrl = NULL; IFC(CopyHeapString(m_targetState.m_url, &m_pendingInternalState.m_url)); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "opening %S", m_pendingInternalState.m_url); IFC(SysAllocStringCheck(m_pendingInternalState.m_url, &bstrUrl)); IFC(IsSupportedWmpReturn(m_pIWMPPlayer->put_URL(bstrUrl))); // // When we have a new Url, the media length might change, so we need to // throw away our cached value. // SetMediaLength(0.0); m_cachedScrubPosition.m_isValid = false; // // Setting a new url resets the play state, sets the rate to 1, // and abandons pending transitions. We reset the pending and current // states so that we'll notice that we need to change these again. // We also need clear m_nextSubArcMethodStack to completely abandon // any arcs that we are in the middle of. // m_currentInternalState.m_actionState = ActionState::Stop; m_pendingInternalState.m_actionState = ActionState::Stop; m_currentInternalState.m_seekTo.m_isValid = false; m_pendingInternalState.m_seekTo.m_isValid = false; m_actualState.m_seekTo.m_isValid = false; m_currentInternalState.m_rate = 1; m_pendingInternalState.m_rate = 1; m_actualState.m_rate = 1; IFC(m_nextSubArcMethodStack.Clear()); // // Opening a new url throws away the graph, so we need to reset the // evr state // m_isEvrClockRunning = false; // // If we're opening a different URL we know longer consider // WMP to be in an ended state // m_isMediaEnded = false; // // The new media may have different characteristics than the old one. // SetHasAudio(false); SetHasVideo(false); SetIsBuffering(false); SetCanPause(false); m_didPreroll = false; m_didRaisePrerolled = false; IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::ContinueUrlArc)); Cleanup: SysFreeString(bstrUrl); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Function: // ContinueUrlArc // // Synopsis: // Handles the notification that the URL has been updated // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: ContinueUrlArc( void ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); // // If we've opened the file, then make a note of it // if (AreStringsEqual(m_actualState.m_url, m_pendingInternalState.m_url)) { IFC(CopyHeapString(m_pendingInternalState.m_url, &m_currentInternalState.m_url)); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "opened %S", m_actualState.m_url); // // No other methods should be scheduled during a URL arc // Assert(m_nextSubArcMethodStack.IsEmpty()); } // // Otherwise, schedule ourselves again // else { IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::ContinueUrlArc)); } Cleanup: RRETURN(S_OK); } //+----------------------------------------------------------------------------- // // Function: // BeginSeekToArc // // Synopsis: // Starts seeking // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: BeginSeekToArc( void ) { HRESULT hr = S_OK; IWMPControls *pControls = NULL; double prevPosition = 0; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); Assert(m_targetInternalState.m_seekTo.m_isValid); // // This may be true if we started a seek while stopped previously. In that // case we wouldn't get a PositionChange notification until we started // playing, so we don't wait for it. We need to reset it here so we will // wait for the seek to complete if necessary and so that we don't mistake // the stale position for the new position to which we are seeking. // m_actualState.m_seekTo.m_isValid = false; m_pendingInternalState.m_seekTo = m_targetInternalState.m_seekTo; m_didSeek = false; if (!m_canSeek) { LogAVDataM( AVTRACE_LEVEL_WARNING, AVCOMP_STATEENGINE, "Ignoring seek to unseekable media"); IFC(PostSeek()); IFC(m_nextSubArcMethodStack.PopAndCall()); } else { IFC(m_pIWMPPlayer->get_controls(&pControls)); if (!m_isMediaEnded) { IFC(IsSupportedWmpReturn(pControls->get_currentPosition(&prevPosition))); } else { prevPosition = m_mediaLength; // // For some reason WMP resets the rate to 1. We note this so that we can // ping WMP again to set the rate to whatever is desired. // m_actualState.m_rate = 1; m_currentInternalState.m_rate = 1; m_pendingInternalState.m_rate = 1; m_actualState.m_actionState = ActionState::Stop; m_currentInternalState.m_actionState = ActionState::Stop; m_pendingInternalState.m_actionState = ActionState::Stop; } // // Don't process seeks that are within our threshold // if (fabs(m_pendingInternalState.m_seekTo.m_value - prevPosition) < SEEK_GRANULARITY) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Not seeking to position %.4f because WMP is already at position %.4f", m_pendingInternalState.m_seekTo.m_value, prevPosition); IFC(PostSeek()); IFC(m_nextSubArcMethodStack.PopAndCall()); } else { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Seeking to position %.4f position", m_pendingInternalState.m_seekTo.m_value); IFC(pControls->put_currentPosition(m_pendingInternalState.m_seekTo.m_value)); if (FAILED(IsSupportedWmpReturn(hr))) { LogAVDataM( AVTRACE_LEVEL_ERROR, AVCOMP_STATEENGINE, "Ignoring seek failure - m_actualState.m_actionState: %!ActionState!", m_actualState.m_actionState); IFC(PostSeek()); IFC(m_nextSubArcMethodStack.PopAndCall()); } else { // // Seek completes synchronously sometimes, so we must call FinishSeekToArc // rather than just pushing it onto the stack // IFC(FinishSeekToArc()); } } } Cleanup: ReleaseInterface(pControls); EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::FinishSeekToArc // // Synopsis: // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: FinishSeekToArc( void ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); // // This method should only be called when a seek is pending // Assert(m_pendingInternalState.m_seekTo.m_isValid); // // We don't do anything unless we've been notified of reaching a position // if (m_actualState.m_seekTo.m_isValid) { m_didSeek = true; // // One case where we can reach the wrong position is if we try to seek beyond // the end of the file. In such a case, WMP will seek to the end, rather // than past it, so it's safe to ignore it. Bug we log it just in case. // if (m_actualState.m_seekTo.m_value != m_pendingInternalState.m_seekTo.m_value) { LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Seek took us to position %f, though we requested %f", m_actualState.m_seekTo.m_value, m_pendingInternalState.m_seekTo.m_value); } IFC(PostSeek()); IFC(m_nextSubArcMethodStack.PopAndCall()); } // // We may not get PositionChange notifications if we're stopped // else if (m_actualState.m_actionState == ActionState::Stop) { m_didSeek = true; LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Seek happened during stopped state - not waiting for PositionChanged event"); IFC(PostSeek()); IFC(m_nextSubArcMethodStack.PopAndCall()); } // // Otherwise we schedule ourselves to be run again next time around // else { IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::FinishSeekToArc)); } Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Function: // BeginSeekToAndScrubArc // // Synopsis: // Starts seeking // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: BeginSeekToAndScrubArc( void ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); // // Begin seeking. When done, ContinueSeekToAndScrubArc will be called // IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::ContinueSeekToAndScrubArc)); IFC(BeginSeekToArc()); Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::ContinueSeekToAndScrubArc // // Synopsis: // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: ContinueSeekToAndScrubArc( void ) { HRESULT hr = S_OK; IWMPControls *pIWMPControls = NULL; IWMPControls2 *pIWMPControls2 = NULL; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); // // This method should only be called after seeking is complete // Assert(!m_targetInternalState.m_seekTo.m_isValid); Assert(!m_pendingInternalState.m_seekTo.m_isValid); Assert(!m_currentInternalState.m_seekTo.m_isValid); Assert(!m_actualState.m_seekTo.m_isValid); // // Scrubbing only applies when we are paused and when we have video. // if ( m_actualState.m_actionState == ActionState::Pause && m_targetState.m_actionState == ActionState::Pause && m_targetInternalState.m_actionState == ActionState::Pause && m_pendingInternalState.m_actionState == ActionState::Pause && m_currentInternalState.m_actionState == ActionState::Pause && m_pSharedState->GetHasVideo() && m_isScrubbingEnabled) { // // We need to do this so that we can be sure the EVR is in a paused state // m_waitForActionState = ActionState::Pause; IFC(m_nextSubArcMethodStack.Push(&CWmpStateEngine::BeginScrubArc)); IFC(Arc_WaitForActionState()); } // // If we can't scrub, and somebody's waiting, we call them // else { IFC(m_nextSubArcMethodStack.PopAndCall()); } Cleanup: ReleaseInterface(pIWMPControls); ReleaseInterface(pIWMPControls2); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::MapWmpStateEngine // // Synopsis: // Maps WMP states to our internal states for controlling media. // //------------------------------------------------------------------------------ /*static*/ Optional<ActionState::Enum> CWmpStateEngine:: MapWmpStateEngine( __in WMPPlayState playerState ) { static const struct { WMPPlayState wmpState; ActionState::Enum ourState; } aPlayStateMap[] = { { wmppsPaused, ActionState::Pause }, { wmppsPlaying, ActionState::Play }, { wmppsReady, ActionState::Stop }, { wmppsStopped, ActionState::Stop }, { wmppsBuffering, ActionState::Buffer }, { wmppsWaiting, ActionState::Buffer } }; Optional<ActionState::Enum> ourState; for(int i = 0; i < COUNTOF(aPlayStateMap); i++) { if (aPlayStateMap[i].wmpState == playerState) { ourState = Optional<ActionState::Enum>(aPlayStateMap[i].ourState); break; } } return ourState; } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::MediaFinished // // Synopsis: // Called when media finishes. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: MediaFinished() { HRESULT hr = S_OK; TRACEF(&hr); m_isMediaEnded = true; // // We only raise the media ended event if we're supposed to be playing. This // prevents false notifications if, for example, we hit the end of media // during a scrub. // if (m_targetState.m_actionState == ActionState::Play) { IFC(RaiseEvent(AVMediaEnded)); } Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::RaiseEvent // // Synopsis: // It's non-trivial to raise an event without causing a race condition or // possible deadlock so we abstract the code out into a separate method. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: RaiseEvent( __in AVEvent event, __in HRESULT failureHr ) { HRESULT hr = S_OK; TRACEF(&hr); // // It's possible for WMP to give us events after Avalon has told us to // shutdown. In this case we just throw the events away. // if (!m_isShutdown) { IFC(m_pMediaInstance->GetMediaEventProxy().RaiseEvent(event, failureHr)); } Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::PlayerReachedActionStatePlay // // Synopsis: // This is called when the player reaches a play state. There are certain // properties that we can query on the player at this point that we can't // (or that are meaningless) until the media actually starts playing. // // Must be called from WMPs STA thread // //------------------------------------------------------------------------------ void CWmpStateEngine:: PlayerReachedActionStatePlay( void ) { HRESULT hr = S_OK; TRACEF(&hr); Assert(m_stateThreadId == GetCurrentThreadId()); IFC(UpdateCanPause()); IFC(InternalCanSeek()); IFC(UpdateHasAudioForWmp11()); IFC(UpdateHasVideoForWmp11()); IFC(UpdateMediaLength()); IFC(UpdateNaturalWidth()); IFC(UpdateNaturalHeight()); Cleanup: EXPECT_SUCCESS(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::SignalSelf // // Synopsis: // Signal the state thread to run us again as a state-item. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: SignalSelf( void ) { HRESULT hr = S_OK; bool isShutdown = false; TRACEF(&hr); isShutdown = (WaitForSingleObject(m_isShutdownEvent, 0) == WAIT_OBJECT_0); if (isShutdown) { // // The managed code should never see this unless they call // something after shutdown. The EvrPresenter may see this // though. // IFC(MF_E_SHUTDOWN); } IFC(AddItem(this)); Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::SubArcMethodStack::SubArcMethodItem::Create // // Synopsis: // Create a new SubArcMethodItem // //------------------------------------------------------------------------------ /*static*/ HRESULT CWmpStateEngine::SubArcMethodStack::SubArcMethodItem:: Create( SubArcMethod method, SubArcMethodItem **ppItem ) { HRESULT hr = S_OK; *ppItem = new SubArcMethodItem; IFCOOM(*ppItem); (*ppItem)->m_method = method; Cleanup: RRETURN(hr); } CWmpStateEngine::SubArcMethodStack:: SubArcMethodStack( UINT uiID ) : m_pCWmpStateEngine(NULL), m_uiID(uiID) { IGNORE_HR(Clear()); } CWmpStateEngine::SubArcMethodStack:: ~SubArcMethodStack( void ) { m_pCWmpStateEngine = NULL; // Not ref-counted IGNORE_HR(Clear()); } void CWmpStateEngine::SubArcMethodStack:: SetStateEngine( CWmpStateEngine *pCWmpStateEngine ) { Assert(m_pCWmpStateEngine == NULL); m_pCWmpStateEngine = pCWmpStateEngine; // Not ref-counted } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::SubArcMethodStack::Push // // Synopsis: // Push a SubArcMethod onto the stack // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine::SubArcMethodStack:: Push( SubArcMethod method ) { HRESULT hr = S_OK; SubArcMethodItem *pItem = NULL; TRACEF(&hr); IFC(SubArcMethodItem::Create(method, &pItem)); m_stack.AddHead(pItem); Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::SubArcMethodStack::PopAndCall // // Synopsis: // If the stack is not empty, pop and call the method at the head. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine::SubArcMethodStack:: PopAndCall( void ) { HRESULT hr = S_OK; TRACEF(&hr); if (!m_stack.IsEmpty()) { SubArcMethodItem *pItem = m_stack.UnlinkHead(); SubArcMethod method = pItem->m_method; delete pItem; IFC((m_pCWmpStateEngine->*method)()); } Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::SubArcMethodStack:: // // Synopsis: // Remove all items from the SubArcMethod stack // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine::SubArcMethodStack:: Clear( void ) { TRACEF(NULL); while (!m_stack.IsEmpty()) { SubArcMethodItem *pItem = m_stack.UnlinkHead(); delete pItem; } RRETURN(S_OK); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::IsEmpty // // Synopsis: // Return whether the set of methods is empty. // //------------------------------------------------------------------------------ bool CWmpStateEngine::SubArcMethodStack:: IsEmpty( void ) const { return !!m_stack.IsEmpty(); } //+----------------------------------------------------------------------------- // // Member: // CWmpStateEngine::SetSafeFOrScripting // // Synopsis: // Set the given media player to be run safe for scripting. // //------------------------------------------------------------------------------ HRESULT CWmpStateEngine:: SetSafeForScripting( __in IWMPPlayer *pIWMPMedia ) { HRESULT hr = S_OK; IObjectSafety *pIObjectSafety = NULL; IFC(pIWMPMedia->QueryInterface(__uuidof(IObjectSafety), reinterpret_cast<void **>(&pIObjectSafety))); // // IDispatch actually applies to all derived interfaces from the Ocx, it is // what a scripting engine would be using. We use the native interfaces // instead, but, this request still applies. // // Note - this doesn't actually do anything in any of our scenarios that we // can discern, but, for future versions of the Ocx, this might change // behavior, so, it is important that we do this. // IFC( pIObjectSafety->SetInterfaceSafetyOptions( __uuidof(IDispatch), INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA, INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA)); LogAVDataM( AVTRACE_LEVEL_INFO, AVCOMP_STATEENGINE, "Set media player to be safe for untrusted callers and data"); Cleanup: EXPECT_SUCCESS(hr); ReleaseInterface(pIObjectSafety); RRETURN(hr); } HRESULT CWmpStateEngine:: RaisePrerolledIfNecessary( void ) { HRESULT hr = S_OK; if (m_didPreroll && !m_didRaisePrerolled) { IFC(UpdateCanPause()); IFC(InternalCanSeek()); IFC(UpdateHasAudioForWmp11()); IFC(UpdateHasVideoForWmp11()); IFC(UpdateMediaLength()); IFC(UpdateNaturalWidth()); IFC(UpdateNaturalHeight()); IFC(RaiseEvent(AVMediaPrerolled)); m_didRaisePrerolled = true; } Cleanup: EXPECT_SUCCESS(hr); RRETURN(hr); }
47,773
2,744
import logging from aiogram import Bot, Dispatcher, executor, types from aiogram.bot.api import TelegramAPIServer from aiogram.types import ContentType API_TOKEN = 'BOT TOKEN HERE' # Configure logging logging.basicConfig(level=logging.INFO) # Create private Bot API server endpoints wrapper local_server = TelegramAPIServer.from_base('http://localhost') # Initialize bot with using local server bot = Bot(token=API_TOKEN, server=local_server) # ... and dispatcher dp = Dispatcher(bot) @dp.message_handler(content_types=ContentType.ANY) async def echo(message: types.Message): await message.copy_to(message.chat.id) if __name__ == '__main__': executor.start_polling(dp, skip_updates=True)
229
460
/* * Copyright (C) 2002 <NAME> (<EMAIL>) * (C) 2002 <NAME> (<EMAIL>) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef AutoTableLayout_h #define AutoTableLayout_h #include "Length.h" #include "TableLayout.h" #include <wtf/Vector.h> namespace WebCore { class RenderTable; class RenderTableCell; class AutoTableLayout : public TableLayout { public: AutoTableLayout(RenderTable*); ~AutoTableLayout(); virtual void calcPrefWidths(int& minWidth, int& maxWidth); virtual void layout(); protected: void fullRecalc(); void recalcColumn(int effCol); void calcPercentages() const; int totalPercent() const { if (m_percentagesDirty) calcPercentages(); return m_totalPercent; } int calcEffectiveWidth(); void insertSpanCell(RenderTableCell*); struct Layout { Layout() : minWidth(0) , maxWidth(0) , effMinWidth(0) , effMaxWidth(0) , calcWidth(0) , emptyCellsOnly(true) {} Length width; Length effWidth; int minWidth; int maxWidth; int effMinWidth; int effMaxWidth; int calcWidth; bool emptyCellsOnly; }; Vector<Layout, 4> m_layoutStruct; Vector<RenderTableCell*, 4> m_spanCells; bool m_hasPercent : 1; mutable bool m_percentagesDirty : 1; mutable bool m_effWidthDirty : 1; mutable unsigned short m_totalPercent; }; } // namespace WebCore #endif // AutoTableLayout_h
916
505
<filename>src/sort.py<gh_stars>100-1000 """ As implemented in https://github.com/abewley/sort but with some modifications """ from __future__ import print_function import lib.utils as utils import numpy as np from src.data_association import associate_detections_to_trackers from src.kalman_tracker import KalmanBoxTracker logger = utils.Logger("MOT") class Sort: def __init__(self, max_age=1, min_hits=3): """ Sets key parameters for SORT """ self.max_age = max_age self.min_hits = min_hits self.trackers = [] self.frame_count = 0 def update(self, dets, img_size, root_dic, addtional_attribute_list, predict_num): """ Params: dets - a numpy array of detections in the format [[x,y,w,h,score],[x,y,w,h,score],...] Requires: this method must be called once for each frame even with empty detections. Returns the a similar array, where the last column is the object ID. NOTE:as in practical realtime MOT, the detector doesn't run on every single frame """ self.frame_count += 1 # get predicted locations from existing trackers. trks = np.zeros((len(self.trackers), 5)) to_del = [] ret = [] for t, trk in enumerate(trks): pos = self.trackers[t].predict() # kalman predict ,very fast ,<1ms trk[:] = [pos[0], pos[1], pos[2], pos[3], 0] if np.any(np.isnan(pos)): to_del.append(t) trks = np.ma.compress_rows(np.ma.masked_invalid(trks)) for t in reversed(to_del): self.trackers.pop(t) if dets != []: matched, unmatched_dets, unmatched_trks = associate_detections_to_trackers(dets, trks) # update matched trackers with assigned detections for t, trk in enumerate(self.trackers): if t not in unmatched_trks: d = matched[np.where(matched[:, 1] == t)[0], 0] trk.update(dets[d, :][0]) trk.face_addtional_attribute.append(addtional_attribute_list[d[0]]) # create and initialise new trackers for unmatched detections for i in unmatched_dets: trk = KalmanBoxTracker(dets[i, :]) trk.face_addtional_attribute.append(addtional_attribute_list[i]) logger.info("new Tracker: {0}".format(trk.id + 1)) self.trackers.append(trk) i = len(self.trackers) for trk in reversed(self.trackers): if dets == []: trk.update([]) d = trk.get_state() if (trk.time_since_update < 1) and (trk.hit_streak >= self.min_hits or self.frame_count <= self.min_hits): ret.append(np.concatenate((d, [trk.id + 1])).reshape(1, -1)) # +1 as MOT benchmark requires positive i -= 1 # remove dead tracklet if trk.time_since_update >= self.max_age or trk.predict_num >= predict_num or d[2] < 0 or d[3] < 0 or d[0] > img_size[1] or d[1] > img_size[0]: if len(trk.face_addtional_attribute) >= 5: utils.save_to_file(root_dic, trk) logger.info('remove tracker: {0}'.format(trk.id + 1)) self.trackers.pop(i) if len(ret) > 0: return np.concatenate(ret) return np.empty((0, 5))
1,639
351
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """\ Anagrams <NAME> - <NAME> - 2013-2019 """ # snip{ # pylint: disable=anomalous-backslash-in-string def anagrams(S): # S is a set of strings """group a set of words into anagrams :param S: set of strings :returns: list of lists of strings :complexity: :math:`O(n k log k)` in average, for n words of length at most k. :math:`O(n^2 k log k)` in worst case due to the usage of a dictionary. """ d = {} # maps s to list of words with signature s for word in S: # group words according to the signature s = ''.join(sorted(word)) # calculate the signature if s in d: d[s].append(word) # append a word to an existing signature else: d[s] = [word] # add a new signature and its first word # -- extract anagrams, ingoring anagram groups of size 1 return [d[s] for s in d if len(d[s]) > 1] # snip}
458
32,544
package com.baeldung.netty.http2.server; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http2.DefaultHttp2DataFrame; import io.netty.handler.codec.http2.DefaultHttp2Headers; import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame; import io.netty.handler.codec.http2.Http2Headers; import io.netty.handler.codec.http2.Http2HeadersFrame; import io.netty.util.CharsetUtil; @Sharable public class Http2ServerResponseHandler extends ChannelDuplexHandler { static final ByteBuf RESPONSE_BYTES = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8)); @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { super.exceptionCaught(ctx, cause); cause.printStackTrace(); ctx.close(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof Http2HeadersFrame) { Http2HeadersFrame msgHeader = (Http2HeadersFrame) msg; if (msgHeader.isEndStream()) { ByteBuf content = ctx.alloc() .buffer(); content.writeBytes(RESPONSE_BYTES.duplicate()); Http2Headers headers = new DefaultHttp2Headers().status(HttpResponseStatus.OK.codeAsText()); ctx.write(new DefaultHttp2HeadersFrame(headers).stream(msgHeader.stream())); ctx.write(new DefaultHttp2DataFrame(content, true).stream(msgHeader.stream())); } } else { super.channelRead(ctx, msg); } } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } }
785
3,714
<filename>labml_nn/transformers/hour_glass/__init__.py """ --- title: Hierarchical Transformers Are More Efficient Language Models summary: > This is an annotated implementation/tutorial of hourglass model in PyTorch. --- # Hierarchical Transformers Are More Efficient Language Models This is a [PyTorch](https://pytorch.org) implementation of the paper [Hierarchical Transformers Are More Efficient Language Models](https://papers.labml.ai/paper/2110.13711). This paper introduces a hierarchical transformer architecture to handle long sequences efficiently. The first half of the transformer layers down-sample tokens and the second half up-samples with direct skip connections between layers of the same resolution. This is a little similar to [U-Net](../../diffusion/ddpm/unet.html) for vision tasks. They try different up-sampling and down-sampling techniques and build a model with the best performing up and down-sampling techniques which they call the hourglass model. Here we have implemented the simplest up-sampling and down-sampling techniques for simplicity. We will consider adding more complex (and better performing) implementations later. Here is [the training code](experiment.html) for the hourglass model. [![View Run](https://img.shields.io/badge/labml-experiment-brightgreen)](https://app.labml.ai/run/855b82363e4911ec9ae4a5b9c69d5061) """ from typing import List import torch from torch import nn from labml_helpers.module import Module from labml_nn.transformers import MultiHeadAttention, TransformerLayer from labml_nn.transformers.feed_forward import FeedForward from labml_nn.transformers.utils import subsequent_mask class HourGlass(Module): """ ## Hourglass model This model recursively adds layers to the middle while shortening the sequence by down-sampling. The shortened sequence processed by another hourglass model is sandwiched between two normal transformer layers. (A transformer layer has a [self-attention layer](../mha.html) and a [position-wise feed-forward layer](../feed_forward.html)). """ def __init__(self, n_heads: int, d_model: int, dropout: float, d_ff: int, shortening_factors: List[int]): """ * `n_heads` is the number of heads in [multi-head attention layers](../mha.html) * `d_model` is the size of the token embeddings * `dropout` is the dropout probability * `d_ff` is the dimensionality of the hidden layer in [position-wise feed-forward layers](../feed_forward.html) * `shortening_factors` is the list of shortening factors """ super().__init__() # The transformer layer before down-sampling self.pre = TransformerLayer(d_model=d_model, # [Multi-head attention layer](../mha.html) self_attn=MultiHeadAttention(n_heads, d_model, dropout), # [Position wise feed-forward layers](.. / feed_forward.html) feed_forward=FeedForward(d_model, d_ff, dropout), # dropout_prob=dropout) # Auto-regressive mask self.mask = AutoregressiveMask() # The shortening factor $k$ (or the down-sampling rate) k = shortening_factors[0] # We shift the tokens to the right by $k - 1$ steps to make sure # information doesn't leak from the future tokens to past tokens # as a result of down-sampling and up-sampling self.shift_right = ShiftRight(k - 1) # Shortening or the down-sampling layer. We use the simplest form - average pooling. # The paper shows that attention based down sampling works best, which we haven't implemented yet. self.shortening = AvgPoolShortening(k) # If there are no more shortening (middle of the hourglass) if len(shortening_factors) == 1: # The center layer is another transformer layer self.shortened = TransformerLayer(d_model=d_model, self_attn=MultiHeadAttention(n_heads, d_model, dropout), feed_forward=FeedForward(d_model, d_ff, dropout), dropout_prob=dropout) # Autoregressive mask self.mask_short = AutoregressiveMask() self.hour_glass = None else: # Insert another hourglass model recursively self.hour_glass = HourGlass(n_heads, d_model, dropout, d_ff, shortening_factors[1:]) # Up-sampling layer. We use naive up-sampling for simplicity and the paper shows attention based up sampling # works better. self.up_sampling = NaiveUpSampling(k) # The final transformer layer after up-sampling self.post = TransformerLayer(d_model=d_model, self_attn=MultiHeadAttention(n_heads, d_model, dropout), feed_forward=FeedForward(d_model, d_ff, dropout), dropout_prob=dropout) def forward(self, x: torch.Tensor): # Initial transformer layer # $$x \leftarrow PreVanillaLayers(x)$$ x = self.pre(x=x, mask=self.mask(x)) # Shifting and shortening # $$x' \leftarrow Shortening(ShiftRight(x,k−1),k)$$ x_short = self.shortening(self.shift_right(x)) # If we are at the center of the hourglass, # $$\textbf{\small if } \text{\small E\scriptsize MPTY}(shorten\_factors) \textbf{\small then}$$ if self.hour_glass is None: # Center transformer layer # $$x' \leftarrow ShortenedLayers(x')$$ x_short = self.shortened(x=x_short, mask=self.mask_short(x_short)) # $$\textbf{else}$$ else: # $$x' \leftarrow \text{\small H\scriptsize OURGLASS}(x, shorten\_factors)$$ x_short = self.hour_glass(x_short) # Up-sample the shortened sequence and add a skip connection # $$x \leftarrow x + Upsampling(x, x', k)$$ x = x + self.up_sampling(x, x_short) # Final transformer layer # $$x \leftarrow PostVanillaLayers(x)$$ x = self.post(x=x, mask=self.mask(x)) # return x class ShiftRight(Module): """ ### Shift right operation This shifts the sequence to the right by the given number of steps """ def __init__(self, shift: int): """ * `shift` is the number of steps to shift by """ super().__init__() # cannot be negative assert shift >= 0 # self.shift = shift def forward(self, x: torch.Tensor): """ * `x` is a tensor of shape `[seq_len, ...]` """ # If the shift is $0$ return the original if self.shift == 0: return x # Zeros to be appended to the left prefix = x.new_zeros([self.shift, *x.shape[1:]]) # Concatenate the zeros and truncate the right return torch.cat([prefix, x[:-self.shift]]) class AvgPoolShortening(Module): """ ### Average pool shortening This down-samples by a given factor with average pooling """ def __init__(self, k: int): """ * `k` is the shortening factor """ super().__init__() # Average pooling layer self.pool = nn.AvgPool1d(k, ceil_mode=True) def forward(self, x: torch.Tensor): """ * `x` is of shape `[seq_len, batch_size, d_model]` """ # Pooling layer accepts shape `[batch_size, d_model, seq_len]` so we # permute axes. return self.pool(x.permute(1, 2, 0)).permute(2, 0, 1) class NaiveUpSampling(Module): """ ### Naive up-sampling This up-samples by repeating """ def __init__(self, k: int): """ * `k` is the shortening factor """ super().__init__() self.k = k def forward(self, x: torch.Tensor, x_short: torch.Tensor): """ * `x` is the tensor with embeddings before down-sampling * `x_short` is the tensor of higher density (to be up-sampled) representations """ # Repeat across the sequence dimension expanded = torch.repeat_interleave(x_short, self.k, dim=0) # Truncate the extra embeddings at the end expanded = expanded[:x.shape[0]] # return expanded class AutoregressiveMask(Module): """ ### Generate auto-regressive mask """ def __init__(self): super().__init__() self.mask = None def forward(self, x: torch.Tensor): # Create a mask if we haven't created or sizes have changed if self.mask is None or self.mask.size(0) != len(x): # [Subsequent mask](../utils.html), will mask out tokens from seeing future tokens self.mask = subsequent_mask(len(x)).to(x.device) # return self.mask class LinearPoolingShortening(Module): """ ### 🚧 Linear pooling for down-sampling This concatenates the consecutive tokens embeddings that need to be merged and do a linear transformation to map it to the size of a single token embedding. """ def __init__(self): super().__init__() raise NotImplementedError class AttentionBasedShortening(Module): """ ### 🚧 Down-sampling with attention \begin{align} x' &= S(x) + Attention \Big(Q=S(x),K = x, V =x \Big) \\ x' &= x' + FFN(x') \end{align} where $S(x)$ is average pooling or linear pooling. """ def __init__(self): super().__init__() raise NotImplementedError class LinearUpSampling(Module): """ ### 🚧 Linear projection for up-sampling Make a linear projection of dense token embeddings to a size of $d_{\text{model}} k$. """ def __init__(self): super().__init__() raise NotImplementedError class AttentionBasedUpSampling(Module): """ ### 🚧 Attention based up-sampling \begin{align} x &= U(x,x') + Attention \Big(Q=U(x,x'),K = x', V = x' \Big) \\ x &= x + FFN(x) \end{align} where $U(x,x') = x + LinearUpsampling(x')$ """ def __init__(self): super().__init__() raise NotImplementedError
4,323
8,629
#include "WatermarkTransform.h" #include <Columns/ColumnTuple.h> #include <Columns/ColumnsNumber.h> #include <Storages/WindowView/StorageWindowView.h> namespace DB { WatermarkTransform::WatermarkTransform( const Block & header_, StorageWindowView & storage_, const String & window_column_name_, UInt32 lateness_upper_bound_) : ISimpleTransform(header_, header_, false) , block_header(header_) , storage(storage_) , window_column_name(window_column_name_) , lateness_upper_bound(lateness_upper_bound_) { } WatermarkTransform::~WatermarkTransform() { if (max_watermark) storage.updateMaxWatermark(max_watermark); if (lateness_upper_bound) storage.addFireSignal(late_signals); } void WatermarkTransform::transform(Chunk & chunk) { auto num_rows = chunk.getNumRows(); auto columns = chunk.detachColumns(); auto column_window_idx = block_header.getPositionByName(window_column_name); const auto & window_column = columns[column_window_idx]; const ColumnUInt32::Container & window_end_data = static_cast<const ColumnUInt32 &>(*window_column).getData(); for (const auto & ts : window_end_data) { if (ts > max_watermark) max_watermark = ts; if (lateness_upper_bound && ts <= lateness_upper_bound) late_signals.insert(ts); } chunk.setColumns(std::move(columns), num_rows); } }
547
15,193
from bokeh.io import export_png from bokeh.plotting import figure # prepare some data x = [1, 2, 3, 4, 5] y = [4, 5, 5, 7, 2] # create a new plot with fixed dimensions p = figure(width=350, height=250) # add a circle renderer circle = p.circle(x, y, fill_color="red", size=15) # save the results to a file export_png(p, filename="plot.png")
129
945
<gh_stars>100-1000 # Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Progressively freeze the layers of the network during training, starting with the earlier layers. See the :doc:`Method Card </method_cards/layer_freezing>` for more details. """ from composer.algorithms.layer_freezing.layer_freezing import LayerFreezing as LayerFreezing from composer.algorithms.layer_freezing.layer_freezing import freeze_layers as freeze_layers __all__ = ["LayerFreezing", "freeze_layers"]
152
396
package com.yeungeek.mvp.common; /** * Created by yeungeek on 2016/1/8. */ public interface MvpView { }
43
953
<reponame>HoppingTappy/sakura /*! @file */ /* Copyright (C) 2018-2021, Sakura Editor Organization This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "StdAfx.h" #include "CNativeA.h" #include "debug/Debug1.h" CNativeA::CNativeA( const char* szData, size_t cchData ) { SetString(szData, cchData); } CNativeA::CNativeA(const char* szData) { SetString(szData); } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- // // ネイティブ設定インターフェース // // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- // // バッファの内容を置き換える void CNativeA::SetString( const char* pszData ) { if( pszData != nullptr ){ std::string_view data( pszData ); SetString( data.data(), data.length() ); }else{ Reset(); } } // バッファの内容を置き換える。nLenは文字単位。 void CNativeA::SetString( const char* pData, size_t nDataLen ) { SetRawData( pData, nDataLen ); } // バッファの内容を置き換える void CNativeA::SetNativeData( const CNativeA& cNative ) { SetRawData( cNative.GetRawPtr(), cNative.GetRawLength() ); } // バッファの最後にデータを追加する void CNativeA::AppendString( const char* pszData ) { AppendString(pszData, strlen(pszData)); } //! バッファの最後にデータを追加する。nLengthは文字単位。 void CNativeA::AppendString( const char* pszData, size_t nLength ) { AppendRawData( pszData, nLength ); } //! バッファの最後にデータを追加する (フォーマット機能付き) void CNativeA::AppendStringF(const char* pszData, ...) { char buf[2048]; // 整形 va_list v; va_start(v, pszData); int len = _vsnprintf_s(buf, _countof(buf), _TRUNCATE, pszData, v); int e = errno; va_end(v); if (len == -1) { DEBUG_TRACE(L"AppendStringF error. errno = %d", e); throw std::exception(); } // 追加 AppendString( buf, len ); } const CNativeA& CNativeA::operator = ( char cChar ) { char pszChar[2]; pszChar[0] = cChar; pszChar[1] = '\0'; SetRawData( pszChar, 1 ); return *this; } //! バッファの最後にデータを追加する void CNativeA::AppendNativeData( const CNativeA& cNative ) { AppendRawData( cNative.GetRawPtr(), cNative.GetRawLength() ); } //! (重要:nDataLenは文字単位) バッファサイズの調整。必要に応じて拡大する。 void CNativeA::AllocStringBuffer( size_t nDataLen ) { AllocBuffer( nDataLen ); } const CNativeA& CNativeA::operator += ( char ch ) { char szChar[2]={ch,'\0'}; AppendString(szChar); return *this; } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- // // ネイティブ取得インターフェース // // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- // int CNativeA::GetStringLength() const { return GetRawLength(); } // 任意位置の文字取得。nIndexは文字単位。 char CNativeA::operator[]( size_t nIndex ) const { if( nIndex < static_cast<size_t>(GetStringLength()) ){ return GetStringPtr()[nIndex]; }else{ return 0; } }
1,540
595
<filename>lib/sw_apps/zynqmp_pmufw/src/xpfw_mod_extwdt.c /****************************************************************************** * Copyright (c) 2021 Xilinx, Inc. All rights reserved. * SPDX-License-Identifier: MIT ******************************************************************************/ #include "xpfw_mod_extwdt.h" #include "xpfw_config.h" #ifdef ENABLE_MOD_EXTWDT #include "xpfw_default.h" #include "xpfw_core.h" #include "xpfw_module.h" #ifndef EXTWDT_INTERVAL_MS #define EXTWDT_INTERVAL_MS 1140U #endif #ifndef EXTWDT_MIO_PIN #define EXTWDT_MIO_PIN 3U #endif #define EXTWDT_MIO_MASK ((u32)1U<<EXTWDT_MIO_PIN) #ifndef ENABLE_SCHEDULER #error "ERROR: External WDT feature requires scheduler to be enabled! Define ENABLE_SCHEDULER" #endif /* Toggle PMU GPO1 bit specified for EXTWDT */ static void ExtWdtToggle(void) { u32 MioVal; /* Read o/p value from GPO1_READ register */ MioVal = XPfw_Read32(PMU_LOCAL_GPO1_READ); /* Toggle GPO1 bit and write back the new o/p value */ XPfw_Write32(PMU_IOMODULE_GPO1, (MioVal^(EXTWDT_MIO_MASK))); } static void ExtWdtCfgInit(const XPfw_Module_t *ModPtr, const u32 *CfgData, u32 Len) { s32 Status; /* Register scheduler task for External WDT service*/ Status = XPfw_CoreScheduleTask(ModPtr, EXTWDT_INTERVAL_MS/2U, ExtWdtToggle); if (XST_SUCCESS != Status) { XPfw_Printf(DEBUG_DETAILED,"EXTWDT: Failed to Init EXT WDT Task\r\n"); } } void ModExtWdtInit(void) { const XPfw_Module_t *ExtWdtModPtr; ExtWdtModPtr = XPfw_CoreCreateMod(); if (XST_SUCCESS != XPfw_CoreSetCfgHandler(ExtWdtModPtr, ExtWdtCfgInit)){ XPfw_Printf(DEBUG_DETAILED,"EXTWDT: Set Cfg handler failed\r\n"); } } #else /* ENABLE_MOD_EXTWDT */ void ModExtWdtInit(void) { } #endif /* ENABLE_MOD_EXTWDT */
723
1,194
<reponame>MFAshby/hapi-fhir<filename>hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/search/builder/SearchQueryExecutorsTest.java package ca.uhn.fhir.jpa.search.builder; import com.google.common.collect.Streams; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import java.util.Spliterators; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.junit.jupiter.api.Assertions.*; class SearchQueryExecutorsTest { @Test public void adaptFromLongArrayYieldsAllValues() { List<Long> listWithValues = Arrays.asList(1L,2L,3L,4L,5L); ISearchQueryExecutor queryExecutor = SearchQueryExecutors.from(listWithValues); assertThat(drain(queryExecutor), contains(1L,2L,3L,4L,5L)); } @Test public void limitedCountDropsTrailingTest() { // given List<Long> vals = Arrays.asList(1L,2L,3L,4L,5L); ISearchQueryExecutor target = SearchQueryExecutors.from(vals); ISearchQueryExecutor queryExecutor = SearchQueryExecutors.limited(target, 3); assertThat(drain(queryExecutor), contains(1L,2L,3L)); } @Test public void limitedCountExhaustsBeforeLimitOkTest() { // given List<Long> vals = Arrays.asList(1L,2L,3L); ISearchQueryExecutor target = SearchQueryExecutors.from(vals); ISearchQueryExecutor queryExecutor = SearchQueryExecutors.limited(target, 5); assertThat(drain(queryExecutor), contains(1L,2L,3L)); } private List<Long> drain(ISearchQueryExecutor theQueryExecutor) { return StreamSupport.stream(Spliterators.spliteratorUnknownSize(theQueryExecutor, 0), false) .collect(Collectors.toList()); } }
650
764
{ "symbol":"TC", "address":"0x2f7315dc40A7f1201b903d65dBD0eEC93cD14f37", "overview":{ "en":"TasteChain is a public chain that focuses on natural ecology,quality of life and future technology.It is committed to creating a distributed and credible top-level ecosystem.Through the public chain aggregation cluster,the application scenarios of the entity enterprise are firstly applied,and various sub-chains and cross-chain projects based on the public chain are gradually issued to enrich the enterprise with the certification,thereby creating a global cross-industry public chain.", "zh":"品链TasteChain独创是专注于自然生态,品质生活和未来科技的公链,致力打造分布式可信上品生态圈。通过公有链聚合集群,先以实体企业落地应用场景,逐步发行基于公有链的各类子链及跨链项目,为企业通证化赋能,从而打造全球跨行业公链全生态。" }, "email":"<EMAIL>", "website":"http://www.taste.link/", "whitepaper":"http://www.taste.link/wp5.pdf", "state":"NORMAL", "published_on":"2019-07-05", "links":{ "blog":"https://m.weibo.cn/u/7155845627", "twitter":"https://twitter.com/Taste_Chain" } }
527
3,442
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "MsOutlookMAPIHResultException.h" void MsOutlookMAPIHResultException_throwNew (JNIEnv *jniEnv, HRESULT hResult, LPCSTR file, ULONG line) { jclass clazz; clazz = jniEnv->FindClass( "net/java/sip/communicator/plugin/addrbook/msoutlook/MsOutlookMAPIHResultException"); if (clazz) { LPCSTR message; switch (hResult) { case MAPI_E_LOGON_FAILED: message = "MAPI_E_LOGON_FAILED"; break; case MAPI_E_NO_ACCESS: message = "MAPI_E_NO_ACCESS"; break; case MAPI_E_NO_SUPPORT: message = "MAPI_E_NO_SUPPORT"; break; case MAPI_E_NOT_ENOUGH_MEMORY: message = "MAPI_E_NOT_ENOUGH_MEMORY"; break; case MAPI_E_NOT_FOUND: message = "MAPI_E_NOT_FOUND"; break; case MAPI_E_NOT_INITIALIZED: message = "MAPI_E_NOT_INITIALIZED"; break; case MAPI_E_TIMEOUT: message = "MAPI_E_TIMEOUT"; break; case MAPI_E_UNKNOWN_ENTRYID: message = "MAPI_E_UNKNOWN_ENTRYID"; break; case MAPI_E_USER_CANCEL: message = "MAPI_E_USER_CANCEL"; break; case MAPI_W_ERRORS_RETURNED: message = "MAPI_W_ERRORS_RETURNED"; break; case S_OK: message = "S_OK"; break; default: message = NULL; break; } if (message) { jmethodID methodID = jniEnv->GetMethodID( clazz, "<init>", "(JLjava/lang/String;)V"); if (methodID) { jstring jmessage = jniEnv->NewStringUTF(message); if (jmessage) { jobject t = jniEnv->NewObject( clazz, methodID, (jlong) hResult, jmessage); if (t) { jniEnv->Throw((jthrowable) t); jniEnv->DeleteLocalRef(t); } jniEnv->DeleteLocalRef(jmessage); } return; } } { jmethodID methodID = jniEnv->GetMethodID(clazz, "<init>", "(J)V"); if (methodID) { jobject t = jniEnv->NewObject(clazz, methodID, hResult); if (t) { jniEnv->Throw((jthrowable) t); jniEnv->DeleteLocalRef(t); } return; } } jniEnv->ThrowNew(clazz, message); jniEnv->DeleteLocalRef(clazz); } }
2,159
1,666
<reponame>Dexus/node-compiler<gh_stars>1000+ #define NODE_EXPERIMENTAL_HTTP 1 #include "node_http_parser_impl.h" #include "memory_tracker-inl.h" #include "node_metadata.h" #include "util-inl.h" namespace node { namespace per_process { const char* const llhttp_version = NODE_STRINGIFY(LLHTTP_VERSION_MAJOR) "." NODE_STRINGIFY(LLHTTP_VERSION_MINOR) "." NODE_STRINGIFY(LLHTTP_VERSION_PATCH); } // namespace per_process } // namespace node NODE_MODULE_CONTEXT_AWARE_INTERNAL(http_parser_llhttp, node::InitializeHttpParser)
262
552
#include "stdafx.h" #include "Archetype.h" #include "ComponentView.h" #include "EcsController.h" namespace et { namespace fw { //==================== // Component Accessor //==================== //------------------------- // ComponentView::Accessor // // Iteratable view of a selection of components // ComponentView::Accessor::Accessor(void** pointerRef, T_CompTypeIdx const type, bool const readAccess) : currentElement(reinterpret_cast<uint8*&>(*pointerRef)) , typeIdx(type) , read(readAccess) { } //================ // Component View //================ //---------------------- // ComponentView::Init // // initialize references to all pointers // void ComponentView::Init(BaseComponentRange* const range) { m_Range = range; // set the pointers to the position within the pool that the range starts from for (Accessor& access : m_Accessors) { access.currentElement = static_cast<uint8*>(m_Range->m_Archetype->GetPool(access.typeIdx).At(m_Range->m_Offset)); } // set the ecs controllers for accessors outside the current entity for (EcsController const** controllerPtr : m_ControllerPtrs) { *controllerPtr = m_Range->m_Controller; } CalcParentPointers(); } //---------------------- // ComponentView::IsEnd // // Whether we are upon the last entity in the range // bool ComponentView::IsEnd() const { return (m_Current >= m_Range->m_Count); } //---------------------------- // ComponentView::GetTypeList // // List of component types we access // T_CompTypeList ComponentView::GetTypeList() const { T_CompTypeList ret; ret.reserve(m_Accessors.size() + m_Includes.size()); for (Accessor const& access : m_Accessors) { ret.emplace_back(access.typeIdx); } ret.insert(ret.end(), m_Includes.begin(), m_Includes.end()); return ret; } //--------------------- // ComponentView::Next // // Increment component pointers // T_EntityId ComponentView::GetCurrentEntity() const { return m_Range->m_Archetype->GetEntity(m_Current); } //--------------------- // ComponentView::Next // // Increment component pointers // bool ComponentView::Next() { m_Current++; if (m_Current >= m_Range->m_Count) { return true; } // components in our entity for (Accessor& access : m_Accessors) { access.currentElement += ComponentRegistry::Instance().GetSize(access.typeIdx); } CalcParentPointers(); return false; } //----------------------------------- // ComponentView::CalcParentPointers // // Set pointers to the parent entities components based on the current entity // void ComponentView::CalcParentPointers() { if (!m_ParentAccessors.empty()) { T_EntityId const current = m_Range->m_Archetype->GetEntity(m_Current + m_Range->m_Offset); T_EntityId const parent = m_Range->m_Controller->GetParent(current); if (parent != INVALID_ENTITY_ID) { for (Accessor& access : m_ParentAccessors) { if (m_Range->m_Controller->HasComponent(parent, access.typeIdx)) { access.currentElement = static_cast<uint8*>(m_Range->m_Controller->GetComponentData(parent, access.typeIdx)); } else { access.currentElement = nullptr; } } } else { for (Accessor& access : m_ParentAccessors) { access.currentElement = nullptr; } } } } } // namespace fw } // namespace et
1,094
312
# Copyright (c) 2019 <NAME> # Licensed under MIT License import json import logging import re from colorama import init as colorama_init from colorama import Fore, Back, Style class Log: """Class responsible for logging information.""" # Define header styles HEADER_W = [Fore.BLACK, Back.WHITE, Style.BRIGHT] HEADER_R = [Fore.WHITE, Back.RED, Style.BRIGHT] HEADER_G = [Fore.WHITE, Back.GREEN, Style.BRIGHT] @classmethod def enable(cls, storage): """Initializes the logger. Args: storage: Storage object. """ # Init colorama to enable colors colorama_init() # Get deepswarm logger cls.logger = logging.getLogger("deepswarm") # Create stream handler stream_handler = logging.StreamHandler() stream_formater = logging.Formatter("%(message)s") stream_handler.setFormatter(stream_formater) # Add stream handler to logger cls.logger.addHandler(stream_handler) # Create and setup file handler file_handler = logging.FileHandler(storage.current_path / "deepswarm.log") file_formater = FileFormatter("%(asctime)s\n%(message)s") file_handler.setFormatter(file_formater) # Add file handle to logger cls.logger.addHandler(file_handler) # Set logger level to debug cls.logger.setLevel(logging.DEBUG) @classmethod def header(cls, message, type="WHITE"): if type == "RED": options = cls.HEADER_R elif type == "GREEN": options = cls.HEADER_G else: options = cls.HEADER_W cls.info(message.center(80, '-'), options) @classmethod def debug(cls, message, options=[Fore.CYAN]): formated_message = cls.create_message(message, options) cls.logger.debug(formated_message) @classmethod def info(cls, message, options=[Fore.GREEN]): formated_message = cls.create_message(message, options) cls.logger.info(formated_message) @classmethod def warning(cls, message, options=[Fore.YELLOW]): formated_message = cls.create_message(message, options) cls.logger.warning(formated_message) @classmethod def error(cls, message, options=[Fore.MAGENTA]): formated_message = cls.create_message(message, options) cls.logger.error(formated_message) @classmethod def critical(cls, message, options=[Fore.RED, Style.BRIGHT]): formated_message = cls.create_message(message, options) cls.logger.critical(formated_message) @classmethod def create_message(cls, message, options): # Convert dictionary to nicely formatted JSON if isinstance(message, dict): message = json.dumps(message, indent=4, sort_keys=True) # Convert all objects that are not strings to strings if isinstance(message, str) is False: message = str(message) return ''.join(options) + message + '\033[0m' class FileFormatter(logging.Formatter): """Class responsible for removing ANSI characters from the log file.""" def plain(self, string): # Regex code adapted from <NAME> https://stackoverflow.com/a/14693789 ansi_escape = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]|[-]{2,}') return ansi_escape.sub('', string) def format(self, record): message = super(FileFormatter, self).format(record) plain_message = self.plain(message) separator = '=' * 80 return ''.join((separator, "\n", plain_message, "\n", separator))
1,478
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.core.annotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Replaces the header with the value of its target. The value specified here replaces headers specified statically in * the {@link Headers}. If the parameter this annotation is attached to is a Map type, then this will be treated as a * header collection. In that case each of the entries in the argument's map will be individual header values that use * the value of this annotation as a prefix to their key/header name. * * <p><strong>Example 1:</strong></p> * * <!-- src_embed com.azure.core.annotation.HeaderParam.class1 --> * <pre> * &#64;Put&#40;&quot;&#123;functionId&#125;&quot;&#41; * Mono&lt;ResponseBase&lt;ResponseHeaders, ResponseBody&gt;&gt; createOrReplace&#40; * &#64;PathParam&#40;value = &quot;functionId&quot;, encoded = true&#41; String functionId, * &#64;BodyParam&#40;&quot;application&#47;json&quot;&#41; RequestBody function, * &#64;HeaderParam&#40;&quot;If-Match&quot;&#41; String ifMatch&#41;; * * &#47;&#47; &quot;If-Match: user passed value&quot; will show up as one of the headers. * </pre> * <!-- end com.azure.core.annotation.HeaderParam.class1 --> * * <p><strong>Example 2:</strong></p> * * <!-- src_embed com.azure.core.annotation.HeaderParam.class2 --> * <pre> * &#64;Get&#40;&quot;subscriptions&#47;&#123;subscriptionId&#125;&#47;providers&#47;Microsoft.ServiceBus&#47;namespaces&quot;&#41; * Mono&lt;ResponseBase&lt;ResponseHeaders, ResponseBody&gt;&gt; list&#40;&#64;PathParam&#40;&quot;subscriptionId&quot;&#41; String subscriptionId, * &#64;HeaderParam&#40;&quot;accept-language&quot;&#41; String acceptLanguage, * &#64;HeaderParam&#40;&quot;User-Agent&quot;&#41; String userAgent&#41;; * * &#47;&#47; &quot;accept-language&quot; generated by the HTTP client will be overwritten by the user passed value. * </pre> * <!-- end com.azure.core.annotation.HeaderParam.class2 --> * * <p><strong>Example 3:</strong></p> * * <!-- src_embed com.azure.core.annotation.HeaderParam.class3 --> * <pre> * &#64;Get&#40;&quot;subscriptions&#47;&#123;subscriptionId&#125;&#47;providers&#47;Microsoft.ServiceBus&#47;namespaces&quot;&#41; * Mono&lt;ResponseBase&lt;ResponseHeaders, ResponseBody&gt;&gt; list&#40;&#64;PathParam&#40;&quot;subscriptionId&quot;&#41; String subscriptionId, * &#64;HeaderParam&#40;&quot;Authorization&quot;&#41; String token&#41;; * * &#47;&#47; The token parameter will replace the effect of any credentials in the HttpPipeline. * </pre> * <!-- end com.azure.core.annotation.HeaderParam.class3 --> * * <p><strong>Example 4:</strong></p> * * <!-- src_embed com.azure.core.annotation.HeaderParam.class4 --> * <pre> * &#64;Put&#40;&quot;&#123;containerName&#125;&#47;&#123;blob&#125;&quot;&#41; * &#64;ExpectedResponses&#40;&#123;200&#125;&#41; * Mono&lt;ResponseBase&lt;ResponseHeaders, Void&gt;&gt; setMetadata&#40;&#64;PathParam&#40;&quot;containerName&quot;&#41; String containerName, * &#64;PathParam&#40;&quot;blob&quot;&#41; String blob, * &#64;HeaderParam&#40;&quot;x-ms-meta-&quot;&#41; Map&lt;String, String&gt; metadata&#41;; * * &#47;&#47; The metadata parameter will be expanded out so that each entry becomes * &#47;&#47; &quot;x-ms-meta-&#123;&#64;literal &lt;entryKey&gt;&#125;: &#123;&#64;literal &lt;entryValue&gt;&#125;&quot;. * </pre> * <!-- end com.azure.core.annotation.HeaderParam.class4 --> */ @Retention(RUNTIME) @Target(PARAMETER) public @interface HeaderParam { /** * The name of the variable in the endpoint uri template which will be replaced with the value of the parameter * annotated with this annotation. * * @return The name of the variable in the endpoint uri template which will be replaced with the value of the * parameter annotated with this annotation. */ String value(); }
1,544
3,494
#pragma once #include "cinder/CinderResources.h" #define RES_FONT CINDER_RESOURCE( ../resources/, YanoneKaffeesatz-Regular.ttf, 128, TTF_FONT ) #define RES_BACKGROUND_IMAGE CINDER_RESOURCE( ../resources/, background.png, 128, IMAGE ) #define RES_CIRCLE_IMAGE CINDER_RESOURCE( ../resources/, circle.png, 129, IMAGE ) #define RES_SMALL_CIRCLE_IMAGE CINDER_RESOURCE( ../resources/, smallCircle.png, 130, IMAGE ) #define RES_DICTIONARY CINDER_RESOURCE( ../resources/, EnglishDictionary.gz, 128, TGZ )
197
335
<reponame>Safal08/Hacktoberfest-1<gh_stars>100-1000 { "word": "Like", "definitions": [ "(of a person or thing) having similar qualities or characteristics to another person or thing.", "(of a portrait or other image) having a faithful resemblance to the original." ], "parts-of-speech": "Adjective" }
118
6,036
#pragma once #include "core/framework/op_kernel.h" #include "core/framework/func_api.h" #include "core/framework/op_kernel_context_internal.h" #include "core/graph/function.h" namespace onnxruntime { void* allocate_helper_func(void* allocator, size_t alignment, size_t size); void release_helper_func(void* allocator, void* p); //A kernel that wrapper the ComputeFunction call generated by execution provider when fuse the sub-graph class FunctionKernel : public OpKernel { public: //The original design is we load the dll, find the entry point and wrapper it. //Here for quick prototype, we keep the entry pointer in the node. explicit FunctionKernel(const OpKernelInfo& info) : OpKernel(info) { num_inputs_ = info.node().InputDefs().size(); num_outputs_ = info.node().OutputDefs().size(); auto status = info.GetFusedFuncs(compute_info_); ORT_ENFORCE(status.IsOK(), status.ErrorMessage()); if (compute_info_->create_state_func) { //TODO: we are only provide host allocate method in compute context. //Do we need to hold the ref-counting here? host_allocator_ = info.GetAllocator(0, OrtMemType::OrtMemTypeDefault); ComputeContext context = {allocate_helper_func, release_helper_func, host_allocator_.get(), info.node().Name().c_str()}; ORT_ENFORCE(compute_info_->create_state_func(&context, &func_state_) == 0); } } ~FunctionKernel() override { if (compute_info_->release_state_func && func_state_) { compute_info_->release_state_func(func_state_); } } virtual Status Compute(OpKernelContext* context) const override { auto* context_internal = static_cast<OpKernelContextInternal*>(context); return compute_info_->compute_func(func_state_, OrtGetApiBase()->GetApi(ORT_API_VERSION), reinterpret_cast<OrtKernelContext*>(context_internal)); } private: NodeComputeInfo* compute_info_{nullptr}; FunctionState func_state_{nullptr}; size_t num_inputs_; size_t num_outputs_; AllocatorPtr host_allocator_; }; } // namespace onnxruntime
780
11,356
<filename>test/project_dependencies.py #!/usr/bin/python # Copyright 2003 <NAME> # Copyright 2002, 2003, 2004 <NAME> # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) # Test that we can specify a dependency property in project requirements, and # that it will not cause every main target in the project to be generated in its # own subdirectory. # The whole test is somewhat moot now. import BoostBuild t = BoostBuild.Tester(use_test_config=False) t.write("jamroot.jam", "build-project src ;") t.write("lib/jamfile.jam", "lib lib1 : lib1.cpp ;") t.write("lib/lib1.cpp", """ #ifdef _WIN32 __declspec(dllexport) #endif void foo() {}\n """) t.write("src/jamfile.jam", """ project : requirements <library>../lib//lib1 ; exe a : a.cpp ; exe b : b.cpp ; """) t.write("src/a.cpp", """ #ifdef _WIN32 __declspec(dllimport) #endif void foo(); int main() { foo(); } """) t.copy("src/a.cpp", "src/b.cpp") t.run_build_system() # Test that there is no "main-target-a" part. # t.expect_addition("src/bin/$toolset/debug*/a.exe") # t.expect_addition("src/bin/$toolset/debug*/b.exe") t.cleanup()
437
2,061
class ClickWebException(Exception): pass class CommandNotFound(ClickWebException): pass
36
534
<filename>src/main/resources/assets/mekanism/models/block/purification_chamber.json<gh_stars>100-1000 { "parent": "mekanism:block/machine", "textures": { "sides": "mekanism:block/purification_chamber/right", "front": "mekanism:block/purification_chamber/front", "west": "mekanism:block/purification_chamber/right", "east": "mekanism:block/purification_chamber/left", "south": "mekanism:block/purification_chamber/back", "up": "mekanism:block/purification_chamber/top", "down": "mekanism:block/purification_chamber/bottom" } }
217
365
// Copyright 2013 Blender Foundation. All rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #ifndef OPENSUBDIV_BASE_TYPE_H_ #define OPENSUBDIV_BASE_TYPE_H_ #include <stdint.h> #include <algorithm> #include <cassert> #include <map> #include <stack> #include <string> #include <unordered_map> #include <utility> #include <vector> namespace blender { namespace opensubdiv { using std::map; using std::pair; using std::stack; using std::string; using std::unordered_map; using std::vector; using std::fill; using std::make_pair; using std::max; using std::min; using std::move; using std::swap; } // namespace opensubdiv } // namespace blender #endif // OPENSUBDIV_BASE_TYPE_H_
414
682
<filename>vpr/src/base/atom_netlist.h #ifndef ATOM_NETLIST_H #define ATOM_NETLIST_H /** * @file * @brief This file defines the AtomNetlist class used to store and manipulate * the primitive (or atom) netlist. * * Overview * ======== * The AtomNetlist is derived from the Netlist class, and contains information on the primitives. * This includes basic components (Blocks, Ports, Pins, & Nets), and physical descriptions (t_model) * of the primitives. * * Most of the functionality relevant to components and their accessors/cross-accessors * is implemented in the Netlist class. Refer to netlist.(h|tpp) for more information. * * * Components * ========== * There are 4 components in the Netlist: Blocks, Ports, Pins, and Nets. * Each component has a unique ID in the netlist, as well as various associations to their * related components (e.g. A pin knows which port it belongs to, and what net it connects to) * * Blocks * ------ * Blocks refer to the atoms (AKA primitives) that are in the the netlist. Each block contains * input/output/clock ports. Blocks have names, and various functionalities (LUTs, FFs, RAMs, ...) * Each block has an associated t_model, describing the physical properties. * * Ports * ----- * Ports are composed of a set of pins that have specific directionality (INPUT, OUTPUT, or CLOCK). * The ports in the AtomNetlist are respective to the atoms. (i.e. the AtomNetlist does not contain * ports of a Clustered Logic Block). Each port has an associated t_model_port, describing the * physical properties. * * Pins * ---- * Pins are single-wire input/outputs. They are part of a port, and are connected to a single net. * * Nets * ---- * Nets in the AtomNetlist track the wiring connections between the atoms. * * Models * ------ * There are two main models, the primitive itself (t_model) and the ports of that primitive (t_model_ports). * The models are created from the architecture file, and describe the physical properties of the atom. * * Truth Table * ----------- * The AtomNetlist also contains a TruthTable for each block, which indicates what the LUTs contain. * * * Implementation * ============== * For all create_* functions, the AtomNetlist will wrap and call the Netlist's version as it contains * additional information that the base Netlist does not know about. * * All functions with suffix *_impl() follow the Non-Virtual Interface (NVI) idiom. * They are called from the base Netlist class to simplify pre/post condition checks and * prevent Fragile Base Class (FBC) problems. * * Refer to netlist.h for more information. * */ #include <vector> #include <unordered_map> #include "vtr_range.h" #include "vtr_logic.h" #include "vtr_vector_map.h" #include "logic_types.h" //For t_model #include "netlist.h" #include "atom_netlist_fwd.h" class AtomNetlist : public Netlist<AtomBlockId, AtomPortId, AtomPinId, AtomNetId> { public: /** * @brief Constructs a netlist * * @param name the name of the netlist (e.g. top-level module) * @param id a unique identifier for the netlist (e.g. a secure digest of the input file) */ AtomNetlist(std::string name = "", std::string id = ""); AtomNetlist(const AtomNetlist& rhs) = default; AtomNetlist& operator=(const AtomNetlist& rhs) = default; public: //Public types typedef std::vector<std::vector<vtr::LogicValue>> TruthTable; public: //Public Accessors /* * Blocks */ void set_block_types(const t_model* inpad, const t_model* outpad); ///@brief Returns the type of the specified block AtomBlockType block_type(const AtomBlockId id) const; ///@brief Returns the model associated with the block const t_model* block_model(const AtomBlockId id) const; /** * @brief Returns the truth table associated with the block * * @note This is only non-empty for LUTs and Flip-Flops/latches. * * For LUTs the truth table stores the single-output cover representing the * logic function. * * For FF/Latches there is only a single entry representing the initial state */ const TruthTable& block_truth_table(const AtomBlockId id) const; /* * Ports */ /** * @brief Returns the model port of the specified port or nullptr if not * * @param id The ID of the port to look for */ const t_model_ports* port_model(const AtomPortId id) const; /* * Lookups */ /** * @brief Returns the AtomPortId of the specifed port if it exists or AtomPortId::INVALID() if not * @note This method is typically more efficient than searching by name * * @param blk_id The ID of the block who's ports will be checked * @param model_port The port model to look for */ AtomPortId find_atom_port(const AtomBlockId blk_id, const t_model_ports* model_port) const; /** * @brief Returns the AtomBlockId of the atom driving the specified pin if it exists or AtomBlockId::INVALID() if not * * @param blk_id The ID of the block whose ports will be checked * @param model_port The port model to look for * @param port_bit The pin number in this port */ AtomBlockId find_atom_pin_driver(const AtomBlockId blk_id, const t_model_ports* model_port, const BitIndex port_bit) const; /** * @brief Returns the a set of aliases relative to the net name. * * If no aliases are found, returns a set with the original net name. * * @param net_name name of the net from which the aliases are extracted */ std::unordered_set<std::string> net_aliases(const std::string net_name) const; public: //Public Mutators /* * Note: all create_*() functions will silently return the appropriate ID if it has already been created */ /** * @brief Create or return an existing block in the netlist * * @param name The unique name of the block * @param model The primitive type of the block * @param truth_table The single-output cover defining the block's logic function * The truth_table is optional and only relevant for LUTs (where it describes the logic function) * and Flip-Flops/latches (where it consists of a single entry defining the initial state). */ AtomBlockId create_block(const std::string name, const t_model* model, const TruthTable truth_table = TruthTable()); /** * @brief Create or return an existing port in the netlist * * @param blk_id The block the port is associated with * @param model_port The model port the port is associated with */ AtomPortId create_port(const AtomBlockId blk_id, const t_model_ports* model_port); /** * @brief Create or return an existing pin in the netlist * * @param port_id The port this pin is associated with * @param port_bit The bit index of the pin in the port * @param net_id The net the pin drives/sinks * @param pin_type The type of the pin (driver/sink) * @param is_const Indicates whether the pin holds a constant value (e. g. vcc/gnd) */ AtomPinId create_pin(const AtomPortId port_id, BitIndex port_bit, const AtomNetId net_id, const PinType pin_type, bool is_const = false); /** * @brief Create an empty, or return an existing net in the netlist * * @param name The unique name of the net */ AtomNetId create_net(const std::string name); //An empty or existing net /** * @brief Create a completely specified net from specified driver and sinks * * @param name The name of the net (Note: must not already exist) * @param driver The net's driver pin * @param sinks The net's sink pins */ AtomNetId add_net(const std::string name, AtomPinId driver, std::vector<AtomPinId> sinks); /** * @brief Adds a value to the net aliases set for a given net name in the net_aliases_map. * * If there is no key/value pair in the net_aliases_map, creates a new set and adds it to the map. * * @param net_name The net to be added to the map * @param alias_net_name The alias of the assigned clock net id */ void add_net_alias(const std::string net_name, std::string alias_net_name); private: //Private members /* * Component removal */ void remove_block_impl(const AtomBlockId blk_id) override; void remove_port_impl(const AtomPortId port_id) override; void remove_pin_impl(const AtomPinId pin_id) override; void remove_net_impl(const AtomNetId net_id) override; /* * Netlist compression/optimization */ //Removes invalid components and reorders them void clean_blocks_impl(const vtr::vector_map<AtomBlockId, AtomBlockId>& block_id_map) override; void clean_ports_impl(const vtr::vector_map<AtomPortId, AtomPortId>& port_id_map) override; void clean_pins_impl(const vtr::vector_map<AtomPinId, AtomPinId>& pin_id_map) override; void clean_nets_impl(const vtr::vector_map<AtomNetId, AtomNetId>& net_id_map) override; void rebuild_block_refs_impl(const vtr::vector_map<AtomPinId, AtomPinId>& pin_id_map, const vtr::vector_map<AtomPortId, AtomPortId>& port_id_map) override; void rebuild_port_refs_impl(const vtr::vector_map<AtomBlockId, AtomBlockId>& block_id_map, const vtr::vector_map<AtomPinId, AtomPinId>& pin_id_map) override; void rebuild_pin_refs_impl(const vtr::vector_map<AtomPortId, AtomPortId>& port_id_map, const vtr::vector_map<AtomNetId, AtomNetId>& net_id_map) override; void rebuild_net_refs_impl(const vtr::vector_map<AtomPinId, AtomPinId>& pin_id_map) override; ///@brief Shrinks internal data structures to required size to reduce memory consumption void shrink_to_fit_impl() override; /* * Sanity checks */ //Verify the internal data structure sizes match bool validate_block_sizes_impl(size_t num_blocks) const override; bool validate_port_sizes_impl(size_t num_ports) const override; bool validate_pin_sizes_impl(size_t num_pins) const override; bool validate_net_sizes_impl(size_t num_nets) const override; private: //Private data //Block data vtr::vector_map<AtomBlockId, const t_model*> block_models_; //Architecture model of each block vtr::vector_map<AtomBlockId, TruthTable> block_truth_tables_; //Truth tables of each block // Input IOs and output IOs always exist and have their own architecture // models. While their models are already included in block_models_, we // also store direct pointers to them to make checks of whether a block is // an INPAD or OUTPAD fast, as such checks are common in some netlist // operations (e.g. clean-up of an input netlist). const t_model* inpad_model_; const t_model* outpad_model_; //Port data vtr::vector_map<AtomPortId, const t_model_ports*> port_models_; //Architecture port models of each port //Net aliases std::unordered_map<std::string, std::unordered_set<std::string>> net_aliases_map_; }; #include "atom_lookup.h" #endif
3,875
2,915
/*!The Treasure Box Library * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (C) 2009-present, TBOOX Open Source Group. * * @author ruki * @file crc8.c * @ingroup hash * */ /* ////////////////////////////////////////////////////////////////////////////////////// * includes */ #include "crc8.h" /* ////////////////////////////////////////////////////////////////////////////////////// * globals */ // the crc8(ANSI) table tb_uint8_t const g_crc8_table[] = { 0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31 , 0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65 , 0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d, 0xe0, 0xe7, 0xee, 0xe9 , 0xfc, 0xfb, 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd , 0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, 0xaf, 0xa6, 0xa1 , 0xb4, 0xb3, 0xba, 0xbd, 0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2 , 0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea, 0xb7, 0xb0, 0xb9, 0xbe , 0xab, 0xac, 0xa5, 0xa2, 0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a , 0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32, 0x1f, 0x18, 0x11, 0x16 , 0x03, 0x04, 0x0d, 0x0a, 0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42 , 0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a, 0x89, 0x8e, 0x87, 0x80 , 0x95, 0x92, 0x9b, 0x9c, 0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4 , 0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec, 0xc1, 0xc6, 0xcf, 0xc8 , 0xdd, 0xda, 0xd3, 0xd4, 0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c , 0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44, 0x19, 0x1e, 0x17, 0x10 , 0x05, 0x02, 0x0b, 0x0c, 0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34 , 0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b, 0x76, 0x71, 0x78, 0x7f , 0x6a, 0x6d, 0x64, 0x63, 0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b , 0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13, 0xae, 0xa9, 0xa0, 0xa7 , 0xb2, 0xb5, 0xbc, 0xbb, 0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8d, 0x84, 0x83 , 0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb, 0xe6, 0xe1, 0xe8, 0xef , 0xfa, 0xfd, 0xf4, 0xf3 }; /* ////////////////////////////////////////////////////////////////////////////////////// * implementation */ tb_uint8_t tb_crc8_make(tb_byte_t const* data, tb_size_t size, tb_uint8_t seed) { // check tb_assert_and_check_return_val(data, 0); // init value tb_uint32_t crc = seed; // done tb_byte_t const* ie = data + size; tb_uint8_t const* pt = (tb_uint8_t const*)g_crc8_table; while (data < ie) crc = pt[((tb_uint8_t)crc) ^ *data++] ^ (crc >> 8); // ok? return (tb_uint8_t)crc; } tb_uint8_t tb_crc8_make_from_cstr(tb_char_t const* cstr, tb_uint8_t seed) { // check tb_assert_and_check_return_val(cstr, 0); // make it return tb_crc8_make((tb_byte_t const*)cstr, tb_strlen(cstr) + 1, seed); }
1,767
13,709
#import "RNNOptions.h" @interface RNNSearchBarOptions : RNNOptions @property(nonatomic, strong) Bool *visible; @property(nonatomic, strong) Bool *focus; @property(nonatomic, strong) Bool *hideOnScroll; @property(nonatomic, strong) Bool *hideTopBarOnFocus; @property(nonatomic, strong) Bool *obscuresBackgroundDuringPresentation; @property(nonatomic, strong) Color *backgroundColor; @property(nonatomic, strong) Color *tintColor; @property(nonatomic, strong) Text *placeholder; @property(nonatomic, strong) Text *cancelText; @end
168
2,508
<gh_stars>1000+ #ifdef HAVE_CONFIG_H #include "../../ext_config.h" #endif #include <php.h> #include "../../php_ext.h" #include "../../ext.h" #include <Zend/zend_operators.h> #include <Zend/zend_exceptions.h> #include <Zend/zend_interfaces.h> #include "kernel/main.h" ZEPHIR_INIT_CLASS(Stub_TypeHinting_TestAbstract) { ZEPHIR_REGISTER_CLASS(Stub\\TypeHinting, TestAbstract, stub, typehinting_testabstract, stub_typehinting_testabstract_method_entry, ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); return SUCCESS; } PHP_METHOD(Stub_TypeHinting_TestAbstract, testFunc) { } PHP_METHOD(Stub_TypeHinting_TestAbstract, returnOneOfScalar) { } PHP_METHOD(Stub_TypeHinting_TestAbstract, returnInt) { } PHP_METHOD(Stub_TypeHinting_TestAbstract, returnUint) { } PHP_METHOD(Stub_TypeHinting_TestAbstract, returnLong) { } PHP_METHOD(Stub_TypeHinting_TestAbstract, returnFloat) { } PHP_METHOD(Stub_TypeHinting_TestAbstract, returnDouble) { } PHP_METHOD(Stub_TypeHinting_TestAbstract, returnString) { } PHP_METHOD(Stub_TypeHinting_TestAbstract, returnBoolean) { } PHP_METHOD(Stub_TypeHinting_TestAbstract, returnChar) { }
477
755
/** * @project: Overload * @author: <NAME>. * @licence: MIT */ #pragma once namespace OvRendering::Geometry { /** * Data structure that defines the geometry of a vertex */ struct Vertex { float position[3]; float texCoords[2]; float normals[3]; float tangent[3]; float bitangent[3]; }; }
122
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.core.windows; import org.openide.ErrorManager; import org.openide.windows.TopComponent; import org.openide.windows.WindowManager; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; /** * * Test component with persistence type PERSISTENCE_ALWAYS and it is singleton. * * @author <NAME> * */ public class Component00 extends TopComponent { static final long serialVersionUID = 6021472310161712674L; private static Component00 component = null; private static final String TC_ID = "component00"; /** * Used to detect if TC instance was created either using deserialization * or by getDefault. */ private static boolean deserialized = false; private Component00 () { } protected String preferredID () { return TC_ID; } /* Singleton accessor. As Component00 is persistent singleton this * accessor makes sure that Component00 is deserialized by window system. * Uses known unique TopComponent ID "component00" to get Component00 instance * from window system. "component00" is name of settings file defined in module layer. */ public static synchronized Component00 findDefault() { if (component == null) { //If settings file is correctly defined call of WindowManager.findTopComponent() will //call TestComponent00.getDefault() and it will set static field component. TopComponent tc = WindowManager.getDefault().findTopComponent(TC_ID); if (tc != null) { if (!(tc instanceof Component00)) { //This should not happen. Possible only if some other module //defines different settings file with the same name but different class. //Incorrect settings file? IllegalStateException exc = new IllegalStateException ("Incorrect settings file. Unexpected class returned." // NOI18N + " Expected:" + Component00.class.getName() // NOI18N + " Returned:" + tc.getClass().getName()); // NOI18N ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, exc); //Fallback to accessor reserved for window system. Component00.getDefault(); } } else { //This should not happen when settings file is correctly defined in module layer. //TestComponent00 cannot be deserialized //Fallback to accessor reserved for window system. ErrorManager.getDefault().log(ErrorManager.WARNING, "Cannot deserialize TopComponent for tcID:'" + TC_ID + "'"); // NOI18N Component00.getDefault(); } } return component; } /* Singleton accessor reserved for window system ONLY. Used by window system to create * TestComponent00 instance from settings file when method is given. Use <code>findDefault</code> * to get correctly deserialized instance of TestComponent00. */ public static synchronized Component00 getDefault() { if (component == null) { component = new Component00(); } deserialized = true; return component; } /** Overriden to explicitely set persistence type of TestComponent00 * to PERSISTENCE_ALWAYS */ public int getPersistenceType() { return TopComponent.PERSISTENCE_ALWAYS; } /** Resolve to singleton instance */ public Object readResolve() throws java.io.ObjectStreamException { return Component00.getDefault(); } public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); deserialized = true; } static void clearRef () { component = null; } public static boolean wasDeserialized () { return deserialized; } }
1,764
2,151
// Copyright 2018 The Feed Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.feed.sharedstream.piet; import android.content.Context; import android.view.View; import com.google.android.libraries.feed.common.logging.Logger; import com.google.android.libraries.feed.piet.host.CustomElementProvider; import com.google.search.now.ui.piet.ElementsProto.CustomElementData; /** * A Stream implementation of a {@link CustomElementProvider} which handles Stream custom elements * and can delegate to a host custom element adapter if needed. */ public class PietCustomElementProvider implements CustomElementProvider { private static final String TAG = "PietCustomElementPro"; private final Context context; /*@Nullable*/ private final CustomElementProvider hostCustomElementProvider; public PietCustomElementProvider( Context context, /*@Nullable*/ CustomElementProvider hostCustomElementProvider) { this.context = context; this.hostCustomElementProvider = hostCustomElementProvider; } @Override public View createCustomElement(CustomElementData customElementData) { // We don't currently implement any custom elements yet. Delegate to host if there is one. if (hostCustomElementProvider != null) { return hostCustomElementProvider.createCustomElement(customElementData); } // Just return an empty view if there is not host. Logger.w(TAG, "Received request for unknown custom element"); return new View(context); } @Override public void releaseCustomView(View customElementView) { if (hostCustomElementProvider != null) { hostCustomElementProvider.releaseCustomView(customElementView); return; } Logger.w(TAG, "Received release for unknown custom element"); } }
626
1,350
<filename>sdk/frontdoor/azure-resourcemanager-frontdoor/src/main/java/com/azure/resourcemanager/frontdoor/models/RulesEngineMatchCondition.java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.frontdoor.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** Define a match condition. */ @Fluent public final class RulesEngineMatchCondition { @JsonIgnore private final ClientLogger logger = new ClientLogger(RulesEngineMatchCondition.class); /* * Match Variable */ @JsonProperty(value = "rulesEngineMatchVariable", required = true) private RulesEngineMatchVariable rulesEngineMatchVariable; /* * Name of selector in RequestHeader or RequestBody to be matched */ @JsonProperty(value = "selector") private String selector; /* * Describes operator to apply to the match condition. */ @JsonProperty(value = "rulesEngineOperator", required = true) private RulesEngineOperator rulesEngineOperator; /* * Describes if this is negate condition or not */ @JsonProperty(value = "negateCondition") private Boolean negateCondition; /* * Match values to match against. The operator will apply to each value in * here with OR semantics. If any of them match the variable with the given * operator this match condition is considered a match. */ @JsonProperty(value = "rulesEngineMatchValue", required = true) private List<String> rulesEngineMatchValue; /* * List of transforms */ @JsonProperty(value = "transforms") private List<Transform> transforms; /** * Get the rulesEngineMatchVariable property: Match Variable. * * @return the rulesEngineMatchVariable value. */ public RulesEngineMatchVariable rulesEngineMatchVariable() { return this.rulesEngineMatchVariable; } /** * Set the rulesEngineMatchVariable property: Match Variable. * * @param rulesEngineMatchVariable the rulesEngineMatchVariable value to set. * @return the RulesEngineMatchCondition object itself. */ public RulesEngineMatchCondition withRulesEngineMatchVariable(RulesEngineMatchVariable rulesEngineMatchVariable) { this.rulesEngineMatchVariable = rulesEngineMatchVariable; return this; } /** * Get the selector property: Name of selector in RequestHeader or RequestBody to be matched. * * @return the selector value. */ public String selector() { return this.selector; } /** * Set the selector property: Name of selector in RequestHeader or RequestBody to be matched. * * @param selector the selector value to set. * @return the RulesEngineMatchCondition object itself. */ public RulesEngineMatchCondition withSelector(String selector) { this.selector = selector; return this; } /** * Get the rulesEngineOperator property: Describes operator to apply to the match condition. * * @return the rulesEngineOperator value. */ public RulesEngineOperator rulesEngineOperator() { return this.rulesEngineOperator; } /** * Set the rulesEngineOperator property: Describes operator to apply to the match condition. * * @param rulesEngineOperator the rulesEngineOperator value to set. * @return the RulesEngineMatchCondition object itself. */ public RulesEngineMatchCondition withRulesEngineOperator(RulesEngineOperator rulesEngineOperator) { this.rulesEngineOperator = rulesEngineOperator; return this; } /** * Get the negateCondition property: Describes if this is negate condition or not. * * @return the negateCondition value. */ public Boolean negateCondition() { return this.negateCondition; } /** * Set the negateCondition property: Describes if this is negate condition or not. * * @param negateCondition the negateCondition value to set. * @return the RulesEngineMatchCondition object itself. */ public RulesEngineMatchCondition withNegateCondition(Boolean negateCondition) { this.negateCondition = negateCondition; return this; } /** * Get the rulesEngineMatchValue property: Match values to match against. The operator will apply to each value in * here with OR semantics. If any of them match the variable with the given operator this match condition is * considered a match. * * @return the rulesEngineMatchValue value. */ public List<String> rulesEngineMatchValue() { return this.rulesEngineMatchValue; } /** * Set the rulesEngineMatchValue property: Match values to match against. The operator will apply to each value in * here with OR semantics. If any of them match the variable with the given operator this match condition is * considered a match. * * @param rulesEngineMatchValue the rulesEngineMatchValue value to set. * @return the RulesEngineMatchCondition object itself. */ public RulesEngineMatchCondition withRulesEngineMatchValue(List<String> rulesEngineMatchValue) { this.rulesEngineMatchValue = rulesEngineMatchValue; return this; } /** * Get the transforms property: List of transforms. * * @return the transforms value. */ public List<Transform> transforms() { return this.transforms; } /** * Set the transforms property: List of transforms. * * @param transforms the transforms value to set. * @return the RulesEngineMatchCondition object itself. */ public RulesEngineMatchCondition withTransforms(List<Transform> transforms) { this.transforms = transforms; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (rulesEngineMatchVariable() == null) { throw logger .logExceptionAsError( new IllegalArgumentException( "Missing required property rulesEngineMatchVariable in model RulesEngineMatchCondition")); } if (rulesEngineOperator() == null) { throw logger .logExceptionAsError( new IllegalArgumentException( "Missing required property rulesEngineOperator in model RulesEngineMatchCondition")); } if (rulesEngineMatchValue() == null) { throw logger .logExceptionAsError( new IllegalArgumentException( "Missing required property rulesEngineMatchValue in model RulesEngineMatchCondition")); } } }
2,403
1,781
<gh_stars>1000+ package chapter4.section4; /** * Created by <NAME> on 27/11/17. */ public class Topological { private Iterable<Integer> topologicalOrder; public Topological(EdgeWeightedDigraph edgeWeightedDigraph) { EdgeWeightedDirectedCycle cycleFinder = new EdgeWeightedDirectedCycle(edgeWeightedDigraph); if (!cycleFinder.hasCycle()) { DepthFirstOrder depthFirstOrder = new DepthFirstOrder(edgeWeightedDigraph); topologicalOrder = depthFirstOrder.reversePostOrder(); } } public Iterable<Integer> order() { return topologicalOrder; } public boolean isDAG() { return topologicalOrder != null; } }
261
742
<gh_stars>100-1000 package org.support.project.di; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * DIで制御する事を表すアノテーション * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface DI { /** * 実装クラス * @return class of implement */ Class<?> impl() default NoImpl.class; /** * インスタンス * @return instance */ Instance instance() default Instance.Prototype; /** * キーでインスタンスのクラスを振り分ける場合のキー * @return keys */ String[] keys() default {}; /** * キーでインスタンスのクラスを振り分ける場合のクラス(キーと同じ個数の配列にすること) * @return classes of implement */ Class<?>[] impls() default {}; }
401
1,653
<reponame>KayaDevSolutions/deepgaze<filename>examples/ex_motion_detectors_comparison_video/ex_motion_detectors_comparison_video.py #!/usr/bin/env python #The MIT License (MIT) #Copyright (c) 2016 <NAME> # #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF #MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY #CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE #SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #In this example three motion detectors are compared: #frame differencing, MOG, MOG2. #Given a video as input "cars.avi" it returns four #different videos: original, differencing, MOG, MOG2 import numpy as np import cv2 from deepgaze.motion_detection import DiffMotionDetector from deepgaze.motion_detection import MogMotionDetector from deepgaze.motion_detection import Mog2MotionDetector #Open the video file and loading the background image video_capture = cv2.VideoCapture("./cars.avi") background_image = cv2.imread("./background.png") #Decalring the diff motion detector object and setting the background my_diff_detector = DiffMotionDetector() my_diff_detector.setBackground(background_image) #Declaring the MOG motion detector my_mog_detector = MogMotionDetector() my_mog_detector.returnMask(background_image) #Declaring the MOG 2 motion detector my_mog2_detector = Mog2MotionDetector() my_mog2_detector.returnGreyscaleMask(background_image) # Define the codec and create VideoWriter objects fourcc = cv2.cv.CV_FOURCC(*'XVID') out = cv2.VideoWriter("./cars_original.avi", fourcc, 20.0, (1920,1080)) out_diff = cv2.VideoWriter("./cars_diff.avi", fourcc, 20.0, (1920,1080)) out_mog = cv2.VideoWriter("./cars_mog.avi", fourcc, 20.0, (1920,1080)) out_mog2 = cv2.VideoWriter("./cars_mog2.avi", fourcc, 20.0, (1920,1080)) while(True): # Capture frame-by-frame ret, frame = video_capture.read() #Get the mask from the detector objects diff_mask = my_diff_detector.returnMask(frame) mog_mask = my_mog_detector.returnMask(frame) mog2_mask = my_mog2_detector.returnGreyscaleMask(frame) #Merge the b/w frame in order to have depth=3 diff_mask = cv2.merge([diff_mask, diff_mask, diff_mask]) mog_mask = cv2.merge([mog_mask, mog_mask, mog_mask]) mog2_mask = cv2.merge([mog2_mask, mog2_mask, mog2_mask]) #Writing in the output file out.write(frame) out_diff.write(diff_mask) out_mog.write(mog_mask) out_mog2.write(mog2_mask) #Showing the frame and waiting # for the exit command if(frame is None): break #check for empty frames cv2.imshow('Original', frame) #show on window cv2.imshow('Diff', diff_mask) #show on window cv2.imshow('MOG', mog_mask) #show on window cv2.imshow('MOG 2', mog2_mask) #show on window if cv2.waitKey(1) & 0xFF == ord('q'): break #Exit when Q is pressed #Release the camera video_capture.release() print("Bye...")
1,136
447
""" Vulnerability service interfaces and implementations for `pip-audit`. """ from .interface import ( Dependency, ResolvedDependency, ServiceError, SkippedDependency, VulnerabilityResult, VulnerabilityService, ) from .osv import OsvService from .pypi import PyPIService __all__ = [ "Dependency", "ResolvedDependency", "ServiceError", "SkippedDependency", "VulnerabilityResult", "VulnerabilityService", "OsvService", "PyPIService", ]
185
5,169
<reponame>Gantios/Specs { "name": "FingerSDKXIF", "version": "1.0.1", "summary": "A short description of FingerSDKXIF.", "description": "this is my first FrameWork", "homepage": "http://EXAMPLE/FingerSDKXIF", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "": "" }, "platforms": { "ios": "14.5" }, "source": { "git": "https://github.com/xifengiOS/FingerSDKXIF.git", "tag": "1.0.1" }, "ios": { "vendored_frameworks": "MyFramework/MyFramework.framework" } }
242
1,980
""" LanguageTool Grammar Checker ------------------------------ """ import language_tool_python from textattack.constraints import Constraint class LanguageTool(Constraint): """Uses languagetool to determine if two sentences have the same number of grammatical erors. (https://languagetool.org/) Args: grammar_error_threshold (int): the number of additional errors permitted in `x_adv` relative to `x` compare_against_original (bool): If `True`, compare against the original text. Otherwise, compare against the most recent text. language: language to use for languagetool (available choices: https://dev.languagetool.org/languages) """ def __init__( self, grammar_error_threshold=0, compare_against_original=True, language="en-US" ): super().__init__(compare_against_original) self.lang_tool = language_tool_python.LanguageTool(language) self.grammar_error_threshold = grammar_error_threshold self.grammar_error_cache = {} def get_errors(self, attacked_text, use_cache=False): text = attacked_text.text if use_cache: if text not in self.grammar_error_cache: self.grammar_error_cache[text] = len(self.lang_tool.check(text)) return self.grammar_error_cache[text] else: return len(self.lang_tool.check(text)) def _check_constraint(self, transformed_text, reference_text): original_num_errors = self.get_errors(reference_text, use_cache=True) errors_added = self.get_errors(transformed_text) - original_num_errors return errors_added <= self.grammar_error_threshold def extra_repr_keys(self): return ["grammar_error_threshold"] + super().extra_repr_keys()
680
2,151
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_UI_WS_PLATFORM_DISPLAY_DEFAULT_H_ #define SERVICES_UI_WS_PLATFORM_DISPLAY_DEFAULT_H_ #include <memory> #include "base/macros.h" #include "services/ui/display/viewport_metrics.h" #include "services/ui/ws/frame_generator.h" #include "services/ui/ws/platform_display.h" #include "services/ui/ws/platform_display_delegate.h" #include "services/ui/ws/server_window.h" #include "ui/platform_window/platform_window_delegate.h" namespace ui { class EventSink; class PlatformWindow; namespace ws { class ThreadedImageCursors; // PlatformDisplay implementation that connects to a PlatformWindow and // FrameGenerator for Chrome OS. class PlatformDisplayDefault : public PlatformDisplay, public ui::PlatformWindowDelegate { public: // |image_cursors| may be null, for example on Android or in tests. PlatformDisplayDefault(ServerWindow* root_window, const display::ViewportMetrics& metrics, std::unique_ptr<ThreadedImageCursors> image_cursors); ~PlatformDisplayDefault() override; // EventSource:: EventSink* GetEventSink() override; // PlatformDisplay: void Init(PlatformDisplayDelegate* delegate) override; void SetViewportSize(const gfx::Size& size) override; void SetTitle(const base::string16& title) override; void SetCapture() override; void ReleaseCapture() override; void SetCursor(const ui::CursorData& cursor) override; void MoveCursorTo(const gfx::Point& window_pixel_location) override; void SetCursorSize(const ui::CursorSize& cursor_size) override; void ConfineCursorToBounds(const gfx::Rect& pixel_bounds) override; void UpdateTextInputState(const ui::TextInputState& state) override; void SetImeVisibility(bool visible) override; void UpdateViewportMetrics(const display::ViewportMetrics& metrics) override; const display::ViewportMetrics& GetViewportMetrics() override; gfx::AcceleratedWidget GetAcceleratedWidget() const override; FrameGenerator* GetFrameGenerator() override; void SetCursorConfig(display::Display::Rotation rotation, float scale) override; private: // ui::PlatformWindowDelegate: void OnBoundsChanged(const gfx::Rect& new_bounds) override; void OnDamageRect(const gfx::Rect& damaged_region) override; void DispatchEvent(ui::Event* event) override; void OnCloseRequest() override; void OnClosed() override; void OnWindowStateChanged(ui::PlatformWindowState new_state) override; void OnLostCapture() override; void OnAcceleratedWidgetAvailable(gfx::AcceleratedWidget widget, float device_scale_factor) override; void OnAcceleratedWidgetDestroying() override; void OnAcceleratedWidgetDestroyed() override; void OnActivationChanged(bool active) override; ServerWindow* root_window_; std::unique_ptr<ThreadedImageCursors> image_cursors_; PlatformDisplayDelegate* delegate_ = nullptr; std::unique_ptr<FrameGenerator> frame_generator_; display::ViewportMetrics metrics_; std::unique_ptr<ui::PlatformWindow> platform_window_; gfx::AcceleratedWidget widget_; DISALLOW_COPY_AND_ASSIGN(PlatformDisplayDefault); }; } // namespace ws } // namespace ui #endif // SERVICES_UI_WS_PLATFORM_DISPLAY_DEFAULT_H_
1,149
468
"""Base task.""" import typing import abc import torch from torch import nn from matchzoo.engine import base_metric from matchzoo.utils import parse_metric, parse_loss class BaseTask(abc.ABC): """Base Task, shouldn't be used directly.""" TYPE = 'base' def __init__(self, losses=None, metrics=None): """ Base task constructor. :param losses: Losses of task. :param metrics: Metrics for evaluating. """ self._losses = self._convert(losses, parse_loss) self._metrics = self._convert(metrics, parse_metric) self._assure_losses() self._assure_metrics() def _convert(self, identifiers, parse): if not identifiers: identifiers = [] elif not isinstance(identifiers, list): identifiers = [identifiers] return [ parse(identifier, self.__class__.TYPE) for identifier in identifiers ] def _assure_losses(self): if not self._losses: first_available = self.list_available_losses()[0] self._losses = self._convert(first_available, parse_loss) def _assure_metrics(self): if not self._metrics: first_available = self.list_available_metrics()[0] self._metrics = self._convert(first_available, parse_metric) @property def losses(self): """:return: Losses used in the task.""" return self._losses @property def metrics(self): """:return: Metrics used in the task.""" return self._metrics @losses.setter def losses( self, new_losses: typing.Union[ typing.List[str], typing.List[nn.Module], str, nn.Module ] ): self._losses = self._convert(new_losses, parse_loss) @metrics.setter def metrics( self, new_metrics: typing.Union[ typing.List[str], typing.List[base_metric.BaseMetric], str, base_metric.BaseMetric ] ): self._metrics = self._convert(new_metrics, parse_metric) @classmethod @abc.abstractmethod def list_available_losses(cls) -> list: """:return: a list of available losses.""" @classmethod @abc.abstractmethod def list_available_metrics(cls) -> list: """:return: a list of available metrics.""" @property @abc.abstractmethod def output_shape(self) -> tuple: """:return: output shape of a single sample of the task.""" @property @abc.abstractmethod def output_dtype(self): """:return: output data type for specific task."""
1,188
2,338
/* * Copyright 2010 INRIA Saclay * Copyright 2013 Ecole Normale Superieure * * Use of this software is governed by the MIT license * * Written by <NAME>, INRIA Saclay - Ile-de-France, * Parc Club Orsay Universite, ZAC des vignes, 4 rue <NAME>, * 91893 Orsay, France * and Ecole Normale Superieure, 45 rue d'Ulm, 75230 Paris, France */ #include <isl/val.h> #include <isl_space_private.h> #include <isl_point_private.h> #include <isl_pw_macro.h> /* Evaluate "pw" in the void point "pnt". * In particular, return the value NaN. */ static __isl_give isl_val *FN(PW,eval_void)(__isl_take PW *pw, __isl_take isl_point *pnt) { isl_ctx *ctx; ctx = isl_point_get_ctx(pnt); FN(PW,free)(pw); isl_point_free(pnt); return isl_val_nan(ctx); } /* Evaluate the piecewise function "pw" in "pnt". * If the point is void, then return NaN. * If the point lies outside the domain of "pw", then return 0 or NaN * depending on whether 0 is the default value for this type of function. */ __isl_give isl_val *FN(PW,eval)(__isl_take PW *pw, __isl_take isl_point *pnt) { int i; isl_bool is_void; isl_bool found; isl_ctx *ctx; isl_bool ok; isl_space *pnt_space, *pw_space; isl_val *v; pnt_space = isl_point_peek_space(pnt); pw_space = FN(PW,peek_space)(pw); ok = isl_space_is_domain_internal(pnt_space, pw_space); if (ok < 0) goto error; ctx = isl_point_get_ctx(pnt); if (!ok) isl_die(ctx, isl_error_invalid, "incompatible spaces", goto error); is_void = isl_point_is_void(pnt); if (is_void < 0) goto error; if (is_void) return FN(PW,eval_void)(pw, pnt); found = isl_bool_false; for (i = 0; i < pw->n; ++i) { found = isl_set_contains_point(pw->p[i].set, pnt); if (found < 0) goto error; if (found) break; } if (found) { v = FN(EL,eval)(FN(EL,copy)(pw->p[i].FIELD), isl_point_copy(pnt)); } else if (DEFAULT_IS_ZERO) { v = isl_val_zero(ctx); } else { v = isl_val_nan(ctx); } FN(PW,free)(pw); isl_point_free(pnt); return v; error: FN(PW,free)(pw); isl_point_free(pnt); return NULL; }
930
331
package com.lauzy.freedom.data.database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.freedom.lauzy.model.RecentSongBean; import java.util.ArrayList; import java.util.List; /** * Desc : 最近播放数据库 * Author : Lauzy * Date : 2017/9/14 * Blog : http://www.jianshu.com/u/e76853f863a9 * Email : <EMAIL> */ public class RecentDb implements BaseDb { private static RecentDb sInstance; private TickDaoHelper mTickDaoHelper; private static final int RECENT_LIMIT = 50;//最多50首 private RecentDb(Context context) { mTickDaoHelper = new TickDaoHelper(context); } public static RecentDb getInstance(final Context context) { if (sInstance == null) { synchronized (RecentDb.class) { if (sInstance == null) { sInstance = new RecentDb(context.getApplicationContext()); } } } return sInstance; } @Override public void createTable(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS " + TickDaoHelper.RECENT_TABLE + " (" + RecentParam.SONG_ID + " VARCHAR(255) PRIMARY KEY NOT NULL," + RecentParam.SOURCE + " VARCHAR(255)," + RecentParam.SONG_NAME + " VARCHAR(255)," + RecentParam.SINGER_NAME + " VARCHAR(255)," + RecentParam.ALBUM_ID + " VARCHAR(255)," + RecentParam.ALBUM_NAME + " VARCHAR(255)," + RecentParam.PLAY_PATH + " VARCHAR(255)," + RecentParam.DURATION + " LONG," + RecentParam.LENGTH + " VARCHAR(255)," + RecentParam.PLAY_TIME + " VARCHAR(255)," + RecentParam.ALBUM_COVER + " VARCHAR(255)," + "CONSTRAINT UC_RECENT UNIQUE (" + RecentParam.SOURCE + "," + RecentParam.SONG_ID + " ));"); } @Override public void upgradeTable(SQLiteDatabase db, int oldVersion, int newVersion) { } /** * 添加最近播放数据 * * @param songBean 音乐Bean */ public void addRecentSong(RecentSongBean songBean) { SQLiteDatabase db = mTickDaoHelper.getReadableDatabase(); db.beginTransaction(); try { //判断是否存在 Cursor exitCursor = null; try { exitCursor = db.query(TickDaoHelper.RECENT_TABLE, new String[]{RecentParam.SONG_ID}, RecentParam.SONG_ID + " = ? ", new String[]{String.valueOf(songBean.id)}, null, null, null, null); if (exitCursor != null && exitCursor.getCount() > 0) { ContentValues values = putContentValue(songBean); db.update(TickDaoHelper.RECENT_TABLE, values, RecentParam.SONG_ID + " = ? ", new String[]{String.valueOf(songBean.id)}); } else { //插入数据 ContentValues values = putContentValue(songBean); db.replace(TickDaoHelper.RECENT_TABLE, null, values); } } finally { if (exitCursor != null) { exitCursor.close(); } } //限制条数 Cursor limitCursor = null; try { limitCursor = db.query(TickDaoHelper.RECENT_TABLE, new String[]{RecentParam.PLAY_TIME}, null, null, null, null, RecentParam.PLAY_TIME + " ASC"); if (limitCursor != null && limitCursor.getCount() > RECENT_LIMIT) { limitCursor.moveToPosition(limitCursor.getCount() - RECENT_LIMIT); long playTime = limitCursor.getLong(limitCursor.getColumnIndex(RecentParam.PLAY_TIME)); db.delete(TickDaoHelper.RECENT_TABLE, RecentParam.PLAY_TIME + " < ?", new String[]{String.valueOf(playTime)}); } } finally { if (limitCursor != null) { limitCursor.close(); } } db.setTransactionSuccessful(); } finally { db.endTransaction(); db.close(); } } private ContentValues putContentValue(RecentSongBean songBean) { ContentValues values = new ContentValues(); values.put(RecentParam.SOURCE, songBean.type); values.put(RecentParam.SONG_ID, songBean.id); values.put(RecentParam.SONG_NAME, songBean.title); values.put(RecentParam.ALBUM_ID, songBean.albumId); values.put(RecentParam.ALBUM_NAME, songBean.albumName); values.put(RecentParam.SINGER_NAME, songBean.artistName); values.put(RecentParam.DURATION, songBean.duration); values.put(RecentParam.LENGTH, songBean.songLength); values.put(RecentParam.PLAY_PATH, songBean.path); values.put(RecentParam.ALBUM_COVER, songBean.albumCover); values.put(RecentParam.PLAY_TIME, System.currentTimeMillis()); return values; } /** * 获取最近播放的数据集合 * @return 最近播放的数据集合 */ public List<RecentSongBean> getRecentSongBean() { SQLiteDatabase db = mTickDaoHelper.getReadableDatabase(); Cursor cursor = null; try { cursor = db.query(TickDaoHelper.RECENT_TABLE, null, null, null, null, null, RecentParam.PLAY_TIME + " DESC"); if (cursor != null && cursor.getCount() > 0) { List<RecentSongBean> songBeen = new ArrayList<>(); while (cursor.moveToNext()) { RecentSongBean listBean = new RecentSongBean(); listBean.id = Long.parseLong(cursor.getString(cursor.getColumnIndex(RecentParam.SONG_ID))); listBean.title = cursor.getString(cursor.getColumnIndex(RecentParam.SONG_NAME)); listBean.artistName = cursor.getString(cursor.getColumnIndex(RecentParam.SINGER_NAME)); listBean.albumName = cursor.getString(cursor.getColumnIndex(RecentParam.ALBUM_NAME)); listBean.albumId = Long.parseLong(cursor.getString(cursor.getColumnIndex(RecentParam.ALBUM_ID))); listBean.path = cursor.getString(cursor.getColumnIndex(RecentParam.PLAY_PATH)); listBean.type = cursor.getString(cursor.getColumnIndex(RecentParam.SOURCE)); listBean.duration = cursor.getLong(cursor.getColumnIndex(RecentParam.DURATION)); listBean.songLength = cursor.getString(cursor.getColumnIndex(RecentParam.LENGTH)); listBean.albumCover = cursor.getString(cursor.getColumnIndex(RecentParam.ALBUM_COVER)); songBeen.add(listBean); } return songBeen; } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } db.close(); } return null; } /** * 删除最近播放的数据 * @param songId songId * @return 删除结果 */ public long deleteRecentSong(long songId) { SQLiteDatabase db = mTickDaoHelper.getReadableDatabase(); db.beginTransaction(); int delete = db.delete(TickDaoHelper.RECENT_TABLE, RecentParam.SONG_ID + " = ? ", new String[]{String.valueOf(songId)}); db.setTransactionSuccessful(); db.endTransaction(); db.close(); return delete; } /** * 清空最近播放数据 * @return 清除结果 */ public int clearRecentSongs() { SQLiteDatabase db = mTickDaoHelper.getReadableDatabase(); db.beginTransaction(); int delete = db.delete(TickDaoHelper.RECENT_TABLE, null, null); db.setTransactionSuccessful(); db.endTransaction(); db.close(); return delete; } }
4,014
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmlsecurity.hxx" #include "encryptorimpl.hxx" #include <com/sun/star/xml/crypto/XXMLEncryptionTemplate.hpp> #include <com/sun/star/xml/wrapper/XXMLElementWrapper.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> namespace cssu = com::sun::star::uno; namespace cssl = com::sun::star::lang; namespace cssxc = com::sun::star::xml::crypto; namespace cssxw = com::sun::star::xml::wrapper; #define SERVICE_NAME "com.sun.star.xml.crypto.sax.Encryptor" #define IMPLEMENTATION_NAME "com.sun.star.xml.security.framework.EncryptorImpl" #define DECLARE_ASCII( SASCIIVALUE ) \ rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( SASCIIVALUE ) ) EncryptorImpl::EncryptorImpl( const cssu::Reference< cssl::XMultiServiceFactory >& rxMSF) { m_nReferenceId = -1; mxMSF = rxMSF; } EncryptorImpl::~EncryptorImpl() { } bool EncryptorImpl::checkReady() const /****** EncryptorImpl/checkReady ********************************************* * * NAME * checkReady -- checks the conditions for the encryption. * * SYNOPSIS * bReady = checkReady( ); * * FUNCTION * checks whether all following conditions are satisfied: * 1. the result listener is ready; * 2. the EncryptionEngine is ready. * * INPUTS * empty * * RESULT * bReady - true if all conditions are satisfied, false otherwise * * HISTORY * 05.01.2004 - implemented * * AUTHOR * <NAME> * Email: <EMAIL> ******************************************************************************/ { sal_Int32 nKeyInc = 0; if (m_nIdOfKeyEC != 0) { nKeyInc = 1; } return (m_xResultListener.is() && (m_nReferenceId != -1) && (2+nKeyInc == m_nNumOfResolvedReferences) && EncryptionEngine::checkReady()); } void EncryptorImpl::notifyResultListener() const throw (cssu::Exception, cssu::RuntimeException) /****** DecryptorImpl/notifyResultListener *********************************** * * NAME * notifyResultListener -- notifies the listener about the encryption * result. * * SYNOPSIS * notifyResultListener( ); * * FUNCTION * see NAME. * * INPUTS * empty * * RESULT * empty * * HISTORY * 05.01.2004 - implemented * * AUTHOR * <NAME> * Email: <EMAIL> ******************************************************************************/ { cssu::Reference< cssxc::sax::XEncryptionResultListener > xEncryptionResultListener ( m_xResultListener , cssu::UNO_QUERY ) ; xEncryptionResultListener->encrypted( m_nSecurityId, m_nStatus ); } void EncryptorImpl::startEngine( const cssu::Reference< cssxc::XXMLEncryptionTemplate >& xEncryptionTemplate) throw (cssu::Exception, cssu::RuntimeException) /****** EncryptorImpl/startEngine ******************************************** * * NAME * startEngine -- generates the encryption. * * SYNOPSIS * startEngine( xEncryptionTemplate ); * * FUNCTION * generates the encryption element, then if succeeds, updates the link * of old template element to the new encryption element in * SAXEventKeeper. * * INPUTS * xEncryptionTemplate - the encryption template to be encrypted. * * RESULT * empty * * HISTORY * 05.01.2004 - implemented * * AUTHOR * <NAME> * Email: <EMAIL> ******************************************************************************/ { cssu::Reference < cssxc::XXMLEncryptionTemplate > xResultTemplate; cssu::Reference< cssxw::XXMLElementWrapper > xXMLElement = m_xSAXEventKeeper->getElement( m_nReferenceId ); xEncryptionTemplate->setTarget(xXMLElement); try { xResultTemplate = m_xXMLEncryption->encrypt( xEncryptionTemplate, m_xSecurityEnvironment); m_nStatus = xResultTemplate->getStatus(); } catch( cssu::Exception& ) { m_nStatus = cssxc::SecurityOperationStatus_RUNTIMEERROR_FAILED; } if (m_nStatus == cssxc::SecurityOperationStatus_OPERATION_SUCCEEDED) { cssu::Reference < cssxw::XXMLElementWrapper > xResultEncryption = xResultTemplate->getTemplate(); m_xSAXEventKeeper->setElement(m_nIdOfTemplateEC, xResultEncryption); m_xSAXEventKeeper->setElement(m_nReferenceId, NULL); } } /* XReferenceCollector */ void SAL_CALL EncryptorImpl::setReferenceCount(sal_Int32) throw (cssu::Exception, cssu::RuntimeException) { /* * dummp method, because there is only one reference in * encryption, different from signature. * so the referenceNumber is always 1 */ } void SAL_CALL EncryptorImpl::setReferenceId( sal_Int32 id ) throw (cssu::Exception, cssu::RuntimeException) { m_nReferenceId = id; } /* XEncryptionResultBroadcaster */ void SAL_CALL EncryptorImpl::addEncryptionResultListener( const cssu::Reference< cssxc::sax::XEncryptionResultListener >& listener ) throw (cssu::Exception, cssu::RuntimeException) { m_xResultListener = listener; tryToPerform(); } void SAL_CALL EncryptorImpl::removeEncryptionResultListener( const cssu::Reference< cssxc::sax::XEncryptionResultListener >&) throw (cssu::RuntimeException) { } /* XInitialization */ void SAL_CALL EncryptorImpl::initialize( const cssu::Sequence< cssu::Any >& aArguments ) throw (cssu::Exception, cssu::RuntimeException) { OSL_ASSERT(aArguments.getLength() == 5); rtl::OUString ouTempString; aArguments[0] >>= ouTempString; m_nSecurityId = ouTempString.toInt32(); aArguments[1] >>= m_xSAXEventKeeper; aArguments[2] >>= ouTempString; m_nIdOfTemplateEC = ouTempString.toInt32(); aArguments[3] >>= m_xSecurityEnvironment; aArguments[4] >>= m_xXMLEncryption; } rtl::OUString EncryptorImpl_getImplementationName () throw (cssu::RuntimeException) { return rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( IMPLEMENTATION_NAME ) ); } sal_Bool SAL_CALL EncryptorImpl_supportsService( const rtl::OUString& ServiceName ) throw (cssu::RuntimeException) { return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME )); } cssu::Sequence< rtl::OUString > SAL_CALL EncryptorImpl_getSupportedServiceNames( ) throw (cssu::RuntimeException) { cssu::Sequence < rtl::OUString > aRet(1); rtl::OUString* pArray = aRet.getArray(); pArray[0] = rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) ); return aRet; } #undef SERVICE_NAME cssu::Reference< cssu::XInterface > SAL_CALL EncryptorImpl_createInstance( const cssu::Reference< cssl::XMultiServiceFactory >& rSMgr) throw( cssu::Exception ) { return (cppu::OWeakObject*) new EncryptorImpl(rSMgr); } /* XServiceInfo */ rtl::OUString SAL_CALL EncryptorImpl::getImplementationName( ) throw (cssu::RuntimeException) { return EncryptorImpl_getImplementationName(); } sal_Bool SAL_CALL EncryptorImpl::supportsService( const rtl::OUString& rServiceName ) throw (cssu::RuntimeException) { return EncryptorImpl_supportsService( rServiceName ); } cssu::Sequence< rtl::OUString > SAL_CALL EncryptorImpl::getSupportedServiceNames( ) throw (cssu::RuntimeException) { return EncryptorImpl_getSupportedServiceNames(); }
2,725
679
<gh_stars>100-1000 /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _SV_REGION_HXX #define _SV_REGION_HXX #include <tools/gen.hxx> #include <vcl/sv.h> #include <vcl/dllapi.h> #include <basegfx/polygon/b2dpolypolygon.hxx> #include <boost/shared_ptr.hpp> class ImplRegionBand; class RegionBand; class Polygon; class PolyPolygon; ////////////////////////////////////////////////////////////////////////////// typedef boost::shared_ptr< RegionBand > RegionBandPtr; typedef boost::shared_ptr< PolyPolygon > PolyPolygonPtr; typedef boost::shared_ptr< basegfx::B2DPolyPolygon > B2DPolyPolygonPtr; typedef std::vector< Rectangle > RectangleVector; ////////////////////////////////////////////////////////////////////////////// class VCL_DLLPUBLIC Region { private: friend class OutputDevice; friend class Window; friend class Bitmap; // possible contents B2DPolyPolygonPtr mpB2DPolyPolygon; PolyPolygonPtr mpPolyPolygon; RegionBandPtr mpRegionBand; /// bitfield bool mbIsNull : 1; // helpers SAL_DLLPRIVATE void ImplCreatePolyPolyRegion( const PolyPolygon& rPolyPoly ); SAL_DLLPRIVATE void ImplCreatePolyPolyRegion( const basegfx::B2DPolyPolygon& rPolyPoly ); SAL_DLLPRIVATE PolyPolygon ImplCreatePolyPolygonFromRegionBand() const; SAL_DLLPRIVATE basegfx::B2DPolyPolygon ImplCreateB2DPolyPolygonFromRegionBand() const; public: Region(bool bIsNull = false); // default creates empty region, with true a null region is created Region(const Rectangle& rRect); Region(const Polygon& rPolygon); Region(const PolyPolygon& rPolyPoly); Region(const basegfx::B2DPolyPolygon&); Region(const Region& rRegion); ~Region(); // direct access to contents const basegfx::B2DPolyPolygon* getB2DPolyPolygon() const { return mpB2DPolyPolygon.get(); } const PolyPolygon* getPolyPolygon() const { return mpPolyPolygon.get(); } const RegionBand* getRegionBand() const { return mpRegionBand.get(); } // access with converters, the asked data will be created from the most // valuable data, buffered and returned const PolyPolygon GetAsPolyPolygon() const; const basegfx::B2DPolyPolygon GetAsB2DPolyPolygon() const; const RegionBand* GetAsRegionBand() const; // manipulators void Move( long nHorzMove, long nVertMove ); void Scale( double fScaleX, double fScaleY ); bool Union( const Rectangle& rRegion ); bool Intersect( const Rectangle& rRegion ); bool Exclude( const Rectangle& rRegion ); bool XOr( const Rectangle& rRegion ); bool Union( const Region& rRegion ); bool Intersect( const Region& rRegion ); bool Exclude( const Region& rRegion ); bool XOr( const Region& rRegion ); bool IsEmpty() const; bool IsNull() const; void SetEmpty(); void SetNull(); Rectangle GetBoundRect() const; bool HasPolyPolygonOrB2DPolyPolygon() const { return (getB2DPolyPolygon() || getPolyPolygon()); } void GetRegionRectangles(RectangleVector& rTarget) const; bool IsInside( const Point& rPoint ) const; bool IsInside( const Rectangle& rRect ) const; bool IsOver( const Rectangle& rRect ) const; Region& operator=( const Region& rRegion ); Region& operator=( const Rectangle& rRect ); bool operator==( const Region& rRegion ) const; bool operator!=( const Region& rRegion ) const { return !(Region::operator==( rRegion )); } friend VCL_DLLPUBLIC SvStream& operator>>( SvStream& rIStm, Region& rRegion ); friend VCL_DLLPUBLIC SvStream& operator<<( SvStream& rOStm, const Region& rRegion ); /* workaround: faster conversion for PolyPolygons * if half of the Polygons contained in rPolyPoly are actually * rectangles, then the returned Region will be constructed by * XOr'ing the contained Polygons together; in the case of * only Rectangles this can be up to eight times faster than * Region( const PolyPolygon& ). * Caution: this is only useful if the Region is known to be * changed to rectangles; e.g. if being set as clip region */ static Region GetRegionFromPolyPolygon( const PolyPolygon& rPolyPoly ); }; #endif // _SV_REGION_HXX ////////////////////////////////////////////////////////////////////////////// // eof
1,607
776
<reponame>Diffblue-benchmarks/actframework package act.data; /*- * #%L * ACT Framework * %% * Copyright (C) 2014 - 2017 ActFramework * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import org.osgl.mvc.util.Binder; import org.osgl.mvc.util.ParamValueProvider; import org.osgl.storage.ISObject; import org.osgl.util.C; import org.osgl.util.IO; import java.util.List; import static act.data.annotation.ReadContent.ATTR_MERCY; /** * Read content lines from resource URL */ public class ContentLinesBinder extends Binder<List<String>> { public static final ContentLinesBinder INSTANCE = new ContentLinesBinder(); @Override public List<String> resolve(List<String> bean, String model, ParamValueProvider params) { try { ISObject sobj = SObjectBinder.INSTANCE.resolve(null, model, params); return null == sobj ? fallBack(model, params) : IO.readLines(sobj.asInputStream()); } catch (Exception e) { return fallBack(model, params); } } private List<String> fallBack(String model, ParamValueProvider params) { Boolean mercy = attribute(ATTR_MERCY); if (null == mercy) { mercy = false; } if (mercy) { String val = params.paramVal(model); return null == val ? C.<String>list() : C.list(val); } return C.list(); } }
690
348
{"nom":"Rillans","circ":"3ème circonscription","dpt":"Doubs","inscrits":63,"abs":20,"votants":43,"blancs":2,"nuls":0,"exp":41,"res":[{"nuance":"LR","nom":"<NAME>","voix":24},{"nuance":"REM","nom":"M. <NAME>","voix":17}]}
90
1,338
<reponame>Kirishikesan/haiku /* File System indices ** ** Distributed under the terms of the MIT License. */ #ifndef _FSSH_FS_INDEX_H #define _FSSH_FS_INDEX_H #include "fssh_defs.h" #include "fssh_dirent.h" typedef struct fssh_index_info { uint32_t type; fssh_off_t size; fssh_time_t modification_time; fssh_time_t creation_time; fssh_uid_t uid; fssh_gid_t gid; } fssh_index_info; #ifdef __cplusplus extern "C" { #endif extern int fssh_fs_create_index(fssh_dev_t device, const char *name, uint32_t type, uint32_t flags); extern int fssh_fs_remove_index(fssh_dev_t device, const char *name); extern int fssh_fs_stat_index(fssh_dev_t device, const char *name, struct fssh_index_info *indexInfo); extern fssh_DIR *fssh_fs_open_index_dir(fssh_dev_t device); extern int fssh_fs_close_index_dir(fssh_DIR *indexDirectory); extern struct fssh_dirent *fssh_fs_read_index_dir(fssh_DIR *indexDirectory); extern void fssh_fs_rewind_index_dir(fssh_DIR *indexDirectory); #ifdef __cplusplus } #endif #endif /* _FSSH_FS_INDEX_H */
470
341
<filename>column-samples/person-localization/person-localization.json { "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json", "elmType": "div", "defaultHoverField": "@currentField", "txtContent": "=if(@lcid==1031,'Erstellt von',if(@lcid==1053,'Skapad av',if(@lcid==1043,'gemaakt door','Created By'))) + ': ' + @currentField.title" }
149
628
from django.db import models from .base import BaseModel class TagManager(models.Manager): """Manager that filters out system tags by default. """ def get_queryset(self): return super(TagManager, self).get_queryset().filter(system=False) class Tag(BaseModel): name = models.CharField(db_index=True, max_length=1024) system = models.BooleanField(default=False) objects = TagManager() all_tags = models.Manager() def __unicode__(self): if self.system: return 'System Tag: {}'.format(self.name) return u'{}'.format(self.name) def _natural_key(self): return hash(self.name + str(self.system)) @property def _id(self): return self.name.lower() @classmethod def load(cls, data, system=False): """For compatibility with v1: the tag name used to be the _id, so we make Tag.load('tagname') work as if `name` were the primary key. """ try: return cls.all_tags.get(system=system, name=data) except cls.DoesNotExist: return None class Meta: unique_together = ('name', 'system') ordering = ('name', )
484
703
<gh_stars>100-1000 #pragma once // This just implements a very simple multi-threaded job system. // It doesn't use lock free queues or anything fancy like that. // It doesn't support cancellation or priorities or anything like that either. // It's just a very simple way to distribute a meaningful amount of // 'work' across <n> number of threads. #include <stdint.h> #include "VHACD.h" #ifdef _MSC_VER # define SJS_ABI __cdecl #else # define SJS_ABI #endif // Callback to actually perform the job typedef void(SJS_ABI* SJS_jobCallback)(void* userPtr); namespace simplejobsystem { class SimpleJobSystem { public: // Create in instance of the SimpleJobSystem with the number of threads specified. // More threads than available cores is not particularly beneficial. static SimpleJobSystem* create(uint32_t maxThreads, VHACD::IVHACD::IUserTaskRunner* taskRunner); // Add a job to the queue of jobs to be performed, does not actually start the job yet. virtual void addJob(void* userPtr, SJS_jobCallback callback) = 0; // Start the jobs that have been posted, returns how many jobs are pending. virtual uint32_t startJobs(void) = 0; // Sleeps until all of the pending jobs have completed. virtual void waitForJobsToComplete(void) = 0; // Releases the SimpleJobSystem instance virtual void release(void) = 0; }; } // namespace simplejobsystem
430
3,651
package com.orientechnologies.orient.core.tx; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import java.util.concurrent.CountDownLatch; public class OTxMetadataHolderImpl implements OTxMetadataHolder { private final CountDownLatch request; private final OTransactionSequenceStatus status; private final OTransactionId id; public OTxMetadataHolderImpl( CountDownLatch request, OTransactionId id, OTransactionSequenceStatus status) { this.request = request; this.id = id; this.status = status; } @Override public byte[] metadata() { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutput output = new DataOutputStream(outputStream); try { id.write(output); byte[] status = this.status.store(); output.writeInt(status.length); output.write(status, 0, status.length); } catch (IOException e) { e.printStackTrace(); } return outputStream.toByteArray(); } public static OTxMetadataHolder read(final byte[] data) { final ByteArrayInputStream inputStream = new ByteArrayInputStream(data); final DataInput input = new DataInputStream(inputStream); try { final OTransactionId txId = OTransactionId.read(input); int size = input.readInt(); byte[] status = new byte[size]; input.readFully(status); return new OTxMetadataHolderImpl( new CountDownLatch(0), txId, OTransactionSequenceStatus.read(status)); } catch (IOException e) { e.printStackTrace(); } return null; } @Override public void notifyMetadataRead() { request.countDown(); } public OTransactionId getId() { return id; } @Override public OTransactionSequenceStatus getStatus() { return status; } }
660
14,668
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. struct A { A&& Pass(); }; struct B { B& Pass(); }; struct C { A a; }; struct D { D&& NotPass(); }; struct E { E() : a(new A) {} ~E() { delete a; } A* a; }; struct F { explicit F(A&&); F&& Pass(); }; void Test() { // Pass that returns rvalue reference should use std::move. A a1; A a2 = std::move(a1); // Pass that doesn't return a rvalue reference should not be rewritten. B b1; B b2 = b1.Pass(); // std::move() needs to wrap the entire expression when passing a member. C c; A a3 = std::move(c.a); // Don't rewrite things that return rvalue references that aren't named Pass. D d1; D d2 = d1.NotPass(); // Pass via a pointer type should dereference the pointer first. E e; A a4 = std::move(*e.a); // Nested Pass() is handled correctly. A a5; F f = std::move(F(std::move(a5))); // Chained Pass is handled correctly. A a6; A a7 = std::move(std::move(a6)); }
400
2,990
/* * GDevelop Core * Copyright 2008-2016 <NAME> (<EMAIL>). All rights * reserved. This project is released under the MIT License. */ #include "GDCore/IDE/Events/EventsTypesLister.h" #include <map> #include <memory> #include <vector> #include "GDCore/Events/Event.h" #include "GDCore/Events/EventsList.h" #include "GDCore/Project/Layout.h" #include "GDCore/Project/Project.h" #include "GDCore/String.h" namespace gd { bool EventsTypesLister::DoVisitEvent(gd::BaseEvent& event) { allEventsTypes.push_back(event.GetType()); return false; } bool EventsTypesLister::DoVisitInstruction(gd::Instruction& instruction, bool isCondition) { if (isCondition) allConditionsTypes.push_back(instruction.GetType()); else allActionsTypes.push_back(instruction.GetType()); return false; } EventsTypesLister::~EventsTypesLister() {} } // namespace gd
338
2,322
/* * RichEdit - ITextHost implementation for windowed richedit controls * * Copyright 2009 by <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #define COBJMACROS #include "editor.h" #include "ole2.h" #include "richole.h" #include "imm.h" #include "textserv.h" #include "wine/debug.h" #include "editstr.h" #include "rtf.h" WINE_DEFAULT_DEBUG_CHANNEL(richedit); struct host { ITextHost2 ITextHost_iface; LONG ref; ITextServices *text_srv; HWND window, parent; unsigned int emulate_10 : 1; unsigned int dialog_mode : 1; unsigned int want_return : 1; unsigned int sel_bar : 1; unsigned int client_edge : 1; unsigned int use_set_rect : 1; unsigned int use_back_colour : 1; unsigned int defer_release : 1; PARAFORMAT2 para_fmt; DWORD props, scrollbars, event_mask; RECT client_rect, set_rect; COLORREF back_colour; WCHAR password_char; unsigned int notify_level; }; static const ITextHost2Vtbl textHostVtbl; static BOOL listbox_registered; static BOOL combobox_registered; static void host_init_props( struct host *host ) { DWORD style; style = GetWindowLongW( host->window, GWL_STYLE ); /* text services assumes the scrollbars are originally not shown, so hide them. However with ES_DISABLENOSCROLL it'll immediately show them, so don't bother */ if (!(style & ES_DISABLENOSCROLL)) ShowScrollBar( host->window, SB_BOTH, FALSE ); host->scrollbars = style & (WS_VSCROLL | WS_HSCROLL | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_DISABLENOSCROLL); if (style & WS_VSCROLL) host->scrollbars |= ES_AUTOVSCROLL; if ((style & WS_HSCROLL) && !host->emulate_10) host->scrollbars |= ES_AUTOHSCROLL; host->props = TXTBIT_RICHTEXT | TXTBIT_ALLOWBEEP; if (style & ES_MULTILINE) host->props |= TXTBIT_MULTILINE; if (style & ES_READONLY) host->props |= TXTBIT_READONLY; if (style & ES_PASSWORD) host->props |= TXTBIT_USEPASSWORD; if (!(style & ES_NOHIDESEL)) host->props |= TXTBIT_HIDESELECTION; if (style & ES_SAVESEL) host->props |= TXTBIT_SAVESELECTION; if (style & ES_VERTICAL) host->props |= TXTBIT_VERTICAL; if (style & ES_NOOLEDRAGDROP) host->props |= TXTBIT_DISABLEDRAG; if (!(host->scrollbars & ES_AUTOHSCROLL)) host->props |= TXTBIT_WORDWRAP; host->sel_bar = !!(style & ES_SELECTIONBAR); host->want_return = !!(style & ES_WANTRETURN); style = GetWindowLongW( host->window, GWL_EXSTYLE ); host->client_edge = !!(style & WS_EX_CLIENTEDGE); } struct host *host_create( HWND hwnd, CREATESTRUCTW *cs, BOOL emulate_10 ) { struct host *texthost; texthost = heap_alloc(sizeof(*texthost)); if (!texthost) return NULL; texthost->ITextHost_iface.lpVtbl = &textHostVtbl; texthost->ref = 1; texthost->text_srv = NULL; texthost->window = hwnd; texthost->parent = cs->hwndParent; texthost->emulate_10 = emulate_10; texthost->dialog_mode = 0; memset( &texthost->para_fmt, 0, sizeof(texthost->para_fmt) ); texthost->para_fmt.cbSize = sizeof(texthost->para_fmt); texthost->para_fmt.dwMask = PFM_ALIGNMENT; texthost->para_fmt.wAlignment = PFA_LEFT; if (cs->style & ES_RIGHT) texthost->para_fmt.wAlignment = PFA_RIGHT; if (cs->style & ES_CENTER) texthost->para_fmt.wAlignment = PFA_CENTER; host_init_props( texthost ); texthost->event_mask = 0; texthost->use_set_rect = 0; SetRectEmpty( &texthost->set_rect ); GetClientRect( hwnd, &texthost->client_rect ); texthost->use_back_colour = 0; texthost->password_char = (texthost->props & TXTBIT_USEPASSWORD) ? '*' : 0; texthost->defer_release = 0; texthost->notify_level = 0; return texthost; } static inline struct host *impl_from_ITextHost( ITextHost2 *iface ) { return CONTAINING_RECORD( iface, struct host, ITextHost_iface ); } static HRESULT WINAPI ITextHostImpl_QueryInterface( ITextHost2 *iface, REFIID iid, void **obj ) { struct host *host = impl_from_ITextHost( iface ); if (IsEqualIID( iid, &IID_IUnknown ) || IsEqualIID( iid, &IID_ITextHost ) || IsEqualIID( iid, &IID_ITextHost2 )) { *obj = &host->ITextHost_iface; ITextHost_AddRef( (ITextHost *)*obj ); return S_OK; } FIXME( "Unknown interface: %s\n", debugstr_guid( iid ) ); return E_NOINTERFACE; } static ULONG WINAPI ITextHostImpl_AddRef( ITextHost2 *iface ) { struct host *host = impl_from_ITextHost( iface ); ULONG ref = InterlockedIncrement( &host->ref ); return ref; } static ULONG WINAPI ITextHostImpl_Release( ITextHost2 *iface ) { struct host *host = impl_from_ITextHost( iface ); ULONG ref = InterlockedDecrement( &host->ref ); if (!ref) { SetWindowLongPtrW( host->window, 0, 0 ); ITextServices_Release( host->text_srv ); heap_free( host ); } return ref; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetDC,4) DECLSPEC_HIDDEN HDC __thiscall ITextHostImpl_TxGetDC( ITextHost2 *iface ) { struct host *host = impl_from_ITextHost( iface ); return GetDC( host->window ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxReleaseDC,8) DECLSPEC_HIDDEN INT __thiscall ITextHostImpl_TxReleaseDC( ITextHost2 *iface, HDC hdc ) { struct host *host = impl_from_ITextHost( iface ); return ReleaseDC( host->window, hdc ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxShowScrollBar,12) DECLSPEC_HIDDEN BOOL __thiscall ITextHostImpl_TxShowScrollBar( ITextHost2 *iface, INT bar, BOOL show ) { struct host *host = impl_from_ITextHost( iface ); return ShowScrollBar( host->window, bar, show ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxEnableScrollBar,12) DECLSPEC_HIDDEN BOOL __thiscall ITextHostImpl_TxEnableScrollBar( ITextHost2 *iface, INT bar, INT arrows ) { struct host *host = impl_from_ITextHost( iface ); return EnableScrollBar( host->window, bar, arrows ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxSetScrollRange,20) DECLSPEC_HIDDEN BOOL __thiscall ITextHostImpl_TxSetScrollRange( ITextHost2 *iface, INT bar, LONG min_pos, INT max_pos, BOOL redraw ) { struct host *host = impl_from_ITextHost( iface ); SCROLLINFO info = { .cbSize = sizeof(info), .fMask = SIF_PAGE | SIF_RANGE }; if (bar != SB_HORZ && bar != SB_VERT) { FIXME( "Unexpected bar %d\n", bar ); return FALSE; } if (host->scrollbars & ES_DISABLENOSCROLL) info.fMask |= SIF_DISABLENOSCROLL; if (host->text_srv) /* This can be called during text services creation */ { if (bar == SB_HORZ) ITextServices_TxGetHScroll( host->text_srv, NULL, NULL, NULL, (LONG *)&info.nPage, NULL ); else ITextServices_TxGetVScroll( host->text_srv, NULL, NULL, NULL, (LONG *)&info.nPage, NULL ); } info.nMin = min_pos; info.nMax = max_pos; return SetScrollInfo( host->window, bar, &info, redraw ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxSetScrollPos,16) DECLSPEC_HIDDEN BOOL __thiscall ITextHostImpl_TxSetScrollPos( ITextHost2 *iface, INT bar, INT pos, BOOL redraw ) { struct host *host = impl_from_ITextHost( iface ); DWORD style = GetWindowLongW( host->window, GWL_STYLE ); DWORD mask = (bar == SB_HORZ) ? WS_HSCROLL : WS_VSCROLL; BOOL show = TRUE, shown = style & mask; if (bar != SB_HORZ && bar != SB_VERT) { FIXME( "Unexpected bar %d\n", bar ); return FALSE; } /* If the application has adjusted the scrollbar's visibility it is reset */ if (!(host->scrollbars & ES_DISABLENOSCROLL)) { if (bar == SB_HORZ) ITextServices_TxGetHScroll( host->text_srv, NULL, NULL, NULL, NULL, &show ); else ITextServices_TxGetVScroll( host->text_srv, NULL, NULL, NULL, NULL, &show ); } if (!show ^ !shown) ShowScrollBar( host->window, bar, show ); return SetScrollPos( host->window, bar, pos, redraw ) != 0; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxInvalidateRect,12) DECLSPEC_HIDDEN void __thiscall ITextHostImpl_TxInvalidateRect( ITextHost2 *iface, const RECT *rect, BOOL mode ) { struct host *host = impl_from_ITextHost( iface ); InvalidateRect( host->window, rect, mode ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxViewChange,8) DECLSPEC_HIDDEN void __thiscall ITextHostImpl_TxViewChange( ITextHost2 *iface, BOOL update ) { struct host *host = impl_from_ITextHost( iface ); if (update) UpdateWindow( host->window ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxCreateCaret,16) DECLSPEC_HIDDEN BOOL __thiscall ITextHostImpl_TxCreateCaret( ITextHost2 *iface, HBITMAP bitmap, INT width, INT height ) { struct host *host = impl_from_ITextHost( iface ); return CreateCaret( host->window, bitmap, width, height ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxShowCaret,8) DECLSPEC_HIDDEN BOOL __thiscall ITextHostImpl_TxShowCaret( ITextHost2 *iface, BOOL show ) { struct host *host = impl_from_ITextHost( iface ); if (show) return ShowCaret( host->window ); else return HideCaret( host->window ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxSetCaretPos,12) DECLSPEC_HIDDEN BOOL __thiscall ITextHostImpl_TxSetCaretPos( ITextHost2 *iface, INT x, INT y ) { return SetCaretPos(x, y); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxSetTimer,12) DECLSPEC_HIDDEN BOOL __thiscall ITextHostImpl_TxSetTimer( ITextHost2 *iface, UINT id, UINT timeout ) { struct host *host = impl_from_ITextHost( iface ); return SetTimer( host->window, id, timeout, NULL ) != 0; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxKillTimer,8) DECLSPEC_HIDDEN void __thiscall ITextHostImpl_TxKillTimer( ITextHost2 *iface, UINT id ) { struct host *host = impl_from_ITextHost( iface ); KillTimer( host->window, id ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxScrollWindowEx,32) DECLSPEC_HIDDEN void __thiscall ITextHostImpl_TxScrollWindowEx( ITextHost2 *iface, INT dx, INT dy, const RECT *scroll, const RECT *clip, HRGN update_rgn, RECT *update_rect, UINT flags ) { struct host *host = impl_from_ITextHost( iface ); ScrollWindowEx( host->window, dx, dy, scroll, clip, update_rgn, update_rect, flags ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxSetCapture,8) DECLSPEC_HIDDEN void __thiscall ITextHostImpl_TxSetCapture( ITextHost2 *iface, BOOL capture ) { struct host *host = impl_from_ITextHost( iface ); if (capture) SetCapture( host->window ); else ReleaseCapture(); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxSetFocus,4) DECLSPEC_HIDDEN void __thiscall ITextHostImpl_TxSetFocus( ITextHost2 *iface ) { struct host *host = impl_from_ITextHost( iface ); SetFocus( host->window ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxSetCursor,12) DECLSPEC_HIDDEN void __thiscall ITextHostImpl_TxSetCursor( ITextHost2 *iface, HCURSOR cursor, BOOL text ) { SetCursor( cursor ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxScreenToClient,8) DECLSPEC_HIDDEN BOOL __thiscall ITextHostImpl_TxScreenToClient( ITextHost2 *iface, POINT *pt ) { struct host *host = impl_from_ITextHost( iface ); return ScreenToClient( host->window, pt ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxClientToScreen,8) DECLSPEC_HIDDEN BOOL __thiscall ITextHostImpl_TxClientToScreen( ITextHost2 *iface, POINT *pt ) { struct host *host = impl_from_ITextHost( iface ); return ClientToScreen( host->window, pt ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxActivate,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxActivate( ITextHost2 *iface, LONG *old_state ) { struct host *host = impl_from_ITextHost( iface ); *old_state = HandleToLong( SetActiveWindow( host->window ) ); return *old_state ? S_OK : E_FAIL; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxDeactivate,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxDeactivate( ITextHost2 *iface, LONG new_state ) { HWND ret = SetActiveWindow( LongToHandle( new_state ) ); return ret ? S_OK : E_FAIL; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetClientRect,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxGetClientRect( ITextHost2 *iface, RECT *rect ) { struct host *host = impl_from_ITextHost( iface ); if (!host->use_set_rect) { *rect = host->client_rect; if (host->client_edge) rect->top += 1; InflateRect( rect, -1, 0 ); } else *rect = host->set_rect; return S_OK; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetViewInset,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxGetViewInset( ITextHost2 *iface, RECT *rect ) { SetRectEmpty( rect ); return S_OK; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetCharFormat,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxGetCharFormat( ITextHost2 *iface, const CHARFORMATW **ppCF ) { return E_NOTIMPL; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetParaFormat,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxGetParaFormat( ITextHost2 *iface, const PARAFORMAT **fmt ) { struct host *host = impl_from_ITextHost( iface ); *fmt = (const PARAFORMAT *)&host->para_fmt; return S_OK; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetSysColor,8) DECLSPEC_HIDDEN COLORREF __thiscall ITextHostImpl_TxGetSysColor( ITextHost2 *iface, int index ) { struct host *host = impl_from_ITextHost( iface ); if (index == COLOR_WINDOW && host->use_back_colour) return host->back_colour; return GetSysColor( index ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetBackStyle,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxGetBackStyle( ITextHost2 *iface, TXTBACKSTYLE *style ) { *style = TXTBACK_OPAQUE; return S_OK; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetMaxLength,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxGetMaxLength( ITextHost2 *iface, DWORD *length ) { *length = INFINITE; return S_OK; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetScrollBars,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxGetScrollBars( ITextHost2 *iface, DWORD *scrollbars ) { struct host *host = impl_from_ITextHost( iface ); *scrollbars = host->scrollbars; return S_OK; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetPasswordChar,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxGetPasswordChar( ITextHost2 *iface, WCHAR *c ) { struct host *host = impl_from_ITextHost( iface ); *c = host->password_char; return *c ? S_OK : S_FALSE; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetAcceleratorPos,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxGetAcceleratorPos( ITextHost2 *iface, LONG *pos ) { *pos = -1; return S_OK; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetExtent,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxGetExtent( ITextHost2 *iface, SIZEL *extent ) { return E_NOTIMPL; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_OnTxCharFormatChange,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_OnTxCharFormatChange( ITextHost2 *iface, const CHARFORMATW *pcf ) { return S_OK; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_OnTxParaFormatChange,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_OnTxParaFormatChange( ITextHost2 *iface, const PARAFORMAT *ppf ) { return S_OK; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetPropertyBits,12) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxGetPropertyBits( ITextHost2 *iface, DWORD mask, DWORD *bits ) { struct host *host = impl_from_ITextHost( iface ); *bits = host->props & mask; return S_OK; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxNotify,12) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxNotify( ITextHost2 *iface, DWORD iNotify, void *pv ) { struct host *host = impl_from_ITextHost( iface ); UINT id; if (!host->parent) return S_OK; id = GetWindowLongW( host->window, GWLP_ID ); switch (iNotify) { case EN_DROPFILES: case EN_LINK: case EN_OLEOPFAILED: case EN_PROTECTED: case EN_REQUESTRESIZE: case EN_SAVECLIPBOARD: case EN_SELCHANGE: case EN_STOPNOUNDO: { /* FIXME: Verify this assumption that pv starts with NMHDR. */ NMHDR *info = pv; if (!info) return E_FAIL; info->hwndFrom = host->window; info->idFrom = id; info->code = iNotify; SendMessageW( host->parent, WM_NOTIFY, id, (LPARAM)info ); break; } case EN_UPDATE: /* Only sent when the window is visible. */ if (!IsWindowVisible( host->window )) break; /* Fall through */ case EN_CHANGE: case EN_ERRSPACE: case EN_HSCROLL: case EN_KILLFOCUS: case EN_MAXTEXT: case EN_SETFOCUS: case EN_VSCROLL: SendMessageW( host->parent, WM_COMMAND, MAKEWPARAM( id, iNotify ), (LPARAM)host->window ); break; case EN_MSGFILTER: FIXME("EN_MSGFILTER is documented as not being sent to TxNotify\n"); /* fall through */ default: return E_FAIL; } return S_OK; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxImmGetContext,4) DECLSPEC_HIDDEN HIMC __thiscall ITextHostImpl_TxImmGetContext( ITextHost2 *iface ) { struct host *host = impl_from_ITextHost( iface ); return ImmGetContext( host->window ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxImmReleaseContext,8) DECLSPEC_HIDDEN void __thiscall ITextHostImpl_TxImmReleaseContext( ITextHost2 *iface, HIMC context ) { struct host *host = impl_from_ITextHost( iface ); ImmReleaseContext( host->window, context ); } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetSelectionBarWidth,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxGetSelectionBarWidth( ITextHost2 *iface, LONG *width ) { struct host *host = impl_from_ITextHost( iface ); *width = host->sel_bar ? 225 : 0; /* in HIMETRIC */ return S_OK; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxIsDoubleClickPending,4) DECLSPEC_HIDDEN BOOL __thiscall ITextHostImpl_TxIsDoubleClickPending( ITextHost2 *iface ) { return FALSE; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetWindow,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxGetWindow( ITextHost2 *iface, HWND *hwnd ) { struct host *host = impl_from_ITextHost( iface ); *hwnd = host->window; return S_OK; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxSetForegroundWindow,4) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxSetForegroundWindow( ITextHost2 *iface ) { return E_NOTIMPL; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetPalette,4) DECLSPEC_HIDDEN HPALETTE __thiscall ITextHostImpl_TxGetPalette( ITextHost2 *iface ) { return NULL; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetEastAsianFlags,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxGetEastAsianFlags( ITextHost2 *iface, LONG *flags ) { return E_NOTIMPL; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxSetCursor2,12) DECLSPEC_HIDDEN HCURSOR __thiscall ITextHostImpl_TxSetCursor2( ITextHost2 *iface, HCURSOR cursor, BOOL text ) { return NULL; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxFreeTextServicesNotification,4) DECLSPEC_HIDDEN void __thiscall ITextHostImpl_TxFreeTextServicesNotification( ITextHost2 *iface ) { return; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetEditStyle,12) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxGetEditStyle( ITextHost2 *iface, DWORD item, DWORD *data ) { return E_NOTIMPL; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetWindowStyles,12) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxGetWindowStyles( ITextHost2 *iface, DWORD *style, DWORD *ex_style ) { return E_NOTIMPL; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxShowDropCaret,16) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxShowDropCaret( ITextHost2 *iface, BOOL show, HDC hdc, const RECT *rect ) { return E_NOTIMPL; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxDestroyCaret,4) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxDestroyCaret( ITextHost2 *iface ) { return E_NOTIMPL; } DEFINE_THISCALL_WRAPPER(ITextHostImpl_TxGetHorzExtent,8) DECLSPEC_HIDDEN HRESULT __thiscall ITextHostImpl_TxGetHorzExtent( ITextHost2 *iface, LONG *horz_extent ) { return E_NOTIMPL; } #ifdef __ASM_USE_THISCALL_WRAPPER #define STDCALL(func) (void *) __stdcall_ ## func #ifdef _MSC_VER #define DEFINE_STDCALL_WRAPPER(num,func,args) \ __declspec(naked) HRESULT __stdcall_##func(void) \ { \ __asm pop eax \ __asm pop ecx \ __asm push eax \ __asm mov eax, [ecx] \ __asm jmp dword ptr [eax + 4*num] \ } #else /* _MSC_VER */ #define DEFINE_STDCALL_WRAPPER(num,func,args) \ extern HRESULT __stdcall_ ## func(void); \ __ASM_GLOBAL_FUNC(__stdcall_ ## func, \ "popl %eax\n\t" \ "popl %ecx\n\t" \ "pushl %eax\n\t" \ "movl (%ecx), %eax\n\t" \ "jmp *(4*(" #num "))(%eax)" ) #endif /* _MSC_VER */ DEFINE_STDCALL_WRAPPER(3,ITextHostImpl_TxGetDC,4) DEFINE_STDCALL_WRAPPER(4,ITextHostImpl_TxReleaseDC,8) DEFINE_STDCALL_WRAPPER(5,ITextHostImpl_TxShowScrollBar,12) DEFINE_STDCALL_WRAPPER(6,ITextHostImpl_TxEnableScrollBar,12) DEFINE_STDCALL_WRAPPER(7,ITextHostImpl_TxSetScrollRange,20) DEFINE_STDCALL_WRAPPER(8,ITextHostImpl_TxSetScrollPos,16) DEFINE_STDCALL_WRAPPER(9,ITextHostImpl_TxInvalidateRect,12) DEFINE_STDCALL_WRAPPER(10,ITextHostImpl_TxViewChange,8) DEFINE_STDCALL_WRAPPER(11,ITextHostImpl_TxCreateCaret,16) DEFINE_STDCALL_WRAPPER(12,ITextHostImpl_TxShowCaret,8) DEFINE_STDCALL_WRAPPER(13,ITextHostImpl_TxSetCaretPos,12) DEFINE_STDCALL_WRAPPER(14,ITextHostImpl_TxSetTimer,12) DEFINE_STDCALL_WRAPPER(15,ITextHostImpl_TxKillTimer,8) DEFINE_STDCALL_WRAPPER(16,ITextHostImpl_TxScrollWindowEx,32) DEFINE_STDCALL_WRAPPER(17,ITextHostImpl_TxSetCapture,8) DEFINE_STDCALL_WRAPPER(18,ITextHostImpl_TxSetFocus,4) DEFINE_STDCALL_WRAPPER(19,ITextHostImpl_TxSetCursor,12) DEFINE_STDCALL_WRAPPER(20,ITextHostImpl_TxScreenToClient,8) DEFINE_STDCALL_WRAPPER(21,ITextHostImpl_TxClientToScreen,8) DEFINE_STDCALL_WRAPPER(22,ITextHostImpl_TxActivate,8) DEFINE_STDCALL_WRAPPER(23,ITextHostImpl_TxDeactivate,8) DEFINE_STDCALL_WRAPPER(24,ITextHostImpl_TxGetClientRect,8) DEFINE_STDCALL_WRAPPER(25,ITextHostImpl_TxGetViewInset,8) DEFINE_STDCALL_WRAPPER(26,ITextHostImpl_TxGetCharFormat,8) DEFINE_STDCALL_WRAPPER(27,ITextHostImpl_TxGetParaFormat,8) DEFINE_STDCALL_WRAPPER(28,ITextHostImpl_TxGetSysColor,8) DEFINE_STDCALL_WRAPPER(29,ITextHostImpl_TxGetBackStyle,8) DEFINE_STDCALL_WRAPPER(30,ITextHostImpl_TxGetMaxLength,8) DEFINE_STDCALL_WRAPPER(31,ITextHostImpl_TxGetScrollBars,8) DEFINE_STDCALL_WRAPPER(32,ITextHostImpl_TxGetPasswordChar,8) DEFINE_STDCALL_WRAPPER(33,ITextHostImpl_TxGetAcceleratorPos,8) DEFINE_STDCALL_WRAPPER(34,ITextHostImpl_TxGetExtent,8) DEFINE_STDCALL_WRAPPER(35,ITextHostImpl_OnTxCharFormatChange,8) DEFINE_STDCALL_WRAPPER(36,ITextHostImpl_OnTxParaFormatChange,8) DEFINE_STDCALL_WRAPPER(37,ITextHostImpl_TxGetPropertyBits,12) DEFINE_STDCALL_WRAPPER(38,ITextHostImpl_TxNotify,12) DEFINE_STDCALL_WRAPPER(39,ITextHostImpl_TxImmGetContext,4) DEFINE_STDCALL_WRAPPER(40,ITextHostImpl_TxImmReleaseContext,8) DEFINE_STDCALL_WRAPPER(41,ITextHostImpl_TxGetSelectionBarWidth,8) /* ITextHost2 */ DEFINE_STDCALL_WRAPPER(42,ITextHostImpl_TxIsDoubleClickPending,4) DEFINE_STDCALL_WRAPPER(43,ITextHostImpl_TxGetWindow,8) DEFINE_STDCALL_WRAPPER(44,ITextHostImpl_TxSetForegroundWindow,4) DEFINE_STDCALL_WRAPPER(45,ITextHostImpl_TxGetPalette,4) DEFINE_STDCALL_WRAPPER(46,ITextHostImpl_TxGetEastAsianFlags,8) DEFINE_STDCALL_WRAPPER(47,ITextHostImpl_TxSetCursor2,12) DEFINE_STDCALL_WRAPPER(48,ITextHostImpl_TxFreeTextServicesNotification,4) DEFINE_STDCALL_WRAPPER(49,ITextHostImpl_TxGetEditStyle,12) DEFINE_STDCALL_WRAPPER(50,ITextHostImpl_TxGetWindowStyles,12) DEFINE_STDCALL_WRAPPER(51,ITextHostImpl_TxShowDropCaret,16) DEFINE_STDCALL_WRAPPER(52,ITextHostImpl_TxDestroyCaret,4) DEFINE_STDCALL_WRAPPER(53,ITextHostImpl_TxGetHorzExtent,8) const ITextHost2Vtbl text_host2_stdcall_vtbl = { NULL, NULL, NULL, STDCALL(ITextHostImpl_TxGetDC), STDCALL(ITextHostImpl_TxReleaseDC), STDCALL(ITextHostImpl_TxShowScrollBar), STDCALL(ITextHostImpl_TxEnableScrollBar), STDCALL(ITextHostImpl_TxSetScrollRange), STDCALL(ITextHostImpl_TxSetScrollPos), STDCALL(ITextHostImpl_TxInvalidateRect), STDCALL(ITextHostImpl_TxViewChange), STDCALL(ITextHostImpl_TxCreateCaret), STDCALL(ITextHostImpl_TxShowCaret), STDCALL(ITextHostImpl_TxSetCaretPos), STDCALL(ITextHostImpl_TxSetTimer), STDCALL(ITextHostImpl_TxKillTimer), STDCALL(ITextHostImpl_TxScrollWindowEx), STDCALL(ITextHostImpl_TxSetCapture), STDCALL(ITextHostImpl_TxSetFocus), STDCALL(ITextHostImpl_TxSetCursor), STDCALL(ITextHostImpl_TxScreenToClient), STDCALL(ITextHostImpl_TxClientToScreen), STDCALL(ITextHostImpl_TxActivate), STDCALL(ITextHostImpl_TxDeactivate), STDCALL(ITextHostImpl_TxGetClientRect), STDCALL(ITextHostImpl_TxGetViewInset), STDCALL(ITextHostImpl_TxGetCharFormat), STDCALL(ITextHostImpl_TxGetParaFormat), STDCALL(ITextHostImpl_TxGetSysColor), STDCALL(ITextHostImpl_TxGetBackStyle), STDCALL(ITextHostImpl_TxGetMaxLength), STDCALL(ITextHostImpl_TxGetScrollBars), STDCALL(ITextHostImpl_TxGetPasswordChar), STDCALL(ITextHostImpl_TxGetAcceleratorPos), STDCALL(ITextHostImpl_TxGetExtent), STDCALL(ITextHostImpl_OnTxCharFormatChange), STDCALL(ITextHostImpl_OnTxParaFormatChange), STDCALL(ITextHostImpl_TxGetPropertyBits), STDCALL(ITextHostImpl_TxNotify), STDCALL(ITextHostImpl_TxImmGetContext), STDCALL(ITextHostImpl_TxImmReleaseContext), STDCALL(ITextHostImpl_TxGetSelectionBarWidth), /* ITextHost2 */ STDCALL(ITextHostImpl_TxIsDoubleClickPending), STDCALL(ITextHostImpl_TxGetWindow), STDCALL(ITextHostImpl_TxSetForegroundWindow), STDCALL(ITextHostImpl_TxGetPalette), STDCALL(ITextHostImpl_TxGetEastAsianFlags), STDCALL(ITextHostImpl_TxSetCursor2), STDCALL(ITextHostImpl_TxFreeTextServicesNotification), STDCALL(ITextHostImpl_TxGetEditStyle), STDCALL(ITextHostImpl_TxGetWindowStyles), STDCALL(ITextHostImpl_TxShowDropCaret), STDCALL(ITextHostImpl_TxDestroyCaret), STDCALL(ITextHostImpl_TxGetHorzExtent) }; #endif /* __ASM_USE_THISCALL_WRAPPER */ static const ITextHost2Vtbl textHostVtbl = { ITextHostImpl_QueryInterface, ITextHostImpl_AddRef, ITextHostImpl_Release, THISCALL(ITextHostImpl_TxGetDC), THISCALL(ITextHostImpl_TxReleaseDC), THISCALL(ITextHostImpl_TxShowScrollBar), THISCALL(ITextHostImpl_TxEnableScrollBar), THISCALL(ITextHostImpl_TxSetScrollRange), THISCALL(ITextHostImpl_TxSetScrollPos), THISCALL(ITextHostImpl_TxInvalidateRect), THISCALL(ITextHostImpl_TxViewChange), THISCALL(ITextHostImpl_TxCreateCaret), THISCALL(ITextHostImpl_TxShowCaret), THISCALL(ITextHostImpl_TxSetCaretPos), THISCALL(ITextHostImpl_TxSetTimer), THISCALL(ITextHostImpl_TxKillTimer), THISCALL(ITextHostImpl_TxScrollWindowEx), THISCALL(ITextHostImpl_TxSetCapture), THISCALL(ITextHostImpl_TxSetFocus), THISCALL(ITextHostImpl_TxSetCursor), THISCALL(ITextHostImpl_TxScreenToClient), THISCALL(ITextHostImpl_TxClientToScreen), THISCALL(ITextHostImpl_TxActivate), THISCALL(ITextHostImpl_TxDeactivate), THISCALL(ITextHostImpl_TxGetClientRect), THISCALL(ITextHostImpl_TxGetViewInset), THISCALL(ITextHostImpl_TxGetCharFormat), THISCALL(ITextHostImpl_TxGetParaFormat), THISCALL(ITextHostImpl_TxGetSysColor), THISCALL(ITextHostImpl_TxGetBackStyle), THISCALL(ITextHostImpl_TxGetMaxLength), THISCALL(ITextHostImpl_TxGetScrollBars), THISCALL(ITextHostImpl_TxGetPasswordChar), THISCALL(ITextHostImpl_TxGetAcceleratorPos), THISCALL(ITextHostImpl_TxGetExtent), THISCALL(ITextHostImpl_OnTxCharFormatChange), THISCALL(ITextHostImpl_OnTxParaFormatChange), THISCALL(ITextHostImpl_TxGetPropertyBits), THISCALL(ITextHostImpl_TxNotify), THISCALL(ITextHostImpl_TxImmGetContext), THISCALL(ITextHostImpl_TxImmReleaseContext), THISCALL(ITextHostImpl_TxGetSelectionBarWidth), /* ITextHost2 */ THISCALL(ITextHostImpl_TxIsDoubleClickPending), THISCALL(ITextHostImpl_TxGetWindow), THISCALL(ITextHostImpl_TxSetForegroundWindow), THISCALL(ITextHostImpl_TxGetPalette), THISCALL(ITextHostImpl_TxGetEastAsianFlags), THISCALL(ITextHostImpl_TxSetCursor2), THISCALL(ITextHostImpl_TxFreeTextServicesNotification), THISCALL(ITextHostImpl_TxGetEditStyle), THISCALL(ITextHostImpl_TxGetWindowStyles), THISCALL(ITextHostImpl_TxShowDropCaret), THISCALL(ITextHostImpl_TxDestroyCaret), THISCALL(ITextHostImpl_TxGetHorzExtent) }; static const char * const edit_messages[] = { "EM_GETSEL", "EM_SETSEL", "EM_GETRECT", "EM_SETRECT", "EM_SETRECTNP", "EM_SCROLL", "EM_LINESCROLL", "EM_SCROLLCARET", "EM_GETMODIFY", "EM_SETMODIFY", "EM_GETLINECOUNT", "EM_LINEINDEX", "EM_SETHANDLE", "EM_GETHANDLE", "EM_GETTHUMB", "EM_UNKNOWN_BF", "EM_UNKNOWN_C0", "EM_LINELENGTH", "EM_REPLACESEL", "EM_UNKNOWN_C3", "EM_GETLINE", "EM_LIMITTEXT", "EM_CANUNDO", "EM_UNDO", "EM_FMTLINES", "EM_LINEFROMCHAR", "EM_UNKNOWN_CA", "EM_SETTABSTOPS", "EM_SETPASSWORDCHAR", "EM_EMPTYUNDOBUFFER", "EM_GETFIRSTVISIBLELINE", "EM_SETREADONLY", "EM_SETWORDBREAKPROC", "EM_GETWORDBREAKPROC", "EM_GETPASSWORDCHAR", "EM_SETMARGINS", "EM_GETMARGINS", "EM_GETLIMITTEXT", "EM_POSFROMCHAR", "EM_CHARFROMPOS", "EM_SETIMESTATUS", "EM_GETIMESTATUS" }; static const char * const richedit_messages[] = { "EM_CANPASTE", "EM_DISPLAYBAND", "EM_EXGETSEL", "EM_EXLIMITTEXT", "EM_EXLINEFROMCHAR", "EM_EXSETSEL", "EM_FINDTEXT", "EM_FORMATRANGE", "EM_GETCHARFORMAT", "EM_GETEVENTMASK", "EM_GETOLEINTERFACE", "EM_GETPARAFORMAT", "EM_GETSELTEXT", "EM_HIDESELECTION", "EM_PASTESPECIAL", "EM_REQUESTRESIZE", "EM_SELECTIONTYPE", "EM_SETBKGNDCOLOR", "EM_SETCHARFORMAT", "EM_SETEVENTMASK", "EM_SETOLECALLBACK", "EM_SETPARAFORMAT", "EM_SETTARGETDEVICE", "EM_STREAMIN", "EM_STREAMOUT", "EM_GETTEXTRANGE", "EM_FINDWORDBREAK", "EM_SETOPTIONS", "EM_GETOPTIONS", "EM_FINDTEXTEX", "EM_GETWORDBREAKPROCEX", "EM_SETWORDBREAKPROCEX", "EM_SETUNDOLIMIT", "EM_UNKNOWN_USER_83", "EM_REDO", "EM_CANREDO", "EM_GETUNDONAME", "EM_GETREDONAME", "EM_STOPGROUPTYPING", "EM_SETTEXTMODE", "EM_GETTEXTMODE", "EM_AUTOURLDETECT", "EM_GETAUTOURLDETECT", "EM_SETPALETTE", "EM_GETTEXTEX", "EM_GETTEXTLENGTHEX", "EM_SHOWSCROLLBAR", "EM_SETTEXTEX", "EM_UNKNOWN_USER_98", "EM_UNKNOWN_USER_99", "EM_SETPUNCTUATION", "EM_GETPUNCTUATION", "EM_SETWORDWRAPMODE", "EM_GETWORDWRAPMODE", "EM_SETIMECOLOR", "EM_GETIMECOLOR", "EM_SETIMEOPTIONS", "EM_GETIMEOPTIONS", "EM_CONVPOSITION", "EM_UNKNOWN_USER_109", "EM_UNKNOWN_USER_110", "EM_UNKNOWN_USER_111", "EM_UNKNOWN_USER_112", "EM_UNKNOWN_USER_113", "EM_UNKNOWN_USER_114", "EM_UNKNOWN_USER_115", "EM_UNKNOWN_USER_116", "EM_UNKNOWN_USER_117", "EM_UNKNOWN_USER_118", "EM_UNKNOWN_USER_119", "EM_SETLANGOPTIONS", "EM_GETLANGOPTIONS", "EM_GETIMECOMPMODE", "EM_FINDTEXTW", "EM_FINDTEXTEXW", "EM_RECONVERSION", "EM_SETIMEMODEBIAS", "EM_GETIMEMODEBIAS" }; static const char *get_msg_name( UINT msg ) { if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS) return edit_messages[msg - EM_GETSEL]; if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS) return richedit_messages[msg - EM_CANPASTE]; return ""; } static BOOL create_windowed_editor( HWND hwnd, CREATESTRUCTW *create, BOOL emulate_10 ) { struct host *host = host_create( hwnd, create, emulate_10 ); IUnknown *unk; HRESULT hr; if (!host) return FALSE; hr = create_text_services( NULL, (ITextHost *)&host->ITextHost_iface, &unk, emulate_10 ); if (FAILED( hr )) { ITextHost2_Release( &host->ITextHost_iface ); return FALSE; } IUnknown_QueryInterface( unk, &IID_ITextServices, (void **)&host->text_srv ); IUnknown_Release( unk ); SetWindowLongPtrW( hwnd, 0, (LONG_PTR)host ); return TRUE; } static HRESULT get_lineA( ITextServices *text_srv, WPARAM wparam, LPARAM lparam, LRESULT *res ) { LRESULT len = USHRT_MAX; WORD sizeA; HRESULT hr; WCHAR *buf; *res = 0; sizeA = *(WORD *)lparam; *(WORD *)lparam = 0; if (!sizeA) return S_OK; buf = heap_alloc( len * sizeof(WCHAR) ); if (!buf) return E_OUTOFMEMORY; *(WORD *)buf = len; hr = ITextServices_TxSendMessage( text_srv, EM_GETLINE, wparam, (LPARAM)buf, &len ); if (hr == S_OK && len) { len = WideCharToMultiByte( CP_ACP, 0, buf, len, (char *)lparam, sizeA, NULL, NULL ); if (!len && GetLastError() == ERROR_INSUFFICIENT_BUFFER) len = sizeA; if (len < sizeA) ((char *)lparam)[len] = '\0'; *res = len; } heap_free( buf ); return hr; } static HRESULT get_text_rangeA( struct host *host, TEXTRANGEA *rangeA, LRESULT *res ) { TEXTRANGEW range; HRESULT hr; unsigned int count; LRESULT len; *res = 0; if (rangeA->chrg.cpMin < 0) return S_OK; ITextServices_TxSendMessage( host->text_srv, WM_GETTEXTLENGTH, 0, 0, &len ); range.chrg = rangeA->chrg; if ((range.chrg.cpMin == 0 && range.chrg.cpMax == -1) || range.chrg.cpMax > len) range.chrg.cpMax = len; if (range.chrg.cpMin >= range.chrg.cpMax) return S_OK; count = range.chrg.cpMax - range.chrg.cpMin + 1; range.lpstrText = heap_alloc( count * sizeof(WCHAR) ); if (!range.lpstrText) return E_OUTOFMEMORY; hr = ITextServices_TxSendMessage( host->text_srv, EM_GETTEXTRANGE, 0, (LPARAM)&range, &len ); if (hr == S_OK && len) { if (!host->emulate_10) count = INT_MAX; len = WideCharToMultiByte( CP_ACP, 0, range.lpstrText, -1, rangeA->lpstrText, count, NULL, NULL ); if (!host->emulate_10) *res = len - 1; else { *res = count - 1; rangeA->lpstrText[*res] = '\0'; } } heap_free( range.lpstrText ); return hr; } static HRESULT set_options( struct host *host, DWORD op, DWORD value, LRESULT *res ) { DWORD style, old_options, new_options, change, props_mask = 0; DWORD mask = ECO_AUTOWORDSELECTION | ECO_AUTOVSCROLL | ECO_AUTOHSCROLL | ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SAVESEL | ECO_SELECTIONBAR | ECO_VERTICAL; new_options = old_options = SendMessageW( host->window, EM_GETOPTIONS, 0, 0 ); switch (op) { case ECOOP_SET: new_options = value; break; case ECOOP_OR: new_options |= value; break; case ECOOP_AND: new_options &= value; break; case ECOOP_XOR: new_options ^= value; } new_options &= mask; change = (new_options ^ old_options); if (change & ECO_AUTOWORDSELECTION) { host->props ^= TXTBIT_AUTOWORDSEL; props_mask |= TXTBIT_AUTOWORDSEL; } if (change & ECO_AUTOVSCROLL) { host->scrollbars ^= WS_VSCROLL; props_mask |= TXTBIT_SCROLLBARCHANGE; } if (change & ECO_AUTOHSCROLL) { host->scrollbars ^= WS_HSCROLL; props_mask |= TXTBIT_SCROLLBARCHANGE; } if (change & ECO_NOHIDESEL) { host->props ^= TXTBIT_HIDESELECTION; props_mask |= TXTBIT_HIDESELECTION; } if (change & ECO_READONLY) { host->props ^= TXTBIT_READONLY; props_mask |= TXTBIT_READONLY; } if (change & ECO_SAVESEL) { host->props ^= TXTBIT_SAVESELECTION; props_mask |= TXTBIT_SAVESELECTION; } if (change & ECO_SELECTIONBAR) { host->sel_bar ^= 1; props_mask |= TXTBIT_SELBARCHANGE; if (host->use_set_rect) { int width = SELECTIONBAR_WIDTH; host->set_rect.left += host->sel_bar ? width : -width; props_mask |= TXTBIT_CLIENTRECTCHANGE; } } if (change & ECO_VERTICAL) { host->props ^= TXTBIT_VERTICAL; props_mask |= TXTBIT_VERTICAL; } if (change & ECO_WANTRETURN) host->want_return ^= 1; if (props_mask) ITextServices_OnTxPropertyBitsChange( host->text_srv, props_mask, host->props & props_mask ); *res = new_options; mask &= ~ECO_AUTOWORDSELECTION; /* doesn't correspond to a window style */ style = GetWindowLongW( host->window, GWL_STYLE ); style = (style & ~mask) | (*res & mask); SetWindowLongW( host->window, GWL_STYLE, style ); return S_OK; } /* handle dialog mode VK_RETURN. Returns TRUE if message has been processed */ static BOOL handle_dialog_enter( struct host *host ) { BOOL ctrl_is_down = GetKeyState( VK_CONTROL ) & 0x8000; if (ctrl_is_down) return TRUE; if (host->want_return) return FALSE; if (host->parent) { DWORD id = SendMessageW( host->parent, DM_GETDEFID, 0, 0 ); if (HIWORD( id ) == DC_HASDEFID) { HWND ctrl = GetDlgItem( host->parent, LOWORD( id )); if (ctrl) { SendMessageW( host->parent, WM_NEXTDLGCTL, (WPARAM)ctrl, TRUE ); PostMessageW( ctrl, WM_KEYDOWN, VK_RETURN, 0 ); } } } return TRUE; } static LRESULT send_msg_filter( struct host *host, UINT msg, WPARAM *wparam, LPARAM *lparam ) { MSGFILTER msgf; LRESULT res; if (!host->parent) return 0; msgf.nmhdr.hwndFrom = host->window; msgf.nmhdr.idFrom = GetWindowLongW( host->window, GWLP_ID ); msgf.nmhdr.code = EN_MSGFILTER; msgf.msg = msg; msgf.wParam = *wparam; msgf.lParam = *lparam; if ((res = SendMessageW( host->parent, WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf ))) return res; *wparam = msgf.wParam; *lparam = msgf.lParam; return 0; } static LRESULT RichEditWndProc_common( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam, BOOL unicode ) { struct host *host; HRESULT hr = S_OK; LRESULT res = 0; TRACE( "enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n", hwnd, msg, get_msg_name(msg), wparam, lparam, unicode ); host = (struct host *)GetWindowLongPtrW( hwnd, 0 ); if (!host) { if (msg == WM_NCCREATE) { CREATESTRUCTW *pcs = (CREATESTRUCTW *)lparam; TRACE( "WM_NCCREATE: hwnd %p style 0x%08x\n", hwnd, pcs->style ); return create_windowed_editor( hwnd, pcs, FALSE ); } else return DefWindowProcW( hwnd, msg, wparam, lparam ); } if ((((host->event_mask & ENM_KEYEVENTS) && msg >= WM_KEYFIRST && msg <= WM_KEYLAST) || ((host->event_mask & ENM_MOUSEEVENTS) && msg >= WM_MOUSEFIRST && msg <= WM_MOUSELAST) || ((host->event_mask & ENM_SCROLLEVENTS) && msg >= WM_HSCROLL && msg <= WM_VSCROLL))) { host->notify_level++; res = send_msg_filter( host, msg, &wparam, &lparam ); if (!--host->notify_level && host->defer_release) { TRACE( "exit (filtered deferred release) hwnd %p msg %04x (%s) %lx %lx -> 0\n", hwnd, msg, get_msg_name(msg), wparam, lparam ); ITextHost2_Release( &host->ITextHost_iface ); return 0; } if (res) { TRACE( "exit (filtered %lu) hwnd %p msg %04x (%s) %lx %lx -> 0\n", res, hwnd, msg, get_msg_name(msg), wparam, lparam ); return 0; } } switch (msg) { case WM_CHAR: { WCHAR wc = wparam; if (!unicode) MultiByteToWideChar( CP_ACP, 0, (char *)&wparam, 1, &wc, 1 ); if (wparam == '\r' && host->dialog_mode && host->emulate_10 && handle_dialog_enter( host )) break; hr = ITextServices_TxSendMessage( host->text_srv, msg, wc, lparam, &res ); break; } case WM_CREATE: { CREATESTRUCTW *createW = (CREATESTRUCTW *)lparam; CREATESTRUCTA *createA = (CREATESTRUCTA *)lparam; void *text; WCHAR *textW = NULL; LONG codepage = unicode ? CP_UNICODE : CP_ACP; int len; ITextServices_OnTxInPlaceActivate( host->text_srv, NULL ); if (lparam) { text = unicode ? (void *)createW->lpszName : (void *)createA->lpszName; textW = ME_ToUnicode( codepage, text, &len ); } ITextServices_TxSetText( host->text_srv, textW ); if (lparam) ME_EndToUnicode( codepage, textW ); break; } case WM_DESTROY: if (!host->notify_level) ITextHost2_Release( &host->ITextHost_iface ); else host->defer_release = 1; return 0; case WM_ERASEBKGND: { HDC hdc = (HDC)wparam; RECT rc; HBRUSH brush; if (GetUpdateRect( hwnd, &rc, TRUE )) { brush = CreateSolidBrush( ITextHost_TxGetSysColor( &host->ITextHost_iface, COLOR_WINDOW ) ); FillRect( hdc, &rc, brush ); DeleteObject( brush ); } return 1; } case EM_FINDTEXT: { FINDTEXTW *params = (FINDTEXTW *)lparam; FINDTEXTW new_params; int len; if (!unicode) { new_params.chrg = params->chrg; new_params.lpstrText = ME_ToUnicode( CP_ACP, (char *)params->lpstrText, &len ); params = &new_params; } hr = ITextServices_TxSendMessage( host->text_srv, EM_FINDTEXTW, wparam, (LPARAM)params, &res ); if (!unicode) ME_EndToUnicode( CP_ACP, (WCHAR *)new_params.lpstrText ); break; } case EM_FINDTEXTEX: { FINDTEXTEXA *paramsA = (FINDTEXTEXA *)lparam; FINDTEXTEXW *params = (FINDTEXTEXW *)lparam; FINDTEXTEXW new_params; int len; if (!unicode) { new_params.chrg = params->chrg; new_params.lpstrText = ME_ToUnicode( CP_ACP, (char *)params->lpstrText, &len ); params = &new_params; } hr = ITextServices_TxSendMessage( host->text_srv, EM_FINDTEXTEXW, wparam, (LPARAM)params, &res ); if (!unicode) { ME_EndToUnicode( CP_ACP, (WCHAR *)new_params.lpstrText ); paramsA->chrgText = params->chrgText; } break; } case WM_GETDLGCODE: if (lparam) host->dialog_mode = TRUE; res = DLGC_WANTCHARS | DLGC_WANTTAB | DLGC_WANTARROWS; if (host->props & TXTBIT_MULTILINE) res |= DLGC_WANTMESSAGE; if (!(host->props & TXTBIT_SAVESELECTION)) res |= DLGC_HASSETSEL; break; case EM_GETLINE: if (unicode) hr = ITextServices_TxSendMessage( host->text_srv, msg, wparam, lparam, &res ); else hr = get_lineA( host->text_srv, wparam, lparam, &res ); break; case EM_GETPASSWORDCHAR: ITextHost_TxGetPasswordChar( &host->ITextHost_iface, (WCHAR *)&res ); break; case EM_GETRECT: hr = ITextHost_TxGetClientRect( &host->ITextHost_iface, (RECT *)lparam ); break; case EM_GETSELTEXT: { TEXTRANGEA range; if (unicode) hr = ITextServices_TxSendMessage( host->text_srv, msg, wparam, lparam, &res ); else { ITextServices_TxSendMessage( host->text_srv, EM_EXGETSEL, 0, (LPARAM)&range.chrg, &res ); range.lpstrText = (char *)lparam; range.lpstrText[0] = '\0'; hr = get_text_rangeA( host, &range, &res ); } break; } case EM_GETOPTIONS: if (host->props & TXTBIT_READONLY) res |= ECO_READONLY; if (!(host->props & TXTBIT_HIDESELECTION)) res |= ECO_NOHIDESEL; if (host->props & TXTBIT_SAVESELECTION) res |= ECO_SAVESEL; if (host->props & TXTBIT_AUTOWORDSEL) res |= ECO_AUTOWORDSELECTION; if (host->props & TXTBIT_VERTICAL) res |= ECO_VERTICAL; if (host->scrollbars & ES_AUTOHSCROLL) res |= ECO_AUTOHSCROLL; if (host->scrollbars & ES_AUTOVSCROLL) res |= ECO_AUTOVSCROLL; if (host->want_return) res |= ECO_WANTRETURN; if (host->sel_bar) res |= ECO_SELECTIONBAR; break; case WM_GETTEXT: { GETTEXTEX params; params.cb = wparam * (unicode ? sizeof(WCHAR) : sizeof(CHAR)); params.flags = GT_USECRLF; params.codepage = unicode ? CP_UNICODE : CP_ACP; params.lpDefaultChar = NULL; params.lpUsedDefChar = NULL; hr = ITextServices_TxSendMessage( host->text_srv, EM_GETTEXTEX, (WPARAM)&params, lparam, &res ); break; } case WM_GETTEXTLENGTH: { GETTEXTLENGTHEX params; params.flags = GTL_CLOSE | (host->emulate_10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS; params.codepage = unicode ? CP_UNICODE : CP_ACP; hr = ITextServices_TxSendMessage( host->text_srv, EM_GETTEXTLENGTHEX, (WPARAM)&params, 0, &res ); break; } case EM_GETTEXTRANGE: if (unicode) hr = ITextServices_TxSendMessage( host->text_srv, msg, wparam, lparam, &res ); else hr = get_text_rangeA( host, (TEXTRANGEA *)lparam, &res ); break; case WM_KEYDOWN: switch (LOWORD( wparam )) { case VK_ESCAPE: if (host->dialog_mode && host->parent) PostMessageW( host->parent, WM_CLOSE, 0, 0 ); break; case VK_TAB: if (host->dialog_mode && host->parent) SendMessageW( host->parent, WM_NEXTDLGCTL, GetKeyState( VK_SHIFT ) & 0x8000, 0 ); break; case VK_RETURN: if (host->dialog_mode && !host->emulate_10 && handle_dialog_enter( host )) break; /* fall through */ default: hr = ITextServices_TxSendMessage( host->text_srv, msg, wparam, lparam, &res ); } break; case WM_PAINT: case WM_PRINTCLIENT: { HDC hdc; RECT rc, client, update; PAINTSTRUCT ps; HBRUSH brush = CreateSolidBrush( ITextHost_TxGetSysColor( &host->ITextHost_iface, COLOR_WINDOW ) ); ITextHost_TxGetClientRect( &host->ITextHost_iface, &client ); if (msg == WM_PAINT) { hdc = BeginPaint( hwnd, &ps ); update = ps.rcPaint; } else { hdc = (HDC)wparam; update = client; } brush = SelectObject( hdc, brush ); /* Erase area outside of the formatting rectangle */ if (update.top < client.top) { rc = update; rc.bottom = client.top; PatBlt( hdc, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, PATCOPY ); update.top = client.top; } if (update.bottom > client.bottom) { rc = update; rc.top = client.bottom; PatBlt( hdc, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, PATCOPY ); update.bottom = client.bottom; } if (update.left < client.left) { rc = update; rc.right = client.left; PatBlt( hdc, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, PATCOPY ); update.left = client.left; } if (update.right > client.right) { rc = update; rc.left = client.right; PatBlt( hdc, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, PATCOPY ); update.right = client.right; } ITextServices_TxDraw( host->text_srv, DVASPECT_CONTENT, 0, NULL, NULL, hdc, NULL, NULL, NULL, &update, NULL, 0, TXTVIEW_ACTIVE ); DeleteObject( SelectObject( hdc, brush ) ); if (msg == WM_PAINT) EndPaint( hwnd, &ps ); return 0; } case EM_REPLACESEL: { int len; LONG codepage = unicode ? CP_UNICODE : CP_ACP; WCHAR *text = ME_ToUnicode( codepage, (void *)lparam, &len ); hr = ITextServices_TxSendMessage( host->text_srv, msg, wparam, (LPARAM)text, &res ); ME_EndToUnicode( codepage, text ); res = len; break; } case EM_SETBKGNDCOLOR: res = ITextHost_TxGetSysColor( &host->ITextHost_iface, COLOR_WINDOW ); host->use_back_colour = !wparam; if (host->use_back_colour) host->back_colour = lparam; InvalidateRect( hwnd, NULL, TRUE ); break; case WM_SETCURSOR: { POINT pos; RECT rect; if (hwnd != (HWND)wparam) break; GetCursorPos( &pos ); ScreenToClient( hwnd, &pos ); ITextHost_TxGetClientRect( &host->ITextHost_iface, &rect ); if (PtInRect( &rect, pos )) ITextServices_OnTxSetCursor( host->text_srv, DVASPECT_CONTENT, 0, NULL, NULL, NULL, NULL, NULL, pos.x, pos.y ); else ITextHost_TxSetCursor( &host->ITextHost_iface, LoadCursorW( NULL, MAKEINTRESOURCEW( IDC_ARROW ) ), FALSE ); break; } case EM_SETEVENTMASK: host->event_mask = lparam; hr = ITextServices_TxSendMessage( host->text_srv, msg, wparam, lparam, &res ); break; case EM_SETOPTIONS: hr = set_options( host, wparam, lparam, &res ); break; case EM_SETPASSWORDCHAR: if (wparam == host->password_char) break; host->password_char = wparam; if (wparam) host->props |= TXTBIT_USEPASSWORD; else host->props &= ~TXTBIT_USEPASSWORD; ITextServices_OnTxPropertyBitsChange( host->text_srv, TXTBIT_USEPASSWORD, host->props & TXTBIT_USEPASSWORD ); break; case EM_SETREADONLY: { DWORD op = wparam ? ECOOP_OR : ECOOP_AND; DWORD mask = wparam ? ECO_READONLY : ~ECO_READONLY; SendMessageW( hwnd, EM_SETOPTIONS, op, mask ); return 1; } case EM_SETRECT: case EM_SETRECTNP: { RECT *rc = (RECT *)lparam; if (!rc) host->use_set_rect = 0; else { if (wparam >= 2) break; host->set_rect = *rc; if (host->client_edge) { InflateRect( &host->set_rect, 1, 0 ); host->set_rect.top -= 1; } if (!wparam) IntersectRect( &host->set_rect, &host->set_rect, &host->client_rect ); host->use_set_rect = 1; } ITextServices_OnTxPropertyBitsChange( host->text_srv, TXTBIT_CLIENTRECTCHANGE, 0 ); break; } case WM_SETTEXT: { char *textA = (char *)lparam; WCHAR *text = (WCHAR *)lparam; int len; if (!unicode && textA && strncmp( textA, "{\\rtf", 5 ) && strncmp( textA, "{\\urtf", 6 )) text = ME_ToUnicode( CP_ACP, textA, &len ); hr = ITextServices_TxSendMessage( host->text_srv, msg, wparam, (LPARAM)text, &res ); if (text != (WCHAR *)lparam) ME_EndToUnicode( CP_ACP, text ); break; } case EM_SHOWSCROLLBAR: { DWORD mask = 0, new; if (wparam == SB_HORZ) mask = WS_HSCROLL; else if (wparam == SB_VERT) mask = WS_VSCROLL; else if (wparam == SB_BOTH) mask = WS_HSCROLL | WS_VSCROLL; if (mask) { new = lparam ? mask : 0; if ((host->scrollbars & mask) != new) { host->scrollbars &= ~mask; host->scrollbars |= new; ITextServices_OnTxPropertyBitsChange( host->text_srv, TXTBIT_SCROLLBARCHANGE, 0 ); } } res = 0; break; } case WM_WINDOWPOSCHANGED: { RECT client; WINDOWPOS *winpos = (WINDOWPOS *)lparam; hr = S_FALSE; /* call defwndproc */ if (winpos->flags & SWP_NOCLIENTSIZE) break; GetClientRect( hwnd, &client ); if (host->use_set_rect) { host->set_rect.right += client.right - host->client_rect.right; host->set_rect.bottom += client.bottom - host->client_rect.bottom; } host->client_rect = client; ITextServices_OnTxPropertyBitsChange( host->text_srv, TXTBIT_CLIENTRECTCHANGE, 0 ); break; } default: hr = ITextServices_TxSendMessage( host->text_srv, msg, wparam, lparam, &res ); } if (hr == S_FALSE) res = DefWindowProcW( hwnd, msg, wparam, lparam ); TRACE( "exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n", hwnd, msg, get_msg_name(msg), wparam, lparam, unicode, res ); return res; } static LRESULT WINAPI RichEditWndProcW( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam ) { BOOL unicode = TRUE; /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */ if (msg == WM_GETTEXT && (GetVersion() & 0x80000000)) unicode = FALSE; return RichEditWndProc_common( hwnd, msg, wparam, lparam, unicode ); } static LRESULT WINAPI RichEditWndProcA( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam ) { return RichEditWndProc_common( hwnd, msg, wparam, lparam, FALSE ); } /****************************************************************** * RichEditANSIWndProc (RICHED20.10) */ LRESULT WINAPI RichEditANSIWndProc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam ) { return RichEditWndProcA( hwnd, msg, wparam, lparam ); } /****************************************************************** * RichEdit10ANSIWndProc (RICHED20.9) */ LRESULT WINAPI RichEdit10ANSIWndProc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam ) { if (msg == WM_NCCREATE && !GetWindowLongPtrW( hwnd, 0 )) { CREATESTRUCTW *pcs = (CREATESTRUCTW *)lparam; TRACE( "WM_NCCREATE: hwnd %p style 0x%08x\n", hwnd, pcs->style ); return create_windowed_editor( hwnd, pcs, TRUE ); } return RichEditANSIWndProc( hwnd, msg, wparam, lparam ); } static LRESULT WINAPI REComboWndProc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam ) { /* FIXME: Not implemented */ TRACE( "hwnd %p msg %04x (%s) %08lx %08lx\n", hwnd, msg, get_msg_name( msg ), wparam, lparam ); return DefWindowProcW( hwnd, msg, wparam, lparam ); } static LRESULT WINAPI REListWndProc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam ) { /* FIXME: Not implemented */ TRACE( "hwnd %p msg %04x (%s) %08lx %08lx\n", hwnd, msg, get_msg_name( msg ), wparam, lparam ); return DefWindowProcW( hwnd, msg, wparam, lparam ); } /****************************************************************** * REExtendedRegisterClass (RICHED20.8) * * FIXME undocumented * Need to check for errors and implement controls and callbacks */ LRESULT WINAPI REExtendedRegisterClass( void ) { WNDCLASSW wc; UINT result; FIXME( "semi stub\n" ); wc.cbClsExtra = 0; wc.cbWndExtra = 4; wc.hInstance = NULL; wc.hIcon = NULL; wc.hCursor = NULL; wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wc.lpszMenuName = NULL; if (!listbox_registered) { wc.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS; wc.lpfnWndProc = REListWndProc; wc.lpszClassName = L"REListBox20W"; if (RegisterClassW( &wc )) listbox_registered = TRUE; } if (!combobox_registered) { wc.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW; wc.lpfnWndProc = REComboWndProc; wc.lpszClassName = L"REComboBox20W"; if (RegisterClassW( &wc )) combobox_registered = TRUE; } result = 0; if (listbox_registered) result += 1; if (combobox_registered) result += 2; return result; } static BOOL register_classes( HINSTANCE instance ) { WNDCLASSW wcW; WNDCLASSA wcA; wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS; wcW.lpfnWndProc = RichEditWndProcW; wcW.cbClsExtra = 0; wcW.cbWndExtra = sizeof(struct host *); wcW.hInstance = NULL; /* hInstance would register DLL-local class */ wcW.hIcon = NULL; wcW.hCursor = LoadCursorW( NULL, (LPWSTR)IDC_IBEAM ); wcW.hbrBackground = GetStockObject( NULL_BRUSH ); wcW.lpszMenuName = NULL; if (!(GetVersion() & 0x80000000)) { wcW.lpszClassName = RICHEDIT_CLASS20W; if (!RegisterClassW( &wcW )) return FALSE; wcW.lpszClassName = MSFTEDIT_CLASS; if (!RegisterClassW( &wcW )) return FALSE; } else { /* WNDCLASSA/W have the same layout */ wcW.lpszClassName = (LPCWSTR)"RichEdit20W"; if (!RegisterClassA( (WNDCLASSA *)&wcW )) return FALSE; wcW.lpszClassName = (LPCWSTR)"RichEdit50W"; if (!RegisterClassA( (WNDCLASSA *)&wcW )) return FALSE; } wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS; wcA.lpfnWndProc = RichEditWndProcA; wcA.cbClsExtra = 0; wcA.cbWndExtra = sizeof(struct host *); wcA.hInstance = NULL; /* hInstance would register DLL-local class */ wcA.hIcon = NULL; wcA.hCursor = LoadCursorW( NULL, (LPWSTR)IDC_IBEAM ); wcA.hbrBackground = GetStockObject(NULL_BRUSH); wcA.lpszMenuName = NULL; wcA.lpszClassName = RICHEDIT_CLASS20A; if (!RegisterClassA( &wcA )) return FALSE; wcA.lpszClassName = "RichEdit50A"; if (!RegisterClassA( &wcA )) return FALSE; return TRUE; } BOOL WINAPI DllMain( HINSTANCE instance, DWORD reason, void *reserved ) { switch (reason) { case DLL_PROCESS_ATTACH: dll_instance = instance; DisableThreadLibraryCalls( instance ); if (!register_classes( instance )) return FALSE; LookupInit(); break; case DLL_PROCESS_DETACH: if (reserved) break; UnregisterClassW( RICHEDIT_CLASS20W, 0 ); UnregisterClassW( MSFTEDIT_CLASS, 0 ); UnregisterClassA( RICHEDIT_CLASS20A, 0 ); UnregisterClassA( "RichEdit50A", 0 ); if (listbox_registered) UnregisterClassW( L"REListBox20W", 0 ); if (combobox_registered) UnregisterClassW( L"REComboBox20W", 0 ); LookupCleanup(); release_typelib(); break; } return TRUE; }
27,361
1,155
package ma.glasnost.orika.test.community; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import org.junit.Test; import ma.glasnost.orika.OrikaSystemProperties; import ma.glasnost.orika.impl.DefaultMapperFactory; public class Issue175Test { @Test public void maps_one_value_to_all_elements_in_collection_and_back() { System.setProperty(OrikaSystemProperties.WRITE_SOURCE_FILES,"true"); DefaultMapperFactory mapper = new DefaultMapperFactory.Builder().build(); mapper.classMap(Source.class, Destination.class) .field("nested", "nested") .field("value", "nested{value}") .byDefault() .register(); Source source = new Source(); source.setValue("some data"); source.setNested(Arrays.asList( aNestedSource("one"), aNestedSource("two"), aNestedSource("three") )); Destination destination = mapper.getMapperFacade().map(source, Destination.class); assertEquals("some data", destination.getNested().get(0).getValue()); assertEquals("one", destination.getNested().get(0).getId()); assertEquals("some data", destination.getNested().get(1).getValue()); assertEquals("two", destination.getNested().get(1).getId()); assertEquals("some data", destination.getNested().get(2).getValue()); assertEquals("three", destination.getNested().get(2).getId()); Source newSource = mapper.getMapperFacade().map(destination, Source.class); assertEquals(source, newSource); } private NestedSource aNestedSource(String id) { NestedSource nested = new NestedSource(); nested.setId(id); return nested; } public static class Source { private String value; private List<NestedSource> nested = new ArrayList<>(); public void setValue(String value) { this.value = value; } public String getValue() { return value; } public void setNested(List<NestedSource> nested) { this.nested = nested; } public List<NestedSource> getNested() { return nested; } @Override public boolean equals(Object obj) { return Objects.equals(value, ((Source) obj).value) && Objects.equals(nested, ((Source) obj).nested); } } public static class Destination { private List<NestedDestination> nested; public List<NestedDestination> getNested() { return nested; } public void setNested(List<NestedDestination> nested) { this.nested = nested; } } public static class NestedSource { private String id; public void setId(String id) { this.id = id; } public String getId() { return id; } @Override public boolean equals(Object obj) { return Objects.equals(id, ((NestedSource) obj).id); } } public static class NestedDestination { private String id; private String value; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } }
1,587
380
<filename>mini/threading/locked_value.h #pragma once #include "mutex.h" #include "event.h" namespace mini::threading { template < typename T > class locked_value { MINI_MAKE_NONCOPYABLE(locked_value); public: locked_value( locked_value<T>&& other ) = default; locked_value( const T& initial_value = T() ); ~locked_value( void ) = default; const T& get_value( void ) const; void set_value( const T& value ); wait_result wait_for_value( const T& value, timeout_type timeout = wait_infinite ); wait_result wait_for_change( timeout_type timeout = wait_infinite ); void cancel_all_waits( void ); private: mutable mutex _mutex; event _event; event _cancel_event; T _value; }; } #include "locked_value.inl"
415
3,269
<gh_stars>1000+ // Time: O(n + m) // Space: O(n + m) class Solution { public: int largestPathValue(string colors, vector<vector<int>>& edges) { vector<vector<int>> adj(size(colors)); vector<int> in_degree(size(colors)); for (const auto& edge : edges) { adj[edge[0]].emplace_back(edge[1]); ++in_degree[edge[1]]; } vector<int> q; for (int i = 0; i < size(colors); ++i) { if (!in_degree[i]) { q.emplace_back(i); } } vector<vector<int>> dp(size(colors), vector<int>(26)); int result = -1, cnt = 0; while (!empty(q)) { vector<int> new_q; for (const auto& u : q) { ++cnt; result = max(result, ++dp[u][colors[u] - 'a']); for (const auto& v : adj[u]) { for (int c = 0; c < 26; ++c) { dp[v][c] = max(dp[v][c], dp[u][c]); } if (!--in_degree[v]) { new_q.emplace_back(v); } } } q = move(new_q); } return cnt == size(colors) ? result : -1; } };
753
389
/* * Copyright 2014 Guidewire Software, Inc. */ package gw.internal.gosu.parser; import gw.lang.reflect.gs.IGosuProgram; import gw.lang.reflect.IType; import gw.lang.parser.ISymbolTable; import gw.lang.parser.ITokenizerInstructor; /** */ public interface IGosuProgramInternal extends IGosuProgram, IGosuClassInternal { ISymbolTable getSymbolTable(); void addCapturedProgramSymbols( ISymbolTable classCompilationSymTable ); void addProgramEntryPoint( ISymbolTable symbolTable, GosuClassParser gosuClassParser ); void addExecuteEntryPoint( ISymbolTable symTable, GosuClassParser parser ); void setExpression( Expression expr ); void setStatement( Statement stmt ); void setExpectedReturnType( IType expectedReturnType ); void setGenRootExprAccess( boolean bGenRootExprAccess ); boolean isGenRootExprAccess(); ITokenizerInstructor getTokenizerInstructor(); void setTokenizerInstructor( ITokenizerInstructor ti ); ISymbolTable getAdditionalDFSDecls(); void setAdditionalDFSDecls( ISymbolTable symbolTable ); void setAnonymous( boolean b ); void setThrowaway( boolean b ); boolean isThrowaway(); void setAllowUses( boolean b ); boolean allowsUses(); void setCtxInferenceMgr( Object ctxInferenceMgr ); void setStatementsOnly( boolean bStatementsOnly ); boolean isStatementsOnly(); void setContextType(IType contextType); boolean isParsingExecutableProgramStatements(); void setParsingExecutableProgramStatements( boolean b ); }
444
678
/* * SectionContents.h * MachOView * * Created by psaghelyi on 15/09/2010. * */ #import "MachOLayout.h" @interface MachOLayout (SectionContents) - (MVNode *)createPointersNode:(MVNode *)parent caption:(NSString *)caption location:(uint32_t)location length:(uint32_t)length; - (MVNode *)createPointers64Node:(MVNode *)parent caption:(NSString *)caption location:(uint32_t)location length:(uint32_t)length; -(MVNode *)createCStringsNode:(MVNode *)parent caption:(NSString *)caption location:(uint32_t)location length:(uint32_t)length; -(MVNode *)createLiteralsNode:(MVNode *)parent caption:(NSString *)caption location:(uint32_t)location length:(uint32_t)length stride:(uint32_t)stride; - (MVNode *)createIndPointersNode:(MVNode *)parent caption:(NSString *)caption location:(uint32_t)location length:(uint32_t)length; - (MVNode *)createIndPointers64Node:(MVNode *)parent caption:(NSString *)caption location:(uint32_t)location length:(uint32_t)length; - (MVNode *)createIndStubsNode:(MVNode *)parent caption:(NSString *)caption location:(uint32_t)location length:(uint32_t)length stride:(uint32_t)stride; - (MVNode *)createIndStubs64Node:(MVNode *)parent caption:(NSString *)caption location:(uint32_t)location length:(uint32_t)length stride:(uint32_t)stride; - (MVNode *)createStubHelperNode:(MVNode *)parent caption:(NSString *)caption location:(uint32_t)location length:(uint32_t)length; - (MVNode *)createTextNode:(MVNode *)parent caption:(NSString *)caption location:(uint32_t)location length:(uint32_t)length reloff:(uint32_t)reloff nreloc:(uint32_t)nreloc extreloff:(uint32_t)extreloff nextrel:(uint32_t)nextrel locreloff:(uint32_t)locreloff nlocrel:(uint32_t)nlocrel; @end
1,486
469
<filename>androidbrowserhelper/src/androidTest/java/com/google/androidbrowserhelper/trusted/testutils/TestUtil.java // Copyright 2019 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.androidbrowserhelper.trusted.testutils; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import android.app.Instrumentation; import android.os.Handler; import android.os.Looper; import com.google.androidbrowserhelper.trusted.testcomponents.TestBrowser; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import androidx.test.platform.app.InstrumentationRegistry; /** * Utilities for testing Custom Tabs. */ public class TestUtil { /** * Waits until {@link TestBrowser} is launched and resumed, and returns it. * * @param launchRunnable Runnable that should start the activity. */ public static TestBrowser getBrowserActivityWhenLaunched(Runnable launchRunnable) { Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); Instrumentation.ActivityMonitor monitor = instrumentation.addMonitor(TestBrowser.class.getName(), null, false); launchRunnable.run(); TestBrowser activity = (TestBrowser) instrumentation.waitForMonitorWithTimeout(monitor, 3000); assertNotNull("TestBrowser wasn't launched", activity); // ActivityMonitor is triggered in onCreate and in onResume, which can lead to races when // launching several activity instances. So wait for onResume before returning. boolean resumed = activity.waitForResume(3000); assertTrue("TestBrowser didn't reach onResume", resumed); return activity; } /** * Runs the supplied Callable on the main thread, returning the result. Blocks until completes. */ public static <T> T runOnUiThreadBlocking(Callable<T> c) { FutureTask<T> task = new FutureTask<>(c); new Handler(Looper.getMainLooper()).post(task); try { return task.get(); } catch (InterruptedException e) { throw new RuntimeException("Interrupted waiting for callable", e); } catch (ExecutionException e) { throw new RuntimeException(e.getCause()); } } /** * Runs the supplied Runnable on the main thread. Blocks until completes. */ public static void runOnUiThreadBlocking(Runnable c) { runOnUiThreadBlocking((Callable<Void>) () -> { c.run(); return null; }); } }
1,066
406
<reponame>ernstki/kASA<gh_stars>100-1000 /*************************************************************************** * include/stxxl/bits/parallel/tags.h * * Tags for compile-time options. * Extracted from MCSTL http://algo2.iti.uni-karlsruhe.de/singler/mcstl/ * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2007 <NAME> <<EMAIL>> * Copyright (C) 2014 <NAME> <<EMAIL>> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #ifndef STXXL_PARALLEL_TAGS_HEADER #define STXXL_PARALLEL_TAGS_HEADER #include <stxxl/bits/namespace.h> STXXL_BEGIN_NAMESPACE namespace parallel { /** Makes the parametrized class actually do work, i. e. actives it. */ class active_tag { }; /** Makes the parametrized class do nothing, i. e. deactives it. */ class inactive_tag { }; } // namespace parallel STXXL_END_NAMESPACE #endif // !STXXL_PARALLEL_TAGS_HEADER
379
713
<reponame>franz1981/infinispan package org.infinispan.server.functional; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.URI; import java.util.Iterator; import java.util.Properties; import javax.cache.Cache; import javax.cache.CacheManager; import javax.cache.Caching; import javax.cache.spi.CachingProvider; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.server.test.junit4.InfinispanServerRule; import org.infinispan.server.test.junit4.InfinispanServerTestMethodRule; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; /** * @author <NAME> &lt;<EMAIL>&gt; * @since 11.0 **/ public class JCacheOperations { @ClassRule public static InfinispanServerRule SERVERS = ClusteredIT.SERVERS; @Rule public InfinispanServerTestMethodRule SERVER_TEST = new InfinispanServerTestMethodRule(SERVERS); @Test public void testJCacheOperations() throws IOException { Properties properties = new Properties(); InetAddress serverAddress = SERVERS.getServerDriver().getServerAddress(0); properties.put(ConfigurationProperties.SERVER_LIST, serverAddress.getHostAddress() + ":11222"); properties.put(ConfigurationProperties.CACHE_PREFIX + SERVER_TEST.getMethodName() + ConfigurationProperties.CACHE_TEMPLATE_NAME_SUFFIX, "org.infinispan.DIST_SYNC"); doJCacheOperations(properties); } @Test public void testJCacheOperationsWildcards() throws IOException { Properties properties = new Properties(); InetAddress serverAddress = SERVERS.getServerDriver().getServerAddress(0); properties.put(ConfigurationProperties.SERVER_LIST, serverAddress.getHostAddress() + ":11222"); properties.put(ConfigurationProperties.CACHE_PREFIX + '[' + SERVER_TEST.getMethodName().substring(0, 8) + "*]" + ConfigurationProperties.CACHE_TEMPLATE_NAME_SUFFIX, "org.infinispan.DIST_SYNC"); doJCacheOperations(properties); } private void doJCacheOperations(Properties properties) throws IOException { File file = new File(String.format("target/test-classes/%s-hotrod-client.properties", SERVER_TEST.getMethodName())); try (FileOutputStream fos = new FileOutputStream(file)) { properties.store(fos, null); } URI uri = file.toURI(); CachingProvider provider = Caching.getCachingProvider(); try (CacheManager cacheManager = provider.getCacheManager(uri, this.getClass().getClassLoader())) { Cache<String, String> cache = cacheManager.getCache(SERVER_TEST.getMethodName()); cache.put("k1", "v1"); int size = getCacheSize(cache); assertEquals(1, size); assertEquals("v1", cache.get("k1")); cache.remove("k1"); assertEquals(0, getCacheSize(cache)); } } private int getCacheSize(Cache<String, String> cache) { int size = 0; for (Iterator<Cache.Entry<String, String>> it = cache.iterator(); it.hasNext(); it.next()) { ++size; } return size; } }
1,140
978
""" Reference: <NAME> et al., "Learning Hierarchical Representation Model for NextBasket Recommendation." in SIGIR 2015. @author: wubin """ import tensorflow as tf import numpy as np from time import time from util import timer from util import learner, tool from util.tool import csr_to_user_dict_bytime from model.AbstractRecommender import SeqAbstractRecommender from util import l2_loss from data import TimeOrderPointwiseSampler class HRM(SeqAbstractRecommender): def __init__(self, sess, dataset, conf): super(HRM, self).__init__(dataset, conf) self.learning_rate = conf["learning_rate"] self.embedding_size = conf["embedding_size"] self.learner = conf["learner"] self.num_epochs = conf["epochs"] self.reg_mf = conf["reg_mf"] self.pre_agg = conf["pre_agg"] self.loss_function = conf["loss_function"] self.session_agg = conf["session_agg"] self.batch_size = conf["batch_size"] self.high_order = conf["high_order"] self.verbose = conf["verbose"] self.num_negatives = conf["num_neg"] self.init_method = conf["init_method"] self.stddev = conf["stddev"] self.num_users = dataset.num_users self.num_items = dataset.num_items self.dataset = dataset self.train_dict = csr_to_user_dict_bytime(dataset.time_matrix, dataset.train_matrix) self.sess = sess def _create_placeholders(self): with tf.name_scope("input_data"): self.user_input = tf.placeholder(tf.int32, shape=[None, ], name="user_input") self.item_input = tf.placeholder(tf.int32, shape=[None, ], name="item_input_pos") self.item_input_recent = tf.placeholder(tf.int32, shape=[None, None], name = "item_input_recent") self.labels = tf.placeholder(tf.float32, shape=[None, ], name="labels") def _create_variables(self): with tf.name_scope("embedding"): initializer = tool.get_initializer(self.init_method, self.stddev) self.user_embeddings = tf.Variable(initializer([self.num_users, self.embedding_size]), name='user_embeddings', dtype=tf.float32) # (users, embedding_size) self.item_embeddings = tf.Variable(initializer([self.num_items, self.embedding_size]), name='item_embeddings', dtype=tf.float32) # (items, embedding_size) def avg_pooling(self, input_embedding): output = tf.reduce_mean(input_embedding, axis=1) return output def max_pooling(self, input_embedding): output = tf.reduce_max(input_embedding, axis=1) return output def _create_inference(self): with tf.name_scope("inference"): # embedding look up user_embedding = tf.nn.embedding_lookup(self.user_embeddings, self.user_input) item_embedding_recent = tf.nn.embedding_lookup(self.item_embeddings, self.item_input_recent) item_embedding = tf.nn.embedding_lookup(self.item_embeddings, self.item_input) if self.high_order > 1: if self.session_agg == "max": item_embedding_short = self.max_pooling(item_embedding_recent) else : item_embedding_short = self.avg_pooling(item_embedding_recent) concat_user_item = tf.concat([tf.expand_dims(user_embedding, 1), tf.expand_dims(item_embedding_short, 1)], axis=1) else: concat_user_item = tf.concat([tf.expand_dims(user_embedding, 1), tf.expand_dims(item_embedding_recent, 1)], axis=1) if self.pre_agg == "max": hybrid_user_embedding = self.max_pooling(concat_user_item) else: hybrid_user_embedding = self.avg_pooling(concat_user_item) predict_vector = tf.multiply(hybrid_user_embedding, item_embedding) predict = tf.reduce_sum(predict_vector, 1) return user_embedding, item_embedding, item_embedding_recent, predict def _create_loss(self): with tf.name_scope("loss"): # loss for L(Theta) p1, q1, r1, self.output = self._create_inference() self.loss = learner.pointwise_loss(self.loss_function, self.labels, self.output) + \ self.reg_mf * l2_loss(p1, r1, q1) def _create_optimizer(self): with tf.name_scope("learner"): self.optimizer = learner.optimizer(self.learner, self.loss, self.learning_rate) def build_graph(self): self._create_placeholders() self._create_variables() self._create_loss() self._create_optimizer() # ---------- training process ------- def train_model(self): self.logger.info(self.evaluator.metrics_info()) data_iter = TimeOrderPointwiseSampler(self.dataset, high_order=self.high_order, neg_num=self.num_negatives, batch_size=self.batch_size, shuffle=True) for epoch in range(1, self.num_epochs+1): num_training_instances = len(data_iter) total_loss = 0.0 training_start_time = time() for bat_users, bat_items_recent, bat_items, bat_labels in data_iter: feed_dict = {self.user_input: bat_users, self.item_input: bat_items, self.item_input_recent: bat_items_recent, self.labels: bat_labels} loss, _ = self.sess.run((self.loss,self.optimizer),feed_dict=feed_dict) total_loss += loss self.logger.info("[iter %d : loss : %f, time: %f]" % (epoch, total_loss/num_training_instances, time()-training_start_time)) if epoch % self.verbose == 0: self.logger.info("epoch %d:\t%s" % (epoch, self.evaluate())) @timer def evaluate(self): return self.evaluator.evaluate(self) def predict(self, user_ids, candidate_items_user_ids): ratings = [] if candidate_items_user_ids is None: all_items = np.arange(self.num_items) for user_id in user_ids: cand_items = self.train_dict[user_id] item_recent = [] for _ in range(self.num_items): item_recent.append(cand_items[len(cand_items)-self.high_order:]) users = np.full(self.num_items, user_id, dtype=np.int32) feed_dict = {self.user_input: users, self.item_input_recent: item_recent, self.item_input: all_items} ratings.append(self.sess.run(self.output, feed_dict=feed_dict)) else: for user_id, items_by_user_id in zip(user_ids, candidate_items_user_ids): cand_items = self.train_dict[user_id] item_recent = [] for _ in range(len(items_by_user_id)): item_recent.append(cand_items[len(cand_items)-self.high_order:]) users = np.full(len(items_by_user_id), user_id, dtype=np.int32) feed_dict = {self.user_input: users, self.item_input_recent: item_recent, self.item_input: items_by_user_id} ratings.append(self.sess.run(self.output, feed_dict=feed_dict)) return ratings
3,897
1,486
#ifndef RAW_H #define RAW_H #include <hiredis/hiredis.h> #include <hiredis/async.h> struct cmd; struct http_client; void raw_reply(redisAsyncContext *c, void *r, void *privdata); struct cmd * raw_ws_extract(struct http_client *c, const char *p, size_t sz); #endif
112
355
<gh_stars>100-1000 package com.github.lindenb.jvarkit.util.vcf; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ContigPosTest{ @DataProvider(name = "src1") public Object[][] createData1() { return new Object[][]{ {"chr1:123","chr1",123} }; } @Test(dataProvider="src1") public void test1(final String s1,String chrom,int pos) { ContigPos cp1 = new ContigPos(s1); Assert.assertEquals(cp1.getContig(), chrom); Assert.assertEquals(cp1.getStart(), pos); Assert.assertEquals(cp1.getEnd(), pos); ContigPos cp2 = new ContigPos(chrom,pos); Assert.assertEquals(cp1, cp2); Assert.assertEquals(0, cp1.compareTo(cp2)); } }
297
427
<filename>src/lib_java/java_classes/enums/AutomapMode.java package vizdoom; public enum AutomapMode{ NORMAL, WHOLE, OBJECTS, OBJECTS_WITH_SIZE; }
73
1,047
package com.hss01248.dialogutildemo; import android.app.AlertDialog; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.widget.Button; import android.widget.TextView; import com.orhanobut.logger.Logger; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by huangshuisheng on 2017/9/30. */ public class BadTokenBeforeActy extends AppCompatActivity { long startTime; @BindView(R.id.textView) TextView textView; @BindView(R.id.button3) Button button3; @Override protected Dialog onCreateDialog(int id) { return super.onCreateDialog(id); } @Nullable @Override protected Dialog onCreateDialog(int id, Bundle args) { return super.onCreateDialog(id, args); } @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.acty_token_before); ButterKnife.bind(this); //new PopupWindow(View.inflate(this,R.layout.dialog_ios_alert,null)).showAsDropDown(button3); // PopupWindow必导致badtoken,如果在onAttachedToWindow里弹出,则不会 new AlertDialog.Builder(this).setTitle("crash").setMessage("ddddd").show(); //AlertDialog测试机未出现badtoken,会等待activity界面就绪后再弹出,不知道其他手机?? startTime = System.currentTimeMillis(); Logger.e("onCreate---time:" + startTime); } private void takeTime() { int length = 10000; int[] arr = new int[length]; for (int i = 0; i < arr.length; i++) { arr[i] = (int) (Math.random() * length); } selectionSort(arr); } @Override protected void onStart() { super.onStart(); Logger.e("onStart---time:" + (System.currentTimeMillis() - startTime)); takeTime(); } @Override protected void onResume() { super.onResume(); Logger.e("onResume---time:" + (System.currentTimeMillis() - startTime)); } @Override public void onAttachedToWindow() { super.onAttachedToWindow(); Logger.e("onAttachedToWindow---time:" + (System.currentTimeMillis() - startTime)); //new PopupWindow(View.inflate(this,R.layout.dialog_ios_alert,null)).showAsDropDown(button3); } @Override protected void onStop() { super.onStop(); Logger.e("onStop---time:" + (System.currentTimeMillis() - startTime)); } @Override protected void onDestroy() { super.onDestroy(); Logger.e("onDestroy---time:" + (System.currentTimeMillis() - startTime)); } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); Logger.e("onDetachedFromWindow---time:" + (System.currentTimeMillis() - startTime)); } public static void selectionSort(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int k = i; // 找出最小值的小标 for (int j = i + 1; j < n; j++) { if (a[j] < a[k]) { k = j; } } // 将最小值放到排序序列末尾 if (k > i) { int tmp = a[i]; a[i] = a[k]; a[k] = tmp; } } } }
1,630
391
/* * * Copyright (C) 2020 iQIYI (www.iqiyi.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.qiyi.lens.utils.reflect; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.os.Build; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentPagerAdapter; import androidx.fragment.app.FragmentStatePagerAdapter; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; import com.qiyi.lens.utils.ViewClassifyUtil; import com.qiyi.lens.utils.configs.ActivityInfoConfig; import com.qiyi.lens.utils.iface.IFragmentHandle; import java.lang.reflect.Field; import java.util.LinkedList; import java.util.List; /** * 页面分析功能 */ public class ActivityObjectFieldInfo extends FieldInfo { public ActivityObjectFieldInfo(Object obj, SparseArray hashMap, Invalidate par) { super(obj, hashMap, par); initHandle(); } public ActivityObjectFieldInfo(Field fld, Object src, SparseArray hs , Invalidate pa) { super(fld, src, hs, pa); initHandle(); } @Override public void makeSpannable(StringBuilder stringBuilder, LinkedList<SpanableInfo> spannableInfo) { super.makeSpannable(stringBuilder, spannableInfo); } @Override public void preBuildSpannables(StringBuilder stringBuilder, LinkedList<SpanableInfo> spanInfos) { if (value != null) { String space = makeSpace(); stringBuilder.append("\n"); stringBuilder.append(space); stringBuilder.append("当前有 " + (list == null ? 0 : list.size()) + " 个Fragments"); } } @Override public void makeList(LinkedList linkedList) { if (list == null) { list = new LinkedList<>(); } else { list.clear(); } if (value instanceof FragmentActivity) { makeSupportFragments(); return; } Activity activity = (Activity) value; List<Fragment> fragments = null; if (Build.VERSION.SDK_INT >= 26) { fragments = activity.getFragmentManager().getFragments(); } else { FragmentManager fragmentManager = activity.getFragmentManager(); try { Field field = fragmentManager.getClass().getDeclaredField("mAdded"); field.setAccessible(true); try { Object object = field.get(fragmentManager); if (object instanceof List) { fragments = (List<Fragment>) object; } } catch (IllegalAccessException e) { e.printStackTrace(); } } catch (NoSuchFieldException e) { e.printStackTrace(); } } if (fragments != null && !fragments.isEmpty()) { // this.list = new LinkedList<>(); for (Fragment fragment : fragments) { FragmentInfo fragmentInfo = new FragmentInfo(fragment, hashMap, this); fragmentInfo.setUtil(util, handle); fragmentInfo.setLevel(level); list.add(fragmentInfo); } } } private void makeSupportFragments() { FragmentActivity fragmentActivity = (FragmentActivity) value; List<androidx.fragment.app.Fragment> fragments = fragmentActivity.getSupportFragmentManager().getFragments(); if (!fragments.isEmpty()) { // this.fragmentsInfos = new LinkedList<>(); for (androidx.fragment.app.Fragment fragment : fragments) { FragmentInfo fragmentInfo = new FragmentInfo(fragment, hashMap, this); fragmentInfo.setUtil(util, handle); fragmentInfo.setLevel(level); list.add(fragmentInfo); } } } public View getContentView() { if (value != null) { Activity activity = (Activity) value; return activity.findViewById(android.R.id.content); } return null; } @Override public void afterBuildSpannables(StringBuilder stringBuilder, LinkedList<SpanableInfo> infoList) { stringBuilder.append("\n视图信息:\n"); stringBuilder.append("视图层级:\t"); stringBuilder.append(util.getViewLevel()); crtf(stringBuilder); stringBuilder.append("视图个数\t"); stringBuilder.append(util.getViewCount()); crtf(stringBuilder); stringBuilder.append("视图分类: 总共有"); int count = util.getTypesCount(); stringBuilder.append(count); stringBuilder.append("种类型的视图\n"); stringBuilder.append("\n"); } private ViewClassifyUtil util; public void setViewClassifyUtils(ViewClassifyUtil util) { this.util = util; //[fix null ptr , as this is set after list build] if (list != null) { for (Info info : list) { if (info instanceof FragmentInfo) { ((FragmentInfo) info).setUtil(util, handle); } } } } public ViewClassifyUtil makeActivityBaseInfo(StringBuilder stringBuilder, ViewClassifyUtil util) { stringBuilder.append("界面信息:\n 当前界面:"); stringBuilder.append(getSimpleName()); crtf(stringBuilder); if (list != null && list.size() > 0) { stringBuilder.append("有如下"); stringBuilder.append(list.size()); stringBuilder.append("个Fragment"); crtf(stringBuilder); for (Info info : list) { stringBuilder.append(((FieldInfo) info).getSimpleName()); stringBuilder.append("<"); Object value = ((FieldInfo) info).value; makeViewPagerFragments(util, stringBuilder, value); stringBuilder.append(">"); //] crtf(stringBuilder); } } stringBuilder.append("视图信息:\n"); // ViewClassifyUtil util = new ViewClassifyUtil(getContentView()); stringBuilder.append("视图层级:\t"); stringBuilder.append(util.getViewLevel()); crtf(stringBuilder); stringBuilder.append("视图个数\t"); stringBuilder.append(util.getViewCount()); crtf(stringBuilder); stringBuilder.append("视图分类: 总共有"); int count = util.getTypesCount(); stringBuilder.append(count); stringBuilder.append("种类型的视图\n"); stringBuilder.append("\n"); //[] return util; } private View getFragmentRootView(Object value) { if (value instanceof Fragment) { Fragment fragment = (Fragment) value; return fragment.getView(); } else if (value instanceof androidx.fragment.app.Fragment) { androidx.fragment.app.Fragment fragment = (androidx.fragment.app.Fragment) value; return fragment.getView(); } return null; } private int getLevel(View view, ViewGroup parent) { int level = 0; while (view != parent) { ViewParent viewParent = view.getParent(); if (viewParent instanceof ViewGroup) { level++; view = (View) viewParent; } else { return Integer.MAX_VALUE; } } return level; } private ViewPager findChildPager(ViewGroup group, LinkedList<ViewPager> pagers) { ViewPager thePager = null; if (pagers != null) { int minLevel = Integer.MAX_VALUE; for (ViewPager pager : pagers) { int level = getLevel(pager, group); if (level < minLevel) { thePager = pager; minLevel = level; } } } return thePager; } //[value is a fragment] //[如果这个fragment 中间含有 View pager 则继续寻找] private void makeViewPagerFragments(ViewClassifyUtil util, StringBuilder stringBuilder, Object value) { //[to do 嵌套的fragment 检查] // Object value = ((FeildInfo) info).value; LinkedList<ViewPager> pagers = util.getPagers(); if (pagers == null || pagers.isEmpty()) { return; } while (value != null) { View view = getFragmentRootView(value); value = null; if (view instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) view; ViewPager pager = findChildPager(viewGroup, pagers); if (pager != null) { PagerAdapter adapter = pager.getAdapter(); // if (adapter instanceof FragmentStatePagerAdapter) { // FragmentStatePagerAdapter fragmentStatePagerAdapter = (FragmentStatePagerAdapter) adapter; int index = pager.getCurrentItem(); Class<? extends IFragmentHandle> handleClass = ActivityInfoConfig.getInstance().getFragClassHandle(); Object fragment = null; IFragmentHandle handle = null; if (handleClass != null) { try { handle = handleClass.newInstance(); fragment = handle.getFragmentInstance(adapter, index); // handle.onFragmentAnalyse(fragment, stringBuilder); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } if (fragment == null) { if (adapter instanceof FragmentStatePagerAdapter) { FragmentStatePagerAdapter pagerAdapter = (FragmentStatePagerAdapter) adapter; fragment = pagerAdapter.getItem(index); } else if (adapter instanceof FragmentPagerAdapter) { FragmentPagerAdapter pagerAdapter = (FragmentPagerAdapter) adapter; fragment = pagerAdapter.getItem(index); } } if (fragment instanceof Fragment || fragment instanceof androidx.fragment.app.Fragment) { stringBuilder.append("发现嵌套的fragment,在ViewPager的第 "); stringBuilder.append(index); stringBuilder.append(" 个位置"); stringBuilder.append("\n"); stringBuilder.append(fragment.getClass().getSimpleName()); if (handleClass != null && handle != null) { stringBuilder.append("("); handle.onFragmentAnalyse(fragment, stringBuilder); stringBuilder.append(")"); } stringBuilder.append("\n"); value = fragment;//getFragmentRootView(fragment); } } // } } } } //[并不全量生成,点击再展开生成 , 除非有watch 的数据。 设置初始展开] public Spannable makeSpannable() { LinkedList<SpanableInfo> list = new LinkedList<>(); StringBuilder builder = new StringBuilder(); makeSpannable(builder, list); builder.append("\n ");//[fix out side touch] //[make spannable] Spannable spannable = new SpannableStringBuilder(builder); while (!list.isEmpty()) { SpanableInfo info = list.pop(); if (info.isClickable()) { spannable.setSpan(info.clickSpan, info.star, info.end , Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } } return spannable; } private IFragmentHandle handle; private void initHandle() { Class<? extends IFragmentHandle> handleClass = ActivityInfoConfig.getInstance().getFragClassHandle(); if (handleClass != null) { try { handle = handleClass.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } }
6,438
852
import FWCore.ParameterSet.Config as cms # File: RecHits.cfi # Author: <NAME> # Date: 03.04.2008 # # Fill validation histograms for ECAL and HCAL RecHits. # Assumes ecalRecHit:EcalRecHitsEE, ecalRecHit:EcalRecHitsEB, hbhereco, horeco, and hfreco # are in the event. from DQMOffline.JetMET.RecHits_cfi import * analyzeRecHits = cms.Sequence(ECALAnalyzer*HCALAnalyzer)
146
321
<reponame>AppSecAI-TEST/qalingo-engine<gh_stars>100-1000 /** * Most of the code in the Qalingo project is copyrighted Hoteia and licensed * under the Apache License Version 2.0 (release version 0.8.0) * http://www.apache.org/licenses/LICENSE-2.0 * * Copyright (c) Hoteia, 2012-2014 * http://www.hoteia.com - http://twitter.com/hoteia - <EMAIL> * */ package org.hoteia.qalingo.core.solr.service; import java.io.IOException; import java.math.BigDecimal; import java.util.Iterator; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrRequest; import org.apache.solr.client.solrj.SolrRequest.METHOD; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.request.QueryRequest; import org.apache.solr.client.solrj.response.FacetField; import org.apache.solr.client.solrj.response.QueryResponse; import org.hibernate.Hibernate; import org.hoteia.qalingo.core.domain.CatalogCategoryVirtual; import org.hoteia.qalingo.core.domain.MarketArea; import org.hoteia.qalingo.core.domain.ProductMarketing; import org.hoteia.qalingo.core.domain.ProductSku; import org.hoteia.qalingo.core.domain.ProductSkuOptionDefinition; import org.hoteia.qalingo.core.domain.ProductSkuOptionRel; import org.hoteia.qalingo.core.domain.ProductSkuPrice; import org.hoteia.qalingo.core.domain.ProductSkuTagRel; import org.hoteia.qalingo.core.domain.Retailer; import org.hoteia.qalingo.core.domain.Tag; import org.hoteia.qalingo.core.service.ProductService; import org.hoteia.qalingo.core.solr.bean.ProductSkuSolr; import org.hoteia.qalingo.core.solr.bean.SortField; import org.hoteia.qalingo.core.solr.bean.SolrParam; import org.hoteia.qalingo.core.solr.response.ProductMarketingResponseBean; import org.hoteia.qalingo.core.solr.response.ProductSkuResponseBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service("productSkuSolrService") @Transactional public class ProductSkuSolrService extends AbstractSolrService { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired protected SolrServer productSkuSolrServer; @Autowired protected ProductService productService; public void addOrUpdateProductSku(final ProductMarketing productMarketing, final ProductSku productSku, final List<CatalogCategoryVirtual> catalogCategories, final MarketArea marketArea, final Retailer retailer) throws SolrServerException, IOException { if (productSku.getId() == null) { throw new IllegalArgumentException("Id cannot be blank or null."); } if (logger.isDebugEnabled()) { logger.debug("Indexing productSku " + productSku.getId() + " : " + productSku.getCode()+ " : " + productSku.getName()); } ProductSkuSolr productSkuSolr = new ProductSkuSolr(); productSkuSolr.setId(productSku.getId()); productSkuSolr.setCode(productSku.getCode()); productSkuSolr.setName(productSku.getName()); productSkuSolr.setDescription(productSku.getDescription()); productSkuSolr.setEnabledB2B(productSku.isEnabledB2B()); productSkuSolr.setEnabledB2C(productSku.isEnabledB2C()); productSkuSolr.setSalableB2B(productSku.isSalableB2B()); productSkuSolr.setSalableB2C(productSku.isSalableB2C()); if(productMarketing.getProductBrand() != null && Hibernate.isInitialized(productMarketing.getProductBrand())){ productSkuSolr.setProductBrandCode(productMarketing.getProductBrand().getCode()); productSkuSolr.setProductBrandName(productMarketing.getProductBrand().getName()); } CatalogCategoryVirtual defaultVirtualCatalogCategory = productService.getDefaultVirtualCatalogCategory(productSku, catalogCategories, true); if(defaultVirtualCatalogCategory != null){ productSkuSolr.setDefaultCategoryCode(defaultVirtualCatalogCategory.getCode()); } if(catalogCategories != null){ for (CatalogCategoryVirtual catalogCategoryVirtual : catalogCategories) { String catalogCode = catalogCategoryVirtual.getCatalog().getCode(); productSkuSolr.addCatalogCode(catalogCode); String catalogCategoryCode = catalogCode + "_" + catalogCategoryVirtual.getCode(); productSkuSolr.addCatalogCategories(catalogCategoryCode); } } if(productSku.getOptionRels() != null && Hibernate.isInitialized(productSku.getOptionRels()) && !productSku.getOptionRels().isEmpty()){ for (ProductSkuOptionRel productSkuOptionRel : productSku.getOptionRels()) { ProductSkuOptionDefinition productSkuOptionDefinition = productSkuOptionRel.getProductSkuOptionDefinition(); productSkuSolr.addOptionDefinition(productSkuOptionDefinition.getCode()); } } if(productSku.getTagRels() != null && Hibernate.isInitialized(productSku.getTagRels()) && !productSku.getTagRels().isEmpty()){ for (ProductSkuTagRel productSkuTagRel : productSku.getTagRels()) { Tag productSkuTag = productSkuTagRel.getProductSkuTag(); productSkuSolr.addTag(productSkuTag.getCode()); } } if(marketArea != null && retailer != null){ ProductSkuPrice productSkuPrice = productSku.getBestPrice(marketArea.getId()); if(productSkuPrice != null){ BigDecimal salePrice = productSkuPrice.getSalePrice(); productSkuSolr.setPrice(salePrice.toString()); } } productSkuSolrServer.addBean(productSkuSolr); productSkuSolrServer.commit(); } public void removeProductSku(final ProductSkuSolr productSkuSolr) throws SolrServerException, IOException { if (productSkuSolr.getId() == null) { throw new IllegalArgumentException("Id cannot be blank or null."); } if (logger.isDebugEnabled()) { logger.debug("Remove Index ProductSku " + productSkuSolr.getId() + " : " + productSkuSolr.getCode() + " : " + productSkuSolr.getName()); } productSkuSolrServer.deleteById(productSkuSolr.getId().toString()); productSkuSolrServer.commit(); } public ProductSkuResponseBean searchProductSku(final String searchQuery, final List<String> facetFields, SolrParam solrParam) throws SolrServerException, IOException { return searchProductSku(searchQuery, facetFields, null, solrParam); } public ProductSkuResponseBean searchProductSku(final String searchQuery, final List<String> facetFields, final List<String> filterQueries, SolrParam solrParam) throws SolrServerException, IOException { SolrQuery solrQuery = new SolrQuery(); if(solrParam != null){ if(solrParam.get("rows") != null){ solrQuery.setParam("rows", (String)solrParam.get("rows")); } else { solrQuery.setParam("rows", getMaxResult()); } if(solrParam.get("sortField") != null){ SortField sortField = (SortField) solrParam.get("sortField"); for (Iterator<String> iterator = sortField.keySet().iterator(); iterator.hasNext();) { String field = (String) iterator.next(); solrQuery.addSortField(field, sortField.get(field)); } } } if (StringUtils.isEmpty(searchQuery)) { throw new IllegalArgumentException("SearchQuery field can not be Empty or Blank!"); } solrQuery.setQuery(searchQuery); if (facetFields != null && !facetFields.isEmpty()) { solrQuery.setFacet(true); solrQuery.setFacetMinCount(1); for (String facetField : facetFields) { solrQuery.addFacetField(facetField); } } if (filterQueries != null && filterQueries.size() > 0) { for (Iterator<String> iterator = filterQueries.iterator(); iterator.hasNext();) { String filterQuery = (String) iterator.next(); solrQuery.addFilterQuery(filterQuery); } } logger.debug("QueryRequest solrQuery: " + solrQuery); SolrRequest request = new QueryRequest(solrQuery, METHOD.POST); QueryResponse response = new QueryResponse(productSkuSolrServer.request(request), productSkuSolrServer); logger.debug("QueryResponse Obj: " + response.toString()); List<ProductSkuSolr> solrList = response.getBeans(ProductSkuSolr.class); ProductSkuResponseBean productResponseBean = new ProductSkuResponseBean(); productResponseBean.setProductSkuSolrList(solrList); if(facetFields != null && !facetFields.isEmpty()){ List<FacetField> solrFacetFieldList = response.getFacetFields(); productResponseBean.setProductSkuSolrFacetFieldList(solrFacetFieldList); } return productResponseBean; } @Deprecated public ProductSkuResponseBean searchProductSku(String searchBy, String searchText, List<String> facetFields) throws SolrServerException, IOException { SolrQuery solrQuery = new SolrQuery(); solrQuery.setParam("rows", getMaxResult()); if (StringUtils.isEmpty(searchBy)) { throw new IllegalArgumentException("SearchBy field can not be Empty or Blank!"); } if (StringUtils.isEmpty(searchText)) { solrQuery.setQuery(searchBy + ":*"); } else { solrQuery.setQuery(searchBy + ":" + searchText + "*"); } if(facetFields != null && !facetFields.isEmpty()){ solrQuery.setFacet(true); solrQuery.setFacetMinCount(1); for(String facetField : facetFields){ solrQuery.addFacetField(facetField); } } logger.debug("QueryRequest solrQuery: " + solrQuery); SolrRequest request = new QueryRequest(solrQuery, METHOD.POST); QueryResponse response = new QueryResponse(productSkuSolrServer.request(request), productSkuSolrServer); logger.debug("QueryResponse Obj: " + response.toString()); List<ProductSkuSolr> solrList = response.getBeans(ProductSkuSolr.class); ProductSkuResponseBean productResponseBean = new ProductSkuResponseBean(); productResponseBean.setProductSkuSolrList(solrList); if(facetFields != null && !facetFields.isEmpty()){ List<FacetField> solrFacetFieldList = response.getFacetFields(); productResponseBean.setProductSkuSolrFacetFieldList(solrFacetFieldList); } return productResponseBean; } public ProductSkuResponseBean searchProductSku() throws SolrServerException, IOException { SolrQuery solrQuery = new SolrQuery(); solrQuery.setParam("rows", getMaxResult()); solrQuery.setQuery("*"); solrQuery.setFacet(true); solrQuery.setFacetMinCount(1); solrQuery.addFacetField("name"); solrQuery.addFacetField("code"); logger.debug("QueryRequest solrQuery: " + solrQuery); SolrRequest request = new QueryRequest(solrQuery, METHOD.POST); QueryResponse response = new QueryResponse(productSkuSolrServer.request(request), productSkuSolrServer); logger.debug("QueryResponse Obj: " + response.toString()); List<ProductSkuSolr> solrList = response.getBeans(ProductSkuSolr.class); List<FacetField> solrFacetFieldList = response.getFacetFields(); ProductSkuResponseBean productSkuResponseBean = new ProductSkuResponseBean(); productSkuResponseBean.setProductSkuSolrList(solrList); productSkuResponseBean.setProductSkuSolrFacetFieldList(solrFacetFieldList); return productSkuResponseBean; } }
5,508
879
package org.zstack.header.rest; import org.springframework.http.HttpEntity; import org.zstack.header.core.AsyncBackup; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.exception.CloudRuntimeException; public abstract class JsonAsyncRESTCallback<T> extends AsyncRESTCallback { public JsonAsyncRESTCallback(AsyncBackup one, AsyncBackup... others) { super(one, others); } public abstract void fail(ErrorCode err); public abstract void success(T ret); public abstract Class<T> getReturnClass(); @Override public final void success(HttpEntity<String> entity) { throw new CloudRuntimeException("this method should not be called"); } }
228
9,778
<filename>src/bin/pg_basebackup/bbstreamer_inject.c<gh_stars>1000+ /*------------------------------------------------------------------------- * * bbstreamer_inject.c * * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group * * IDENTIFICATION * src/bin/pg_basebackup/bbstreamer_inject.c *------------------------------------------------------------------------- */ #include "postgres_fe.h" #include "bbstreamer.h" #include "common/file_perm.h" #include "common/logging.h" typedef struct bbstreamer_recovery_injector { bbstreamer base; bool skip_file; bool is_recovery_guc_supported; bool is_postgresql_auto_conf; bool found_postgresql_auto_conf; PQExpBuffer recoveryconfcontents; bbstreamer_member member; } bbstreamer_recovery_injector; static void bbstreamer_recovery_injector_content(bbstreamer *streamer, bbstreamer_member *member, const char *data, int len, bbstreamer_archive_context context); static void bbstreamer_recovery_injector_finalize(bbstreamer *streamer); static void bbstreamer_recovery_injector_free(bbstreamer *streamer); const bbstreamer_ops bbstreamer_recovery_injector_ops = { .content = bbstreamer_recovery_injector_content, .finalize = bbstreamer_recovery_injector_finalize, .free = bbstreamer_recovery_injector_free }; /* * Create a bbstreamer that can edit recoverydata into an archive stream. * * The input should be a series of typed chunks (not BBSTREAMER_UNKNOWN) as * per the conventions described in bbstreamer.h; the chunks forwarded to * the next bbstreamer will be similarly typed, but the * BBSTREAMER_MEMBER_HEADER chunks may be zero-length in cases where we've * edited the archive stream. * * Our goal is to do one of the following three things with the content passed * via recoveryconfcontents: (1) if is_recovery_guc_supported is false, then * put the content into recovery.conf, replacing any existing archive member * by that name; (2) if is_recovery_guc_supported is true and * postgresql.auto.conf exists in the archive, then append the content * provided to the existing file; and (3) if is_recovery_guc_supported is * true but postgresql.auto.conf does not exist in the archive, then create * it with the specified content. * * In addition, if is_recovery_guc_supported is true, then we create a * zero-length standby.signal file, dropping any file with that name from * the archive. */ extern bbstreamer * bbstreamer_recovery_injector_new(bbstreamer *next, bool is_recovery_guc_supported, PQExpBuffer recoveryconfcontents) { bbstreamer_recovery_injector *streamer; streamer = palloc0(sizeof(bbstreamer_recovery_injector)); *((const bbstreamer_ops **) &streamer->base.bbs_ops) = &bbstreamer_recovery_injector_ops; streamer->base.bbs_next = next; streamer->is_recovery_guc_supported = is_recovery_guc_supported; streamer->recoveryconfcontents = recoveryconfcontents; return &streamer->base; } /* * Handle each chunk of tar content while injecting recovery configuration. */ static void bbstreamer_recovery_injector_content(bbstreamer *streamer, bbstreamer_member *member, const char *data, int len, bbstreamer_archive_context context) { bbstreamer_recovery_injector *mystreamer; mystreamer = (bbstreamer_recovery_injector *) streamer; Assert(member != NULL || context == BBSTREAMER_ARCHIVE_TRAILER); switch (context) { case BBSTREAMER_MEMBER_HEADER: /* Must copy provided data so we have the option to modify it. */ memcpy(&mystreamer->member, member, sizeof(bbstreamer_member)); /* * On v12+, skip standby.signal and edit postgresql.auto.conf; on * older versions, skip recovery.conf. */ if (mystreamer->is_recovery_guc_supported) { mystreamer->skip_file = (strcmp(member->pathname, "standby.signal") == 0); mystreamer->is_postgresql_auto_conf = (strcmp(member->pathname, "postgresql.auto.conf") == 0); if (mystreamer->is_postgresql_auto_conf) { /* Remember we saw it so we don't add it again. */ mystreamer->found_postgresql_auto_conf = true; /* Increment length by data to be injected. */ mystreamer->member.size += mystreamer->recoveryconfcontents->len; /* * Zap data and len because the archive header is no * longer valid; some subsequent bbstreamer must * regenerate it if it's necessary. */ data = NULL; len = 0; } } else mystreamer->skip_file = (strcmp(member->pathname, "recovery.conf") == 0); /* Do not forward if the file is to be skipped. */ if (mystreamer->skip_file) return; break; case BBSTREAMER_MEMBER_CONTENTS: /* Do not forward if the file is to be skipped. */ if (mystreamer->skip_file) return; break; case BBSTREAMER_MEMBER_TRAILER: /* Do not forward it the file is to be skipped. */ if (mystreamer->skip_file) return; /* Append provided content to whatever we already sent. */ if (mystreamer->is_postgresql_auto_conf) bbstreamer_content(mystreamer->base.bbs_next, member, mystreamer->recoveryconfcontents->data, mystreamer->recoveryconfcontents->len, BBSTREAMER_MEMBER_CONTENTS); break; case BBSTREAMER_ARCHIVE_TRAILER: if (mystreamer->is_recovery_guc_supported) { /* * If we didn't already find (and thus modify) * postgresql.auto.conf, inject it as an additional archive * member now. */ if (!mystreamer->found_postgresql_auto_conf) bbstreamer_inject_file(mystreamer->base.bbs_next, "postgresql.auto.conf", mystreamer->recoveryconfcontents->data, mystreamer->recoveryconfcontents->len); /* Inject empty standby.signal file. */ bbstreamer_inject_file(mystreamer->base.bbs_next, "standby.signal", "", 0); } else { /* Inject recovery.conf file with specified contents. */ bbstreamer_inject_file(mystreamer->base.bbs_next, "recovery.conf", mystreamer->recoveryconfcontents->data, mystreamer->recoveryconfcontents->len); } /* Nothing to do here. */ break; default: /* Shouldn't happen. */ pg_log_error("unexpected state while injecting recovery settings"); exit(1); } bbstreamer_content(mystreamer->base.bbs_next, &mystreamer->member, data, len, context); } /* * End-of-stream processing for this bbstreamer. */ static void bbstreamer_recovery_injector_finalize(bbstreamer *streamer) { bbstreamer_finalize(streamer->bbs_next); } /* * Free memory associated with this bbstreamer. */ static void bbstreamer_recovery_injector_free(bbstreamer *streamer) { bbstreamer_free(streamer->bbs_next); pfree(streamer); } /* * Inject a member into the archive with specified contents. */ void bbstreamer_inject_file(bbstreamer *streamer, char *pathname, char *data, int len) { bbstreamer_member member; strlcpy(member.pathname, pathname, MAXPGPATH); member.size = len; member.mode = pg_file_create_mode; member.is_directory = false; member.is_link = false; member.linktarget[0] = '\0'; /* * There seems to be no principled argument for these values, but they are * what PostgreSQL has historically used. */ member.uid = 04000; member.gid = 02000; /* * We don't know here how to generate valid member headers and trailers * for the archiving format in use, so if those are needed, some successor * bbstreamer will have to generate them using the data from 'member'. */ bbstreamer_content(streamer, &member, NULL, 0, BBSTREAMER_MEMBER_HEADER); bbstreamer_content(streamer, &member, data, len, BBSTREAMER_MEMBER_CONTENTS); bbstreamer_content(streamer, &member, NULL, 0, BBSTREAMER_MEMBER_TRAILER); }
3,000
3,921
/* * Created by LuaView. * Copyright (c) 2017, Alibaba Group. All rights reserved. * * This source code is licensed under the MIT. * For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. */ package com.taobao.luaview.userdata.ui; import android.graphics.Canvas; import android.view.ViewGroup; import com.taobao.luaview.util.LuaUtil; import com.taobao.luaview.view.LVViewGroup; import org.luaj.vm2.Globals; import org.luaj.vm2.LuaValue; import org.luaj.vm2.Varargs; /** * 容器类 * * @author song * @date 15/8/20 */ public class UDCustomView<T extends ViewGroup> extends UDViewGroup<T> { private LuaValue mOnDraw; private UDCanvas mCanvas; public UDCustomView(T view, Globals globals, LuaValue metatable, Varargs initParams) { super(view, globals, metatable, initParams); } @Override public UDCustomView setCallback(LuaValue callbacks) { super.setCallback(callbacks); if (this.mCallback != null) { mOnDraw = LuaUtil.getFunction(mCallback, "onDraw", "OnDraw"); } return this; } public LuaValue setOnDrawCallback(LuaValue mOnDraw) { this.mOnDraw = mOnDraw; return this; } public LuaValue getOnDrawCallback() { return this.mOnDraw; } public boolean hasOnDrawCallback() { return this.mOnDraw != null && this.mOnDraw.isfunction(); } public LuaValue callOnDraw(LVViewGroup viewGroup, Canvas canvas) { if (mCanvas == null) { mCanvas = new UDCanvas(viewGroup, canvas, getGlobals(), getmetatable(), null); } else { mCanvas.setCanvas(canvas); mCanvas.setTarget(viewGroup); } return LuaUtil.callFunction(mOnDraw, mCanvas); } }
728
2,073
/** * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.mahout.math; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.hadoop.io.Writable; import org.apache.mahout.math.Vector.Element; import org.junit.Test; import com.carrotsearch.randomizedtesting.RandomizedTest; import com.carrotsearch.randomizedtesting.annotations.Repeat; import com.google.common.io.Closeables; public final class VectorWritableTest extends RandomizedTest { private static final int MAX_VECTOR_SIZE = 100; public void createRandom(Vector v) { int size = randomInt(v.size() - 1); for (int i = 0; i < size; ++i) { v.set(randomInt(v.size() - 1), randomDouble()); } int zeros = Math.max(2, size / 4); for (Element e : v.nonZeroes()) { if (e.index() % zeros == 0) { e.set(0.0); } } } @Test @Repeat(iterations = 20) public void testViewSequentialAccessSparseVectorWritable() throws Exception { Vector v = new SequentialAccessSparseVector(MAX_VECTOR_SIZE); createRandom(v); Vector view = new VectorView(v, 0, v.size()); doTestVectorWritableEquals(view); } @Test @Repeat(iterations = 20) public void testSequentialAccessSparseVectorWritable() throws Exception { Vector v = new SequentialAccessSparseVector(MAX_VECTOR_SIZE); createRandom(v); doTestVectorWritableEquals(v); } @Test @Repeat(iterations = 20) public void testRandomAccessSparseVectorWritable() throws Exception { Vector v = new RandomAccessSparseVector(MAX_VECTOR_SIZE); createRandom(v); doTestVectorWritableEquals(v); } @Test @Repeat(iterations = 20) public void testDenseVectorWritable() throws Exception { Vector v = new DenseVector(MAX_VECTOR_SIZE); createRandom(v); doTestVectorWritableEquals(v); } @Test @Repeat(iterations = 20) public void testNamedVectorWritable() throws Exception { Vector v = new DenseVector(MAX_VECTOR_SIZE); v = new NamedVector(v, "Victor"); createRandom(v); doTestVectorWritableEquals(v); } private static void doTestVectorWritableEquals(Vector v) throws IOException { Writable vectorWritable = new VectorWritable(v); VectorWritable vectorWritable2 = new VectorWritable(); writeAndRead(vectorWritable, vectorWritable2); Vector v2 = vectorWritable2.get(); if (v instanceof NamedVector) { assertTrue(v2 instanceof NamedVector); NamedVector nv = (NamedVector) v; NamedVector nv2 = (NamedVector) v2; assertEquals(nv.getName(), nv2.getName()); assertEquals("Victor", nv.getName()); } assertEquals(v, v2); } private static void writeAndRead(Writable toWrite, Writable toRead) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); try { toWrite.write(dos); } finally { Closeables.close(dos, false); } ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); DataInputStream dis = new DataInputStream(bais); try { toRead.readFields(dis); } finally { Closeables.close(dos, true); } } }
1,359
1,645
/* * Seldon -- open source prediction engine * ======================================= * * Copyright 2011-2015 Seldon Technologies Ltd and Rummble Ltd (http://www.seldon.io/) * * ******************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ******************************************************************************************** */ package io.seldon.api.jdo; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Date; import io.seldon.api.Constants; /** * @author claudio */ public class Token { public final static String DEFAULT_SCOPE = "all"; public final static String DEFAULT_TYPE = "rummblelabs"; public final static int TOKEN_MIN_LEN = 15; private final static SecureRandom random = new SecureRandom(); //ATTRIBUTES String tokenKey; //token value Date time; //token creation time String type; //token type String scope; //token scope long expires_in; //token expire time boolean active; //show if the token is valid or not Consumer consumer; //consumer owner of the token //CONSTRUCTOR public Token(Consumer consumer) { tokenKey = randomString(12); time = new Date(); type = DEFAULT_TYPE; if(consumer.getScope() != null) { scope = consumer.getScope(); } else { scope = DEFAULT_SCOPE; } expires_in = Constants.TOKEN_TIMEOUT; active = true; this.consumer = consumer; } //GETTERS AND SETTERS public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } public String getType() { return type; } public void setType(String type) { this.type = type; } public long getExpires_in() { return expires_in; } public void setExpires_in(long expiresIn) { expires_in = expiresIn; } public String getKey() { return tokenKey; } public void setKey(String key) { this.tokenKey = key; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public Consumer getConsumer() { return consumer; } public void setConsumer(Consumer consumer) { this.consumer = consumer; } //METHODS public String randomString(int size) { return new BigInteger(130,random).toString(32); } }
896
501
<reponame>shujaatak/finplot #!/usr/bin/env python3 from collections import defaultdict import dateutil.parser import finplot as fplt import numpy as np import pandas as pd import requests baseurl = 'https://www.bitmex.com/api' def local2timestamp(s): return int(dateutil.parser.parse(s).timestamp()) def download_price_history(symbol='XBTUSD', start_time='2020-01-10', end_time='2020-05-07', interval_mins=60): start_time = local2timestamp(start_time) end_time = local2timestamp(end_time) data = defaultdict(list) for start_t in range(start_time, end_time, 10000*60*interval_mins): end_t = start_t + 10000*60*interval_mins if end_t > end_time: end_t = end_time url = '%s/udf/history?symbol=%s&resolution=%s&from=%s&to=%s' % (baseurl, symbol, interval_mins, start_t, end_t) print(url) d = requests.get(url).json() del d['s'] # ignore status=ok for col in d: data[col] += d[col] df = pd.DataFrame(data) df = df.rename(columns={'t':'time', 'o':'open', 'c':'close', 'h':'high', 'l':'low', 'v':'volume'}) return df.set_index('time') def plot_accumulation_distribution(df, ax): ad = (2*df.close-df.high-df.low) * df.volume / (df.high - df.low) ad.cumsum().ffill().plot(ax=ax, legend='Accum/Dist', color='#f00000') def plot_bollinger_bands(df, ax): mean = df.close.rolling(20).mean() stddev = df.close.rolling(20).std() df['boll_hi'] = mean + 2.5*stddev df['boll_lo'] = mean - 2.5*stddev p0 = df.boll_hi.plot(ax=ax, color='#808080', legend='BB') p1 = df.boll_lo.plot(ax=ax, color='#808080') fplt.fill_between(p0, p1, color='#bbb') def plot_ema(df, ax): df.close.ewm(span=9).mean().plot(ax=ax, legend='EMA') def plot_heikin_ashi(df, ax): df['h_close'] = (df.open+df.close+df.high+df.low) / 4 ho = (df.open.iloc[0] + df.close.iloc[0]) / 2 for i,hc in zip(df.index, df['h_close']): df.loc[i, 'h_open'] = ho ho = (ho + hc) / 2 print(df['h_open']) df['h_high'] = df[['high','h_open','h_close']].max(axis=1) df['h_low'] = df[['low','h_open','h_close']].min(axis=1) df[['h_open','h_close','h_high','h_low']].plot(ax=ax, kind='candle') def plot_heikin_ashi_volume(df, ax): df[['h_open','h_close','volume']].plot(ax=ax, kind='volume') def plot_on_balance_volume(df, ax): obv = df.volume.copy() obv[df.close < df.close.shift()] = -obv obv[df.close==df.close.shift()] = 0 obv.cumsum().plot(ax=ax, legend='OBV', color='#008800') def plot_rsi(df, ax): diff = df.close.diff().values gains = diff losses = -diff with np.errstate(invalid='ignore'): gains[(gains<0)|np.isnan(gains)] = 0.0 losses[(losses<=0)|np.isnan(losses)] = 1e-10 # we don't want divide by zero/NaN n = 14 m = (n-1) / n ni = 1 / n g = gains[n] = np.nanmean(gains[:n]) l = losses[n] = np.nanmean(losses[:n]) gains[:n] = losses[:n] = np.nan for i,v in enumerate(gains[n:],n): g = gains[i] = ni*v + m*g for i,v in enumerate(losses[n:],n): l = losses[i] = ni*v + m*l rs = gains / losses df['rsi'] = 100 - (100/(1+rs)) df.rsi.plot(ax=ax, legend='RSI') fplt.set_y_range(0, 100, ax=ax) fplt.add_band(30, 70, ax=ax) def plot_vma(df, ax): df.volume.rolling(20).mean().plot(ax=ax, color='#c0c030') symbol = 'XBTUSD' df = download_price_history(symbol=symbol) ax,axv,ax2,ax3,ax4 = fplt.create_plot('BitMEX %s heikin-ashi price history' % symbol, rows=5) ax.set_visible(xgrid=True, ygrid=True) # price chart plot_heikin_ashi(df, ax) plot_bollinger_bands(df, ax) plot_ema(df, ax) # volume chart plot_heikin_ashi_volume(df, axv) plot_vma(df, ax=axv) # some more charts plot_accumulation_distribution(df, ax2) plot_on_balance_volume(df, ax3) plot_rsi(df, ax4) # restore view (X-position and zoom) when we run this example again fplt.autoviewrestore() fplt.show()
1,859
6,989
<filename>chatbot_env/Lib/site-packages/sklearn/inspection/partial_dependence.py # THIS FILE WAS AUTOMATICALLY GENERATED BY deprecated_modules.py import sys from . import _partial_dependence from ..externals._pep562 import Pep562 from ..utils.deprecation import _raise_dep_warning_if_not_pytest deprecated_path = 'sklearn.inspection.partial_dependence' correct_import_path = 'sklearn.inspection' _raise_dep_warning_if_not_pytest(deprecated_path, correct_import_path) def __getattr__(name): return getattr(_partial_dependence, name) if not sys.version_info >= (3, 7): Pep562(__name__)
205
1,128
<filename>configs/fdf/retinanet/128.py import os _base_config_ = "base.py" model_url = "http://folk.ntnu.no/haakohu/checkpoints/fdf/retinanet128.ckpt" models = dict( generator=dict( type="MSGGenerator", scalar_pose_input=True ), discriminator=dict( residual=True ) ) trainer = dict( progressive=dict( enabled=False, ) )
179
348
{"nom":"Beaulieu","circ":"4ème circonscription","dpt":"Puy-de-Dôme","inscrits":346,"abs":221,"votants":125,"blancs":16,"nuls":3,"exp":106,"res":[{"nuance":"LR","nom":"M. <NAME>","voix":63},{"nuance":"MDM","nom":"<NAME>","voix":43}]}
97
1,293
/* * Copyright (c) 2020 - Manifold Systems LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package manifold.ext.rt; import java.lang.reflect.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; import manifold.ext.rt.extensions.java.util.Map.MapStructExt; import manifold.rt.api.Bindings; import manifold.rt.api.util.ManClassUtil; import manifold.ext.rt.api.*; import manifold.rt.api.util.ServiceUtil; import manifold.util.ReflectUtil; import manifold.util.ReflectUtil.FakeProxy; import manifold.util.concurrent.LocklessLazyVar; public class RuntimeMethods { private static Map<Class, Map<Class, IProxyFactory<?,?>>> PROXY_CACHE = new ConcurrentHashMap<>(); private static final LocklessLazyVar<Set<IProxyFactory>> _registeredProxyFactories = LocklessLazyVar.make( () -> { Set<IProxyFactory> registered = new HashSet<>(); ServiceUtil.loadRegisteredServices( registered, IProxyFactory.class, RuntimeMethods.class.getClassLoader() ); return registered; } ); private static final LocklessLazyVar<IDynamicProxyFactory> _dynamicProxyFactory = LocklessLazyVar.make( () -> { Set<IDynamicProxyFactory> registered = new HashSet<>(); ServiceUtil.loadRegisteredServices( registered, IDynamicProxyFactory.class, RuntimeMethods.class.getClassLoader() ); return registered.isEmpty() ? null : registered.iterator().next(); } ); @SuppressWarnings({"UnusedDeclaration", "WeakerAccess"}) public static Object constructProxy( Object root, Class iface ) { // return findCachedProxy( root, iface ); // this is only beneficial when structural invocation happens in a loop, otherwise too costly return createNewProxy( root, iface ); } public static Object coerceFromBindingsValue( Object value, Type t ) { //## would like to do this to limit proxies to just structural calls, however since we support default interface methods //## we have a situation where a more specific interface "implements" using a default method a less specific interface, //## however if a bindings/map is cast to the less specific one, there the default impl isn't there... boom. Therefore, //## we have to keep the proxies alive, thereby allowing such casts to work. // if( value instanceof Bindings ) // { // return value; // } return coerce( value, t ); } /** * Coerce a value e.g., from a JSON bindings, to a more specific a Java value, using {@link ICoercionProvider} * where applicable. Note, for {@code List} the {@code type} corresponds with the deepest component type of the list, * see {@code ListCoercer}. */ public static Object coerce( Object value, Type t ) { Class<?> type = t instanceof ParameterizedType ? (Class<?>)((ParameterizedType)t).getRawType() : (Class)t; if( value == null ) { if( type.isPrimitive() ) { return defaultPrimitiveValue( type ); } return null; } if( value instanceof List ) { Object result = callCoercionProviders( value, t ); if( result != ICallHandler.UNHANDLED ) { return result; } return value; } if( type.isPrimitive() ) { type = ManClassUtil.box( type ); } Class<?> valueClass = value.getClass(); if( valueClass == type || type.isAssignableFrom( valueClass ) ) { return value; } Object result = callCoercionProviders( value, t ); if( result != ICallHandler.UNHANDLED ) { return result; } if( value instanceof String && ((String)value).isEmpty() && type != String.class ) { // empty string is null e.g., CSV empty values are empty strings return null; } Object boxedValue = coerceBoxed( value, type ); if( boxedValue != null ) { return boxedValue; } if( type == BigInteger.class ) { if( value instanceof Number ) { return BigInteger.valueOf( ((Number)value).longValue() ); } if( value instanceof Boolean ) { return ((Boolean)value) ? BigInteger.ONE : BigInteger.ZERO; } return new BigInteger( value.toString() ); } if( type == BigDecimal.class ) { if( value instanceof Boolean ) { return ((Boolean)value) ? BigDecimal.ONE : BigDecimal.ZERO; } return new BigDecimal( value.toString() ); } if( type == String.class ) { return String.valueOf( value ); } if( type.isEnum() ) { String name = String.valueOf( value ); //noinspection unchecked return Enum.valueOf( (Class<Enum>)type, name ); } if( type.isArray() && valueClass.isArray() ) { int length = Array.getLength( value ); Class<?> componentType = type.getComponentType(); Object array = Array.newInstance( componentType, length ); for( int i = 0; i < length; i++ ) { Array.set( array, i, coerce( Array.get( value, i ), componentType ) ); } return array; } // let the ClassCastException happen return value; } private static Object defaultPrimitiveValue( Class<?> type ) { if( type == int.class || type == short.class ) { return 0; } if( type == byte.class ) { return (byte)0; } if( type == long.class ) { return 0L; } if( type == float.class ) { return 0f; } if( type == double.class ) { return 0d; } if( type == boolean.class ) { return false; } if( type == char.class ) { return (char)0; } if( type == void.class ) { return null; } throw new IllegalArgumentException( "Unsupported primitive type: " + type.getSimpleName() ); } private static Object coerceBoxed( Object value, Class<?> type ) { if( type == Boolean.class || type == boolean.class ) { if( value instanceof Number ) { return ((Number)value).intValue() != 0; } return Boolean.parseBoolean( value.toString() ); } if( type == Byte.class || type == byte.class ) { if( value instanceof Number ) { return ((Number)value).byteValue() != 0; } if( value instanceof Boolean ) { return ((Boolean)value) ? (byte)1 : (byte)0; } return Byte.parseByte( value.toString() ); } if( type == Character.class || type == char.class ) { if( value instanceof Number ) { return (char)((Number)value).intValue(); } String s = value.toString(); return s.isEmpty() ? (char)0 : s.charAt( 0 ); } if( type == Short.class || type == short.class ) { if( value instanceof Number ) { return ((Number)value).shortValue(); } if( value instanceof Boolean ) { return ((Boolean)value) ? (short)1 : (short)0; } return Short.parseShort( value.toString() ); } if( type == Integer.class || type == int.class ) { if( value instanceof Number ) { return ((Number)value).intValue(); } if( value instanceof Boolean ) { return ((Boolean)value) ? 1 : 0; } return Integer.parseInt( value.toString() ); } if( type == Long.class || type == long.class ) { if( value instanceof Number ) { return ((Number)value).longValue(); } if( value instanceof Boolean ) { return ((Boolean)value) ? 1L : 0L; } return Long.parseLong( value.toString() ); } if( type == Float.class || type == float.class ) { if( value instanceof Number ) { return ((Number)value).floatValue(); } if( value instanceof Boolean ) { return ((Boolean)value) ? 1f : 0f; } return Float.parseFloat( value.toString() ); } if( type == Double.class || type == double.class ) { if( value instanceof Number ) { return ((Number)value).doubleValue(); } if( value instanceof Boolean ) { return ((Boolean)value) ? 1d : 0d; } return Double.parseDouble( value.toString() ); } return null; } private static Object callCoercionProviders( Object value, Type type ) { for( ICoercionProvider coercer: CoercionProviders.get() ) { Object coercedValue = coercer.coerce( value, type ); if( coercedValue != ICallHandler.UNHANDLED ) { return coercedValue; } } return ICallHandler.UNHANDLED; } private static Method findMethod( Class<?> iface, String name, Class[] paramTypes ) { try { Method m = iface.getDeclaredMethod( name, paramTypes ); if( m == null ) { for( Class superIface: iface.getInterfaces() ) { m = findMethod( superIface, name, paramTypes ); if( m != null ) { break; } } } if( m != null ) { return m; } } catch( Exception e ) { return null; } return null; } private static Object createNewProxy( Object root, Class<?> iface ) { if( root == null ) { return null; } Class rootClass = root.getClass(); if( iface.isAssignableFrom( rootClass ) ) { return root; } Map<Class, IProxyFactory<?,?>> proxyByClass = PROXY_CACHE.get( iface ); if( proxyByClass == null ) { PROXY_CACHE.put( iface, proxyByClass = new ConcurrentHashMap<>() ); } IProxyFactory proxyFactory = proxyByClass.get( rootClass ); if( proxyFactory == null ) { proxyFactory = createProxy( iface, rootClass ); proxyByClass.put( rootClass, proxyFactory ); } try { // in Java 9+ in modular mode the proxy class belongs to the owner's module, // therefore we need to make it accessible from the manifold module before // calling newInstance() //noinspection unchecked return proxyFactory.proxy( root, iface ); } catch( Exception e ) { throw new RuntimeException( e ); } } private static IProxyFactory createProxy( Class iface, Class rootClass ) { IProxyFactory proxyFactory = maybeSelfProxyClass( rootClass, iface ); if( proxyFactory == null ) { IDynamicProxyFactory dynamicProxyFactory = _dynamicProxyFactory.get(); if( dynamicProxyFactory == null || rootClass.isAnonymousClass() ) { // No Manifold runtime operating (manifold was used exclusively at compile-time), so we use a proxy that calls dynamically at runtime return makeDynamicProxyNoManifoldRuntimeHost( rootClass, iface ); } proxyFactory = dynamicProxyFactory.makeProxyFactory( iface, rootClass ); } return proxyFactory; } private static IProxyFactory makeDynamicProxyNoManifoldRuntimeHost( Class rootClass, Class intface ) { if( Map.class.isAssignableFrom( rootClass ) ) { return (target, iface) -> manifold.ext.rt.proxy.Proxy.newProxyInstance( intface.getClassLoader(), new Class[]{iface}, (proxy, method, args) -> MapStructExt.invoke( (Map)target, proxy, method, args) ); } if( List.class.isAssignableFrom( rootClass ) ) { return (target, iface) -> manifold.ext.rt.proxy.Proxy.newProxyInstance( intface.getClassLoader(), new Class[]{iface}, (proxy, method, args) -> ListProxy.invoke( (List)target, proxy, method, args) ); } return (target, iface) -> manifold.ext.rt.proxy.Proxy.newProxyInstance( intface.getClassLoader(), new Class[]{iface}, (proxy, method, args) -> ReflectUtil.structuralCallByProxy( method, proxy, target, args ) ); } public static IProxyFactory maybeSelfProxyClass( Class<?> rootClass, Class<?> iface ) { // The self-proxy strategy avoids costs otherwise involved with generating a proxy dynamically, // and since it's compiled statically with manifold, the proxy source can use manifold features // such as extension methods, operator overloading, etc. Structural anno = iface.getAnnotation( Structural.class ); if( anno != null ) { Class factoryClass = anno.factoryClass(); if( factoryClass != Void.class ) { // If the proxy factory declared in @Structural handles the rootClass, create the proxy via the factory IProxyFactory proxyFactory = maybeMakeProxyFactory( rootClass, iface, factoryClass, RuntimeMethods::constructProxyFactory ); if( proxyFactory != null ) { return proxyFactory; } } } // See if there is a registered IProxyFactory for the rootClass and iface, so create one that way, // otherwise return null return findRegisteredFactory( rootClass, iface ); } private static IProxyFactory findRegisteredFactory( Class<?> rootClass, Class<?> iface ) { //noinspection ConstantConditions return _registeredProxyFactories.get().stream() .filter( e -> !(e instanceof IDynamicProxyFactory) ) .filter( e -> maybeMakeProxyFactory( rootClass, iface, e.getClass(), c -> e ) != null ) .findFirst().orElse( null ); } private static IProxyFactory maybeMakeProxyFactory( Class<?> rootClass, Class<?> ifaceClass, Class factoryClass, Function<Class<?>, IProxyFactory> proxyFactoryMaker ) { Type type = Arrays.stream( factoryClass.getGenericInterfaces() ) .filter( e -> e.getTypeName().startsWith( IProxyFactory.class.getTypeName() ) ) .findFirst().orElse( null ); if( type instanceof ParameterizedType ) { Type typeArg1 = ((ParameterizedType)type).getActualTypeArguments()[0]; if( typeArg1 instanceof ParameterizedType ) { typeArg1 = ((ParameterizedType)typeArg1).getRawType(); } if( !((Class<?>)typeArg1).isAssignableFrom( rootClass ) ) { return null; } Type typeArg2 = ((ParameterizedType)type).getActualTypeArguments()[1]; if( typeArg2 instanceof ParameterizedType ) { typeArg2 = ((ParameterizedType)typeArg2).getRawType(); } if( ((Class<?>)typeArg2).isAssignableFrom( ifaceClass ) ) { return proxyFactoryMaker.apply( factoryClass ); } } return null; } private static IProxyFactory constructProxyFactory( Class factoryClass ) { try { // In Java 9+ in modular mode the proxy factory class belongs to the owner's module, // therefore we need to use the constructor and make it accessible from the manifold module // before calling newInstance() (as opposed to calling newInstance() from the class) Constructor constructor = factoryClass.getConstructors()[0]; ReflectUtil.setAccessible( constructor ); return (IProxyFactory)constructor.newInstance(); //return (IProxyFactory)factoryClass.newInstance(); } catch( Exception e ) { throw new RuntimeException( e ); } } public static Object coerceToBindingValue( Object arg ) { if( arg instanceof IBindingType ) { return ((IBindingType)arg).toBindingValue(); } if( arg instanceof IBindingsBacked ) { return ((IBindingsBacked)arg).getBindings(); } if( arg instanceof IListBacked ) { return ((IListBacked) arg).getList(); } if( arg instanceof List ) { //noinspection unchecked return ((List)arg).stream() .map( e -> coerceToBindingValue( e ) ) .collect( Collectors.toList() ); } if( needsCoercion( arg ) ) { for( ICoercionProvider coercer: CoercionProviders.get() ) { Object coercedValue = coercer.toBindingValue( arg ); if( coercedValue != ICallHandler.UNHANDLED ) { return coercedValue; } } } return arg; } private static boolean needsCoercion( Object arg ) { return arg != null && !(arg instanceof Bindings) && !isPrimitiveType( arg.getClass() ); } private static boolean isPrimitiveType( Class<?> type ) { return type == String.class || type == Boolean.class || type == Character.class || type == Byte.class || type == Short.class || type == Integer.class || type == Long.class || type == Float.class || type == Double.class; } @SuppressWarnings( "unused" ) public static Object unFakeProxy( Object proxy ) { if( proxy == null || !Proxy.isProxyClass( proxy.getClass() ) ) { return proxy; } InvocationHandler invocationHandler = Proxy.getInvocationHandler( proxy ); if( invocationHandler instanceof FakeProxy ) { return ((FakeProxy)invocationHandler).getTarget(); } return proxy; } }
6,686
488
// test lots of combinations of forwarding template<class T, int I> T f(T x, T i[I]); template<class T, int I> T f(T x, T i[I]); template<class T, int I> T f(T x, T i[I]) { return x; } template<class T, int I> T f(T x, T i[I]); template<class T, int I> T f(T x, T i[I]); template<class T, int I> struct A; template<class T, int I> struct A; template<class T, int I> struct A { T x; A() : x(I) {} }; template<class T, int I> struct A; template<class T, int I> struct A; // Hmm, you just can't do this // template<class T, int I> T g(A<T*, I+1> a, (*f1)f<T[], I+2>, I z); template<class T, int I> T g(A<T*, I> a, T i[I]); template<class T, int I> T g(A<T*, I> a, T i[I]); template<class T, int I> T g(A<T*, I> a, T i[I]) { return i[0]; } template<class T, int I> T g(A<T*, I> a, T i[I]); template<class T, int I> T g(A<T*, I> a, T i[I]); int main() { int x = 3; int y[4]; f<int, 4>(x, y); A<int*, 0/*NULL*/> b; g(b, y); }
435
603
<gh_stars>100-1000 import json import os from whylogs.proto import DoublesMessage from whylogs.util import protobuf _MY_DIR = os.path.realpath(os.path.dirname(__file__)) def test_message_to_dict_returns_default_values(): msg1 = DoublesMessage(min=0, max=0, sum=0, count=10) d1 = protobuf.message_to_dict(msg1) msg2 = DoublesMessage(count=10) d2 = protobuf.message_to_dict(msg2) true_val = { "min": 0.0, "max": 0.0, "sum": 0.0, "count": "10", } assert d1 == true_val assert d2 == true_val def test_message_to_dict_equals_message_to_json(): msg = DoublesMessage(min=0, max=1.0, sum=2.0, count=10) d1 = protobuf.message_to_dict(msg) d2 = json.loads(protobuf.message_to_json(msg)) assert d1 == d2 def test_message_to_dict(): msg1 = DoublesMessage(min=0, max=0, sum=0, count=10) protobuf.repr_message(msg1)
415
3,181
/* * SPDX-FileCopyrightText: 2020, microG Project Team * SPDX-License-Identifier: Apache-2.0 */ package org.microg.gms.nearby.exposurenotification; import static org.microg.gms.common.Constants.GMS_VERSION_CODE; public class Constants { public static final String ACTION_EXPOSURE_NOTIFICATION_SETTINGS = "com.google.android.gms.settings.EXPOSURE_NOTIFICATION_SETTINGS"; public static final String ACTION_EXPOSURE_NOT_FOUND = "com.google.android.gms.exposurenotification.ACTION_EXPOSURE_NOT_FOUND"; public static final String ACTION_EXPOSURE_STATE_UPDATED = "com.google.android.gms.exposurenotification.ACTION_EXPOSURE_STATE_UPDATED"; public static final String ACTION_PRE_AUTHORIZE_RELEASE_PHONE_UNLOCKED = "com.google.android.gms.exposurenotification.ACTION_PRE_AUTHORIZE_RELEASE_PHONE_UNLOCKED"; public static final String ACTION_SERVICE_STATE_UPDATED = "com.google.android.gms.exposurenotification.ACTION_SERVICE_STATE_UPDATED"; public static final String EXTRA_EXPOSURE_SUMMARY = "com.google.android.gms.exposurenotification.EXTRA_EXPOSURE_SUMMARY"; public static final String EXTRA_SERVICE_STATE = "com.google.android.gms.exposurenotification.EXTRA_SERVICE_STATE"; public static final String EXTRA_TEMPORARY_EXPOSURE_KEY_LIST = "com.google.android.gms.exposurenotification.EXTRA_TEMPORARY_EXPOSURE_KEY_LIST"; public static final String EXTRA_TOKEN = "com.google.android.gms.exposurenotification.EXTRA_TOKEN"; public static final String TOKEN_A = "<KEY>"; public static final int DAYS_SINCE_ONSET_OF_SYMPTOMS_UNKNOWN = Integer.MAX_VALUE; public static final int VERSION = 18; public static final long VERSION_FULL = ((long)VERSION) * 1000000000L + GMS_VERSION_CODE; }
600
348
<filename>docs/data/leg-t2/021/02104685.json<gh_stars>100-1000 {"nom":"Villaines-en-Duesmois","circ":"4ème circonscription","dpt":"Côte-d'Or","inscrits":215,"abs":119,"votants":96,"blancs":7,"nuls":1,"exp":88,"res":[{"nuance":"REM","nom":"<NAME>","voix":51},{"nuance":"LR","nom":"M. <NAME>","voix":37}]}
130
461
<reponame>The0x539/wasp<gh_stars>100-1000 /* category data */ enum category { #include "categories.cat" }; extern enum category category(wint_t ucs);
58
3,051
package org.gridkit.sjk.test.console.junit4; import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.util.Supplier; import org.gridkit.sjk.test.console.ConsoleTracker; import org.junit.rules.TestWatcher; import org.junit.runner.Description; public class ConsoleRule extends TestWatcher { public static ConsoleRule out() { return new ConsoleRule(ConsoleTracker.out()); } public static ConsoleRule err() { return new ConsoleRule(ConsoleTracker.err()); } private final ConsoleTracker tracker; private final List<Runnable> postInitHooks = new ArrayList<Runnable>(); public ConsoleRule(ConsoleTracker tracker) { this.tracker = tracker; } @Override protected void starting(Description description) { super.starting(description); tracker.init(); for (Runnable r: postInitHooks) { r.run(); } } @Override protected void finished(Description description) { super.finished(description); tracker.complete(); } /** * Some loggers may need reconfiguration to start logging to overriden our/err streams. */ public ConsoleRule postInit(Runnable r) { this.postInitHooks.add(r); return this; } public void verify() { tracker.verify(); } public boolean tryMatch() { return tracker.tryMatch(); } public void waitForMatch(Supplier<Boolean> until) throws InterruptedException { tracker.waitForMatch(until); } public void clean() { tracker.clean(); } public ConsoleRule skip() { tracker.skip(); return this; } public ConsoleRule skip(int lines) { tracker.skip(lines); return this; } public ConsoleRule line(String exact) { tracker.line(exact); return this; } public ConsoleRule lineStarts(String starts) { tracker.lineStarts(starts); return this; } public ConsoleRule lineStartsEx(String starts, String... vars) { tracker.lineStartsEx(starts, vars); return this; } public ConsoleRule lineContains(String... substring) { tracker.lineContains(substring); return this; } public ConsoleRule lineContainsEx(String substring, String... vars) { tracker.lineContainsEx(substring, vars); return this; } public ConsoleRule lineEx(String pattern, String... vars) { tracker.lineEx(pattern, vars); return this; } @Override public String toString() { return tracker.toString(); } }
1,035
310
<gh_stars>100-1000 package org.seasar.doma.jdbc; /** A provider for a {@link Config} object. */ public interface ConfigProvider { /** * Returns the configuration. * * @return the configuration */ Config getConfig(); }
79
809
<reponame>MrSquanchee/dev-embox #include <stdio.h> #include <embox/unit.h> EMBOX_UNIT_INIT(reent_init); struct _reent { int _errno; /* local copy of errno */ /* FILE is a big struct and may change over time. To try to achieve binary compatibility with future versions, put stdin,stdout,stderr here. These are pointers into member __sf defined below. */ FILE *_stdin, *_stdout, *_stderr; }; struct _reent global_newlib_reent; void *_impure_ptr = &global_newlib_reent; static int reent_init(void) { global_newlib_reent._stdin = stdin; global_newlib_reent._stdout = stdout; global_newlib_reent._stderr = stderr; return 0; }
264
351
<filename>zulip_bots/zulip_bots/bots/chessbot/test_chessbot.py from zulip_bots.test_lib import BotTestCase, DefaultTests class TestChessBot(BotTestCase, DefaultTests): bot_name = "chessbot" START_RESPONSE = """New game! The board looks like this: ``` a b c d e f g h 8 ♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜ 8 7 ♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟ 7 6 · · · · · · · · 6 5 · · · · · · · · 5 4 · · · · · · · · 4 3 · · · · · · · · 3 2 ♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙ 2 1 ♖ ♘ ♗ ♕ ♔ ♗ ♘ ♖ 1 a b c d e f g h ``` Now it's **white**'s turn. To make your next move, respond to Chess Bot with ```do <your move>``` *Remember to @-mention Chess Bot at the beginning of your response.*""" DO_E4_RESPONSE = """The board was like this: ``` h g f e d c b a 1 ♖ ♘ ♗ ♔ ♕ ♗ ♘ ♖ 1 2 ♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙ 2 3 · · · · · · · · 3 4 · · · · · · · · 4 5 · · · · · · · · 5 6 · · · · · · · · 6 7 ♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟ 7 8 ♜ ♞ ♝ ♚ ♛ ♝ ♞ ♜ 8 h g f e d c b a ``` Then *white* moved *e4*: ``` h g f e d c b a 1 ♖ ♘ ♗ ♔ ♕ ♗ ♘ ♖ 1 2 ♙ ♙ ♙ · ♙ ♙ ♙ ♙ 2 3 · · · · · · · · 3 4 · · · ♙ · · · · 4 5 · · · · · · · · 5 6 · · · · · · · · 6 7 ♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟ 7 8 ♜ ♞ ♝ ♚ ♛ ♝ ♞ ♜ 8 h g f e d c b a ``` Now it's **black**'s turn. To make your next move, respond to Chess Bot with ```do <your move>``` *Remember to @-mention Chess Bot at the beginning of your response.*""" DO_KE4_RESPONSE = """Sorry, the move *Ke4* isn't legal. ``` h g f e d c b a 1 ♖ ♘ ♗ ♔ ♕ ♗ ♘ ♖ 1 2 ♙ ♙ ♙ · ♙ ♙ ♙ ♙ 2 3 · · · · · · · · 3 4 · · · ♙ · · · · 4 5 · · · · · · · · 5 6 · · · · · · · · 6 7 ♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟ 7 8 ♜ ♞ ♝ ♚ ♛ ♝ ♞ ♜ 8 h g f e d c b a ``` To make your next move, respond to Chess Bot with ```do <your move>``` *Remember to @-mention Chess Bot at the beginning of your response.*""" RESIGN_RESPONSE = """*Black* resigned. **White** wins! ``` h g f e d c b a 1 ♖ ♘ ♗ ♔ ♕ ♗ ♘ ♖ 1 2 ♙ ♙ ♙ · ♙ ♙ ♙ ♙ 2 3 · · · · · · · · 3 4 · · · ♙ · · · · 4 5 · · · · · · · · 5 6 · · · · · · · · 6 7 ♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟ 7 8 ♜ ♞ ♝ ♚ ♛ ♝ ♞ ♜ 8 h g f e d c b a ```""" def test_bot_responds_to_empty_message(self) -> None: with self.mock_config_info({"stockfish_location": "/foo/bar"}): response = self.get_response(dict(content="")) self.assertIn("play chess", response["content"]) def test_main(self) -> None: with self.mock_config_info({"stockfish_location": "/foo/bar"}): self.verify_dialog( [ ("start with other user", self.START_RESPONSE), ("do e4", self.DO_E4_RESPONSE), ("do Ke4", self.DO_KE4_RESPONSE), ("resign", self.RESIGN_RESPONSE), ] )
1,427
2,770
<reponame>abadurehman/FlowingDrawer package com.mxn.soul.flowingdrawer; import com.squareup.picasso.Picasso; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.Toast; /** * Created by mxn on 2016/12/13. * MenuListFragment */ public class MenuListFragment extends Fragment { private ImageView ivMenuUserProfilePhoto; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_menu, container, false); ivMenuUserProfilePhoto = (ImageView) view.findViewById(R.id.ivMenuUserProfilePhoto); NavigationView vNavigation = (NavigationView) view.findViewById(R.id.vNavigation); vNavigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { Toast.makeText(getActivity(),menuItem.getTitle(),Toast.LENGTH_SHORT).show(); return false; } }) ; setupHeader(); return view ; } private void setupHeader() { int avatarSize = getResources().getDimensionPixelSize(R.dimen.global_menu_avatar_size); String profilePhoto = getResources().getString(R.string.user_profile_photo); Picasso.with(getActivity()) .load(profilePhoto) .placeholder(R.drawable.img_circle_placeholder) .resize(avatarSize, avatarSize) .centerCrop() .transform(new CircleTransformation()) .into(ivMenuUserProfilePhoto); } }
829