code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ /* Rosegarden A MIDI and audio sequencer and musical notation editor. Copyright 2000-2018 the Rosegarden development team. Other copyrights also apply to some parts of this work. Please see the AUTHORS file and individual file headers for details. 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. See the file COPYING included with this distribution for more information. */ #ifndef RG_CONFIGUREDIALOGBASE_H #define RG_CONFIGUREDIALOGBASE_H #include <QMessageBox> #include <QDialog> #include <QString> #include <vector> class QWidget; class QTabWidget; class QDialogButtonBox; class IconStackedWidget; namespace Rosegarden { class ConfigurationPage; class ConfigureDialogBase : public QDialog { Q_OBJECT public: ConfigureDialogBase(QWidget *parent = nullptr, const QString &label = {}, const char *name = nullptr); ~ConfigureDialogBase() override; typedef std::vector<ConfigurationPage*> configurationpages; void addPage( const QString& name, const QString& title, const QPixmap& icon, QWidget *page ); void setPageByIndex(int index); protected slots: void accept() override; virtual void slotApply(); virtual void slotCancelOrClose(); virtual void slotHelpRequested(); public slots: virtual void slotActivateApply(); public: void deactivateApply(); protected: configurationpages m_configurationPages; QPushButton *m_applyButton; QDialogButtonBox *m_dialogButtonBox; IconStackedWidget *m_iconWidget; }; } #endif
bownie/RosegardenW
gui/dialogs/ConfigureDialogBase.h
C
gpl-2.0
1,826
<?php /** * OrangeHRM is a comprehensive Human Resource Management (HRM) System that captures * all the essential functionalities required for any enterprise. * Copyright (C) 2006 OrangeHRM Inc., http://www.orangehrm.com * * OrangeHRM 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. * * OrangeHRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA */ class ReportGeneratorService extends BaseService { const LIST_SEPARATOR = "|\n|"; // ReportableService Data Access Object private $reportableService; /** * Gets the ReportableService Data Access Object * @return ReportableService */ public function getReportableService() { if (is_null($this->reportableService)) { $this->reportableService = new ReportableService(); } return $this->reportableService; } /** * Sets ReportableService Data Access Object * @param ReportableService $ReportableService * @return void */ public function setReportableService(ReportableService $ReportableService) { $this->reportableService = $ReportableService; } /** * Gets ids of the selectedFilterFields of a report, given the report id. * @param integer $reportId * @return array */ public function getSelectedFilterFieldIdsByReportId($reportId) { $selectedFilterFields = $this->getReportableService()->getSelectedFilterFields($reportId, true); if ($selectedFilterFields != null) { $selectedFilterFieldIdArray = array(); foreach ($selectedFilterFields as $selectedFilterField) { $selectedFilterFieldIdArray[] = $selectedFilterField->getFilterFieldId(); } return $selectedFilterFieldIdArray; } else { return null; } } /** * Gets the id of the report group that is related to a report. ( given report id ) * @param integer $reportId * @return integer */ public function getReportGroupIdOfAReport($reportId) { $report = $this->getReportableService()->getReport($reportId); if ($report != null) { $reportGroup = $report->getReportGroup(); $reportGroupId = $reportGroup->getReportGroupId(); return $reportGroupId; } else { return null; } } /** * Reorders FilterFields according to ids, in the order given in selectedFilterFieldIds array. * @param integer[] $selectedFilterFieldIds * @param FilterField[] $runtimeFilterFields * @return Doctrine_Collection (FilterField) */ public function orderRuntimeFilterFields($selectedFilterFieldIds, $runtimeFilterFields) { $filterFields = new Doctrine_Collection("FilterField"); foreach ($selectedFilterFieldIds as $id) { foreach ($runtimeFilterFields as $runtimeFilterField) { if ($runtimeFilterField->getFilterFieldId() == $id) { $filterFields->add($runtimeFilterField); break; } } } return $filterFields; } /** * Gets widget names and label names of runtime filter fields for a given report (ie. given report id) * @param integer $reportId * @return array */ public function getRuntimeFilterFieldWidgetNamesAndLabels($reportId) { $reportGroupId = $this->getReportGroupIdOfAReport($reportId); $type = PluginSelectedFilterField::RUNTIME_FILTER_FIELD; $runtimeSelectedFilterFields = $this->getReportableService()->getSelectedFilterFieldsByType($reportId, $type, true); if (($reportGroupId != null) && ($runtimeSelectedFilterFields != null)) { $runtimeFilterFieldWidgetNamesAndLabels = array(); foreach ($runtimeSelectedFilterFields as $runtimeSelectedFilterField) { $runtimeFilterField = $runtimeSelectedFilterField->getFilterField(); $tempArray['widgetName'] = $runtimeFilterField->getFilterFieldWidget(); $tempArray['labelName'] = $runtimeFilterField->getName(); $tempArray['required'] = $runtimeFilterField->getRequired(); $runtimeFilterFieldWidgetNamesAndLabels[] = $tempArray; } return $runtimeFilterFieldWidgetNamesAndLabels; } else { return null; } } /** * Generates runtime where clause conditions using the value * @param FilterField[] $selectedRuntimeFilterFields * @param array $values * @return array */ public function generateRuntimeWhereClauseConditions($selectedRuntimeFilterFields, $values) { $conditionArray = array(); foreach ($selectedRuntimeFilterFields as $runtimeFilterField) { $labelName = $runtimeFilterField->getName(); $widgetName = $runtimeFilterField->getFilterFieldWidget(); $widget = new $widgetName(array(), array('id' => $labelName)); $conditionNo = $runtimeFilterField->getConditionNo(); if (array_key_exists($conditionNo, $conditionArray)) { if ($widget->generateWhereClausePart($runtimeFilterField->getWhereClausePart(), $values[$runtimeFilterField->getName()]) != null) { $conditionArray[$conditionNo] = $conditionArray[$conditionNo] . " AND " . $widget->generateWhereClausePart($runtimeFilterField->getWhereClausePart(), $values[$runtimeFilterField->getName()]); } } else { if ($widget->generateWhereClausePart($runtimeFilterField->getWhereClausePart(), $values[$runtimeFilterField->getName()]) != null) { $conditionArray[$conditionNo] = $widget->generateWhereClausePart($runtimeFilterField->getWhereClausePart(), $values[$runtimeFilterField->getName()]); } } } return $conditionArray; } /** * Gets filter fields that are selected for a given report and are of type Runtime. * @param integer $reportId * @return array ( array of FilterFiled ) */ public function getSelectedRuntimeFilterFields($reportId) { $reportGroupId = $this->getReportGroupIdOfAReport($reportId); $type = PluginSelectedFilterField::RUNTIME_FILTER_FIELD; $runtimeSelectedFilterFields = $this->getReportableService()->getSelectedFilterFieldsByType($reportId, $type, true); $runtimeFilterFieldList = new Doctrine_Collection("FilterField"); foreach ($runtimeSelectedFilterFields as $runtimeSelectedFilterField) { $runtimeFilterFieldList->add($runtimeSelectedFilterField->getFilterField()); } return $runtimeFilterFieldList; } /** * Generates select condition excluding summary function for a given report (ie. given report id). * @param integer $reportId * @return string */ public function getSelectConditionWithoutSummaryFunction($reportId) { $selectCondition = null; $displayGroups = $this->getGroupedDisplayFieldsForReport($reportId); $selectCondition = $this->constructSelectStatement($displayGroups); return $selectCondition; } public function getGroupedDisplayFieldsForReport($reportId) { $displayFields = $this->getSelectedDisplayFields($reportId); $metaFields = $this->getSelectedMetaDisplayFields($reportId); $compositeFields = $this->getSelectedCompositeDisplayFields($reportId); $selectedDisplayFields = array_merge($displayFields, $compositeFields, $metaFields); $displayGroups = $this->getGroupedDisplayFields($selectedDisplayFields); return $displayGroups; } public function getAllSelectedFieldsGrouped($reportId) { $displayFields = $this->getSelectedDisplayFields($reportId); $metaFields = $this->getSelectedMetaDisplayFields($reportId); $compositeFields = $this->getSelectedCompositeDisplayFields($reportId); $selectedDisplayFields = array_merge($selectedDisplayFields, $compositeFields, $displayFields, $summaryFields); $headerGroups = array(); // Default Group - for headers without a display group $defaultGroup = new DisplayFieldGroup(); //$defaultGroup; $selectedDisplayGroupIds = array(); $selectedDisplayGroups = $this->getReportableService()->getSelectedDisplayFieldGroups($reportId); if (!empty($selectedDisplayGroups)) { foreach ($selectedDisplayGroups as $group) { $selectedDisplayGroupIds[] = $group['display_field_group_id']; } } foreach ($displayFields as $displayField) { if ($displayField->getIsSortable() == "false") { $isSortable = false; } else { $isSortable = true; } if ($displayField->getIsValueList()) { $isValueList = true; } else { $isValueList = false; } $properties = array( 'name' => $displayField->getLabel(), 'isSortable' => $isSortable, 'sortOrder' => $displayField->getSortOrder(), 'sortField' => $displayField->getSortField(), 'elementType' => $displayField->getElementType(), 'width' => $displayField->getWidth(), 'isExportable' => $displayField->getIsExportable(), 'textAlignmentStyle' => $displayField->getTextAlignmentStyle(), ); $elementPropertyArray['default'] = $displayField->getDefaultValue(); $properties = array_filter($properties, 'strlen'); $elementPropertyXmlString = $this->escapeSpecialCharacters($displayField->getElementProperty()); $xmlIterator = new SimpleXMLIterator($elementPropertyXmlString); $elementPropertyArray = $this->simplexmlToArray($xmlIterator); $elementPropertyArray['isValueList'] = $isValueList; $elementPropertyArray['listSeparator'] = self::LIST_SEPARATOR; if ($displayField->getDefaultValue() != null) { $elementPropertyArray['default'] = $displayField->getDefaultValue(); } $properties['elementProperty'] = $elementPropertyArray; $header = new ListHeader; $header->populateFromArray($properties); // Set to correct display group $displayGroupId = $displayField->getDisplayFieldGroupId(); if ($displayGroupId === null) { $defaultGroup->addHeader($header); } else { if (!isset($headerGroups[$displayGroupId])) { $displayFieldGroup = $displayField->getDisplayFieldGroup(); if (in_array($displayGroupId, $selectedDisplayGroupIds)) { $groupName = $displayFieldGroup->getName(); } else { $groupName = null; } // Check if group is selected in report. $headerGroup = new ListHeaderGroup(array($header), $groupName); $headerGroups[$displayGroupId] = $headerGroup; } else { $headerGroups[$displayGroupId]->addHeader($header); } } } // Add the default group if it has any headers if ($defaultGroup->getHeaderCount() > 0) { $headerGroups[] = $defaultGroup; } return $headerGroups; } /** * Appends display field names to select statement. * @param string $selectStatement * @param DisplayField $displayField * @return string */ public function constructSelectClauseForDisplayField($selectStatement, $displayField) { $clause = $displayField->getName(); if (KeyHandler::keyExists() && $displayField->getIsEncrypted()) { $pattern = '/(\{\{)(.{0,})(\}\})/'; if (preg_match($pattern, $clause)) { $clause = preg_replace($pattern, 'AES_DECRYPT(UNHEX($2),"' . KeyHandler::readKey() . '")', $clause); } else { $clause = 'AES_DECRYPT(UNHEX('. $displayField->getName() . '),"' . KeyHandler::readKey() . '")'; } } if ($displayField->getIsValueList()) { $clause = "GROUP_CONCAT(DISTINCT " . $clause . " SEPARATOR '|\\n|' ) "; } $fieldAlias = $displayField->getFieldAlias(); if (!empty($fieldAlias)) { $clause = $clause . " AS " . $fieldAlias; } if (empty($selectStatement)) { $selectStatement = $clause; } else { $selectStatement .= ',' . $clause; } return $selectStatement; } public function constructSelectClauseForListGroup($selectStatement, $displayFieldGroup, $displayFields) { $fieldList = ''; $isEncryptEnabled = KeyHandler::keyExists(); foreach ($displayFields as $field) { $fieldName = $field->getName(); if ($isEncryptEnabled && $field->getIsEncrypted()) { $pattern = '/(\{\{)(.{0,})(\}\})/'; if (preg_match($pattern, $fieldName)) { $fieldName = preg_replace($pattern, 'AES_DECRYPT(UNHEX($2),"' . KeyHandler::readKey() . '")', $fieldName); } else { $fieldName = 'AES_DECRYPT(UNHEX('. $fieldName . '),"' . KeyHandler::readKey() . '")'; } } // If null, change to empty string since CONCAT_WS will skip nulls, causing problems with the field list order. $fieldName = 'IFNULL(' . $fieldName . ",'')"; if (empty($fieldList)) { $fieldList = $fieldName; } else { $fieldList .= ',' . $fieldName; } } $alias = "DisplayFieldGroup" . $displayFieldGroup->getId(); $clause = "CONCAT_WS('|^^|', " . $fieldList . ")"; $clause = "GROUP_CONCAT(DISTINCT " . $clause . " SEPARATOR '|\\n|' ) AS " . $alias; if (empty($selectStatement)) { $selectStatement = $clause; } else { $selectStatement .= ',' . $clause; } return $selectStatement; } /** * Constructs select statement part with meta display fields. * @param integer $reportId * @return string */ public function constructSelectStatement(array $displayFieldGroups) { $selectStatement = null; foreach ($displayFieldGroups as $groupDetails) { $group = $groupDetails[0]; $displayFields = $groupDetails[1]; if (count($displayFields) > 0) { if ($group->getIsList()) { $selectStatement = $this->constructSelectClauseForListGroup($selectStatement, $group, $displayFields); } else { foreach ($displayFields as $displayField) { $selectStatement = $this->constructSelectClauseForDisplayField($selectStatement, $displayField); } } } } return $selectStatement; } /** * Generates data set for a given sql. * @param string $sql * @return string[] */ public function generateReportDataSet($reportId, $sql) { $dataSet = $this->getReportableService()->executeSql($sql); $dataSet = $this->processListsInDataSet($reportId, $dataSet); return $dataSet; } public function processListsInDataSet($reportId, $dataSet) { $displayGroups = $this->getGroupedDisplayFieldsForReport($reportId); for($rowNdx = 0; $rowNdx < count($dataSet); $rowNdx++) { $dataRow = $dataSet[$rowNdx]; foreach ($displayGroups as $groupDetails) { $group = $groupDetails[0]; $displayFields = $groupDetails[1]; if ($group->getIsList() && count($displayFields) > 0) { $groupAlias = 'DisplayFieldGroup' . $group->getId(); $groupValue = $dataRow[$groupAlias]; $fieldValues = array(); foreach($displayFields as $displayField) { $fieldValues[$displayField->getFieldAlias()] = array(); } if (!empty($groupValue)) { $rows = explode(self::LIST_SEPARATOR, $groupValue); foreach ($rows as $row) { $fields = explode('|^^|', $row); $fieldNdx = 0; foreach($displayFields as $displayField) { if (isset($fields[$fieldNdx])) { $fieldValue = $fields[$fieldNdx]; } else { $fieldValue = ""; } $fieldValues[$displayField->getFieldAlias()][] = $fieldValue; $fieldNdx++; } } } foreach($fieldValues as $key=>$value) { $dataRow[$key] = $value; } } } $dataSet[$rowNdx] = $dataRow; } return $dataSet; } /** * Generates all headers that are to be used in the list component for a given report. * @param integer $reportId * @return ListHeader[] */ public function getHeaderGroups($reportId) { $selectedDisplayFields = array(); $compositeFields = $this->getSelectedCompositeDisplayFields($reportId); $summaryFields = $this->getSelectedSummaryDisplayFields($reportId); $displayFields = $this->getSelectedDisplayFields($reportId); $selectedDisplayFields = array_merge($selectedDisplayFields, $compositeFields, $displayFields, $summaryFields); $headerGroups = $this->getHeaderGroupsForDisplayFields($reportId, $selectedDisplayFields); return $headerGroups; } /** * Get list of selected composite display fields for given report * @param integer $reportId * @return CompositeDisplayField[] */ private function getSelectedCompositeDisplayFields($reportId) { $compositeDisplayFields = array(); $selectedCompositeDisplayFields = $this->getReportableService()->getSelectedCompositeDisplayFields($reportId); if ($selectedCompositeDisplayFields != null) { foreach ($selectedCompositeDisplayFields as $selectedCompositeDisplayField) { $compositeDisplayFields[] = $selectedCompositeDisplayField->getCompositeDisplayField(); } } return $compositeDisplayFields; } /** * Get list of selected summary display fields for given report * @param integer $reportId * @return SummaryDisplayField[] */ private function getSelectedSummaryDisplayFields($reportId) { $summaryDisplayFields = array(); $selectedGroupField = $this->getReportableService()->getSelectedGroupField($reportId); if ($selectedGroupField != null) { $summaryDisplayFields[] = $selectedGroupField->getSummaryDisplayField(); } return $summaryDisplayFields; } /** * Get list of selected selected display fields for given report * @param integer $reportId * @return SelectedDisplayField[] */ private function getSelectedDisplayFields($reportId) { $displayFields = array(); $selectedDisplayFields = $this->getReportableService()->getSelectedDisplayFields($reportId); if ($selectedDisplayFields != null) { foreach ($selectedDisplayFields as $selectedDisplayField) { $displayFields[] = $selectedDisplayField->getDisplayField(); } } return $displayFields; } /** * Get list of selected selected display fields for given report * @param integer $reportId * @return SelectedDisplayField[] */ private function getSelectedMetaDisplayFields($reportId) { $report = $this->getReportableService()->getReport($reportId); $reportGroupId = $report->getReportGroupId(); $displayFields = array(); $metaFields = $this->getReportableService()->getMetaDisplayFields($reportGroupId); if (!empty($metaFields)) { foreach ($metaFields as $displayField) { $displayFields[] = $displayField; } } return $displayFields; } /** * Get list of header groups for the given display fields. * @param array $displayFields Array of DisplayFields * @return array ListHeaderGroup */ private function getHeaderGroupsForDisplayFields($reportId, $displayFields) { $headerGroups = array(); // Default Group - for headers without a display group $defaultGroup = new ListHeaderGroup(array()); $selectedDisplayGroupIds = array(); $selectedDisplayGroups = $this->getReportableService()->getSelectedDisplayFieldGroups($reportId); if (!empty($selectedDisplayGroups)) { foreach ($selectedDisplayGroups as $group) { $selectedDisplayGroupIds[] = $group['display_field_group_id']; } } foreach ($displayFields as $displayField) { if ($displayField->getIsSortable() == "false") { $isSortable = false; } else { $isSortable = true; } if ($displayField->getIsValueList()) { $isValueList = true; } else { $isValueList = false; } $properties = array( 'name' => $displayField->getLabel(), 'isSortable' => $isSortable, 'sortOrder' => $displayField->getSortOrder(), 'sortField' => $displayField->getSortField(), 'elementType' => $displayField->getElementType(), 'width' => $displayField->getWidth(), 'isExportable' => $displayField->getIsExportable(), 'textAlignmentStyle' => $displayField->getTextAlignmentStyle(), ); $elementPropertyArray['default'] = $displayField->getDefaultValue(); $properties = array_filter($properties, 'strlen'); $elementPropertyXmlString = $this->escapeSpecialCharacters($displayField->getElementProperty()); $xmlIterator = new SimpleXMLIterator($elementPropertyXmlString); $elementPropertyArray = $this->simplexmlToArray($xmlIterator); $elementPropertyArray['isValueList'] = $isValueList; $elementPropertyArray['listSeparator'] = self::LIST_SEPARATOR; if ($displayField->getDefaultValue() != null) { $elementPropertyArray['default'] = $displayField->getDefaultValue(); } $properties['elementProperty'] = $elementPropertyArray; $header = new ListHeader; $header->populateFromArray($properties); // Set to correct display group $displayGroupId = $displayField->getDisplayFieldGroupId(); if ($displayGroupId === null) { $defaultGroup->addHeader($header); } else { if (!isset($headerGroups[$displayGroupId])) { $displayFieldGroup = $displayField->getDisplayFieldGroup(); if (in_array($displayGroupId, $selectedDisplayGroupIds)) { $groupName = $displayFieldGroup->getName(); } else { $groupName = null; } // Check if group is selected in report. $headerGroup = new ListHeaderGroup(array($header), $groupName); $headerGroups[$displayGroupId] = $headerGroup; } else { $headerGroups[$displayGroupId]->addHeader($header); } } } // Add the default group if it has any headers if ($defaultGroup->getHeaderCount() > 0) { $headerGroups[] = $defaultGroup; } return $headerGroups; } /* * NOTE : * There is a bug in the installer. If there is any semicolon in a string that we insert into the database, * the installer interpret it in a wrong way and bread. That occurs when the installer run the dbscript-2.sql file. * So this method replaces the "#" character with "&amp;" string. */ private function escapeSpecialCharacters($string) { $string = str_replace("#", "&amp;", $string); return $string; } /** * Converts SimpleXMLIterator object into an array. * @param SimpleXMLIterator $xmlIterator * @return string[] */ public function simplexmlToArray($xmlIterator) { $xmlStringArray = array(); for ($xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next()) { if ($xmlIterator->hasChildren()) { $object = $xmlIterator->current(); $xmlStringArray[$object->getName()] = $this->simplexmlToArray($object); } else { $object = $xmlIterator->current(); $xmlStringArray[$object->getName()] = (string) $xmlIterator->current(); } } return $xmlStringArray; } /** * Generates a complete sql to retrieve report data set. * @param integer $reportId * @param array $conditionArray * @return string */ public function generateSql($reportId, $conditionArray, $staticColumns = null) { $report = $this->getReportableService()->getReport($reportId); $reportGroupId = $report->getReportGroupId(); $reportGroup = $this->getReportableService()->getReportGroup($reportGroupId); $coreSql = $reportGroup->getCoreSql(); $selectStatement = $this->getSelectConditionWithoutSummaryFunction($reportId); $selectedGroupField = $this->getReportableService()->getSelectedGroupField($reportId); $summaryDisplayField = null; $groupByClause = ""; if (!is_null($selectedGroupField)) { $summaryDisplayField = $selectedGroupField->getSummaryDisplayField(); $function = $summaryDisplayField->getFunction(); $summaryFieldAlias = $summaryDisplayField->getFieldAlias(); $summaryFunction = $function . " AS " . $summaryFieldAlias; $groupField = $selectedGroupField->getGroupField(); $groupByClause = $groupField->getGroupByClause(); } if (isset($summaryFunction)) { $selectStatement = $selectStatement . "," . $summaryFunction; } $sql = str_replace("selectCondition", $selectStatement, $coreSql); foreach ($conditionArray as $key => $condition) { $searchString = "whereCondition" . $key; if (empty($condition)) { $condition = 'TRUE'; } $sql = str_replace($searchString, $condition, $sql); } $pattern = "/whereCondition\d+/"; $sql = preg_replace($pattern, "true", $sql); $sql = str_replace("groupByClause", $groupByClause, $sql); if ($staticColumns != null) { $sql = $this->insertStaticColumnsInSelectStatement($sql, $staticColumns); } return $sql; } /** * Static columns are just texts that appear in every records. Those are same in every records. * This method inserts static columns in to the select statement. Its inserted just after the * SELECT clause. * @param string $statement * @param array $staticColumns * @return string */ private function insertStaticColumnsInSelectStatement($statement, $staticColumns) { $staticSelectStatement = null; foreach ($staticColumns as $key => $value) { if ($staticSelectStatement == null) { $staticSelectStatement = "'" . $value . "' AS " . $key . " , "; } else { $staticSelectStatement .= "'" . $value . "' AS " . $key . " , "; } } $statement = substr_replace($statement, $staticSelectStatement, 7, 0); return $statement; } /** * Constructs filter field id, form value pair array when filter field list and form values are given. * It maps filter field id to form value. * @param FilterField $selectedRuntimeFilterFieldList * @param string[] $formValues * @return string[] */ public function linkFilterFieldIdsToFormValues($selectedRuntimeFilterFieldList, $formValues) { $filterFieldIdAndValueArray = array(); if ($selectedRuntimeFilterFieldList[0]->getFilterFieldId() != null) { foreach ($selectedRuntimeFilterFieldList as $runtimeFilterField) { $filterFieldId = $runtimeFilterField->getFilterFieldId(); $value = $formValues[$runtimeFilterField->getName()]; $filterFieldIdAndValueArray[] = array("filterFieldId" => $filterFieldId, "value" => $value); } } return $filterFieldIdAndValueArray; } /** * Generates where clause condition array. It takes an array of filterFieldId and value. * According to the condition number, it inserts the where clause part into an array. * Key of the condition array is condition number and the Value is where clause string, * that should be replaced with whereConditing in the core sql. * @param array $filterFieldIdsAndValues * @return string[] */ public function generateWhereClauseConditionArray($selectedFilterFields, $formValues) { $conditionArray = array(); foreach ($selectedFilterFields as $selectedFilterField) { $type = $selectedFilterField->getType(); $filterFieldId = $selectedFilterField->getFilterFieldId(); if ($type == "Predefined") { $predefinedFilterField = $this->getReportableService()->getFilterFieldById($filterFieldId); $conditionNo = $predefinedFilterField->getConditionNo(); $whereClause = $this->generateWhereClauseForPredefinedReport($selectedFilterField); if (!empty($whereClause)) { if (array_key_exists($conditionNo, $conditionArray)) { $conditionArray[$conditionNo] = $conditionArray[$conditionNo] . " AND " . $whereClause; } else { $conditionArray[$conditionNo] = $whereClause; } } } else if ($type == "Runtime") { $runtimeFilterField = $selectedFilterField->getFilterField(); $labelName = $runtimeFilterField->getName(); $widgetName = $runtimeFilterField->getFilterFieldWidget(); $widget = new $widgetName(array(), array('id' => $labelName)); $value = $formValues[$runtimeFilterField->getName()]; $conditionNo = $runtimeFilterField->getConditionNo(); if (array_key_exists($conditionNo, $conditionArray)) { if ($widget->generateWhereClausePart($runtimeFilterField->getWhereClausePart(), $value) != null) { $conditionArray[$conditionNo] = $conditionArray[$conditionNo] . " AND " . $widget->generateWhereClausePart($runtimeFilterField->getWhereClausePart(), $value); } } else { if ($widget->generateWhereClausePart($runtimeFilterField->getWhereClausePart(), $value) != null) { $conditionArray[$conditionNo] = $widget->generateWhereClausePart($runtimeFilterField->getWhereClausePart(), $value); } } } } return $conditionArray; } /** * Gets project activity name for a given activity id. * @param integer $activityId * @return string */ public function getProjectActivityNameByActivityId($activityId) { $projectActivity = $this->getReportableService()->getProjectActivityByActivityId($activityId); $activityName = $projectActivity->getName(); return $activityName; } /** * Gets the name of the report given report id * @param integer $reportId * @return string */ public function getReportName($reportId) { $reportName = NULL; $report = $this->getReportableService()->getReport($reportId); if (!empty($report)) { $reportName = $report->getName(); } return $reportName; } public function generateSqlForNotUseFilterFieldReports($reportId, $formValues) { $report = $this->getReportableService()->getReport($reportId); $reportGroupId = $report->getReportGroupId(); $reportGroup = $this->getReportableService()->getReportGroup($reportGroupId); $coreSql = $reportGroup->getCoreSql(); $selectStatement = $this->getSelectConditionWithoutSummaryFunction($reportId); $selectedGroupField = $this->getReportableService()->getSelectedGroupField($reportId); $summaryDisplayField = null; $groupByClause = ''; if (!is_null($selectedGroupField)) { $summaryDisplayField = $selectedGroupField->getSummaryDisplayField(); $function = $summaryDisplayField->getFunction(); $summaryFieldAlias = $summaryDisplayField->getFieldAlias(); $summaryFunction = $function . " AS " . $summaryFieldAlias; $groupField = $selectedGroupField->getGroupField(); $groupByClause = $groupField->getGroupByClause(); } if (isset($summaryFunction)) { $selectStatement = $selectStatement . "," . $summaryFunction; } $sql = str_replace("selectCondition", $selectStatement, $coreSql); $sql = str_replace("groupByClause", $groupByClause, $sql); foreach ($formValues as $key => $value) { $pattern = '/#@[\"]*' . $key . '[\)\"]*@,@[a-zA-Z0-9\(\)_\.\-\ !\"\=]*@#/'; preg_match($pattern, $sql, $matches); if (!empty($matches)) { $str = $matches[0]; $array = explode("@", $str); if (($value == '-1') || ($value == '0') || ($value == '')) { $sql = str_replace($str, $array[3], $sql); } else { $value = str_replace($key, $value, $array[1]); $sql = str_replace($str, $value, $sql); } } } return $sql; } public function generateWhereClause() { $value = "no"; $jobTitle = "jobTitle"; $sql = 'select #@jobTitle)@,@de_f-a.u_lt @# where'; $pattern = '/#@[\"]*' . $jobTitle . "[\)]*[\"]*@,@[a-zA-Z_\.\-\ ]*@#/"; preg_match($pattern, $sql, $matches); $str = $matches[0]; $array = explode("@", $str); if ($value == null) { $sql = str_replace($str, $array[3], $sql); } else { $value = str_replace($jobTitle, $value, $array[1]); $sql = str_replace($str, $value, $sql); } } public function generateWhereClauseForPredefinedReport($selectedFilterField) { $whereCondition = $selectedFilterField->getWhereCondition(); $whereClause = null; switch ($whereCondition) { case "=": $whereClause = $this->constructWhereStatementForUneryOperator($selectedFilterField, $whereCondition); break; case ">": $whereClause = $this->constructWhereStatementForUneryOperator($selectedFilterField, $whereCondition); break; case "<": $whereClause = $this->constructWhereStatementForUneryOperator($selectedFilterField, $whereCondition); break; case "<>": $whereClause = $this->constructWhereStatementForUneryOperator($selectedFilterField, $whereCondition); break; case "BETWEEN": $whereClause = $this->constructWhereStatementForBetweenOperator($selectedFilterField, $whereCondition); break; case "IN": $whereClause = $this->constructWhereStatementForInOperator($selectedFilterField, $whereCondition); break; case "IS NULL": $whereClause = $this->constructWhereStatementForIsNullOperator($selectedFilterField, $whereCondition); break; case "IS NOT NULL": $whereClause = $this->constructWhereStatementForIsNotNullOperator($selectedFilterField, $whereCondition); break; default: break; } return $whereClause; } public function constructWhereStatementForUneryOperator($selectedFilterField, $whereCondition) { $whereClausePart = $selectedFilterField->getFilterField()->getWhereClausePart(); $value1 = $selectedFilterField->getValue1(); $whereClause = $whereClausePart . " " . $whereCondition . " '" . $value1 . "'"; return $whereClause; } public function constructWhereStatementForBetweenOperator($selectedFilterField, $whereCondition) { $whereClausePart = $selectedFilterField->getFilterField()->getWhereClausePart(); $value1 = $selectedFilterField->getValue1(); $value2 = $selectedFilterField->getValue2(); $whereClause = $whereClausePart . " BETWEEN '" . $value1 . "' AND '" . $value2 . "'"; return $whereClause; } public function constructWhereStatementForInOperator($selectedFilterField, $whereCondition){ $whereClausePart = $selectedFilterField->getFilterField()->getWhereClausePart(); $value1 = $selectedFilterField->getValue1(); $whereClause = $whereClausePart . " " . $whereCondition . " " . "(" . $value1 . ")"; return $whereClause; } public function constructWhereStatementForIsNullOperator($selectedFilterField, $whereCondition){ $whereClausePart = $selectedFilterField->getFilterField()->getWhereClausePart(); $whereClause = $whereClausePart . " IS NULL"; return $whereClause; } public function constructWhereStatementForIsNotNullOperator($selectedFilterField, $whereCondition){ $whereClausePart = $selectedFilterField->getFilterField()->getWhereClausePart(); $whereClause = $whereClausePart . " IS NOT NULL"; return $whereClause; } public function saveSelectedFilterFields($formValues, $reportId, $type) { $reportableService = $this->getReportableService(); $reportableService->removeSelectedFilterFields($reportId); foreach ($formValues as $key => $value) { $filterField = $this->getReportableService()->getFilterFieldByName($key); $filterFieldId = $filterField->getFilterFieldId(); $filterFieldOrder = 0; $widgetName = $filterField->getFilterFieldWidget(); $widget = new $widgetName(); if (array_key_exists("comparision", $value)) { $widget->setWhereClauseCondition($value['comparision']); if (is_array($value)) { $value1 = next($value); if ($value1 === false) { $value1 = null; } $value2 = next($value); if ($value2 === false) { $value2 = null; } } else { $value1 = next($value); $value2 = null; } } else { if (is_array($value)) { $value1 = current($value); } else { $value1 = $value; } $value2 = null; } $whereClausePart = $widget->generateWhereClausePart("fieldName", $value); if ($whereClausePart == null) { $whereCondition = null; } else { $whereCondition = $widget->getWhereClauseCondition(); } $this->getReportableService()->saveSelectedFilterField($reportId, $filterFieldId, $filterFieldOrder, $value1, $value2, $whereCondition, $type); } } public function saveSelectedDisplayFields($displayFieldIds, $reportId) { $reportableService = $this->getReportableService(); $reportableService->removeSelectedDisplayFields($reportId); foreach ($displayFieldIds as $displayFieldId) { $reportableService->saveSelectedDispalyField($displayFieldId, $reportId); } } public function saveSelectedDisplayFieldGroups($displayFieldGroupIds, $reportId) { $reportableService = $this->getReportableService(); $reportableService->removeSelectedDisplayFieldGroups($reportId); foreach ($displayFieldGroupIds as $displayFieldGroupId) { $reportableService->saveSelectedDisplayFieldGroup($displayFieldGroupId, $reportId); } } /** * * @param <type> $customField * @param <type> $reportGroupId * @return <type> */ public function saveCustomDisplayField($customField, $reportGroupId) { $reportableService = $this->getReportableService(); $reportableService->removeSelectedDisplayFieldGroups($reportId); $customFieldNo = $customField->getFieldNum(); $name = "hs_hr_employee.custom" . $customFieldNo; $displayField = $this->getReportableService()->getDisplayFieldByName($name); if ($displayField != null) { $columns['displayFieldId'] = $displayField[0]->getDisplayFieldId(); } $columns['reportGroupId'] = $reportGroupId; $columns['name'] = $name; $columns['label'] = $customField->getName(); $columns['fieldAlias'] = "customField" . $customFieldNo; $columns['isSortable'] = "false"; $columns['sortOrder'] = null; $columns['sortField'] = null; $columns['elementType'] = "label"; $columns['elementProperty'] = "<xml><getter>customField" . $customFieldNo . "</getter></xml>"; $columns['width'] = "200"; $columns['isExportable'] = "1"; $columns['textAlignmentStyle'] = null; $columns['isValueList'] = "0"; $columns['displayFieldGroupId'] = "16"; $columns['defaultValue'] = "---"; $columns['isEncrypted'] = false; return $this->getReportableService()->saveCustomDisplayField($columns); } public function deleteCustomDisplayFieldList($customFieldList) { foreach ($customFieldList as $customField) { $customDisplayFieldName = "hs_hr_employee.custom" . $customField; $result = $this->getReportableService()->deleteCustomDisplayField($customDisplayFieldName); } } /** * Gets all display field groups for given report group */ public function getGroupedDisplayFieldsForReportGroup($reportGroupId) { $displayFields = $this->getReportableService()->getDisplayFieldsForReportGroup($reportGroupId); $groups = $this->getGroupedDisplayFields($displayFields); return $groups; } public function getGroupedDisplayFields($displayFields) { // Organize by groups $groups = array(); $defaultDisplayFieldGroup = new DisplayFieldGroup(); $defaultDisplayFieldGroup->setIsList(false); $defaultGroup = array($defaultDisplayFieldGroup, array()); foreach ($displayFields as $field) { $displayGroupId = $field->getDisplayFieldGroupId(); if (empty($displayGroupId)) { $defaultGroup[1][] = $field; } else { if (!isset($groups[$displayGroupId])) { $displayFieldGroup = $field->getDisplayFieldGroup(); $groups[$displayGroupId] = array($displayFieldGroup, array($field)); } else { $groups[$displayGroupId][1][] = $field; } } } // Add the default group if it has any fields if (count($defaultGroup[1]) > 0) { $groups[] = $defaultGroup; } return $groups; } }
monokal/docker-orangehrm
www/symfony/plugins/orangehrmCorePlugin/lib/service/ReportGeneratorService.php
PHP
gpl-2.0
46,201
@echo off color A title Half-Life1 set DIR="%CD%" set PWD=%CD%\wine\data\drive_c\Juegos\Inukaze\Half-Life-EE set key1=HKEY_CURRENT_USER\Software\Valve set key2=HKEY_CURRENT_USER\Software\Valve\Half-Life set key3=HKEY_CURRENT_USER\Software\Valve\Half-Life\Settings set key4=HKEY_CURRENT_USER\Software\Valve\Half-Life\valve set key5=HKEY_CURRENT_USER\Software\Valve\Half-Life\valve\Settings set key6=HKEY_CURRENT_USER\Software\Valve\Steam REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop FOR /F "tokens=2*" %%i in ('REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop^|findstr /C:"REG_SZ" /C:"REG_EXPAND_SZ"') DO SET "DEEE=%%j" FOR /F "usebackq delims=" %%i in (`ECHO %DEEE%`) DO SET DEEE=%%i set DEEEDHL1EE=%DEEE%\Half-Life1 echo ===========Configurando el Software========= echo. echo Borrando Entradas de Registro echo Anteriores para evitar Conflictos (reg delete "%key6%" /f) (reg delete "%key5%" /f) (reg delete "%key4%" /f) (reg delete "%key3%" /f) (reg delete "%key2%" /f) (reg delete "%key1%" /f) echo. echo ============================================ echo. echo Agregando Entradas de Registro echo Para que el Software Funcione Correctamente (reg add "%key1%" /f) (reg add "%key2%" /f) (reg add "%key3%" /f) (reg add "%key4%" /f) (reg add "%key5%" /f) (reg add "%key6%" /f) (reg add "%key3%" /t REG_DWORD /v CrashInitializingVideoMode /d 0 /f) (reg add "%key3%" /t REG_DWORD /v EngineD3D /d 0 /f) (reg add "%key3%" /t REG_SZ /v EngineDLL /d hw.dll /f) (reg add "%key3%" /t REG_SZ /v io /d "" /f) (reg add "%key3%" /t REG_DWORD /v ScreenBPP /d 32 /f) (reg add "%key3%" /t REG_DWORD /v ScreenHeight /d 600 /f) (reg add "%key3%" /t REG_DWORD /v ScreenWidth /d 800 /f) (reg add "%key3%" /t REG_DWORD /v ScreenWindowed /d 0 /f) (reg add "%key3%" /t REG_SZ /v "User Token 2" /d "" /f) (reg add "%key3%" /t REG_SZ /v "User Token 3" /d "" /f) (reg add "%key3%" /t REG_SZ /v ValveKey /d AAAAA-AAAAA-AAAAA-AAAAA-AAAAA /f) (reg add "%key3%" /t REG_SZ /v yeK1 /d A0B8FF7E9183788F769199CA89976F05705483F7CEDBBEE8693B8FA228C58EF63F8BA37D480A765A7DB49811E5BA386B6D214CD687AD585FCD837BD523D8A86410ABC84CC2D0EECF0EFB6820DB3664C2ED313B5FF40A577775E8B96C8B187EC362EF8EC4729864A544849EF39173AB1C30B88803612D2B66A390096322534B /f) (reg add "%key3%" /t REG_SZ /v yeK2 /d C3A53B015287AC10FA40BA8A80BB7C978BCD3C76804288AB164EC591FE37EDB3E7D401ADC30483F42280D228D9DE74EFA4A15C8206D0 /f) (reg add "%key5%" /t REG_SZ /v "User Token 2" /d "" /f) (reg add "%key5%" /t REG_SZ /v "User Token 3" /d "" /f) (reg add "%key6%" /t REG_SZ /v Language /d spanish /f) (reg add "%key6%" /t REG_SZ /v Rate /d 3500 /f) (reg add "%key6%" /t REG_SZ /v Skin /d "" /f) echo. echo ============================================ cd "%DEEE%" if exist "%DEEEDHL1EE%" ( echo "Verificando que existen los Accesos Directos" if not exist "%DEEEDHL1EE%\Half-Life 1 - Original.lnk" goto crear_hl1o if not exist "%DEEEDHL1EE%\Half-Life 1 - Opposing Force.lnk" goto crear_hl1of if not exist "%DEEEDHL1EE%\Half-Life 1 - Blue Shift.lnk" goto crear_hl1bs if not exist "%DEEEDHL1EE%\Half-Life 1 - Ricochet.lnk" goto crear_hl1r if not exist "%DEEEDHL1EE%\Half-Life 1 - Team Fortress Classic.lnk" goto crear_hl1tfc if not exist "%DEEEDHL1EE%\Half-Life 1 - Deathmatch Classic.lnk" goto crear_hl1dc if not exist "%DEEEDHL1EE%\Half-Life 1 - Counter Strike.lnk" goto crear_hl1cs if not exist "%DEEEDHL1EE%\Half-Life 1 - Decay.lnk" goto crear_hl1d if not exist "%DEEEDHL1EE%\Half-Life 1 - Zombie.lnk" goto crear_hl1z ) :AccesosDirectos echo. cd "%DEEE%" If NOT exist "%DEEEDHL1EE%" ( echo "Creando Accesos Directos" md "%DEEEDHL1EE%" cd "%DEEEDHL1EE%" goto AccesosDirectos echo. ) echo. :crear_hl1o echo "Half-Life 1 - Original" set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs" echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT% echo sLinkFile = "%DEEEDHL1EE%\Half-Life 1 - Original.lnk" >> %SCRIPT% echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT% echo oLink.TargetPath = "%PWD%\hl.exe" >> %SCRIPT% echo oLink.Arguments = "-nomaster" >> %SCRIPT% echo oLink.IconLocation = "%PWD%\hl.ico, 0" >> %SCRIPT% echo oLink.WorkingDirectory = "%PWD%" >> %SCRIPT% echo oLink.Save >> %SCRIPT% cscript /nologo %SCRIPT% del %SCRIPT% echo. :crear_hl1of echo "Half-Life 1 - Opposing Force" set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs" echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT% echo sLinkFile = "%DEEEDHL1EE%\Half-Life 1 - Opposing Force.lnk" >> %SCRIPT% echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT% echo oLink.TargetPath = "%PWD%\hl.exe" >> %SCRIPT% echo oLink.Arguments = "-nomaster -game gearbox" >> %SCRIPT% echo oLink.IconLocation = "%PWD%\gearbox\game.ico, 0" >> %SCRIPT% echo oLink.WorkingDirectory = "%PWD%" >> %SCRIPT% echo oLink.Save >> %SCRIPT% cscript /nologo %SCRIPT% del %SCRIPT% echo. :crear_hl1bs echo "Half-Life 1 - Blue Shift" set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs" echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT% echo sLinkFile = "%DEEEDHL1EE%\Half-Life 1 - Blue Shift.lnk" >> %SCRIPT% echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT% echo oLink.TargetPath = "%PWD%\hl.exe" >> %SCRIPT% echo oLink.Arguments = "-nomaster -game bshift" >> %SCRIPT% echo oLink.IconLocation = "%PWD%\bshift\game.ico, 0" >> %SCRIPT% echo oLink.WorkingDirectory = "%PWD%" >> %SCRIPT% echo oLink.Save >> %SCRIPT% cscript /nologo %SCRIPT% del %SCRIPT% echo. :crear_hl1r echo "Half-Life 1 - Ricochet" set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs" echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT% echo sLinkFile = "%DEEEDHL1EE%\Half-Life 1 - Ricochet.lnk" >> %SCRIPT% echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT% echo oLink.TargetPath = "%PWD%\hl.exe" >> %SCRIPT% echo oLink.Arguments = " -nomaster -game ricochet" >> %SCRIPT% echo oLink.IconLocation = "%PWD%\ricochet\game.ico, 0" >> %SCRIPT% echo oLink.WorkingDirectory = "%PWD%" >> %SCRIPT% echo oLink.Save >> %SCRIPT% cscript /nologo %SCRIPT% del %SCRIPT% :crear_hl1tfc echo "Half-Life 1 - Team Fortress Classic" set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs" echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT% echo sLinkFile = "%DEEEDHL1EE%\Half-Life 1 - Team Fortress Classic.lnk" >> %SCRIPT% echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT% echo oLink.TargetPath = "%PWD%\hl.exe" >> %SCRIPT% echo oLink.Arguments = "-nomaster -game tfc" >> %SCRIPT% echo oLink.IconLocation = "%PWD%\tfc\game.ico, 0" >> %SCRIPT% echo oLink.WorkingDirectory = "%PWD%" >> %SCRIPT% echo oLink.Save >> %SCRIPT% cscript /nologo %SCRIPT% del %SCRIPT% echo. :crear_hl1dc echo "Half-Life 1 - Deathmatch Classic" set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs" echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT% echo sLinkFile = "%DEEEDHL1EE%\Half-Life 1 - Deathmatch Classic.lnk" >> %SCRIPT% echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT% echo oLink.TargetPath = "%PWD%\hl.exe" >> %SCRIPT% echo oLink.Arguments = "-nomaster -game dmc" >> %SCRIPT% echo oLink.IconLocation = "%PWD%\dmc\game.ico, 0" >> %SCRIPT% echo oLink.WorkingDirectory = "%PWD%" >> %SCRIPT% echo oLink.Save >> %SCRIPT% cscript /nologo %SCRIPT% del %SCRIPT% echo. :crear_hl1cs echo "Half-Life 1 - Counter Strike" set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs" echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT% echo sLinkFile = "%DEEEDHL1EE%\Half-Life 1 - Counter Strike.lnk" >> %SCRIPT% echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT% echo oLink.TargetPath = "%PWD%\hl.exe" >> %SCRIPT% echo oLink.Arguments = "-nomaster -game cstrike" >> %SCRIPT% echo oLink.IconLocation = "%PWD%\cstrike\cstrike.ico, 0" >> %SCRIPT% echo oLink.WorkingDirectory = "%PWD%" >> %SCRIPT% echo oLink.Save >> %SCRIPT% cscript /nologo %SCRIPT% del %SCRIPT% echo. :crear_hl1d echo "Half-Life 1 - Decay" set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs" echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT% echo sLinkFile = "%DEEEDHL1EE%\Half-Life 1 - Decay.lnk" >> %SCRIPT% echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT% echo oLink.TargetPath = "%PWD%\hl.exe" >> %SCRIPT% echo oLink.Arguments = "-nomaster -game decay" >> %SCRIPT% echo oLink.IconLocation = "%PWD%\decay\Decay.ico, 0" >> %SCRIPT% echo oLink.WorkingDirectory = "%PWD%" >> %SCRIPT% echo oLink.Save >> %SCRIPT% cscript /nologo %SCRIPT% del %SCRIPT% echo. :crear_hl1z echo "Half-Life 1 - Zombie" set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs" echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT% echo sLinkFile = "%DEEEDHL1EE%\Half-Life 1 - Zombie.lnk" >> %SCRIPT% echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT% echo oLink.TargetPath = "%PWD%\hl.exe" >> %SCRIPT% echo oLink.Arguments = "-nomaster -game zombie" >> %SCRIPT% echo oLink.IconLocation = "%PWD%\zombie\zombielogo.ico, 0" >> %SCRIPT% echo oLink.WorkingDirectory = "%PWD%" >> %SCRIPT% echo oLink.Save >> %SCRIPT% cscript /nologo %SCRIPT% del %SCRIPT% echo. echo ===========Configurando el Software========= goto deeedhl1ee :deeedhl1ee echo. start /b %windir%\explorer.exe "%DEEEDHL1EE%" cd %DIR%
inukaze/maestro
Videojuegos/Guion/Windows/Configurar_en_Windows_HalfLifeEE.bat
Batchfile
gpl-2.0
9,522
DROP PROCEDURE IF EXISTS add_migration; delimiter ?? CREATE PROCEDURE `add_migration`() BEGIN DECLARE v INT DEFAULT 1; SET v = (SELECT COUNT(*) FROM `migrations` WHERE `id`='20180117231403'); IF v=0 THEN INSERT INTO `migrations` VALUES ('20180117231403'); -- Add your query below. INSERT INTO `spell_mod` (`Id`, `Attributes`, `Comment`) VALUES (26656, 286327056, 'Black Qiraji Battle Tank not usable in combat'); -- End of migration. END IF; END?? delimiter ; CALL add_migration(); DROP PROCEDURE IF EXISTS add_migration;
EinBaum/server
sql/migrations/20180117231403_world.sql
SQL
gpl-2.0
525
package in.shabhushan.algo_trials.clrs.chapter9; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MedianOfMedians { /** * Sort the List and return the middle elemnt */ public static int getMedian(List<Integer> list) { Collections.sort(list); return list.get(list.size() / 2); } public static int getMedianOfMedians(List<List<Integer>> values) { List<Integer> medians = new ArrayList<>(); for (int i = 0; i < values.size(); i++) { int m = getMedian(values.get(i)); medians.add(m); } return getMedian(medians); } /** * Finds what's the value at index ${key} in the sorted arr array without actually sorting it * key is 0 based */ public static int getSelectionByMedianOfMedians(List<Integer> values, int key) { List<List<Integer>> dividedList = new ArrayList<>(); int count = 0; while (count < values.size()) { int rowCount = 0; List<Integer> list = new ArrayList<>(); while (rowCount < 5 && count < values.size()) { list.add(values.get(count)); rowCount++; count++; } dividedList.add(list); } int medianOfMedians = getMedianOfMedians(dividedList); List<Integer> l1 = new ArrayList<>(); List<Integer> l2 = new ArrayList<>(); for (List<Integer> outerList: dividedList) { for (int num: outerList) { if (num < medianOfMedians) { l1.add(num); } else if (num > medianOfMedians) { l2.add(num); } } } // this includes +1 for pivot as well, since l1.size() is one based index and key is zero based // key will be +1 than l1.size() anyhow if (key == l1.size()) { return medianOfMedians; } else if (key < l1.size()) { return getSelectionByMedianOfMedians(l1, key); } else { return getSelectionByMedianOfMedians(l2, key - l1.size() - 1); } } }
Shashi-Bhushan/General
algo-trials/src/main/java/in/shabhushan/algo_trials/clrs/chapter9/MedianOfMedians.java
Java
gpl-2.0
1,948
#include <iostream> #include "series.h" int solve(int p); #ifndef TESTING int main () { int p; std::cin >> p; std::cout << solve(p) << std::endl; } #endif int solve(int p) { int su = sum_naturals(p); int suosq = sum_squares(p); return su * su - suosq; }
NorfairKing/project-euler
006/c++/solution.cc
C++
gpl-2.0
270
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +build 386 amd64 s390x package sha256 //go:noescape func block(dig *digest, p []byte)
paranoiacblack/gcc
libgo/go/crypto/sha256/sha256block_decl.go
GO
gpl-2.0
269
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package com.github.smeny.jpc.emulator.execution.opcodes.vm; import com.github.smeny.jpc.emulator.execution.*; import com.github.smeny.jpc.emulator.execution.decoder.*; import com.github.smeny.jpc.emulator.processor.*; import com.github.smeny.jpc.emulator.processor.fpu64.*; import static com.github.smeny.jpc.emulator.processor.Processor.*; public class shld_Ed_Gd_CL extends Executable { final int op1Index; final int op2Index; public shld_Ed_Gd_CL(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); int modrm = input.readU8(); op1Index = Modrm.Ed(modrm); op2Index = Modrm.Gd(modrm); } public Branch execute(Processor cpu) { Reg op1 = cpu.regs[op1Index]; Reg op2 = cpu.regs[op2Index]; if(cpu.r_cl.get8() != 0) { int shift = cpu.r_cl.get8() & 0x1f; cpu.flagOp1 = op1.get32(); cpu.flagOp2 = shift; long rot = ((0xffffffffL &op2.get32()) << 32) | (0xffffffffL &op1.get32()); cpu.flagResult = ((int)((rot << shift) | (rot >>> (2*32-shift)))); op1.set32(cpu.flagResult); cpu.flagIns = UCodes.SHLD32; cpu.flagStatus = OSZAPC; } return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
smeny/JPC
src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/vm/shld_Ed_Gd_CL.java
Java
gpl-2.0
2,403
<?php if(function_exists("printAllNewsCategories")) { ?> <div class="menu"> <h3><?php echo gettext("News articles"); ?></h3> <?php printAllNewsCategories("All news",TRUE,"","menu-active"); ?> </div> <?php } ?> <?php if(function_exists("printAlbumMenu")) { ?> <div class="menu"> <h3><?php echo gettext("Gallery"); ?></h3> <?php printAlbumMenu("list","count","","menu-active","submenu","menu-active",""); ?> </div> <?php } ?> <?php if(function_exists("printPageMenu")) { ?> <div class="menu"> <h3><?php echo gettext("Pages"); ?></h3> <?php printPageMenu("list","","menu-active","submenu","menu-active"); ?> </div> <?php } ?> <div class="menu"> <h3><?php echo gettext("Archive"); ?></h3> <ul> <?php if($_zp_gallery_page == "archive.php") { echo "<li class='menu-active'>".gettext("Gallery And News")."</li>"; } else { echo "<li>"; printCustomPageURL(gettext("Gallery and News"),"archive")."</li>"; } ?> </ul> </div> <div class="menu"> <h3><?php echo gettext("RSS"); ?></h3> <ul> <li><?php printRSSLink('Gallery','','Gallery', ''); ?></li> <?php if(function_exists("printZenpageRSSLink")) { ?> <li><?php printZenpageRSSLink("News","","","News"); ?></li> <li><?php printZenpageRSSLink("NewsWithImages","","","News and Gallery"); ?></li> <?php } ?> </ul> </div> <?php if (function_exists('printLanguageSelector')) { ?> <?php printLanguageSelector("langselector"); ?> <?php } ?>
jewsroch/sf-photos
themes/zenpage/themes/zenpage-default/sidebar.php
PHP
gpl-2.0
1,420
package com.refugiate.app.utilidades.route; import com.google.android.gms.maps.model.PolylineOptions; public interface RoutingListener { public void onRoutingFailure(); public void onRoutingStart(); public void onRoutingSuccess(PolylineOptions mPolyOptions); }
marvindelarc/Refugiate
Proyecto Tesis/RefugiateApp/app/src/main/java/com/refugiate/app/utilidades/route/RoutingListener.java
Java
gpl-2.0
268
package dynamickyManazeri; import dynamickyAgenti.AgentVozidla; import simulacia.Mc; import simulacia.Sprava; import OSPABA.DynamicAgent; import OSPABA.DynamicAgentManager; import OSPABA.MessageForm; import OSPABA.Simulation; public class ManazerVozidla extends DynamicAgentManager { public ManazerVozidla(int id, Simulation mySim, DynamicAgent myAgent) { super(id, mySim, myAgent); } @Override public void processMessage(MessageForm message) { Sprava sprava = (Sprava)message; switch (sprava.code()) { case Mc.goal: myAgent().setCasZaciatkuPrace(mySim().currentTime()); myAgent().setStoji(false); sprava.setAddressee(myAgent().procesPresunu()); startContinualAssistant(sprava); break; case Mc.finish: // procesPresunu Sprava copy = new Sprava(sprava); transfer(copy); myAgent().zvisCelkovyCasPrace(mySim().currentTime() - myAgent().casZaciatkuPrace()); myAgent().setStoji(true); done(sprava); break; } } @Override public AgentVozidla myAgent() { return (AgentVozidla)super.myAgent(); } }
nixone/ds-sem
lib/ospaba-1.6.3/samples/Oceliaren/dynamickyManazeri/ManazerVozidla.java
Java
gpl-2.0
1,054
/* * Copyright (C) 2011-2021 Project SkyFire <https://www.projectskyfire.org/> * Copyright (C) 2008-2021 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2021 MaNGOS <https://www.getmangos.eu/> * Copyright (C) 2006-2014 ScriptDev2 <https://github.com/scriptdev2/scriptdev2/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "SpellScript.h" #include "SpellAuraEffects.h" #include "oculus.h" enum Says { SAY_AGGRO = 0, SAY_AZURE = 1, SAY_AZURE_EMOTE = 2, SAY_DEATH = 3 }; enum Spells { SPELL_ENERGIZE_CORES_VISUAL = 62136, SPELL_ENERGIZE_CORES = 50785, //Damage 5938 to 6562, effec2 Triggers 54069, effect3 Triggers 56251 SPELL_CALL_AZURE_RING_CAPTAIN = 51002, //Effect Send Event (12229) /*SPELL_CALL_AZURE_RING_CAPTAIN_2 = 51006, //Effect Send Event (10665) SPELL_CALL_AZURE_RING_CAPTAIN_3 = 51007, //Effect Send Event (18454) SPELL_CALL_AZURE_RING_CAPTAIN_4 = 51008, //Effect Send Event (18455)*/ SPELL_CALL_AMPLIFY_MAGIC = 51054, SPELL_ICE_BEAM = 49549, SPELL_ARCANE_BEAM_PERIODIC = 51019, SPELL_SUMMON_ARCANE_BEAM = 51017 }; enum Events { EVENT_ENERGIZE_CORES = 1, EVENT_CALL_AZURE, EVENT_AMPLIFY_MAGIC, EVENT_ENERGIZE_CORES_VISUAL }; class boss_varos : public CreatureScript { public: boss_varos() : CreatureScript("boss_varos") { } CreatureAI* GetAI(Creature* creature) const OVERRIDE { return new boss_varosAI(creature); } struct boss_varosAI : public BossAI { boss_varosAI(Creature* creature) : BossAI(creature, DATA_VAROS_EVENT) { if (instance->GetBossState(DATA_DRAKOS_EVENT) != DONE) DoCast(me, SPELL_CENTRIFUGE_SHIELD); } void Reset() OVERRIDE { _Reset(); events.ScheduleEvent(EVENT_AMPLIFY_MAGIC, urand(20, 25) * IN_MILLISECONDS); events.ScheduleEvent(EVENT_ENERGIZE_CORES_VISUAL, 5000); // not sure if this is handled by a timer or hp percentage events.ScheduleEvent(EVENT_CALL_AZURE, urand(15, 30) * IN_MILLISECONDS); firstCoreEnergize = false; coreEnergizeOrientation = 0.0f; } void EnterCombat(Unit* /*who*/) OVERRIDE { _EnterCombat(); Talk(SAY_AGGRO); } float GetCoreEnergizeOrientation() { return coreEnergizeOrientation; } void UpdateAI(uint32 diff) OVERRIDE { //Return since we have no target if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_ENERGIZE_CORES: DoCast(me, SPELL_ENERGIZE_CORES); events.CancelEvent(EVENT_ENERGIZE_CORES); break; case EVENT_ENERGIZE_CORES_VISUAL: if (!firstCoreEnergize) { coreEnergizeOrientation = me->GetOrientation(); firstCoreEnergize = true; } else coreEnergizeOrientation = Position::NormalizeOrientation(coreEnergizeOrientation - 2.0f); DoCast(me, SPELL_ENERGIZE_CORES_VISUAL); events.ScheduleEvent(EVENT_ENERGIZE_CORES_VISUAL, 5000); events.ScheduleEvent(EVENT_ENERGIZE_CORES, 4000); break; case EVENT_CALL_AZURE: // not sure how blizz handles this, i cant see any pattern between the differnt spells DoCast(me, SPELL_CALL_AZURE_RING_CAPTAIN); Talk(SAY_AZURE); Talk(SAY_AZURE_EMOTE); events.ScheduleEvent(EVENT_CALL_AZURE, urand(20, 25) * IN_MILLISECONDS); break; case EVENT_AMPLIFY_MAGIC: DoCastVictim(SPELL_CALL_AMPLIFY_MAGIC); events.ScheduleEvent(EVENT_AMPLIFY_MAGIC, urand(17, 20) * IN_MILLISECONDS); break; } } DoMeleeAttackIfReady(); } void JustDied(Unit* /*killer*/) OVERRIDE { _JustDied(); Talk(SAY_DEATH); DoCast(me, SPELL_DEATH_SPELL, true); // we cast the spell as triggered or the summon effect does not occur } private: bool firstCoreEnergize; float coreEnergizeOrientation; }; }; class npc_azure_ring_captain : public CreatureScript { public: npc_azure_ring_captain() : CreatureScript("npc_azure_ring_captain") { } struct npc_azure_ring_captainAI : public ScriptedAI { npc_azure_ring_captainAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } void Reset() OVERRIDE { targetGUID = 0; me->SetWalk(true); //! HACK: Creature's can't have MOVEMENTFLAG_FLYING me->AddUnitMovementFlag(MOVEMENTFLAG_FLYING); me->SetReactState(REACT_AGGRESSIVE); } void SpellHitTarget(Unit* target, SpellInfo const* spell) OVERRIDE { if (spell->Id == SPELL_ICE_BEAM) { target->CastSpell(target, SPELL_SUMMON_ARCANE_BEAM, true); me->DespawnOrUnsummon(); } } void UpdateAI(uint32 /*diff*/) OVERRIDE { if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } void MovementInform(uint32 type, uint32 id) OVERRIDE { if (type != POINT_MOTION_TYPE || id != ACTION_CALL_DRAGON_EVENT) return; me->GetMotionMaster()->MoveIdle(); if (Unit* target = ObjectAccessor::GetUnit(*me, targetGUID)) DoCast(target, SPELL_ICE_BEAM); } void DoAction(int32 action) OVERRIDE { switch (action) { case ACTION_CALL_DRAGON_EVENT: if (instance) { if (Creature* varos = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_VAROS))) { if (Unit* victim = varos->AI()->SelectTarget(SELECT_TARGET_RANDOM, 0)) { me->SetReactState(REACT_PASSIVE); me->SetWalk(false); me->GetMotionMaster()->MovePoint(ACTION_CALL_DRAGON_EVENT, victim->GetPositionX(), victim->GetPositionY(), victim->GetPositionZ() + 20.0f); targetGUID = victim->GetGUID(); } } } break; } } private: uint64 targetGUID; InstanceScript* instance; }; CreatureAI* GetAI(Creature* creature) const OVERRIDE { return new npc_azure_ring_captainAI(creature); } }; class spell_varos_centrifuge_shield : public SpellScriptLoader { public: spell_varos_centrifuge_shield() : SpellScriptLoader("spell_varos_centrifuge_shield") { } class spell_varos_centrifuge_shield_AuraScript : public AuraScript { PrepareAuraScript(spell_varos_centrifuge_shield_AuraScript); bool Load() OVERRIDE { Unit* caster = GetCaster(); return (caster && caster->ToCreature()); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (Unit* caster = GetCaster()) { // flags taken from sniffs // UNIT_FLAG_UNK_9 -> means passive but it is not yet implemented in core if (caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_15|UNIT_FLAG_IMMUNE_TO_NPC|UNIT_FLAG_IMMUNE_TO_PC|UNIT_FLAG_UNK_6)) { caster->ToCreature()->SetReactState(REACT_PASSIVE); caster->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_15|UNIT_FLAG_IMMUNE_TO_NPC|UNIT_FLAG_IMMUNE_TO_PC|UNIT_FLAG_UNK_6); } } } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (Unit* caster = GetCaster()) { caster->ToCreature()->SetReactState(REACT_AGGRESSIVE); caster->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_15|UNIT_FLAG_IMMUNE_TO_NPC|UNIT_FLAG_IMMUNE_TO_PC|UNIT_FLAG_UNK_6); } } void Register() OVERRIDE { OnEffectRemove += AuraEffectRemoveFn(spell_varos_centrifuge_shield_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); OnEffectApply += AuraEffectApplyFn(spell_varos_centrifuge_shield_AuraScript::OnApply, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_varos_centrifuge_shield_AuraScript(); } }; class spell_varos_energize_core_area_enemy : public SpellScriptLoader { public: spell_varos_energize_core_area_enemy() : SpellScriptLoader("spell_varos_energize_core_area_enemy") { } class spell_varos_energize_core_area_enemySpellScript : public SpellScript { PrepareSpellScript(spell_varos_energize_core_area_enemySpellScript) void FilterTargets(std::list<WorldObject*>& targets) { Creature* varos = GetCaster()->ToCreature(); if (!varos) return; if (varos->GetEntry() != NPC_VAROS) return; float orientation = CAST_AI(boss_varos::boss_varosAI, varos->AI())->GetCoreEnergizeOrientation(); for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end();) { Position pos; (*itr)->GetPosition(&pos); float angle = varos->GetAngle((*itr)->GetPositionX(), (*itr)->GetPositionY()); float diff = fabs(orientation - angle); if (diff > 1.0f) itr = targets.erase(itr); else ++itr; } } void Register() OVERRIDE { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_varos_energize_core_area_enemySpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY); } }; SpellScript* GetSpellScript() const OVERRIDE { return new spell_varos_energize_core_area_enemySpellScript(); } }; class spell_varos_energize_core_area_entry : public SpellScriptLoader { public: spell_varos_energize_core_area_entry() : SpellScriptLoader("spell_varos_energize_core_area_entry") { } class spell_varos_energize_core_area_entrySpellScript : public SpellScript { PrepareSpellScript(spell_varos_energize_core_area_entrySpellScript) void FilterTargets(std::list<WorldObject*>& targets) { Creature* varos = GetCaster()->ToCreature(); if (!varos) return; if (varos->GetEntry() != NPC_VAROS) return; float orientation = CAST_AI(boss_varos::boss_varosAI, varos->AI())->GetCoreEnergizeOrientation(); for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end();) { Position pos; (*itr)->GetPosition(&pos); float angle = varos->GetAngle((*itr)->GetPositionX(), (*itr)->GetPositionY()); float diff = fabs(orientation - angle); if (diff > 1.0f) itr = targets.erase(itr); else ++itr; } } void Register() OVERRIDE { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_varos_energize_core_area_entrySpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENTRY); } }; SpellScript* GetSpellScript() const OVERRIDE { return new spell_varos_energize_core_area_entrySpellScript(); } }; void AddSC_boss_varos() { new boss_varos(); new npc_azure_ring_captain(); new spell_varos_centrifuge_shield(); new spell_varos_energize_core_area_enemy(); new spell_varos_energize_core_area_entry(); }
ProjectSkyfire/SkyFire.548
src/server/scripts/Northrend/Nexus/Oculus/boss_varos.cpp
C++
gpl-2.0
14,377
// Copyright 2015, Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // // Copyright (c) XeLabs // BohuTANG package sqltypes import ( "bytes" ) // Operator used to do the aggregator for sum/min/max/ etc. func Operator(v1 Value, v2 Value, fn func(x interface{}, y interface{}) interface{}) Value { // Sum field type is Decimal, we convert it to golang Float64. switch v1.Type() { case Decimal: v1 = MakeTrusted(Float64, v1.Raw()) } switch v2.Type() { case Decimal: v2 = MakeTrusted(Float64, v2.Raw()) } v1n := v1.ToNative() v2n := v2.ToNative() val := fn(v1n, v2n) v, err := BuildValue(val) if err != nil { panic(err) } return v } // SumFn used to do sum of two values. func SumFn(x interface{}, y interface{}) interface{} { var v interface{} switch x.(type) { case int64: v = (x.(int64) + y.(int64)) case uint64: v = (x.(uint64) + y.(uint64)) case float64: v = (x.(float64) + y.(float64)) case []uint8: // We only support numerical value sum. v = 0 } return v } // MinFn returns the min value of two. func MinFn(x interface{}, y interface{}) interface{} { v := x switch x.(type) { case int64: if x.(int64) > y.(int64) { v = y } case uint64: if x.(uint64) > y.(uint64) { v = y } case float64: if x.(float64) > y.(float64) { v = y } case []uint8: if bytes.Compare(x.([]uint8), y.([]uint8)) > 0 { v = y } } return v } // MaxFn returns the max value of two. func MaxFn(x interface{}, y interface{}) interface{} { v := x switch x.(type) { case int64: if x.(int64) < y.(int64) { v = y } case uint64: if x.(uint64) < y.(uint64) { v = y } case float64: if x.(float64) < y.(float64) { v = y } case []uint8: if bytes.Compare(x.([]uint8), y.([]uint8)) < 0 { v = y } } return v } // DivFn returns the div value of two. func DivFn(x interface{}, y interface{}) interface{} { var v1, v2 float64 switch x.(type) { case int64: v1 = float64(x.(int64)) case uint64: v1 = float64(x.(uint64)) case float64: v1 = x.(float64) case []uint8: // We only support numerical value div. return 0 } switch y.(type) { case int64: v2 = float64(y.(int64)) case uint64: v2 = float64(y.(uint64)) case float64: v2 = y.(float64) case []uint8: // We only support numerical value div. return 0 } return v1 / v2 }
XeLabs/go-mysqlstack
sqlparser/depends/sqltypes/aggregator.go
GO
gpl-2.0
2,409
/* Copyright (c) 2009 Richard G. Todd. * Licensed under the terms of the Microsoft Public License (Ms-PL). */ using System; using Test.CalculatorParser.Terminals; namespace LinguaDemo.Calculator { public class TermOperator : CalculatorNonterminal { #region Fields #endregion #region Rules public static void Rule(TermOperator result, OperatorMultiplication op) { result.Function = (lhs, rhs) => lhs*rhs; } public static void Rule(TermOperator result, OperatorDivision op) { result.Function = (lhs, rhs) => lhs/rhs; } #endregion #region Public Properties public Func<int, int, int> Function { get; private set; } #endregion } }
furesoft/Creek
Test/CalculatorParser/Nonterminals/TermOperator.cs
C#
gpl-2.0
778
/* Theme Name: Restaurant Theme URI: http://opal375.ru Description: Easy to use but functional responsive theme to build a website for restaurants or other types of business that work on any device. Features include a loading page, an intergrated slider library to manage sliders, and optional Google Map plugins, Restaurant SimpleBooings plugins (available at Designpromote.co.uk/wordpress). Author: Ruslan Grigoryev Author URI: Ruslan Grigoryev Template: twentytwelve Version: 1.10 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Tags: light, one-column, two-columns, flexible-width, custom-header, full-width-template, flexible-width Text Domain: restaurant Restaurant theme, photos/images included are licensed under the GPL. jQuery FlexSlider v2.0 Copyright 2012 WooThemes */ @import url("../twentytwelve/style.css"); /* =Basic structure */ body { background: url(images/bg-main.jpg)no-repeat center center fixed; -webkit-background-size: cover; /* For WebKit*/ -moz-background-size: cover; /* Mozilla*/ -o-background-size: cover; /* Opera*/ background-size: cover; /* Generic*/ } a { outline: none; color: #660000; } a:hover { color: #0f3647; } /* Page structure */ #top-page { display:block;float:left;height:5px;width:100%;background-color:#660000; } .site-header { padding: 24px 0 12px; padding: 1.714285714rem 0 0.86rem; } .site-content { margin: 0; padding-left: 14px; } .site-content.front-page { padding-left: 0; } .home-widget { display: block; float: left; width: 100%; } .main-navigation { margin-top: 12px; } hgroup, .main-navigation ul, footer .site-info { padding: 0 1rem; padding: 0 14px; } /* Navigation Menu */ .main-navigation li { font-size: 13px; font-size: 1rem; line-height: 1.42857143; } .main-navigation a { color: #660000; } .main-navigation a:hover { color: #21759b; } /* Header */ .site-header h1 a, .site-header h2 a { color: #660000; display: inline-block; text-decoration: none; } .site-header h1 a:hover, .site-header h2 a:hover { color: #660000; } .site-header h1 { color: #660000; font-size: 28px; font-family: "Times New Roman",Times,serif; /*font-size: 1.714285714rem;*/ line-height: 1.285714286; /*line-height: 1;*/ margin-bottom: 8px; } .site-header h2 { color: #749e6e; /*margin-top: -10px;*/ line-height: 1.4; } .site-header .site-contact{ margin-top: 8px; } .site-header .site-contact, .site-header .site-contact .widget{ /*float:right; display:none; margin-top:-50px;*/ color: #000; line-height: 1.4; text-align: center; } .site-header .site-contact a { color: #515151; text-decoration: none; } .flex-caption{ color: #fff; font-size: 17px; font-size:1.2rem; font-weight: normal; line-height: 1.4; background-color: #660000; opacity: 0.6; filter: alpha(opacity=60); padding: 5px; position: absolute; bottom: 10%; right:0; /*left:500px;*/ width: 40%; /*margin-top: -35px;*/ } /* homewidget */ /*.template-front-page .home-widget .widget-title,*/ .home-widget .widget-title { line-height: 2.181818182; background-color: #660000; color: #fff; text-align: center; display: block; font-weight: normal; font-size: 14px; font-size: 1rem; } .home-widget .widget { margin-bottom: 25px; } .home-widget .textwidget { line-height: 1.846153846; /*padding: 0 5px;*/ } .home-widget img{ float:left; margin-right: 5px; } .home-widget img:hover { opacity: 0.7; filter:Alpha(opacity=70); /* ie8 and earlier */ } /* =Main content and comment content */ .entry-header { margin-bottom: 24px; margin-bottom: 1.714285714rem; margin-top: 24px; margin-top: 1.714285714rem; } .template-front-page .entry-header { display: none; } .template-front-page .entry-content h2{ margin: 0; } .entry-content h3 a[target="_blank"]:after, .entry-content h3 a[target="new"]:after { margin: 0; } .entry-content .menu-text { background: none; padding-bottom: 10px; } .entry-content .menu-title { color:#fff; margin-bottom:1px; padding: 5px; background-color:#660000; text-align: left; } .entry-content .menu-top{ float:right; } .entry-content .toggle-sign { display: inline-block; width: 10px; font-weight: bold; color: #fff; } .widget-area .widget input[type="button"], .content-area input[type="button"], .head-widget input[type="button"]{ width: 150px; color: #ffffff; background-color: #660000; background-repeat: repeat-x; background-image: -moz-linear-gradient(top, #660000, #660000); background-image: -ms-linear-gradient(top, #660000, #660000); background-image: -webkit-linear-gradient(top, #660000, #660000); background-image: -o-linear-gradient(top, #660000, #660000); background-image: linear-gradient(top, #660000, #660000); border: 1px solid #660000; } .content-area input[type="button"] { margin: 0 auto; display: block; } select{ border: 1px solid #ccc; border-radius: 3px; font-family: inherit; padding: 6px; padding: 0.428571429rem; } /* Sidebar */ .widget-area .widget { margin-bottom: 20px; } .widget-area .widget h3 { margin-bottom: 5px; } .widget-title { color: #660000; } .widget-area .widget a { text-decoration: none; } /* Google maps */ #map_canvas{ width: 245px; height: 250px; border: 1px solid #660000; } #map_canvas img{ max-width:none; /*google map infowindow can show correctly.*/ } .zn-gmap{ border: 1px solid #660000; } /* Footer */ footer[role="contentinfo"] { background-color: #660000; margin-top: 0; padding: 0 0 5px 0; } footer[role="contentinfo"] a { color: #ffffff; text-decoration: none; } footer[role="contentinfo"] a:hover { color: #ffffff; text-decoration: underline; } footer .site-info{ border-top: solid 1px #ffffff; } footer .widget-area { margin: 5px 0 0; } footer .widget-area .widget h3 { margin-bottom: 5px; } footer .site-info{ text-align: right; } /*.template-front-page .widget-area.three,*/ #footer-widgets.widget-area.three{ clear: both; float: none; width: auto; padding-top: 0px; padding-left: 14px; /*padding-top: 1.714285714rem; border-top: 1px solid #ededed;*/ } /* =Main content and comment content */ .site-content article { border-bottom: 0px; } /* ===[ Footer Widget Areas ]=== */ .site-info { clear: both; } #footer-widgets { border-top: none; /*float: left;*/ } #footer-widgets .widget-title, #footer-widgets .textwidget{ color: #ffffff; } #footer-widgets .widget li { list-style-type: none; } /* Minimum width of 960 pixels. */ @media screen and (min-width: 960px) { body .site { padding: 0; margin-top: 0; /*48px;*/ margin-bottom: 0; box-shadow: 0 0px 0px rgba(100, 100, 100, 0.3); } } @media screen and (min-width: 600px) { .site-header { padding: 24px 0 0; padding: 1.714285714rem 0 0; } .site-header h1 { margin-bottom: 0; } .site-header h2 { line-height: 1.8262; } .main-navigation li a { border-bottom: 0; color: #fff; } .main-navigation .current-menu-item > a, .main-navigation .current-menu-ancestor > a, .main-navigation .current_page_item > a, .main-navigation .current_page_ancestor > a { color: #660000; } .site-header .site-contact{ float:right; display:block; padding-right: 1rem; padding-right: 14px; margin-top:-50px; color: #515151; font-weight: normal; } .home-widget .widget{ float: left; width: 300px; } .home-widget .widget:first-child{ margin-right: 30px; } .home-widget .widget:last-child{ float: right; } .home-widget a:hover{ text-decoration: none; } .home-widget article{ padding-bottom: 0px; } .home-widget .widget-title { line-height: 2.181818182; background-color: #660000; color: #fff; text-align: center; display: block; font-weight: normal; font-size: 14px; font-size: 1rem; } .home-widget .widget img { border-radius: 0; } /*footer[role="contentinfo"]{ padding: 0 14px; }*/ #footer-widgets { width: 100%; } #footer-widgets.three .widget { clear: none; float: left; margin-right: 1.71429rem; max-width: 29.85%; width: 29.85%; } } /* for IE8 and IE7 */ .ie #footer-widgets.three .widget { float: left; margin-right: 3.1%; width: 29.85%; clear: none; } .ie #footer-widgets.three .widget + .widget + .widget { margin-right: 3.1%; }
RuslanGrigoryev/wp_restaraunt
wp-content/themes/restaurant/style.css
CSS
gpl-2.0
8,259
package net.mightypixel; public interface MonsterPrototype { public MonsterPrototype clone(); public int getEyeCount(); }
MightyPixel/MightyPatterns
Prototype/src/net/mightypixel/MonsterPrototype.java
Java
gpl-2.0
128
cmd_drivers/ieee1394/built-in.o := rm -f drivers/ieee1394/built-in.o; /home/spacecaker/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi-ar rcs drivers/ieee1394/built-in.o
spacecaker/Stock_spacecaker_kernel
drivers/ieee1394/.built-in.o.cmd
Batchfile
gpl-2.0
191
from enigma import eEPGCache, getBestPlayableServiceReference, \ eServiceReference, iRecordableService, quitMainloop from Components.config import config from Components.UsageConfig import defaultMoviePath from Components.TimerSanityCheck import TimerSanityCheck from Screens.MessageBox import MessageBox import Screens.Standby from Tools import Directories, Notifications, ASCIItranslit, Trashcan from Tools.XMLTools import stringToXML import timer import xml.etree.cElementTree import NavigationInstance from ServiceReference import ServiceReference from time import localtime, strftime, ctime, time from bisect import insort # ok, for descriptions etc we have: # service reference (to get the service name) # name (title) # description (description) # event data (ONLY for time adjustments etc.) # parses an event, and gives out a (begin, end, name, duration, eit)-tuple. # begin and end will be corrected def parseEvent(ev, description = True): if description: name = ev.getEventName() description = ev.getShortDescription() if description == "": description = ev.getExtendedDescription() else: name = "" description = "" begin = ev.getBeginTime() end = begin + ev.getDuration() eit = ev.getEventId() begin -= config.recording.margin_before.value * 60 end += config.recording.margin_after.value * 60 return (begin, end, name, description, eit) class AFTEREVENT: NONE = 0 STANDBY = 1 DEEPSTANDBY = 2 AUTO = 3 # please do not translate log messages class RecordTimerEntry(timer.TimerEntry, object): ######### the following static methods and members are only in use when the box is in (soft) standby receiveRecordEvents = False @staticmethod def shutdown(): quitMainloop(1) @staticmethod def staticGotRecordEvent(recservice, event): if event == iRecordableService.evEnd: print "RecordTimer.staticGotRecordEvent(iRecordableService.evEnd)" recordings = NavigationInstance.instance.getRecordings() if not recordings: # no more recordings exist rec_time = NavigationInstance.instance.RecordTimer.getNextRecordingTime() if rec_time > 0 and (rec_time - time()) < 360: print "another recording starts in", rec_time - time(), "seconds... do not shutdown yet" else: print "no starting records in the next 360 seconds... immediate shutdown" RecordTimerEntry.shutdown() # immediate shutdown elif event == iRecordableService.evStart: print "RecordTimer.staticGotRecordEvent(iRecordableService.evStart)" @staticmethod def stopTryQuitMainloop(): print "RecordTimer.stopTryQuitMainloop" NavigationInstance.instance.record_event.remove(RecordTimerEntry.staticGotRecordEvent) RecordTimerEntry.receiveRecordEvents = False @staticmethod def TryQuitMainloop(default_yes = True): if not RecordTimerEntry.receiveRecordEvents: print "RecordTimer.TryQuitMainloop" NavigationInstance.instance.record_event.append(RecordTimerEntry.staticGotRecordEvent) RecordTimerEntry.receiveRecordEvents = True # send fake event.. to check if another recordings are running or # other timers start in a few seconds RecordTimerEntry.staticGotRecordEvent(None, iRecordableService.evEnd) # send normal notification for the case the user leave the standby now.. Notifications.AddNotification(Screens.Standby.TryQuitMainloop, 1, onSessionOpenCallback=RecordTimerEntry.stopTryQuitMainloop, default_yes = default_yes) ################################################################# def __init__(self, serviceref, begin, end, name, description, eit, disabled = False, justplay = False, afterEvent = AFTEREVENT.AUTO, checkOldTimers = False, dirname = None, tags = None): timer.TimerEntry.__init__(self, int(begin), int(end)) if checkOldTimers == True: if self.begin < time() - 1209600: self.begin = int(time()) if self.end < self.begin: self.end = self.begin assert isinstance(serviceref, ServiceReference) if serviceref.isRecordable(): self.service_ref = serviceref else: self.service_ref = ServiceReference(None) self.eit = eit self.dontSave = False self.name = name self.description = description self.disabled = disabled self.timer = None self.__record_service = None self.start_prepare = 0 self.justplay = justplay self.afterEvent = afterEvent self.dirname = dirname self.dirnameHadToFallback = False self.autoincrease = False self.autoincreasetime = 3600 * 24 # 1 day self.tags = tags or [] self.log_entries = [] self.resetState() def log(self, code, msg): self.log_entries.append((int(time()), code, msg)) print "[TIMER]", msg def calculateFilename(self): service_name = self.service_ref.getServiceName() begin_date = strftime("%Y%m%d %H%M", localtime(self.begin)) begin_shortdate = strftime("%Y%m%d", localtime(self.begin)) print "begin_date: ", begin_date print "service_name: ", service_name print "name:", self.name print "description: ", self.description filename = begin_date + " - " + service_name if self.name: if config.usage.setup_level.index >= 2: # expert+ if config.recording.filename_composition.value == "short": filename = begin_shortdate + " - " + self.name elif config.recording.filename_composition.value == "long": filename += " - " + self.name + " - " + self.description else: filename += " - " + self.name # standard else: filename += " - " + self.name if config.recording.ascii_filenames.value: filename = ASCIItranslit.legacyEncode(filename) if not self.dirname or not Directories.fileExists(self.dirname, 'w'): if self.dirname: self.dirnameHadToFallback = True dirname = defaultMoviePath() else: dirname = self.dirname self.Filename = Directories.getRecordingFilename(filename, dirname) self.log(0, "Filename calculated as: '%s'" % self.Filename) #begin_date + " - " + service_name + description) def tryPrepare(self): if self.justplay: return True else: self.calculateFilename() rec_ref = self.service_ref and self.service_ref.ref if rec_ref and rec_ref.flags & eServiceReference.isGroup: rec_ref = getBestPlayableServiceReference(rec_ref, eServiceReference()) if not rec_ref: self.log(1, "'get best playable service for group... record' failed") return False self.record_service = rec_ref and NavigationInstance.instance.recordService(rec_ref) if not self.record_service: self.log(1, "'record service' failed") return False if self.repeated: epgcache = eEPGCache.getInstance() queryTime=self.begin+(self.end-self.begin)/2 evt = epgcache.lookupEventTime(rec_ref, queryTime) if evt: self.description = evt.getShortDescription() if self.description == "": description = evt.getExtendedDescription() event_id = evt.getEventId() else: event_id = -1 else: event_id = self.eit if event_id is None: event_id = -1 prep_res=self.record_service.prepare(self.Filename + ".ts", self.begin, self.end, event_id, self.name.replace("\n", ""), self.description.replace("\n", ""), ' '.join(self.tags)) if prep_res: if prep_res == -255: self.log(4, "failed to write meta information") else: self.log(2, "'prepare' failed: error %d" % prep_res) # we must calc nur start time before stopRecordService call because in Screens/Standby.py TryQuitMainloop tries to get # the next start time in evEnd event handler... self.do_backoff() self.start_prepare = time() + self.backoff NavigationInstance.instance.stopRecordService(self.record_service) self.record_service = None return False return True def do_backoff(self): if self.backoff == 0: self.backoff = 5 else: self.backoff *= 2 if self.backoff > 100: self.backoff = 100 self.log(10, "backoff: retry in %d seconds" % self.backoff) def activate(self): next_state = self.state + 1 self.log(5, "activating state %d" % next_state) if next_state == self.StatePrepared: if self.tryPrepare(): self.log(6, "prepare ok, waiting for begin") # create file to "reserve" the filename # because another recording at the same time on another service can try to record the same event # i.e. cable / sat.. then the second recording needs an own extension... when we create the file # here than calculateFilename is happy if not self.justplay: open(self.Filename + ".ts", "w").close() # Give the Trashcan a chance to clean up try: Trashcan.instance.cleanIfIdle() except Exception, e: print "[TIMER] Failed to call Trashcan.instance.cleanIfIdle()" print "[TIMER] Error:", e # fine. it worked, resources are allocated. self.next_activation = self.begin self.backoff = 0 return True self.log(7, "prepare failed") if self.first_try_prepare: self.first_try_prepare = False cur_ref = NavigationInstance.instance.getCurrentlyPlayingServiceReference() if cur_ref and not cur_ref.getPath(): if not config.recording.asktozap.value: self.log(8, "asking user to zap away") Notifications.AddNotificationWithCallback(self.failureCB, MessageBox, _("A timer failed to record!\nDisable TV and try again?\n"), timeout=20) else: # zap without asking self.log(9, "zap without asking") Notifications.AddNotification(MessageBox, _("In order to record a timer, the TV was switched to the recording service!\n"), type=MessageBox.TYPE_INFO, timeout=20) self.failureCB(True) elif cur_ref: self.log(8, "currently running service is not a live service.. so stop it makes no sense") else: self.log(8, "currently no service running... so we dont need to stop it") return False elif next_state == self.StateRunning: # if this timer has been cancelled, just go to "end" state. if self.cancelled: return True if self.justplay: if Screens.Standby.inStandby: self.log(11, "wakeup and zap") #set service to zap after standby Screens.Standby.inStandby.prev_running_service = self.service_ref.ref #wakeup standby Screens.Standby.inStandby.Power() else: self.log(11, "zapping") NavigationInstance.instance.playService(self.service_ref.ref) return True else: self.log(11, "start recording") record_res = self.record_service.start() if record_res: self.log(13, "start record returned %d" % record_res) self.do_backoff() # retry self.begin = time() + self.backoff return False return True elif next_state == self.StateEnded: old_end = self.end if self.setAutoincreaseEnd(): self.log(12, "autoincrase recording %d minute(s)" % int((self.end - old_end)/60)) self.state -= 1 return True self.log(12, "stop recording") if not self.justplay: NavigationInstance.instance.stopRecordService(self.record_service) self.record_service = None if self.afterEvent == AFTEREVENT.STANDBY: if not Screens.Standby.inStandby: # not already in standby Notifications.AddNotificationWithCallback(self.sendStandbyNotification, MessageBox, _("A finished record timer wants to set your\nBox to standby. Do that now?"), timeout = 20) elif self.afterEvent == AFTEREVENT.DEEPSTANDBY: if not Screens.Standby.inTryQuitMainloop: # not a shutdown messagebox is open if Screens.Standby.inStandby: # in standby RecordTimerEntry.TryQuitMainloop() # start shutdown handling without screen else: Notifications.AddNotificationWithCallback(self.sendTryQuitMainloopNotification, MessageBox, _("A finished record timer wants to shut down\nyour Box. Shutdown now?"), timeout = 20) return True def setAutoincreaseEnd(self, entry = None): if not self.autoincrease: return False if entry is None: new_end = int(time()) + self.autoincreasetime else: new_end = entry.begin -30 dummyentry = RecordTimerEntry(self.service_ref, self.begin, new_end, self.name, self.description, self.eit, disabled=True, justplay = self.justplay, afterEvent = self.afterEvent, dirname = self.dirname, tags = self.tags) dummyentry.disabled = self.disabled timersanitycheck = TimerSanityCheck(NavigationInstance.instance.RecordTimer.timer_list, dummyentry) if not timersanitycheck.check(): simulTimerList = timersanitycheck.getSimulTimerList() new_end = simulTimerList[1].begin del simulTimerList new_end -= 30 # 30 Sekunden Prepare-Zeit lassen del dummyentry if new_end <= time(): return False self.end = new_end return True def sendStandbyNotification(self, answer): if answer: Notifications.AddNotification(Screens.Standby.Standby) def sendTryQuitMainloopNotification(self, answer): if answer: Notifications.AddNotification(Screens.Standby.TryQuitMainloop, 1) def getNextActivation(self): if self.state == self.StateEnded: return self.end next_state = self.state + 1 return {self.StatePrepared: self.start_prepare, self.StateRunning: self.begin, self.StateEnded: self.end }[next_state] def failureCB(self, answer): if answer == True: self.log(13, "ok, zapped away") #NavigationInstance.instance.stopUserServices() NavigationInstance.instance.playService(self.service_ref.ref) else: self.log(14, "user didn't want to zap away, record will probably fail") def timeChanged(self): old_prepare = self.start_prepare self.start_prepare = self.begin - self.prepare_time self.backoff = 0 if int(old_prepare) != int(self.start_prepare): self.log(15, "record time changed, start prepare is now: %s" % ctime(self.start_prepare)) def gotRecordEvent(self, record, event): # TODO: this is not working (never true), please fix. (comparing two swig wrapped ePtrs) if self.__record_service.__deref__() != record.__deref__(): return self.log(16, "record event %d" % event) if event == iRecordableService.evRecordWriteError: print "WRITE ERROR on recording, disk full?" # show notification. the 'id' will make sure that it will be # displayed only once, even if more timers are failing at the # same time. (which is very likely in case of disk fullness) Notifications.AddPopup(text = _("Write error while recording. Disk full?\n"), type = MessageBox.TYPE_ERROR, timeout = 0, id = "DiskFullMessage") # ok, the recording has been stopped. we need to properly note # that in our state, with also keeping the possibility to re-try. # TODO: this has to be done. elif event == iRecordableService.evStart: text = _("A record has been started:\n%s") % self.name if self.dirnameHadToFallback: text = '\n'.join((text, _("Please note that the previously selected media could not be accessed and therefore the default directory is being used instead."))) if config.usage.show_message_when_recording_starts.value: Notifications.AddPopup(text = text, type = MessageBox.TYPE_INFO, timeout = 8) # we have record_service as property to automatically subscribe to record service events def setRecordService(self, service): if self.__record_service is not None: print "[remove callback]" NavigationInstance.instance.record_event.remove(self.gotRecordEvent) self.__record_service = service if self.__record_service is not None: print "[add callback]" NavigationInstance.instance.record_event.append(self.gotRecordEvent) record_service = property(lambda self: self.__record_service, setRecordService) def createTimer(xml): begin = int(xml.get("begin")) end = int(xml.get("end")) serviceref = ServiceReference(xml.get("serviceref").encode("utf-8")) description = xml.get("description").encode("utf-8") repeated = xml.get("repeated").encode("utf-8") disabled = long(xml.get("disabled") or "0") justplay = long(xml.get("justplay") or "0") afterevent = str(xml.get("afterevent") or "nothing") afterevent = { "nothing": AFTEREVENT.NONE, "standby": AFTEREVENT.STANDBY, "deepstandby": AFTEREVENT.DEEPSTANDBY, "auto": AFTEREVENT.AUTO }[afterevent] eit = xml.get("eit") if eit and eit != "None": eit = long(eit); else: eit = None location = xml.get("location") if location and location != "None": location = location.encode("utf-8") else: location = None tags = xml.get("tags") if tags and tags != "None": tags = tags.encode("utf-8").split(' ') else: tags = None name = xml.get("name").encode("utf-8") #filename = xml.get("filename").encode("utf-8") entry = RecordTimerEntry(serviceref, begin, end, name, description, eit, disabled, justplay, afterevent, dirname = location, tags = tags) entry.repeated = int(repeated) for l in xml.findall("log"): time = int(l.get("time")) code = int(l.get("code")) msg = l.text.strip().encode("utf-8") entry.log_entries.append((time, code, msg)) return entry class RecordTimer(timer.Timer): def __init__(self): timer.Timer.__init__(self) self.Filename = Directories.resolveFilename(Directories.SCOPE_CONFIG, "timers.xml") try: self.loadTimer() except IOError: print "unable to load timers from file!" def doActivate(self, w): # when activating a timer which has already passed, # simply abort the timer. don't run trough all the stages. if w.shouldSkip(): w.state = RecordTimerEntry.StateEnded else: # when active returns true, this means "accepted". # otherwise, the current state is kept. # the timer entry itself will fix up the delay then. if w.activate(): w.state += 1 self.timer_list.remove(w) # did this timer reached the last state? if w.state < RecordTimerEntry.StateEnded: # no, sort it into active list insort(self.timer_list, w) else: # yes. Process repeated, and re-add. if w.repeated: w.processRepeated() w.state = RecordTimerEntry.StateWaiting self.addTimerEntry(w) else: # Remove old timers as set in config self.cleanupDaily(config.recording.keep_timers.value) insort(self.processed_timers, w) self.stateChanged(w) def isRecording(self): isRunning = False for timer in self.timer_list: if timer.isRunning() and not timer.justplay: isRunning = True return isRunning def loadTimer(self): # TODO: PATH! if not Directories.fileExists(self.Filename): return try: doc = xml.etree.cElementTree.parse(self.Filename) except SyntaxError: from Tools.Notifications import AddPopup from Screens.MessageBox import MessageBox AddPopup(_("The timer file (timers.xml) is corrupt and could not be loaded."), type = MessageBox.TYPE_ERROR, timeout = 0, id = "TimerLoadFailed") print "timers.xml failed to load!" try: import os os.rename(self.Filename, self.Filename + "_old") except (IOError, OSError): print "renaming broken timer failed" return except IOError: print "timers.xml not found!" return root = doc.getroot() # put out a message when at least one timer overlaps checkit = True for timer in root.findall("timer"): newTimer = createTimer(timer) if (self.record(newTimer, True, dosave=False) is not None) and (checkit == True): from Tools.Notifications import AddPopup from Screens.MessageBox import MessageBox AddPopup(_("Timer overlap in timers.xml detected!\nPlease recheck it!"), type = MessageBox.TYPE_ERROR, timeout = 0, id = "TimerLoadFailed") checkit = False # at moment it is enough when the message is displayed one time def saveTimer(self): #root_element = xml.etree.cElementTree.Element('timers') #root_element.text = "\n" #for timer in self.timer_list + self.processed_timers: # some timers (instant records) don't want to be saved. # skip them #if timer.dontSave: #continue #t = xml.etree.cElementTree.SubElement(root_element, 'timers') #t.set("begin", str(int(timer.begin))) #t.set("end", str(int(timer.end))) #t.set("serviceref", str(timer.service_ref)) #t.set("repeated", str(timer.repeated)) #t.set("name", timer.name) #t.set("description", timer.description) #t.set("afterevent", str({ # AFTEREVENT.NONE: "nothing", # AFTEREVENT.STANDBY: "standby", # AFTEREVENT.DEEPSTANDBY: "deepstandby", # AFTEREVENT.AUTO: "auto"})) #if timer.eit is not None: # t.set("eit", str(timer.eit)) #if timer.dirname is not None: # t.set("location", str(timer.dirname)) #t.set("disabled", str(int(timer.disabled))) #t.set("justplay", str(int(timer.justplay))) #t.text = "\n" #t.tail = "\n" #for time, code, msg in timer.log_entries: #l = xml.etree.cElementTree.SubElement(t, 'log') #l.set("time", str(time)) #l.set("code", str(code)) #l.text = str(msg) #l.tail = "\n" #doc = xml.etree.cElementTree.ElementTree(root_element) #doc.write(self.Filename) list = [] list.append('<?xml version="1.0" ?>\n') list.append('<timers>\n') for timer in self.timer_list + self.processed_timers: if timer.dontSave: continue list.append('<timer') list.append(' begin="' + str(int(timer.begin)) + '"') list.append(' end="' + str(int(timer.end)) + '"') list.append(' serviceref="' + stringToXML(str(timer.service_ref)) + '"') list.append(' repeated="' + str(int(timer.repeated)) + '"') list.append(' name="' + str(stringToXML(timer.name)) + '"') list.append(' description="' + str(stringToXML(timer.description)) + '"') list.append(' afterevent="' + str(stringToXML({ AFTEREVENT.NONE: "nothing", AFTEREVENT.STANDBY: "standby", AFTEREVENT.DEEPSTANDBY: "deepstandby", AFTEREVENT.AUTO: "auto" }[timer.afterEvent])) + '"') if timer.eit is not None: list.append(' eit="' + str(timer.eit) + '"') if timer.dirname is not None: list.append(' location="' + str(stringToXML(timer.dirname)) + '"') if timer.tags is not None: list.append(' tags="' + str(stringToXML(' '.join(timer.tags))) + '"') list.append(' disabled="' + str(int(timer.disabled)) + '"') list.append(' justplay="' + str(int(timer.justplay)) + '"') list.append('>\n') if config.recording.debug.value: for time, code, msg in timer.log_entries: list.append('<log') list.append(' code="' + str(code) + '"') list.append(' time="' + str(time) + '"') list.append('>') list.append(str(stringToXML(msg))) list.append('</log>\n') list.append('</timer>\n') list.append('</timers>\n') file = open(self.Filename, "w") for x in list: file.write(x) file.close() def getNextZapTime(self): now = time() for timer in self.timer_list: if not timer.justplay or timer.begin < now: continue return timer.begin return -1 def getNextRecordingTime(self): now = time() for timer in self.timer_list: next_act = timer.getNextActivation() if timer.justplay or next_act < now: continue return next_act return -1 def isNextRecordAfterEventActionAuto(self): now = time() t = None for timer in self.timer_list: if timer.justplay or timer.begin < now: continue if t is None or t.begin == timer.begin: t = timer if t.afterEvent == AFTEREVENT.AUTO: return True return False def record(self, entry, ignoreTSC=False, dosave=True): #wird von loadTimer mit dosave=False aufgerufen timersanitycheck = TimerSanityCheck(self.timer_list,entry) if not timersanitycheck.check(): if ignoreTSC != True: print "timer conflict detected!" print timersanitycheck.getSimulTimerList() return timersanitycheck.getSimulTimerList() else: print "ignore timer conflict" elif timersanitycheck.doubleCheck(): print "ignore double timer" return None entry.timeChanged() print "[Timer] Record " + str(entry) entry.Timer = self self.addTimerEntry(entry) if dosave: self.saveTimer() return None def isInTimer(self, eventid, begin, duration, service): time_match = 0 chktime = None chktimecmp = None chktimecmp_end = None end = begin + duration refstr = str(service) for x in self.timer_list: check = x.service_ref.ref.toString() == refstr if not check: sref = x.service_ref.ref parent_sid = sref.getUnsignedData(5) parent_tsid = sref.getUnsignedData(6) if parent_sid and parent_tsid: # check for subservice sid = sref.getUnsignedData(1) tsid = sref.getUnsignedData(2) sref.setUnsignedData(1, parent_sid) sref.setUnsignedData(2, parent_tsid) sref.setUnsignedData(5, 0) sref.setUnsignedData(6, 0) check = sref.toCompareString() == refstr num = 0 if check: check = False event = eEPGCache.getInstance().lookupEventId(sref, eventid) num = event and event.getNumOfLinkageServices() or 0 sref.setUnsignedData(1, sid) sref.setUnsignedData(2, tsid) sref.setUnsignedData(5, parent_sid) sref.setUnsignedData(6, parent_tsid) for cnt in range(num): subservice = event.getLinkageService(sref, cnt) if sref.toCompareString() == subservice.toCompareString(): check = True break if check: if x.repeated != 0: if chktime is None: chktime = localtime(begin) chktimecmp = chktime.tm_wday * 1440 + chktime.tm_hour * 60 + chktime.tm_min chktimecmp_end = chktimecmp + (duration / 60) time = localtime(x.begin) for y in (0, 1, 2, 3, 4, 5, 6): if x.repeated & (1 << y) and (x.begin <= begin or begin <= x.begin <= end): timecmp = y * 1440 + time.tm_hour * 60 + time.tm_min if timecmp <= chktimecmp < (timecmp + ((x.end - x.begin) / 60)): time_match = ((timecmp + ((x.end - x.begin) / 60)) - chktimecmp) * 60 elif chktimecmp <= timecmp < chktimecmp_end: time_match = (chktimecmp_end - timecmp) * 60 else: #if x.eit is None: if begin <= x.begin <= end: diff = end - x.begin if time_match < diff: time_match = diff elif x.begin <= begin <= x.end: diff = x.end - begin if time_match < diff: time_match = diff if time_match: break return time_match def removeEntry(self, entry): print "[Timer] Remove " + str(entry) # avoid re-enqueuing entry.repeated = False # abort timer. # this sets the end time to current time, so timer will be stopped. entry.autoincrease = False entry.abort() if entry.state != entry.StateEnded: self.timeChanged(entry) print "state: ", entry.state print "in processed: ", entry in self.processed_timers print "in running: ", entry in self.timer_list # autoincrease instanttimer if possible if not entry.dontSave: for x in self.timer_list: if x.setAutoincreaseEnd(): self.timeChanged(x) # now the timer should be in the processed_timers list. remove it from there. self.processed_timers.remove(entry) self.saveTimer() def shutdown(self): self.saveTimer()
openpli-arm/enigma2-arm
RecordTimer.py
Python
gpl-2.0
26,731
# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest distro zip help: @echo "Please use \`make <target>' where <target> is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django-selector.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-selector.qhc" latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ "run these through (pdf)latex." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." distro: html @echo @echo "Pushing documents to http://dev.jmoiron.net/uromkan/" scp -r $(BUILDDIR)/html/* jmoiron@jmoiron.net:dev.jmoiron.net/uromkan/ zip: html @echo @echo "Making zip file 'uromkan.zip'" cd $(BUILDDIR)/html/; zip -r 'uromkan.zip' * mv $(BUILDDIR)/html/'uromkan.zip' .
jmoiron/uromkan
docs/Makefile
Makefile
gpl-2.0
3,450
/* Company : Nequeo Pty Ltd, http://www.nequeo.com.au/ * Copyright : Copyright © Nequeo Pty Ltd 2015 http://www.nequeo.com.au/ * * File : OnCallRxOfferParam.h * Purpose : SIP OnCallRxOfferParam class. * */ /* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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. */ #pragma once #ifndef _ONCALLRXOFFERPARAM_H #define _ONCALLRXOFFERPARAM_H #include "stdafx.h" #include "Call.h" #include "CallInfo.h" #include "SipEventType.h" #include "SdpSession.h" #include "CallSetting.h" #include "StatusCode.h" #include "pjsua2.hpp" using namespace System; using namespace System::Collections; using namespace System::Collections::Generic; namespace Nequeo { namespace Net { namespace PjSip { /// <summary> /// This structure contains parameters for Call::onCallRxOffer() callback. /// </summary> public ref class OnCallRxOfferParam sealed { public: /// <summary> /// This structure contains parameters for Call::onCallRxOffer() callback. /// </summary> OnCallRxOfferParam(); /// <summary> /// Gets or sets the current call. /// </summary> property Call^ CurrentCall { Call^ get(); void set(Call^ value); } /// <summary> /// Gets or sets the call information. /// </summary> property CallInfo^ Info { CallInfo^ get(); void set(CallInfo^ value); } /// <summary> /// Gets or sets the new offer received. /// </summary> property SdpSession^ Offer { SdpSession^ get(); void set(SdpSession^ value); } /// <summary> /// Gets or sets the current call setting, application can update this setting for answering the offer. /// </summary> property CallSetting^ Setting { CallSetting^ get(); void set(CallSetting^ value); } /// <summary> /// Gets or sets the Status code to be returned for answering the offer. On input, /// it contains status code 200. Currently, valid values are only 200 and 488. /// </summary> property StatusCode Code { StatusCode get(); void set(StatusCode value); } private: Call^ _currentCall; CallInfo^ _info; SdpSession^ _offer; CallSetting^ _setting; StatusCode _code; }; } } } #endif
drazenzadravec/nequeo
Source/Components/Net/Nequeo.Sip/Nequeo.PjSip/Nequeo.PjSip/OnCallRxOfferParam.h
C
gpl-2.0
3,366
<?php namespace Drupal\Tests\typed_data\Kernel; use Drupal\Core\Entity\TypedData\EntityDataDefinition; use Drupal\Core\Render\BubbleableMetadata; use Drupal\KernelTests\KernelTestBase; use Drupal\field\Entity\FieldConfig; use Drupal\field\Entity\FieldStorageConfig; use Drupal\Core\Field\FieldStorageDefinitionInterface; use Drupal\Core\TypedData\Exception\MissingDataException; use Drupal\typed_data\Exception\InvalidArgumentException; /** * Class DataFetcherTest. * * @group typed_data * * @coversDefaultClass \Drupal\typed_data\DataFetcher */ class DataFetcherTest extends KernelTestBase { /** * The typed data manager. * * @var \Drupal\Core\TypedData\TypedDataManagerInterface */ protected $typedDataManager; /** * The data fetcher object we want to test. * * @var \Drupal\typed_data\DataFetcherInterface */ protected $dataFetcher; /** * A node used for testing. * * @var \Drupal\node\NodeInterface */ protected $node; /** * An entity type manager used for testing. * * @var \Drupal\Core\Entity\EntityTypeManager */ protected $entityTypeManager; /** * Modules to enable. * * @var array */ public static $modules = [ 'typed_data', 'system', 'node', 'field', 'text', 'user', ]; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->installEntitySchema('user'); $this->installEntitySchema('node'); $this->installSchema('system', ['sequences']); $this->typedDataManager = $this->container->get('typed_data_manager'); $this->dataFetcher = $this->container->get('typed_data.data_fetcher'); $this->entityTypeManager = $this->container->get('entity_type.manager'); $this->entityTypeManager->getStorage('node_type') ->create(['type' => 'page']) ->save(); // Create a multi-value integer field for testing. FieldStorageConfig::create([ 'field_name' => 'field_integer', 'type' => 'integer', 'entity_type' => 'node', 'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED, ])->save(); FieldConfig::create([ 'field_name' => 'field_integer', 'entity_type' => 'node', 'bundle' => 'page', ])->save(); $this->node = $this->entityTypeManager->getStorage('node') ->create([ 'title' => 'test', 'type' => 'page', ]); } /** * @covers ::fetchDataByPropertyPath */ public function testFetchingByBasicPropertyPath() { $this->assertEquals( $this->node->title->value, $this->dataFetcher ->fetchDataByPropertyPath($this->node->getTypedData(), 'title.0.value') ->getValue() ); } /** * @covers ::fetchDataBySubPaths */ public function testFetchingByBasicSubPath() { $this->assertEquals( $this->node->title->value, $this->dataFetcher ->fetchDataBySubPaths( $this->node->getTypedData(), ['title', '0', 'value'] ) ->getValue() ); } /** * @covers ::fetchDataByPropertyPath */ public function testFetchingEntityReference() { $user = $this->entityTypeManager->getStorage('user') ->create([ 'name' => 'test', 'type' => 'user', ]); $this->node->uid->entity = $user; $fetched_user = $this->dataFetcher ->fetchDataByPropertyPath($this->node->getTypedData(), 'uid.entity') ->getValue(); $this->assertSame($fetched_user, $user); } /** * @covers ::fetchDataByPropertyPath */ public function testFetchingAcrossReferences() { $user = $this->entityTypeManager->getStorage('user') ->create([ 'name' => 'test', 'type' => 'user', ]); $this->node->uid->entity = $user; $fetched_value = $this->dataFetcher ->fetchDataByPropertyPath($this->node->getTypedData(), 'uid.entity.name.value') ->getValue(); $this->assertSame($fetched_value, 'test'); } /** * @covers ::fetchDataByPropertyPath */ public function testFetchingNonExistingEntityReference() { $fetched_user = $this->dataFetcher ->fetchDataByPropertyPath($this->node->getTypedData(), 'uid.0.entity') ->getValue(); $this->assertNull($fetched_user); } /** * @covers ::fetchDataByPropertyPath */ public function testFetchingValueAtValidPositions() { $this->node->field_integer->setValue(['0' => 1, '1' => 2]); $fetched_value = $this->dataFetcher ->fetchDataByPropertyPath($this->node->getTypedData(), 'field_integer.0.value') ->getValue(); $this->assertEquals($fetched_value, 1); $fetched_value = $this->dataFetcher ->fetchDataByPropertyPath($this->node->getTypedData(), 'field_integer.1.value') ->getValue(); $this->assertEquals($fetched_value, 2); } /** * @covers ::fetchDataByPropertyPath */ public function testFetchingValueAtInvalidPosition() { $this->setExpectedException(MissingDataException::class, "Unable to apply data selector 'field_integer.0.value' at 'field_integer.0'"); $this->node->field_integer->setValue([]); // This should trigger an exception. $this->dataFetcher ->fetchDataByPropertyPath($this->node->getTypedData(), 'field_integer.0.value') ->getValue(); } /** * @covers ::fetchDataByPropertyPath */ public function testFetchingInvalidProperty() { $this->setExpectedException(InvalidArgumentException::class, "Unable to apply data selector 'field_invalid.0.value' at 'field_invalid'"); // This should trigger an exception. $this->dataFetcher ->fetchDataByPropertyPath($this->node->getTypedData(), 'field_invalid.0.value') ->getValue(); } /** * @covers ::fetchDataByPropertyPath */ public function testFetchingEmptyProperty() { $this->node->field_integer->setValue([]); $fetched_value = $this->dataFetcher ->fetchDataByPropertyPath($this->node->getTypedData(), 'field_integer') ->getValue(); $this->assertEquals($fetched_value, []); } /** * @covers ::fetchDataByPropertyPath */ public function testFetchingNotExistingListItem() { $this->setExpectedException(MissingDataException::class); $this->node->field_integer->setValue([]); // This will throw an exception. $this->dataFetcher ->fetchDataByPropertyPath($this->node->getTypedData(), 'field_integer.0') ->getValue(); } /** * @covers ::fetchDataByPropertyPath */ public function testFetchingFromEmptyData() { $this->setExpectedException(MissingDataException::class, "Unable to apply data selector 'field_integer.0.value' at 'field_integer': Unable to get property field_integer as no entity has been provided."); $data_empty = $this->typedDataManager->create(EntityDataDefinition::create('node')); // This should trigger an exception. $this->dataFetcher ->fetchDataByPropertyPath($data_empty, 'field_integer.0.value') ->getValue(); } /** * @covers ::fetchDataByPropertyPath */ public function testBubbleableMetadata() { $this->node->field_integer->setValue([]); // Save the node, so that it gets an ID and it has a cache tag. $this->node->save(); // Also add a user for testing cache tags of references. $user = $this->entityTypeManager->getStorage('user') ->create([ 'name' => 'test', 'type' => 'user', ]); $user->save(); $this->node->uid->entity = $user; $bubbleable_metadata = new BubbleableMetadata(); $this->dataFetcher ->fetchDataByPropertyPath($this->node->getTypedData(), 'title.value', $bubbleable_metadata) ->getValue(); $expected = ['node:' . $this->node->id()]; $this->assertEquals($expected, $bubbleable_metadata->getCacheTags()); // Test cache tags of references are added correctly. $this->dataFetcher ->fetchDataByPropertyPath($this->node->getTypedData(), 'uid.entity.name', $bubbleable_metadata) ->getValue(); $expected = ['node:' . $this->node->id(), 'user:' . $user->id()]; $this->assertEquals($expected, $bubbleable_metadata->getCacheTags()); } }
marteenzh/d1
modules/typed_data/tests/src/Kernel/DataFetcherTest.php
PHP
gpl-2.0
8,146
/* Copyright (C) 2013 Lasath Fernando <kde@lasath.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef NOTIFYFILTER_H #define NOTIFYFILTER_H #include "chat-widget.h" #include <KTp/abstract-message-filter.h> class NotifyFilter : public KTp::AbstractMessageFilter { Q_OBJECT public: explicit NotifyFilter(ChatWidget *widget); public Q_SLOTS: void sendMessageNotification(const KTp::Message &message); private: ChatWidget *m_widget; }; #endif // NOTIFYFILTER_H
leonhandreke/ktp-text-ui
lib/notify-filter.h
C
gpl-2.0
1,198
<!doctype html> <html> <head> <title>Votación Live Tv y Novelas 2015</title> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" /> <script src="../socket.io/socket.io.js"></script> <script src="../resources/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="../style.css"> </head> <body> <div id="overlayLogo"><img src="../resources/TVyNovelasWeb.png"/></div> <div id="overlayConfirmacion"> <div id="confirmaVoto"> Por favor confirma tu voto a<br/><br/> <span id="nombreCandidatoVotado"></span><br/><br/><br/> <a href="javascript:void(0)"><div id="btnConfirma">confirmar</div></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:void(0)"><div id="btnCancela">cancelar</div></a> </div> </div> <div id="overlayBlockVoto"></div> <div id="contenedor" > <h1>Mejor Actor</h1> <div id="candidatos"> <a href="javascript:void(0)" valor="cc1j2" class="candidato" ><div class="cuadroCandidato"><div class="imgCandidato"><img src="../resources/imgs/cc1.jpg" width="220" height="220"></div>Sebastián Rulli<br/><i>Lo que la vida me robó</i>&nbsp;</div></a> <a href="javascript:void(0)" valor="cc2j2" class="candidato" ><div class="cuadroCandidato"><div class="imgCandidato"><img src="../resources/imgs/cc2.jpg" width="220" height="220"></div>Jorge Salinas<br/><i>Mi corazón es tuyo</i>&nbsp;</div></a> <a href="javascript:void(0)" valor="cc3j2" class="candidato" ><div class="cuadroCandidato"><div class="imgCandidato"><img src="../resources/imgs/cc3.jpg" width="220" height="220"></div>Erick Elías<br/><i>El color de la pasión</i>&nbsp;</div></a> <a href="javascript:void(0)" valor="cc4j2" class="candidato" ><div class="cuadroCandidato"><div class="imgCandidato"><img src="../resources/imgs/cc4.jpg" width="220" height="220"></div>Gabriel Soto<br/><i>Yo no creo en los hombres</i>&nbsp;</div></a> <a href="javascript:void(0)" valor="cc5j2" class="candidato" ><div class="cuadroCandidato"><div class="imgCandidato"><img src="../resources/imgs/cc5.jpg" width="220" height="220"></div>Daniel Arenas<br/><i>La Gata</i>&nbsp;</div></a> </div><!-- candidatos --> </div><!-- contenedor --> <script> var socket = io(); var mensaje; $( "#candidatos" ).on( 'click', '.candidato', function(){ var valorImagen = $( this ).attr( 'valor' ); var idImagen = valorImagen.split( 'j' ); var mensajeLargo = $( this ).children( ".cuadroCandidato" ).html(); var nombreCandidato = mensajeLargo.replace( "<div class=\"imgCandidato\"><img src=\"../resources/imgs/" + idImagen[ 0 ] + ".jpg\" width=\"220\" height=\"220\"></div>" , ""); $( "#nombreCandidatoVotado" ).html( nombreCandidato ); $( "#overlayConfirmacion" ).fadeToggle( "slow" ); mensaje = $( this ).attr( "valor"); }); $( "#btnConfirma" ).on( 'click', function(){ socket.emit( "votoDesdeJurado", mensaje ); $("*[valor='" + mensaje + "']").children( ".cuadroCandidato" ).children( ".imgCandidato" ).append( "<div id='palomita' style='position:absolute;margin-top:-190px'><img src='../resources/paloma.png'/></div>" ); $( "#overlayConfirmacion" ).fadeToggle( "slow" ); //$( "#candidatos" ).children().click( false ); $( "#overlayBlockVoto" ).show(); return false; }); $( "#btnCancela" ).on( 'click', function(){ $( "#overlayConfirmacion" ).fadeToggle( "slow" ); }); socket.on( "ordenaSegundaVotacion", function( msg ){ $( "#candidatos" ).html( "" ); for( var i = 0; i < ( msg.length / 2 ); i++ ){ var soloNombre = msg[ i ].split( "&nbsp;" ); $( "#candidatos" ).append( "<a href='javascript:void(0)' valor='cc" + msg[ i + ( msg.length / 2 ) ] + "j2' class='candidato' ><div class='cuadroCandidato'><div class='imgCandidato'><img src='../resources/imgs/cc" + msg[ i + ( msg.length / 2 ) ] + ".jpg' width='220' height='220'></div>" + soloNombre[ 0 ] + "</div></a> " ); } //$( "#candidatos" ).children().click( true ); $( "#overlayBlockVoto" ).hide(); realinea(); }); socket.on( "activaOverlayLogoVotante", function( msg ){ if( msg == 1 ){ $( "#overlayLogo" ).fadeIn( "slow" ); } }); socket.on( "desactivaOverlayLogoVotante", function( msg ){ if( msg == 1 ){ $( "#overlayLogo" ).fadeOut( "slow" ); } }); /*socket.on( "siguienteSeccionVotante", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_d.html"; } });*/ //---------------------------------------cues de teclas para llevar a secciones socket.on( "jveaA", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_a.html"; } }); socket.on( "jveaB", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_b.html"; } }); socket.on( "jveaC", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_c.html"; } }); socket.on( "jveaD", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_d.html"; } }); socket.on( "jveaE", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_e.html"; } }); socket.on( "jveaF", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_f.html"; } }); socket.on( "jveaG", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_g.html"; } }); socket.on( "jveaH", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_h.html"; } }); socket.on( "jveaI", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_i.html"; } }); socket.on( "jveaK", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_k.html"; } }); socket.on( "jveaL", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_l.html"; } }); socket.on( "jveaM", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_m.html"; } }); socket.on( "jveaN", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_n.html"; } }); socket.on( "jveaO", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_o.html"; } }); socket.on( "jveaP", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_p.html"; } }); socket.on( "jveaQ", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_q.html"; } }); socket.on( "jveaR", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_r.html"; } }); socket.on( "jveaS", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_s.html"; } }); socket.on( "jveaT", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_t.html"; } }); socket.on( "jveaU", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_u.html"; } }); socket.on( "jveaV", function( msg ){ if( msg == 1 ){ window.location.href = "categoria_v.html"; } }); //---------------------------------------cues de teclas para llevar a secciones socket.on( "recibeRefresh", function( msg ){ if( msg == 1 ){ location.reload(); } }); function realinea(){ var numChildCandidatos = $( "#candidatos" ).children().length; if( numChildCandidatos == 6 ){ $( "#candidatos a:nth-child( 5 )" ).children( ".cuadroCandidato" ).css( "margin-left", "220px" ); } if( numChildCandidatos == 5 ){ $( "#candidatos a:nth-child( 5 )" ).children( ".cuadroCandidato" ).css( "margin-left", "320px" ); } if( numChildCandidatos == 3 ){ $( "#candidatos a:nth-child( 1 )" ).children( ".cuadroCandidato" ).css( "margin-left", "120px" ); } if( numChildCandidatos == 2 ){ $( "#candidatos a:nth-child( 1 )" ).children( ".cuadroCandidato" ).css( "margin-left", "220px" ); } } realinea(); </script> </body> </html>
alfredoBorboa/tvynovelas-live
public/jurado2/categoria_c.html
HTML
gpl-2.0
8,557
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>schrodinger.pipeline.pipeio.Grid</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="schrodinger-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" >Suite 2012 Schrodinger Python API</th> </tr></table></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="schrodinger-module.html">Package&nbsp;schrodinger</a> :: <a href="schrodinger.pipeline-module.html">Package&nbsp;pipeline</a> :: <a href="schrodinger.pipeline.pipeio-module.html">Module&nbsp;pipeio</a> :: Class&nbsp;Grid </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="schrodinger.pipeline.pipeio.Grid-class.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <!-- ==================== CLASS DESCRIPTION ==================== --> <h1 class="epydoc">Class Grid</h1><p class="nomargin-top"></p> <pre class="base-tree"> <a href="schrodinger.pipeline.pipeio.PipeIO-class.html">PipeIO</a> --+ | <strong class="uidshort">Grid</strong> </pre> <hr /> <p>A class to hold a set of grid files (compressed or uncompressed).</p> <!-- ==================== INSTANCE METHODS ==================== --> <a name="section-InstanceMethods"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Instance Methods</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-InstanceMethods" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.pipeline.pipeio.Grid-class.html#__init__" class="summary-sig-name">__init__</a>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">gridfile</span>=<span class="summary-sig-default">None</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.pipeline.pipeio.Grid-class.html#check" class="summary-sig-name">check</a>(<span class="summary-sig-arg">self</span>)</span><br /> Check that the grid file exists.</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="getPath"></a><span class="summary-sig-name">getPath</span>(<span class="summary-sig-arg">self</span>)</span><br /> Return the grid file name.</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.pipeline.pipeio.Grid-class.html#getData" class="summary-sig-name">getData</a>(<span class="summary-sig-arg">self</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="__str__"></a><span class="summary-sig-name">__str__</span>(<span class="summary-sig-arg">self</span>)</span><br /> Return a string representation of the object.</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.pipeline.pipeio.Grid-class.html#setData" class="summary-sig-name">setData</a>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">gridfile</span>)</span><br /> Replace the grid file name.</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.pipeline.pipeio.Grid-class.html#addData" class="summary-sig-name">addData</a>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">gridfile</span>)</span><br /> Set the grid file name, but only if it hadn't already been set.</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.pipeline.pipeio.Grid-class.html#getFiles" class="summary-sig-name">getFiles</a>(<span class="summary-sig-arg">self</span>)</span><br /> Return a list of grid file names, expanded from the representative file name, after checking for their existence.</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.pipeline.pipeio.Grid-class.html#isFilled" class="summary-sig-name">isFilled</a>(<span class="summary-sig-arg">self</span>)</span><br /> Check whether the object is used or empty.</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.pipeline.pipeio.PipeIO-class.html">PipeIO</a></code></b>: <code><a href="schrodinger.pipeline.pipeio.PipeIO-class.html#getCount">getCount</a></code> </p> </td> </tr> </table> <!-- ==================== METHOD DETAILS ==================== --> <a name="section-MethodDetails"></a> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Method Details</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-MethodDetails" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> </table> <a name="__init__"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">__init__</span>(<span class="sig-arg">self</span>, <span class="sig-arg">gridfile</span>=<span class="sig-default">None</span>)</span> <br /><em class="fname">(Constructor)</em> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <dl class="fields"> <dt>Parameters:</dt> <dd><ul class="nomargin-top"> <li><strong class="pname"><code>gridfile</code></strong> (str) - The name of the grid file (for example, <code>&lt;gridjobname&gt;.grd</code> or <code>&lt;gridjobname&gt;.zip</code>). The value can be changed later with <a href="schrodinger.pipeline.pipeio.Grid-class.html#setData" class="link">setData</a>.</li> </ul></dd> </dl> </td></tr></table> </div> <a name="check"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">check</span>(<span class="sig-arg">self</span>)</span> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>Check that the grid file exists.</p> <dl class="fields"> <dt>Raises:</dt> <dd><ul class="nomargin-top"> <li><code><strong class='fraise'>RuntimeError</strong></code> - Raised if the file is missing.</li> </ul></dd> <dt>Overrides: <a href="schrodinger.pipeline.pipeio.PipeIO-class.html#check">PipeIO.check</a> </dt> </dl> </td></tr></table> </div> <a name="getData"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">getData</span>(<span class="sig-arg">self</span>)</span> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <dl class="fields"> </dl> <div class="fields"> <p><strong>Deprecated:</strong> Use <a href="schrodinger.pipeline.pipeio.Grid-class.html#getFiles" class="link">getFiles</a> instead. </p> </div></td></tr></table> </div> <a name="setData"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">setData</span>(<span class="sig-arg">self</span>, <span class="sig-arg">gridfile</span>)</span> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>Replace the grid file name.</p> <dl class="fields"> <dt>Parameters:</dt> <dd><ul class="nomargin-top"> <li><strong class="pname"><code>gridfile</code></strong> (str) - The replacement grid file name.</li> </ul></dd> </dl> </td></tr></table> </div> <a name="addData"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">addData</span>(<span class="sig-arg">self</span>, <span class="sig-arg">gridfile</span>)</span> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>Set the grid file name, but only if it hadn't already been set.</p> <dl class="fields"> <dt>Raises:</dt> <dd><ul class="nomargin-top"> <li><code><strong class='fraise'>RuntimeError</strong></code> - Raised if the grid file name is already set.</li> </ul></dd> </dl> <div class="fields"> <p><strong>Deprecated:</strong> Set all ligand files in input or via <a href="schrodinger.pipeline.pipeio.Grid-class.html#setData" class="link">setData</a>. </p> </div></td></tr></table> </div> <a name="getFiles"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">getFiles</span>(<span class="sig-arg">self</span>)</span> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>Return a list of grid file names, expanded from the representative file name, after checking for their existence.</p> <p>For compressed grids, the <code>.zip</code> file is the only item returned, but for uncompressed grids, all the standard grid component file names are returned.</p> <dl class="fields"> <dt>Overrides: <a href="schrodinger.pipeline.pipeio.PipeIO-class.html#getFiles">PipeIO.getFiles</a> </dt> </dl> </td></tr></table> </div> <a name="isFilled"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">isFilled</span>(<span class="sig-arg">self</span>)</span> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>Check whether the object is used or empty.</p> <p>This method must be implemented in subclasses.</p> <dl class="fields"> <dt>Overrides: <a href="schrodinger.pipeline.pipeio.PipeIO-class.html#isFilled">PipeIO.isFilled</a> <dd><em class="note">(inherited documentation)</em></dd> </dt> </dl> </td></tr></table> </div> <br /> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="schrodinger-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" >Suite 2012 Schrodinger Python API</th> </tr></table></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Tue Sep 25 02:23:05 2012 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
platinhom/ManualHom
Schrodinger/Schrodinger_2012_docs/python_api/api/schrodinger.pipeline.pipeio.Grid-class.html
HTML
gpl-2.0
17,898
<?php /** * @package HikaShop for Joomla! * @version 2.6.3 * @author hikashop.com * @copyright (C) 2010-2016 HIKARI SOFTWARE. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ defined('_JEXEC') or die('Restricted access'); ?><?php class hikashopCharsetType{ function __construct(){ $charsets = array( 'BIG5'=>'BIG5',//Iconv,mbstring 'ISO-8859-1'=>'ISO-8859-1',//Iconv,mbstring 'ISO-8859-2'=>'ISO-8859-2',//Iconv,mbstring 'ISO-8859-3'=>'ISO-8859-3',//Iconv,mbstring 'ISO-8859-4'=>'ISO-8859-4',//Iconv,mbstring 'ISO-8859-5'=>'ISO-8859-5',//Iconv,mbstring 'ISO-8859-6'=>'ISO-8859-6',//Iconv,mbstring 'ISO-8859-7'=>'ISO-8859-7',//Iconv,mbstring 'ISO-8859-8'=>'ISO-8859-8',//Iconv,mbstring 'ISO-8859-9'=>'ISO-8859-9',//Iconv,mbstring 'ISO-8859-10'=>'ISO-8859-10',//Iconv,mbstring 'ISO-8859-13'=>'ISO-8859-13',//Iconv,mbstring 'ISO-8859-14'=>'ISO-8859-14',//Iconv,mbstring 'ISO-8859-15'=>'ISO-8859-15',//Iconv,mbstring 'ISO-2022-JP'=>'ISO-2022-JP',//mbstring for sure... not sure about Iconv 'US-ASCII'=>'US-ASCII', //Iconv,mbstring 'UTF-7'=>'UTF-7',//Iconv,mbstring 'UTF-8'=>'UTF-8',//Iconv,mbstring 'Windows-1250'=>'Windows-1250', //Iconv,mbstring 'Windows-1251'=>'Windows-1251', //Iconv,mbstring 'Windows-1252'=>'Windows-1252' //Iconv,mbstring ); if(function_exists('iconv')){ $charsets['ARMSCII-8'] = 'ARMSCII-8'; $charsets['ISO-8859-16'] = 'ISO-8859-16'; } $this->values = array(); foreach($charsets as $code => $charset){ $this->values[] = JHTML::_('select.option', $code,$charset); } } function display($map,$value){ return JHTML::_('select.genericlist', $this->values, $map , 'size="1"', 'value', 'text', $value); } }
IYEO/Sweettaste
administrator/components/com_hikashop/types/charset.php
PHP
gpl-2.0
1,849
# OptimizePress Optimizely fix ##Description Removes optimizely_enqueue_scripts action from LiveEditor pages ##Installation 1. Click Download ZIP button on the right 2. Install plugin archive through WordPress' Add plugin screen 3. Activate the plugin ##Requirements * Requires at least: 3.5 * Stable tag: 1.0 * License: GPLv2 or later * License URI: [http://www.gnu.org/licenses/gpl-2.0.html](http://www.gnu.org/licenses/gpl-2.0.html) ##Changelog ####1.0 * Initial release
OptimizePress/op-optimizely-fix
README.md
Markdown
gpl-2.0
481
import AppBar from './app-bar'; import AutoComplete from './text-fields/auto-complete'; import Avatar from './avatar'; import BottomSheet from './bottom-sheet'; import Chip from './chip'; import DialogAlert from './dialog/alert'; import DialogFullScreen from './dialog/full-screen'; import FontIcon from './font-icon'; import IconButton from './buttons/icon-button'; import FlatButton from './buttons/flat-button'; import FloatingActionButton from './buttons/floating-action-button'; import MenuItem from './menu/item'; import MenuDropDown from './menu/drop-down'; import RaisedButton from './buttons/raised-button'; import Card from './card'; import CardHeader from './card/card-header'; import Header from './header'; import List from './list/index'; import ListItem from './list/item'; import Tabs from './tabs/index'; import Tab from './tabs/tab'; import Paper from './paper'; import PickerDate from './picker/date'; import RichMedia from './rich-media'; import SearchFilter from './text-fields/search-filter'; import Snackbar from './snackbar'; import Stepper from './stepper'; import StepperStep from './stepper/step'; import ProgressLinear from './progress/linear'; import InputText from './form/input-text'; import InputSelect from './form/input-select'; import InputArea from './form/input-area'; import InputControl from './form/input-control'; import SelectionControl from './form/selection-control'; import getClasses, { getClassesStatic } from './addons/get-classes'; import hasTouchEvents from './addons/has-touch-events'; import touchPoint from './addons/touch-point'; export { AppBar, AutoComplete, Avatar, BottomSheet, DialogAlert, DialogFullScreen, FontIcon, getClasses, getClassesStatic, hasTouchEvents, IconButton, FlatButton, FloatingActionButton, MenuItem, MenuDropDown, RaisedButton, Card, CardHeader, Chip, Header, List, ListItem, Tab, Tabs, InputControl, InputText, InputSelect, InputArea, SelectionControl, Paper, PickerDate, RichMedia, SearchFilter, Snackbar, Stepper, StepperStep, ProgressLinear, touchPoint };
joxoo/react-material
src/index.js
JavaScript
gpl-2.0
2,193
<?php namespace Rasty\app; use Rasty\cache\RastyCache; /** * Colabora con el mapeo de los componentes. * * @author bernardo * @since 02-03-2010 * */ class RastyMapHelper{ private static $instance; //array con el mapeo de los componentes. private $components_map = array(); //( [component_name] = array( location_of_descriptor, app_path, web_path) ) //array con el mapeo de las pages. private $pages_map = array(); // ( [page] = array(location_of_descriptor, url, app_path, web_path) ) //array con el mapeo de las actions. private $actions_map = array(); // ( [action] = array(url, name, class) ) //M�todo constructor public function __construct(){ $composite = LoadRasty::getInstance(); foreach ($composite->getComponents() as $component) { $this->setComponent($component['name'], $component['location'], $component['app_path'], $component['web_path']); } foreach ($composite->getPages() as $page) { $this->setPage($page['name'], $page['location'], $page['url'], $page['app_path'], $page['web_path']); } foreach ($composite->getActions() as $action) { $this->setAction($action['name'], $action['class'], $action['url']); } } public static function getInstance(){ if ( !self::$instance instanceof self ) { $cache = RastyCache::getInstance(); if($cache->contains("RastyMapHelper") ) self::$instance = $cache->fetch("RastyMapHelper"); else{ self::$instance = new self; $cache->save("RastyMapHelper", self::$instance ); } } return self::$instance; } function getComponent($name) { if( array_key_exists($name, $this->components_map) ) return $this->components_map[$name]; echo " no está!! ( $name )"; } /* function getPage($name) { return $this->pages_map[$name]; }*/ function getPage($url) { //var_dump($this->pages_map); return $this->pages_map[$url]; } function getPageByName($name) { foreach ($this->pages_map as $value) { $current = $value["name"]; if( $current == $name ) return $value; } } function getAction($url) { //var_dump($this->pages_map); return $this->actions_map[$url]; } function setComponent($name,$location, $app_path, $web_path){ $this->components_map[$name]= array( "location"=>$location, "app_path" => $app_path, "web_path" => $web_path ); } function setPage($name,$location,$url, $app_path, $web_path){ //$this->pages_map[$name]=array(location=>$location, url=>$url); $this->pages_map[$url]=array("name"=>$name, "location"=>$location, "app_path" => $app_path, "web_path" => $web_path ); } function setAction($name,$class,$url){ //$this->pages_map[$name]=array(location=>$location, url=>$url); $this->actions_map[$url]=array("name"=>$name, "class"=>$class ); } function getComponentDescriptor( $type ){ $component = $this->getComponent( $type ); //$component_descriptor = APP_PATH . $component_location . "/$type.rasty"; $component_descriptor = $component['app_path']. $component['location'] . "/$type.rasty"; return $component_descriptor; } function getComponentTemplatePath( $type ){ $component = $this->getComponent( $type ); //$component_template = APP_PATH . $component_location ; $component_template = $component['app_path']. $component['location'] ; return $component_template; } function getComponentWebPath( $type ){ $component = $this->getComponent( $type ); $component_web_path = $component['web_path']. $component['location'] ; return $component_web_path; } function getPageAppPath( $type ){ $page = $this->getPageByName( $type ); //$component_template = APP_PATH . $component_location ; $page_app_path = $page['app_path'] ; return $page_app_path; } function getPageUrl($name) { foreach ($this->pages_map as $url => $value) { $current = $value["name"]; if( $current == $name ) return $url; } } function getActionUrl($name) { foreach ($this->actions_map as $url => $value) { $current = $value["name"]; if( $current == $name ) return $url; } } }
iriber/phprasty
src/main/php/Rasty/app/RastyMapHelper.php
PHP
gpl-2.0
4,241
/* Copyright (c) 2013, 2014 Montel Laurent <montel@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SENDLATERJOB_H #define SENDLATERJOB_H #include <QObject> #include "sendlatermanager.h" #include <KMime/Message> #include <Akonadi/ItemFetchScope> #include <Akonadi/Item> namespace SendLater { class SendLaterInfo; } class KJob; class SendLaterJob : public QObject { Q_OBJECT public: explicit SendLaterJob(SendLaterManager *manager, SendLater::SendLaterInfo *info, QObject *parent = 0); ~SendLaterJob(); void start(); private Q_SLOTS: void sendDone(); void sendError(const QString &error, SendLaterManager::ErrorType type); void slotMessageTransfered(const Akonadi::Item::List& ); void slotJobFinished(KJob*); void slotDeleteItem(KJob*); private: void updateAndCleanMessageBeforeSending(const KMime::Message::Ptr &msg); Akonadi::ItemFetchScope mFetchScope; SendLaterManager *mManager; SendLater::SendLaterInfo *mInfo; Akonadi::Item mItem; }; #endif // SENDLATERJOB_H
kolab-groupware/kdepim
agents/sendlateragent/sendlaterjob.h
C
gpl-2.0
1,644
### Results of 2 Hour Vehicle Survey - Diggle 19/2/2019 16:30 445 - For First Hour of Survey Average Vehicles Per Hour Survey The charts show a continuing average based on the 1st hour count, for an extra 44mins. There were 6 occasions of about 1000 vehicles per hour, 10 cases where traffic was over 700 in the first hour. The road was observably congested, as can be seen from the chart, large increase in traffic is due to batch queuing. This case was novel in that congestio continued over 2 blocks of 10 cars on 2 occasions The average after the 1hour count survey was completed shows continuing sever levels of traffic. It can be seen where small increases in traffic causes bunching. #### Vehicles per hour against time measured ![Vehicles /hour - Oldham 19.2.2019](https://raw.githubusercontent.com/wrapperband/OpenTrafficSurvey/master/CaseStudies/2019-02-19%20-%20Oldham%20Test%20Site2HrSurvey/Images/2019-2-19-vph-01.png) #### Vehicles per hour for each 10 car sample ![Vehicles /hour - Oldham 18.2.2019](https://raw.githubusercontent.com/wrapperband/OpenTrafficSurvey/master/CaseStudies/2019-02-19%20-%20Oldham%20Test%20Site2HrSurvey/Images/2019-2-19-vph-02.png)
wrapperband/OpenTrafficSurvey
CaseStudies/2019-02-19 - Oldham Test Site2HrSurvey/README.md
Markdown
gpl-2.0
1,202
--- layout: default title: (unrecognied function)(FIXME!) --- [Top](../index.html) --- ### 定義場所(file name) hotspot/src/cpu/x86/vm/templateTable_x86_64.cpp ### 名前(function name) ``` void TemplateTable::anewarray() { ``` ### 本体部(body) ``` {- ------------------------------------------- (1) InterpreterRuntime::anewarray() を呼び出すだけ. ---------------------------------------- -} transition(itos, atos); __ get_unsigned_2_byte_index_at_bcp(c_rarg2, 1); __ get_constant_pool(c_rarg1); __ movl(c_rarg3, rax); call_VM(rax, CAST_FROM_FN_PTR(address, InterpreterRuntime::anewarray), c_rarg1, c_rarg2, c_rarg3); } ```
hsmemo/hsmemo.github.com
articles/no28916r7x.md
Markdown
gpl-2.0
683
<?php /* core/themes/classy/templates/views/views-exposed-form.html.twig */ class __TwigTemplate_5fc5d24b391a167116517fc031d87374232681461f0e8ded9bd1aef1601521b2 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { $tags = array("if" => 12); $filters = array(); $functions = array(); try { $this->env->getExtension('sandbox')->checkSecurity( array('if'), array(), array() ); } catch (Twig_Sandbox_SecurityError $e) { $e->setTemplateFile($this->getTemplateName()); if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } // line 12 if ( !twig_test_empty((isset($context["q"]) ? $context["q"] : null))) { // line 13 echo " "; // line 17 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["q"]) ? $context["q"] : null), "html", null, true)); echo " "; } // line 19 echo "<div class=\"form--inline clearfix\"> "; // line 20 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["form"]) ? $context["form"] : null), "html", null, true)); echo " </div> "; } public function getTemplateName() { return "core/themes/classy/templates/views/views-exposed-form.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 55 => 20, 52 => 19, 47 => 17, 45 => 13, 43 => 12,); } } /* {#*/ /* /***/ /* * @file*/ /* * Theme override for a views exposed form.*/ /* **/ /* * Available variables:*/ /* * - form: A render element representing the form.*/ /* **/ /* * @see template_preprocess_views_exposed_form()*/ /* *//* */ /* #}*/ /* {% if q is not empty %}*/ /* {#*/ /* This ensures that, if clean URLs are off, the 'q' is added first,*/ /* as a hidden form element, so that it shows up first in the POST URL.*/ /* #}*/ /* {{ q }}*/ /* {% endif %}*/ /* <div class="form--inline clearfix">*/ /* {{ form }}*/ /* </div>*/ /* */
panchaldhruv29/rc_dev
sites/default/files/php/twig/57d84834_views-exposed-form.html.twig_06b040b09f94a9393d5cc270d7f689da539203d5eefd94819e931d63f119de35/0ec3f452699ad49fcab38710434c3be77c5c8d9e1f04061c841bd24652cc0d81.php
PHP
gpl-2.0
3,073
import java.awt.*; import java.awt.event.*; import static java.lang.Math.*; import javax.swing.*; /** * Java. Cube 3D * based on https://rosettacode.org/wiki/Draw_a_cuboid#Java * and http://compgraphics.info/3D/3d_affine_transformations.php * * @author Sergey Iryupin * @version 0.0.3 dated Dec 28, 2018 */ public class Cuboid extends JPanel { final int RD = 10; double[][] nodes = {{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1}, {1, -1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1}}; int[][] edges = {{0, 1}, {1, 3}, {3, 2}, {2, 0}, {4, 5}, {5, 7}, {7, 6}, {6, 4}, {0, 4}, {1, 5}, {2, 6}, {3, 7}}; int mouseX, prevMouseX, mouseY, prevMouseY; public Cuboid() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.black); scale(100, 100, 100); //80, 120, 160); rotateCube(PI / 5, PI / 9); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); } }); addMouseMotionListener(new MouseAdapter() { @Override public void mouseDragged(MouseEvent e) { prevMouseX = mouseX; prevMouseY = mouseY; mouseX = e.getX(); mouseY = e.getY(); double incrX = (mouseX - prevMouseX) * 0.01; double incrY = (mouseY - prevMouseY) * 0.01; rotateCube(incrX, incrY); repaint(); } }); } private void scale(double sx, double sy, double sz) { for (double[] node : nodes) { node[0] *= sx; node[1] *= sy; node[2] *= sz; } } private void rotateCube(double angleX, double angleY) { double sinX = sin(angleX); double cosX = cos(angleX); double sinY = sin(angleY); double cosY = cos(angleY); for (double[] node : nodes) { double x = node[0]; double y = node[1]; double z = node[2]; node[0] = x * cosX - z * sinX; node[2] = z * cosX + x * sinX; z = node[2]; node[1] = y * cosY - z * sinY; node[2] = z * cosY + y * sinY; } } void drawCube(Graphics2D g) { g.translate(getWidth() / 2, getHeight() / 2); //g.setStroke(new BasicStroke(2)); g.setColor(Color.white); for (int[] edge : edges) { double[] xy1 = nodes[edge[0]]; double[] xy2 = nodes[edge[1]]; g.drawLine((int) round(xy1[0]), (int) round(xy1[1]), (int) round(xy2[0]), (int) round(xy2[1])); } for (double[] node : nodes) g.fillOval((int) round(node[0]) - RD/2, (int) round(node[1]) - RD/2, RD, RD); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawCube(g); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Cuboid"); f.setResizable(false); f.add(new Cuboid(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
biblelamp/JavaExercises
Experiments/Cuboid.java
Java
gpl-2.0
3,618
//#include "opencv2/core.hpp" #include <opencv2/opencv.hpp> #include "opencv2/imgproc.hpp" #include "opencv2/core/ocl.hpp" #include <stdio.h> #include <iostream> using namespace cv; using namespace std; int main(int, char**) { cv::VideoCapture vcap, vcap2; cv::Mat image, image2; // This works on a TrendNet TV-IP422WN //const std::string videoStreamAddress = "http://admin:admin@192.168.69.52/cgi/mjpg/mjpg.cgi"; //const std::string videoStreamAddress = "http://admin:admin@192.168.69.52/cgi/mjpg/mjpg.cgi?bogus=foo.mjpg"; const std::string videoStreamAddress = "http://admin:admin@192.168.69.52/cgi/jpg/image.cgi?bogus=foo.jpg"; //const std::string videoStreamAddress = "rtsp://admin:admin@192.168.69.52:554/mpeg4"; //const std::string videoStreamAddress = "rtsp://admin:admin@192.168.69.52:554/3gp"; //open the video stream and make sure it's opened if(!vcap.open(videoStreamAddress)) { std::cout << "Error opening video stream1 or file" << std::endl; return -1; } if(!vcap2.open(videoStreamAddress)) { std::cout << "Error opening video stream2 or file" << std::endl; return -1; } for(;;) { //if(!vcap.read(image)) { //image = imread(videoStreamAddress, 1); vcap >> image; // std::cout << "No frame from vcap" << std::endl; // cv::waitKey(); //} //if(!vcap2.read(image2)) { //image2 = imread(videoStreamAddress, 1); vcap2 >> image2; // std::cout << "No frame from vcap2" << std::endl; // cv::waitKey(); //} cv::Mat image_copy = image.clone(); cv::Mat image2_copy = image2.clone(); cv::Mat gray, gray2; // Convert the current frame to grayscale: cv::cvtColor(image_copy, gray, COLOR_BGR2GRAY); cv::cvtColor(image2_copy, gray2, COLOR_BGR2GRAY); // We need to equalize the histo to reduce the impact of lighting cv::equalizeHist(gray,gray); cv::equalizeHist(gray2,gray2); cv::imshow("Output Window1", gray); cv::imshow("Output Window2", gray2); if(cv::waitKey(1) >= 0) break; } }
rudybrian/CV_Playground
streamtest-multi-cam/streamtest-multi-cam.cpp
C++
gpl-2.0
2,064
<!DOCTYPE html> <html> <head> <meta name="eecription" content="Ejemplo d HTML"/> <meta name="keywors" content="HTML%;CSS3;JavaScript/> <title>Fomulario</title> </head> <body> <div> <form action="datos.html" method="post"> <fieldset> <legend>Contacto</legend> <label for="txtNombre">Laboral</label><br/> <label for="txtNombre">Emplado</label> <br/> <br/> <label for="txtNombre">codigo</label></br> <input type="password" size="40" maxlength="255" id="txtcodigo" name="codigo" /> <br/> <br/> <label for="txtFechaI">Fecha de Ingreso</label> <input type="text" size="40" maxlength="255" id="txtFechaI" name="FechaI" /> <br/> <br/> <label for="txtnumero">Numero</label> <input type="text" size="40" maxlength="255" id="txtFechaI" name="numero" /> <br/> <br/> <label for="txtSeguridad">Seguridad Social</label></br> <input type="password"size"40" maxlength="255" id="textSeguro" name="Segurdiad" /> <br/> <br/> </fieldset> <fieldset> <legend>Personal</legend> <label for="txtCorreo">Nombre</label><br/> <input type="text" size="40" maxlength="255" id="txtNombre" name="Nombre" /> <br/> <br/> <label for="ApellidoP">Apellido Paterno</label> <input type="text" size="40" maxlength="255" id="txtPaterno" name="paternoP" /> <br/> <br/> <label for="Foto">Foto de Perfil</label><br/> <img src="CNBlue.gif" width="135" height="135"></br> <label for="txtApellidoM">Apellido Materno</label><br/> <input type="text" size="40" maxlength="255" id="txtApellidoM" name="ApellidoM" /> <br/> <br/> <label for="txtSexo"> Sexo</label><br/> <input type="radio" id="pro1" name="sexo" value="1"/> <label for="hombre"> Hombre </label><br/> <input type="radio" id="pro2" name="sexo" value="2"> <label for="mujer"> Mujer </label><br/> <label for="txtEstado Civil">Estado Civil</label><br/> <select> <option value="Casada">Casad@</option> <option value="Soltera">Solter@</option> <option value="Divorciada">Divorciad@</option> <option value="Viudo">Viud@</option> </select> </fieldset> <fieldset> <legend>Nacimiento</legend> <label for="txtFecha">Fecha</label><br/> <input type="text"size="40" maxlength="225" id="txtFecha" name="Fecha"/> <br/> <br/> <label for="txtPais">Pais</label><br/> <select> <option value="Mexico">Mexico</option> <option value="Corea">Corea</option> <option value="Japon">Japon</option> <option value="EUA">EUA</option> <option value="Canada">Canada</option> </select> </fieldset> <fieldset> <legend>Contacto</legend> <label for="Titulo">Titulo</label><br/> <input type="text" size="40" maxlength="255" id="txttitulo" name="Titulo" /> <br/> <br/> <label for="Curp">Curp</label> <input type="text" size="40" maxlength="255" id="txtCurp" name="Curp" /> <br/> <br/> <label for="RFC">RFC</label> <input type="text" size="40" maxlength="255" id="txtRFC" name="RFC" /> <br/> <br/> <label for="Telefono">Telefono</label><br/> <input type="text" size="40" maxlength="255" id="txtTelefono" name="Telefono" /> <br/> <br/> <label for="Celular">Celular</label><br/> <input type="text" size="40" maxlength="255" id="txtCelular" name="Celular" /> <br/> <br/> <label for="Domicilio">Domicilio</label><br/> <input type="text" size="40" maxlength="255" id="txtDomicilio" name="Domicilio" /> <br/> <br/> <label for="Colonia">Colonia</label><br/> <input type="text" size="40" maxlength="255" id="txtColonia" name="Colonia" /> <br/> <br/> <label for="codigoP">Codigo Postal</label><br/> <input type="text" size="40" maxlength="255" id="txtcodigoP" name="codigoP" /> <br/> <br/> <label for="txtPais">Pais</label><br/> <select> <option value="Mexico">Mexico</option> <option value="Corea">Corea</option> <option value="Japon">Japon</option> <option value="EUA">EUA</option> <option value="Canada">Canada</option> </select> <br/> <br/> <label for="Radio">Radio</label><br/> <input type="text" size="40" maxlength="255" id="txtRadio" name="Radio" /> <br/> <br/> <label for="correo">Correo Electronico</label><br/> <input type="text" size="40" maxlength="255" id="txtcorreo" name="correo" /> <br/> <br/> <label for="Observaciones">Observaciones</label></br> <textarea name="Obrvaciones" cools"40" rows="10">Escribe mensaje</textarea> <br/> <br/> </fieldset> <input type="submit" name="Cancelar" value="Cancelar"/> <input type="submit" name="Agregar" value="Agregar"/> </form> </div> </body> </html>
AraceliRey/Programacion4_practica_2
Practica2.html
HTML
gpl-2.0
4,373
//*********************************************************** // Copyright © 2003-2008 Alexander S. Kiselev, Valentin Pavlyuchenko // // This file is part of Boltun. // // Boltun 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. // // Boltun 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 Boltun. If not, see <http://www.gnu.org/licenses/>. // //*********************************************************** #ifndef ACTIONQUEUE_H #define ACTIONQUEUE_H void AnswerToContact(MCONTACT hContact, const wchar_t* messageToAnswer); void StartChatting(MCONTACT hContact); #endif /* ACTIONQUEUE_H */
miranda-ng/miranda-ng
plugins/Boltun/src/actionQueue.h
C
gpl-2.0
1,104
/* * Copyright (C) 2007 Marco Gerards <marco@gnu.org> * Copyright (C) 2009 David Conrad * Copyright (C) 2011 Jordi Ortiz * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Dirac Decoder * @author Marco Gerards <marco@gnu.org>, David Conrad, Jordi Ortiz <nenjordi@gmail.com> */ #include "avcodec.h" #include "dsputil.h" #include "get_bits.h" #include "bytestream.h" #include "golomb.h" #include "dirac_arith.h" #include "mpeg12data.h" #include "dwt.h" #include "dirac.h" #include "diracdsp.h" /** * The spec limits the number of wavelet decompositions to 4 for both * level 1 (VC-2) and 128 (long-gop default). * 5 decompositions is the maximum before >16-bit buffers are needed. * Schroedinger allows this for DD 9,7 and 13,7 wavelets only, limiting * the others to 4 decompositions (or 3 for the fidelity filter). * * We use this instead of MAX_DECOMPOSITIONS to save some memory. */ #define MAX_DWT_LEVELS 5 /** * The spec limits this to 3 for frame coding, but in practice can be as high as 6 */ #define MAX_REFERENCE_FRAMES 8 #define MAX_DELAY 5 /* limit for main profile for frame coding (TODO: field coding) */ #define MAX_FRAMES (MAX_REFERENCE_FRAMES + MAX_DELAY + 1) #define MAX_QUANT 68 /* max quant for VC-2 */ #define MAX_BLOCKSIZE 32 /* maximum xblen/yblen we support */ /** * DiracBlock->ref flags, if set then the block does MC from the given ref */ #define DIRAC_REF_MASK_REF1 1 #define DIRAC_REF_MASK_REF2 2 #define DIRAC_REF_MASK_GLOBAL 4 /** * Value of Picture.reference when Picture is not a reference picture, but * is held for delayed output. */ #define DELAYED_PIC_REF 4 #define ff_emulated_edge_mc ff_emulated_edge_mc_8 /* Fix: change the calls to this function regarding bit depth */ #define CALC_PADDING(size, depth) \ (((size + (1 << depth) - 1) >> depth) << depth) #define DIVRNDUP(a, b) (((a) + (b) - 1) / (b)) typedef struct { AVFrame avframe; int interpolated[3]; /* 1 if hpel[] is valid */ uint8_t *hpel[3][4]; uint8_t *hpel_base[3][4]; } DiracFrame; typedef struct { union { int16_t mv[2][2]; int16_t dc[3]; } u; /* anonymous unions aren't in C99 :( */ uint8_t ref; } DiracBlock; typedef struct SubBand { int level; int orientation; int stride; int width; int height; int quant; IDWTELEM *ibuf; struct SubBand *parent; /* for low delay */ unsigned length; const uint8_t *coeff_data; } SubBand; typedef struct Plane { int width; int height; int stride; int idwt_width; int idwt_height; int idwt_stride; IDWTELEM *idwt_buf; IDWTELEM *idwt_buf_base; IDWTELEM *idwt_tmp; /* block length */ uint8_t xblen; uint8_t yblen; /* block separation (block n+1 starts after this many pixels in block n) */ uint8_t xbsep; uint8_t ybsep; /* amount of overspill on each edge (half of the overlap between blocks) */ uint8_t xoffset; uint8_t yoffset; SubBand band[MAX_DWT_LEVELS][4]; } Plane; typedef struct DiracContext { AVCodecContext *avctx; DSPContext dsp; DiracDSPContext diracdsp; GetBitContext gb; dirac_source_params source; int seen_sequence_header; int frame_number; /* number of the next frame to display */ Plane plane[3]; int chroma_x_shift; int chroma_y_shift; int zero_res; /* zero residue flag */ int is_arith; /* whether coeffs use arith or golomb coding */ int low_delay; /* use the low delay syntax */ int globalmc_flag; /* use global motion compensation */ int num_refs; /* number of reference pictures */ /* wavelet decoding */ unsigned wavelet_depth; /* depth of the IDWT */ unsigned wavelet_idx; /** * schroedinger older than 1.0.8 doesn't store * quant delta if only one codebook exists in a band */ unsigned old_delta_quant; unsigned codeblock_mode; struct { unsigned width; unsigned height; } codeblock[MAX_DWT_LEVELS+1]; struct { unsigned num_x; /* number of horizontal slices */ unsigned num_y; /* number of vertical slices */ AVRational bytes; /* average bytes per slice */ uint8_t quant[MAX_DWT_LEVELS][4]; /* [DIRAC_STD] E.1 */ } lowdelay; struct { int pan_tilt[2]; /* pan/tilt vector */ int zrs[2][2]; /* zoom/rotate/shear matrix */ int perspective[2]; /* perspective vector */ unsigned zrs_exp; unsigned perspective_exp; } globalmc[2]; /* motion compensation */ uint8_t mv_precision; /* [DIRAC_STD] REFS_WT_PRECISION */ int16_t weight[2]; /* [DIRAC_STD] REF1_WT and REF2_WT */ unsigned weight_log2denom; /* [DIRAC_STD] REFS_WT_PRECISION */ int blwidth; /* number of blocks (horizontally) */ int blheight; /* number of blocks (vertically) */ int sbwidth; /* number of superblocks (horizontally) */ int sbheight; /* number of superblocks (vertically) */ uint8_t *sbsplit; DiracBlock *blmotion; uint8_t *edge_emu_buffer[4]; uint8_t *edge_emu_buffer_base; uint16_t *mctmp; /* buffer holding the MC data multipled by OBMC weights */ uint8_t *mcscratch; DECLARE_ALIGNED(16, uint8_t, obmc_weight)[3][MAX_BLOCKSIZE*MAX_BLOCKSIZE]; void (*put_pixels_tab[4])(uint8_t *dst, const uint8_t *src[5], int stride, int h); void (*avg_pixels_tab[4])(uint8_t *dst, const uint8_t *src[5], int stride, int h); void (*add_obmc)(uint16_t *dst, const uint8_t *src, int stride, const uint8_t *obmc_weight, int yblen); dirac_weight_func weight_func; dirac_biweight_func biweight_func; DiracFrame *current_picture; DiracFrame *ref_pics[2]; DiracFrame *ref_frames[MAX_REFERENCE_FRAMES+1]; DiracFrame *delay_frames[MAX_DELAY+1]; DiracFrame all_frames[MAX_FRAMES]; } DiracContext; /** * Dirac Specification -> * Parse code values. 9.6.1 Table 9.1 */ enum dirac_parse_code { pc_seq_header = 0x00, pc_eos = 0x10, pc_aux_data = 0x20, pc_padding = 0x30, }; enum dirac_subband { subband_ll = 0, subband_hl = 1, subband_lh = 2, subband_hh = 3 }; static const uint8_t default_qmat[][4][4] = { { { 5, 3, 3, 0}, { 0, 4, 4, 1}, { 0, 5, 5, 2}, { 0, 6, 6, 3} }, { { 4, 2, 2, 0}, { 0, 4, 4, 2}, { 0, 5, 5, 3}, { 0, 7, 7, 5} }, { { 5, 3, 3, 0}, { 0, 4, 4, 1}, { 0, 5, 5, 2}, { 0, 6, 6, 3} }, { { 8, 4, 4, 0}, { 0, 4, 4, 0}, { 0, 4, 4, 0}, { 0, 4, 4, 0} }, { { 8, 4, 4, 0}, { 0, 4, 4, 0}, { 0, 4, 4, 0}, { 0, 4, 4, 0} }, { { 0, 4, 4, 8}, { 0, 8, 8, 12}, { 0, 13, 13, 17}, { 0, 17, 17, 21} }, { { 3, 1, 1, 0}, { 0, 4, 4, 2}, { 0, 6, 6, 5}, { 0, 9, 9, 7} }, }; static const int qscale_tab[MAX_QUANT+1] = { 4, 5, 6, 7, 8, 10, 11, 13, 16, 19, 23, 27, 32, 38, 45, 54, 64, 76, 91, 108, 128, 152, 181, 215, 256, 304, 362, 431, 512, 609, 724, 861, 1024, 1218, 1448, 1722, 2048, 2435, 2896, 3444, 4096, 4871, 5793, 6889, 8192, 9742, 11585, 13777, 16384, 19484, 23170, 27554, 32768, 38968, 46341, 55109, 65536, 77936 }; static const int qoffset_intra_tab[MAX_QUANT+1] = { 1, 2, 3, 4, 4, 5, 6, 7, 8, 10, 12, 14, 16, 19, 23, 27, 32, 38, 46, 54, 64, 76, 91, 108, 128, 152, 181, 216, 256, 305, 362, 431, 512, 609, 724, 861, 1024, 1218, 1448, 1722, 2048, 2436, 2897, 3445, 4096, 4871, 5793, 6889, 8192, 9742, 11585, 13777, 16384, 19484, 23171, 27555, 32768, 38968 }; static const int qoffset_inter_tab[MAX_QUANT+1] = { 1, 2, 2, 3, 3, 4, 4, 5, 6, 7, 9, 10, 12, 14, 17, 20, 24, 29, 34, 41, 48, 57, 68, 81, 96, 114, 136, 162, 192, 228, 272, 323, 384, 457, 543, 646, 768, 913, 1086, 1292, 1536, 1827, 2172, 2583, 3072, 3653, 4344, 5166, 6144, 7307, 8689, 10333, 12288, 14613, 17378, 20666, 24576, 29226 }; /* magic number division by 3 from schroedinger */ static inline int divide3(int x) { return ((x+1)*21845 + 10922) >> 16; } static DiracFrame *remove_frame(DiracFrame *framelist[], int picnum) { DiracFrame *remove_pic = NULL; int i, remove_idx = -1; for (i = 0; framelist[i]; i++) if (framelist[i]->avframe.display_picture_number == picnum) { remove_pic = framelist[i]; remove_idx = i; } if (remove_pic) for (i = remove_idx; framelist[i]; i++) framelist[i] = framelist[i+1]; return remove_pic; } static int add_frame(DiracFrame *framelist[], int maxframes, DiracFrame *frame) { int i; for (i = 0; i < maxframes; i++) if (!framelist[i]) { framelist[i] = frame; return 0; } return -1; } static int alloc_sequence_buffers(DiracContext *s) { int sbwidth = DIVRNDUP(s->source.width, 4); int sbheight = DIVRNDUP(s->source.height, 4); int i, w, h, top_padding; /* todo: think more about this / use or set Plane here */ for (i = 0; i < 3; i++) { int max_xblen = MAX_BLOCKSIZE >> (i ? s->chroma_x_shift : 0); int max_yblen = MAX_BLOCKSIZE >> (i ? s->chroma_y_shift : 0); w = s->source.width >> (i ? s->chroma_x_shift : 0); h = s->source.height >> (i ? s->chroma_y_shift : 0); /* we allocate the max we support here since num decompositions can * change from frame to frame. Stride is aligned to 16 for SIMD, and * 1<<MAX_DWT_LEVELS top padding to avoid if(y>0) in arith decoding * MAX_BLOCKSIZE padding for MC: blocks can spill up to half of that * on each side */ top_padding = FFMAX(1<<MAX_DWT_LEVELS, max_yblen/2); w = FFALIGN(CALC_PADDING(w, MAX_DWT_LEVELS), 8); /* FIXME: Should this be 16 for SSE??? */ h = top_padding + CALC_PADDING(h, MAX_DWT_LEVELS) + max_yblen/2; s->plane[i].idwt_buf_base = av_mallocz((w+max_xblen)*h * sizeof(IDWTELEM)); s->plane[i].idwt_tmp = av_malloc((w+16) * sizeof(IDWTELEM)); s->plane[i].idwt_buf = s->plane[i].idwt_buf_base + top_padding*w; if (!s->plane[i].idwt_buf_base || !s->plane[i].idwt_tmp) return AVERROR(ENOMEM); } w = s->source.width; h = s->source.height; /* fixme: allocate using real stride here */ s->sbsplit = av_malloc(sbwidth * sbheight); s->blmotion = av_malloc(sbwidth * sbheight * 16 * sizeof(*s->blmotion)); s->edge_emu_buffer_base = av_malloc((w+64)*MAX_BLOCKSIZE); s->mctmp = av_malloc((w+64+MAX_BLOCKSIZE) * (h*MAX_BLOCKSIZE) * sizeof(*s->mctmp)); s->mcscratch = av_malloc((w+64)*MAX_BLOCKSIZE); if (!s->sbsplit || !s->blmotion) return AVERROR(ENOMEM); return 0; } static void free_sequence_buffers(DiracContext *s) { int i, j, k; for (i = 0; i < MAX_FRAMES; i++) { if (s->all_frames[i].avframe.data[0]) { s->avctx->release_buffer(s->avctx, &s->all_frames[i].avframe); memset(s->all_frames[i].interpolated, 0, sizeof(s->all_frames[i].interpolated)); } for (j = 0; j < 3; j++) for (k = 1; k < 4; k++) av_freep(&s->all_frames[i].hpel_base[j][k]); } memset(s->ref_frames, 0, sizeof(s->ref_frames)); memset(s->delay_frames, 0, sizeof(s->delay_frames)); for (i = 0; i < 3; i++) { av_freep(&s->plane[i].idwt_buf_base); av_freep(&s->plane[i].idwt_tmp); } av_freep(&s->sbsplit); av_freep(&s->blmotion); av_freep(&s->edge_emu_buffer_base); av_freep(&s->mctmp); av_freep(&s->mcscratch); } static av_cold int dirac_decode_init(AVCodecContext *avctx) { DiracContext *s = avctx->priv_data; s->avctx = avctx; s->frame_number = -1; if (avctx->flags&CODEC_FLAG_EMU_EDGE) { av_log(avctx, AV_LOG_ERROR, "Edge emulation not supported!\n"); return AVERROR_PATCHWELCOME; } ff_dsputil_init(&s->dsp, avctx); ff_diracdsp_init(&s->diracdsp); return 0; } static void dirac_decode_flush(AVCodecContext *avctx) { DiracContext *s = avctx->priv_data; free_sequence_buffers(s); s->seen_sequence_header = 0; s->frame_number = -1; } static av_cold int dirac_decode_end(AVCodecContext *avctx) { dirac_decode_flush(avctx); return 0; } #define SIGN_CTX(x) (CTX_SIGN_ZERO + ((x) > 0) - ((x) < 0)) static inline void coeff_unpack_arith(DiracArith *c, int qfactor, int qoffset, SubBand *b, IDWTELEM *buf, int x, int y) { int coeff, sign; int sign_pred = 0; int pred_ctx = CTX_ZPZN_F1; /* Check if the parent subband has a 0 in the corresponding position */ if (b->parent) pred_ctx += !!b->parent->ibuf[b->parent->stride * (y>>1) + (x>>1)] << 1; if (b->orientation == subband_hl) sign_pred = buf[-b->stride]; /* Determine if the pixel has only zeros in its neighbourhood */ if (x) { pred_ctx += !(buf[-1] | buf[-b->stride] | buf[-1-b->stride]); if (b->orientation == subband_lh) sign_pred = buf[-1]; } else { pred_ctx += !buf[-b->stride]; } coeff = dirac_get_arith_uint(c, pred_ctx, CTX_COEFF_DATA); if (coeff) { coeff = (coeff * qfactor + qoffset + 2) >> 2; sign = dirac_get_arith_bit(c, SIGN_CTX(sign_pred)); coeff = (coeff ^ -sign) + sign; } *buf = coeff; } static inline int coeff_unpack_golomb(GetBitContext *gb, int qfactor, int qoffset) { int sign, coeff; coeff = svq3_get_ue_golomb(gb); if (coeff) { coeff = (coeff * qfactor + qoffset + 2) >> 2; sign = get_bits1(gb); coeff = (coeff ^ -sign) + sign; } return coeff; } /** * Decode the coeffs in the rectangle defined by left, right, top, bottom * [DIRAC_STD] 13.4.3.2 Codeblock unpacking loop. codeblock() */ static inline void codeblock(DiracContext *s, SubBand *b, GetBitContext *gb, DiracArith *c, int left, int right, int top, int bottom, int blockcnt_one, int is_arith) { int x, y, zero_block; int qoffset, qfactor; IDWTELEM *buf; /* check for any coded coefficients in this codeblock */ if (!blockcnt_one) { if (is_arith) zero_block = dirac_get_arith_bit(c, CTX_ZERO_BLOCK); else zero_block = get_bits1(gb); if (zero_block) return; } if (s->codeblock_mode && !(s->old_delta_quant && blockcnt_one)) { int quant = b->quant; if (is_arith) quant += dirac_get_arith_int(c, CTX_DELTA_Q_F, CTX_DELTA_Q_DATA); else quant += dirac_get_se_golomb(gb); if (quant < 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid quant\n"); return; } b->quant = quant; } b->quant = FFMIN(b->quant, MAX_QUANT); qfactor = qscale_tab[b->quant]; /* TODO: context pointer? */ if (!s->num_refs) qoffset = qoffset_intra_tab[b->quant]; else qoffset = qoffset_inter_tab[b->quant]; buf = b->ibuf + top * b->stride; for (y = top; y < bottom; y++) { for (x = left; x < right; x++) { /* [DIRAC_STD] 13.4.4 Subband coefficients. coeff_unpack() */ if (is_arith) coeff_unpack_arith(c, qfactor, qoffset, b, buf+x, x, y); else buf[x] = coeff_unpack_golomb(gb, qfactor, qoffset); } buf += b->stride; } } /** * Dirac Specification -> * 13.3 intra_dc_prediction(band) */ static inline void intra_dc_prediction(SubBand *b) { IDWTELEM *buf = b->ibuf; int x, y; for (x = 1; x < b->width; x++) buf[x] += buf[x-1]; buf += b->stride; for (y = 1; y < b->height; y++) { buf[0] += buf[-b->stride]; for (x = 1; x < b->width; x++) { int pred = buf[x - 1] + buf[x - b->stride] + buf[x - b->stride-1]; buf[x] += divide3(pred); } buf += b->stride; } } /** * Dirac Specification -> * 13.4.2 Non-skipped subbands. subband_coeffs() */ static av_always_inline void decode_subband_internal(DiracContext *s, SubBand *b, int is_arith) { int cb_x, cb_y, left, right, top, bottom; DiracArith c; GetBitContext gb; int cb_width = s->codeblock[b->level + (b->orientation != subband_ll)].width; int cb_height = s->codeblock[b->level + (b->orientation != subband_ll)].height; int blockcnt_one = (cb_width + cb_height) == 2; if (!b->length) return; init_get_bits(&gb, b->coeff_data, b->length*8); if (is_arith) ff_dirac_init_arith_decoder(&c, &gb, b->length); top = 0; for (cb_y = 0; cb_y < cb_height; cb_y++) { bottom = (b->height * (cb_y+1)) / cb_height; left = 0; for (cb_x = 0; cb_x < cb_width; cb_x++) { right = (b->width * (cb_x+1)) / cb_width; codeblock(s, b, &gb, &c, left, right, top, bottom, blockcnt_one, is_arith); left = right; } top = bottom; } if (b->orientation == subband_ll && s->num_refs == 0) intra_dc_prediction(b); } static int decode_subband_arith(AVCodecContext *avctx, void *b) { DiracContext *s = avctx->priv_data; decode_subband_internal(s, b, 1); return 0; } static int decode_subband_golomb(AVCodecContext *avctx, void *arg) { DiracContext *s = avctx->priv_data; SubBand **b = arg; decode_subband_internal(s, *b, 0); return 0; } /** * Dirac Specification -> * [DIRAC_STD] 13.4.1 core_transform_data() */ static void decode_component(DiracContext *s, int comp) { AVCodecContext *avctx = s->avctx; SubBand *bands[3*MAX_DWT_LEVELS+1]; enum dirac_subband orientation; int level, num_bands = 0; /* Unpack all subbands at all levels. */ for (level = 0; level < s->wavelet_depth; level++) { for (orientation = !!level; orientation < 4; orientation++) { SubBand *b = &s->plane[comp].band[level][orientation]; bands[num_bands++] = b; align_get_bits(&s->gb); /* [DIRAC_STD] 13.4.2 subband() */ b->length = svq3_get_ue_golomb(&s->gb); if (b->length) { b->quant = svq3_get_ue_golomb(&s->gb); align_get_bits(&s->gb); b->coeff_data = s->gb.buffer + get_bits_count(&s->gb)/8; b->length = FFMIN(b->length, FFMAX(get_bits_left(&s->gb)/8, 0)); skip_bits_long(&s->gb, b->length*8); } } /* arithmetic coding has inter-level dependencies, so we can only execute one level at a time */ if (s->is_arith) avctx->execute(avctx, decode_subband_arith, &s->plane[comp].band[level][!!level], NULL, 4-!!level, sizeof(SubBand)); } /* golomb coding has no inter-level dependencies, so we can execute all subbands in parallel */ if (!s->is_arith) avctx->execute(avctx, decode_subband_golomb, bands, NULL, num_bands, sizeof(SubBand*)); } /* [DIRAC_STD] 13.5.5.2 Luma slice subband data. luma_slice_band(level,orient,sx,sy) --> if b2 == NULL */ /* [DIRAC_STD] 13.5.5.3 Chroma slice subband data. chroma_slice_band(level,orient,sx,sy) --> if b2 != NULL */ static void lowdelay_subband(DiracContext *s, GetBitContext *gb, int quant, int slice_x, int slice_y, int bits_end, SubBand *b1, SubBand *b2) { int left = b1->width * slice_x / s->lowdelay.num_x; int right = b1->width *(slice_x+1) / s->lowdelay.num_x; int top = b1->height * slice_y / s->lowdelay.num_y; int bottom = b1->height *(slice_y+1) / s->lowdelay.num_y; int qfactor = qscale_tab[FFMIN(quant, MAX_QUANT)]; int qoffset = qoffset_intra_tab[FFMIN(quant, MAX_QUANT)]; IDWTELEM *buf1 = b1->ibuf + top * b1->stride; IDWTELEM *buf2 = b2 ? b2->ibuf + top * b2->stride : NULL; int x, y; /* we have to constantly check for overread since the spec explictly requires this, with the meaning that all remaining coeffs are set to 0 */ if (get_bits_count(gb) >= bits_end) return; for (y = top; y < bottom; y++) { for (x = left; x < right; x++) { buf1[x] = coeff_unpack_golomb(gb, qfactor, qoffset); if (get_bits_count(gb) >= bits_end) return; if (buf2) { buf2[x] = coeff_unpack_golomb(gb, qfactor, qoffset); if (get_bits_count(gb) >= bits_end) return; } } buf1 += b1->stride; if (buf2) buf2 += b2->stride; } } struct lowdelay_slice { GetBitContext gb; int slice_x; int slice_y; int bytes; }; /** * Dirac Specification -> * 13.5.2 Slices. slice(sx,sy) */ static int decode_lowdelay_slice(AVCodecContext *avctx, void *arg) { DiracContext *s = avctx->priv_data; struct lowdelay_slice *slice = arg; GetBitContext *gb = &slice->gb; enum dirac_subband orientation; int level, quant, chroma_bits, chroma_end; int quant_base = get_bits(gb, 7); /*[DIRAC_STD] qindex */ int length_bits = av_log2(8 * slice->bytes)+1; int luma_bits = get_bits_long(gb, length_bits); int luma_end = get_bits_count(gb) + FFMIN(luma_bits, get_bits_left(gb)); /* [DIRAC_STD] 13.5.5.2 luma_slice_band */ for (level = 0; level < s->wavelet_depth; level++) for (orientation = !!level; orientation < 4; orientation++) { quant = FFMAX(quant_base - s->lowdelay.quant[level][orientation], 0); lowdelay_subband(s, gb, quant, slice->slice_x, slice->slice_y, luma_end, &s->plane[0].band[level][orientation], NULL); } /* consume any unused bits from luma */ skip_bits_long(gb, get_bits_count(gb) - luma_end); chroma_bits = 8*slice->bytes - 7 - length_bits - luma_bits; chroma_end = get_bits_count(gb) + FFMIN(chroma_bits, get_bits_left(gb)); /* [DIRAC_STD] 13.5.5.3 chroma_slice_band */ for (level = 0; level < s->wavelet_depth; level++) for (orientation = !!level; orientation < 4; orientation++) { quant = FFMAX(quant_base - s->lowdelay.quant[level][orientation], 0); lowdelay_subband(s, gb, quant, slice->slice_x, slice->slice_y, chroma_end, &s->plane[1].band[level][orientation], &s->plane[2].band[level][orientation]); } return 0; } /** * Dirac Specification -> * 13.5.1 low_delay_transform_data() */ static void decode_lowdelay(DiracContext *s) { AVCodecContext *avctx = s->avctx; int slice_x, slice_y, bytes, bufsize; const uint8_t *buf; struct lowdelay_slice *slices; int slice_num = 0; slices = av_mallocz(s->lowdelay.num_x * s->lowdelay.num_y * sizeof(struct lowdelay_slice)); align_get_bits(&s->gb); /*[DIRAC_STD] 13.5.2 Slices. slice(sx,sy) */ buf = s->gb.buffer + get_bits_count(&s->gb)/8; bufsize = get_bits_left(&s->gb); for (slice_y = 0; bufsize > 0 && slice_y < s->lowdelay.num_y; slice_y++) for (slice_x = 0; bufsize > 0 && slice_x < s->lowdelay.num_x; slice_x++) { bytes = (slice_num+1) * s->lowdelay.bytes.num / s->lowdelay.bytes.den - slice_num * s->lowdelay.bytes.num / s->lowdelay.bytes.den; slices[slice_num].bytes = bytes; slices[slice_num].slice_x = slice_x; slices[slice_num].slice_y = slice_y; init_get_bits(&slices[slice_num].gb, buf, bufsize); slice_num++; buf += bytes; bufsize -= bytes*8; } avctx->execute(avctx, decode_lowdelay_slice, slices, NULL, slice_num, sizeof(struct lowdelay_slice)); /* [DIRAC_STD] 13.5.2 Slices */ intra_dc_prediction(&s->plane[0].band[0][0]); /* [DIRAC_STD] 13.3 intra_dc_prediction() */ intra_dc_prediction(&s->plane[1].band[0][0]); /* [DIRAC_STD] 13.3 intra_dc_prediction() */ intra_dc_prediction(&s->plane[2].band[0][0]); /* [DIRAC_STD] 13.3 intra_dc_prediction() */ av_free(slices); } static void init_planes(DiracContext *s) { int i, w, h, level, orientation; for (i = 0; i < 3; i++) { Plane *p = &s->plane[i]; p->width = s->source.width >> (i ? s->chroma_x_shift : 0); p->height = s->source.height >> (i ? s->chroma_y_shift : 0); p->idwt_width = w = CALC_PADDING(p->width , s->wavelet_depth); p->idwt_height = h = CALC_PADDING(p->height, s->wavelet_depth); p->idwt_stride = FFALIGN(p->idwt_width, 8); for (level = s->wavelet_depth-1; level >= 0; level--) { w = w>>1; h = h>>1; for (orientation = !!level; orientation < 4; orientation++) { SubBand *b = &p->band[level][orientation]; b->ibuf = p->idwt_buf; b->level = level; b->stride = p->idwt_stride << (s->wavelet_depth - level); b->width = w; b->height = h; b->orientation = orientation; if (orientation & 1) b->ibuf += w; if (orientation > 1) b->ibuf += b->stride>>1; if (level) b->parent = &p->band[level-1][orientation]; } } if (i > 0) { p->xblen = s->plane[0].xblen >> s->chroma_x_shift; p->yblen = s->plane[0].yblen >> s->chroma_y_shift; p->xbsep = s->plane[0].xbsep >> s->chroma_x_shift; p->ybsep = s->plane[0].ybsep >> s->chroma_y_shift; } p->xoffset = (p->xblen - p->xbsep)/2; p->yoffset = (p->yblen - p->ybsep)/2; } } /** * Unpack the motion compensation parameters * Dirac Specification -> * 11.2 Picture prediction data. picture_prediction() */ static int dirac_unpack_prediction_parameters(DiracContext *s) { static const uint8_t default_blen[] = { 4, 12, 16, 24 }; static const uint8_t default_bsep[] = { 4, 8, 12, 16 }; GetBitContext *gb = &s->gb; unsigned idx, ref; align_get_bits(gb); /* [DIRAC_STD] 11.2.2 Block parameters. block_parameters() */ /* Luma and Chroma are equal. 11.2.3 */ idx = svq3_get_ue_golomb(gb); /* [DIRAC_STD] index */ if (idx > 4) { av_log(s->avctx, AV_LOG_ERROR, "Block prediction index too high\n"); return -1; } if (idx == 0) { s->plane[0].xblen = svq3_get_ue_golomb(gb); s->plane[0].yblen = svq3_get_ue_golomb(gb); s->plane[0].xbsep = svq3_get_ue_golomb(gb); s->plane[0].ybsep = svq3_get_ue_golomb(gb); } else { /*[DIRAC_STD] preset_block_params(index). Table 11.1 */ s->plane[0].xblen = default_blen[idx-1]; s->plane[0].yblen = default_blen[idx-1]; s->plane[0].xbsep = default_bsep[idx-1]; s->plane[0].ybsep = default_bsep[idx-1]; } /*[DIRAC_STD] 11.2.4 motion_data_dimensions() Calculated in function dirac_unpack_block_motion_data */ if (!s->plane[0].xbsep || !s->plane[0].ybsep || s->plane[0].xbsep < s->plane[0].xblen/2 || s->plane[0].ybsep < s->plane[0].yblen/2) { av_log(s->avctx, AV_LOG_ERROR, "Block separation too small\n"); return -1; } if (s->plane[0].xbsep > s->plane[0].xblen || s->plane[0].ybsep > s->plane[0].yblen) { av_log(s->avctx, AV_LOG_ERROR, "Block separation greater than size\n"); return -1; } if (FFMAX(s->plane[0].xblen, s->plane[0].yblen) > MAX_BLOCKSIZE) { av_log(s->avctx, AV_LOG_ERROR, "Unsupported large block size\n"); return -1; } /*[DIRAC_STD] 11.2.5 Motion vector precision. motion_vector_precision() Read motion vector precision */ s->mv_precision = svq3_get_ue_golomb(gb); if (s->mv_precision > 3) { av_log(s->avctx, AV_LOG_ERROR, "MV precision finer than eighth-pel\n"); return -1; } /*[DIRAC_STD] 11.2.6 Global motion. global_motion() Read the global motion compensation parameters */ s->globalmc_flag = get_bits1(gb); if (s->globalmc_flag) { memset(s->globalmc, 0, sizeof(s->globalmc)); /* [DIRAC_STD] pan_tilt(gparams) */ for (ref = 0; ref < s->num_refs; ref++) { if (get_bits1(gb)) { s->globalmc[ref].pan_tilt[0] = dirac_get_se_golomb(gb); s->globalmc[ref].pan_tilt[1] = dirac_get_se_golomb(gb); } /* [DIRAC_STD] zoom_rotate_shear(gparams) zoom/rotation/shear parameters */ if (get_bits1(gb)) { s->globalmc[ref].zrs_exp = svq3_get_ue_golomb(gb); s->globalmc[ref].zrs[0][0] = dirac_get_se_golomb(gb); s->globalmc[ref].zrs[0][1] = dirac_get_se_golomb(gb); s->globalmc[ref].zrs[1][0] = dirac_get_se_golomb(gb); s->globalmc[ref].zrs[1][1] = dirac_get_se_golomb(gb); } else { s->globalmc[ref].zrs[0][0] = 1; s->globalmc[ref].zrs[1][1] = 1; } /* [DIRAC_STD] perspective(gparams) */ if (get_bits1(gb)) { s->globalmc[ref].perspective_exp = svq3_get_ue_golomb(gb); s->globalmc[ref].perspective[0] = dirac_get_se_golomb(gb); s->globalmc[ref].perspective[1] = dirac_get_se_golomb(gb); } } } /*[DIRAC_STD] 11.2.7 Picture prediction mode. prediction_mode() Picture prediction mode, not currently used. */ if (svq3_get_ue_golomb(gb)) { av_log(s->avctx, AV_LOG_ERROR, "Unknown picture prediction mode\n"); return -1; } /* [DIRAC_STD] 11.2.8 Reference picture weight. reference_picture_weights() just data read, weight calculation will be done later on. */ s->weight_log2denom = 1; s->weight[0] = 1; s->weight[1] = 1; if (get_bits1(gb)) { s->weight_log2denom = svq3_get_ue_golomb(gb); s->weight[0] = dirac_get_se_golomb(gb); if (s->num_refs == 2) s->weight[1] = dirac_get_se_golomb(gb); } return 0; } /** * Dirac Specification -> * 11.3 Wavelet transform data. wavelet_transform() */ static int dirac_unpack_idwt_params(DiracContext *s) { GetBitContext *gb = &s->gb; int i, level; unsigned tmp; #define CHECKEDREAD(dst, cond, errmsg) \ tmp = svq3_get_ue_golomb(gb); \ if (cond) { \ av_log(s->avctx, AV_LOG_ERROR, errmsg); \ return -1; \ }\ dst = tmp; align_get_bits(gb); s->zero_res = s->num_refs ? get_bits1(gb) : 0; if (s->zero_res) return 0; /*[DIRAC_STD] 11.3.1 Transform parameters. transform_parameters() */ CHECKEDREAD(s->wavelet_idx, tmp > 6, "wavelet_idx is too big\n") CHECKEDREAD(s->wavelet_depth, tmp > MAX_DWT_LEVELS || tmp < 1, "invalid number of DWT decompositions\n") if (!s->low_delay) { /* Codeblock parameters (core syntax only) */ if (get_bits1(gb)) { for (i = 0; i <= s->wavelet_depth; i++) { CHECKEDREAD(s->codeblock[i].width , tmp < 1, "codeblock width invalid\n") CHECKEDREAD(s->codeblock[i].height, tmp < 1, "codeblock height invalid\n") } CHECKEDREAD(s->codeblock_mode, tmp > 1, "unknown codeblock mode\n") } else for (i = 0; i <= s->wavelet_depth; i++) s->codeblock[i].width = s->codeblock[i].height = 1; } else { /* Slice parameters + quantization matrix*/ /*[DIRAC_STD] 11.3.4 Slice coding Parameters (low delay syntax only). slice_parameters() */ s->lowdelay.num_x = svq3_get_ue_golomb(gb); s->lowdelay.num_y = svq3_get_ue_golomb(gb); s->lowdelay.bytes.num = svq3_get_ue_golomb(gb); s->lowdelay.bytes.den = svq3_get_ue_golomb(gb); if (s->lowdelay.bytes.den <= 0) { av_log(s->avctx,AV_LOG_ERROR,"Invalid lowdelay.bytes.den\n"); return AVERROR_INVALIDDATA; } /* [DIRAC_STD] 11.3.5 Quantisation matrices (low-delay syntax). quant_matrix() */ if (get_bits1(gb)) { av_log(s->avctx,AV_LOG_DEBUG,"Low Delay: Has Custom Quantization Matrix!\n"); /* custom quantization matrix */ s->lowdelay.quant[0][0] = svq3_get_ue_golomb(gb); for (level = 0; level < s->wavelet_depth; level++) { s->lowdelay.quant[level][1] = svq3_get_ue_golomb(gb); s->lowdelay.quant[level][2] = svq3_get_ue_golomb(gb); s->lowdelay.quant[level][3] = svq3_get_ue_golomb(gb); } } else { if (s->wavelet_depth > 4) { av_log(s->avctx,AV_LOG_ERROR,"Mandatory custom low delay matrix missing for depth %d\n", s->wavelet_depth); return AVERROR_INVALIDDATA; } /* default quantization matrix */ for (level = 0; level < s->wavelet_depth; level++) for (i = 0; i < 4; i++) { s->lowdelay.quant[level][i] = default_qmat[s->wavelet_idx][level][i]; /* haar with no shift differs for different depths */ if (s->wavelet_idx == 3) s->lowdelay.quant[level][i] += 4*(s->wavelet_depth-1 - level); } } } return 0; } static inline int pred_sbsplit(uint8_t *sbsplit, int stride, int x, int y) { static const uint8_t avgsplit[7] = { 0, 0, 1, 1, 1, 2, 2 }; if (!(x|y)) return 0; else if (!y) return sbsplit[-1]; else if (!x) return sbsplit[-stride]; return avgsplit[sbsplit[-1] + sbsplit[-stride] + sbsplit[-stride-1]]; } static inline int pred_block_mode(DiracBlock *block, int stride, int x, int y, int refmask) { int pred; if (!(x|y)) return 0; else if (!y) return block[-1].ref & refmask; else if (!x) return block[-stride].ref & refmask; /* return the majority */ pred = (block[-1].ref & refmask) + (block[-stride].ref & refmask) + (block[-stride-1].ref & refmask); return (pred >> 1) & refmask; } static inline void pred_block_dc(DiracBlock *block, int stride, int x, int y) { int i, n = 0; memset(block->u.dc, 0, sizeof(block->u.dc)); if (x && !(block[-1].ref & 3)) { for (i = 0; i < 3; i++) block->u.dc[i] += block[-1].u.dc[i]; n++; } if (y && !(block[-stride].ref & 3)) { for (i = 0; i < 3; i++) block->u.dc[i] += block[-stride].u.dc[i]; n++; } if (x && y && !(block[-1-stride].ref & 3)) { for (i = 0; i < 3; i++) block->u.dc[i] += block[-1-stride].u.dc[i]; n++; } if (n == 2) { for (i = 0; i < 3; i++) block->u.dc[i] = (block->u.dc[i]+1)>>1; } else if (n == 3) { for (i = 0; i < 3; i++) block->u.dc[i] = divide3(block->u.dc[i]); } } static inline void pred_mv(DiracBlock *block, int stride, int x, int y, int ref) { int16_t *pred[3]; int refmask = ref+1; int mask = refmask | DIRAC_REF_MASK_GLOBAL; /* exclude gmc blocks */ int n = 0; if (x && (block[-1].ref & mask) == refmask) pred[n++] = block[-1].u.mv[ref]; if (y && (block[-stride].ref & mask) == refmask) pred[n++] = block[-stride].u.mv[ref]; if (x && y && (block[-stride-1].ref & mask) == refmask) pred[n++] = block[-stride-1].u.mv[ref]; switch (n) { case 0: block->u.mv[ref][0] = 0; block->u.mv[ref][1] = 0; break; case 1: block->u.mv[ref][0] = pred[0][0]; block->u.mv[ref][1] = pred[0][1]; break; case 2: block->u.mv[ref][0] = (pred[0][0] + pred[1][0] + 1) >> 1; block->u.mv[ref][1] = (pred[0][1] + pred[1][1] + 1) >> 1; break; case 3: block->u.mv[ref][0] = mid_pred(pred[0][0], pred[1][0], pred[2][0]); block->u.mv[ref][1] = mid_pred(pred[0][1], pred[1][1], pred[2][1]); break; } } static void global_mv(DiracContext *s, DiracBlock *block, int x, int y, int ref) { int ez = s->globalmc[ref].zrs_exp; int ep = s->globalmc[ref].perspective_exp; int (*A)[2] = s->globalmc[ref].zrs; int *b = s->globalmc[ref].pan_tilt; int *c = s->globalmc[ref].perspective; int m = (1<<ep) - (c[0]*x + c[1]*y); int mx = m * ((A[0][0] * x + A[0][1]*y) + (1<<ez) * b[0]); int my = m * ((A[1][0] * x + A[1][1]*y) + (1<<ez) * b[1]); block->u.mv[ref][0] = (mx + (1<<(ez+ep))) >> (ez+ep); block->u.mv[ref][1] = (my + (1<<(ez+ep))) >> (ez+ep); } static void decode_block_params(DiracContext *s, DiracArith arith[8], DiracBlock *block, int stride, int x, int y) { int i; block->ref = pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_REF1); block->ref ^= dirac_get_arith_bit(arith, CTX_PMODE_REF1); if (s->num_refs == 2) { block->ref |= pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_REF2); block->ref ^= dirac_get_arith_bit(arith, CTX_PMODE_REF2) << 1; } if (!block->ref) { pred_block_dc(block, stride, x, y); for (i = 0; i < 3; i++) block->u.dc[i] += dirac_get_arith_int(arith+1+i, CTX_DC_F1, CTX_DC_DATA); return; } if (s->globalmc_flag) { block->ref |= pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_GLOBAL); block->ref ^= dirac_get_arith_bit(arith, CTX_GLOBAL_BLOCK) << 2; } for (i = 0; i < s->num_refs; i++) if (block->ref & (i+1)) { if (block->ref & DIRAC_REF_MASK_GLOBAL) { global_mv(s, block, x, y, i); } else { pred_mv(block, stride, x, y, i); block->u.mv[i][0] += dirac_get_arith_int(arith + 4 + 2 * i, CTX_MV_F1, CTX_MV_DATA); block->u.mv[i][1] += dirac_get_arith_int(arith + 5 + 2 * i, CTX_MV_F1, CTX_MV_DATA); } } } /** * Copies the current block to the other blocks covered by the current superblock split mode */ static void propagate_block_data(DiracBlock *block, int stride, int size) { int x, y; DiracBlock *dst = block; for (x = 1; x < size; x++) dst[x] = *block; for (y = 1; y < size; y++) { dst += stride; for (x = 0; x < size; x++) dst[x] = *block; } } /** * Dirac Specification -> * 12. Block motion data syntax */ static int dirac_unpack_block_motion_data(DiracContext *s) { GetBitContext *gb = &s->gb; uint8_t *sbsplit = s->sbsplit; int i, x, y, q, p; DiracArith arith[8]; align_get_bits(gb); /* [DIRAC_STD] 11.2.4 and 12.2.1 Number of blocks and superblocks */ s->sbwidth = DIVRNDUP(s->source.width, 4*s->plane[0].xbsep); s->sbheight = DIVRNDUP(s->source.height, 4*s->plane[0].ybsep); s->blwidth = 4 * s->sbwidth; s->blheight = 4 * s->sbheight; /* [DIRAC_STD] 12.3.1 Superblock splitting modes. superblock_split_modes() decode superblock split modes */ ff_dirac_init_arith_decoder(arith, gb, svq3_get_ue_golomb(gb)); /* svq3_get_ue_golomb(gb) is the length */ for (y = 0; y < s->sbheight; y++) { for (x = 0; x < s->sbwidth; x++) { unsigned int split = dirac_get_arith_uint(arith, CTX_SB_F1, CTX_SB_DATA); if (split > 2) return -1; sbsplit[x] = (split + pred_sbsplit(sbsplit+x, s->sbwidth, x, y)) % 3; } sbsplit += s->sbwidth; } /* setup arith decoding */ ff_dirac_init_arith_decoder(arith, gb, svq3_get_ue_golomb(gb)); for (i = 0; i < s->num_refs; i++) { ff_dirac_init_arith_decoder(arith + 4 + 2 * i, gb, svq3_get_ue_golomb(gb)); ff_dirac_init_arith_decoder(arith + 5 + 2 * i, gb, svq3_get_ue_golomb(gb)); } for (i = 0; i < 3; i++) ff_dirac_init_arith_decoder(arith+1+i, gb, svq3_get_ue_golomb(gb)); for (y = 0; y < s->sbheight; y++) for (x = 0; x < s->sbwidth; x++) { int blkcnt = 1 << s->sbsplit[y * s->sbwidth + x]; int step = 4 >> s->sbsplit[y * s->sbwidth + x]; for (q = 0; q < blkcnt; q++) for (p = 0; p < blkcnt; p++) { int bx = 4 * x + p*step; int by = 4 * y + q*step; DiracBlock *block = &s->blmotion[by*s->blwidth + bx]; decode_block_params(s, arith, block, s->blwidth, bx, by); propagate_block_data(block, s->blwidth, step); } } return 0; } static int weight(int i, int blen, int offset) { #define ROLLOFF(i) offset == 1 ? ((i) ? 5 : 3) : \ (1 + (6*(i) + offset - 1) / (2*offset - 1)) if (i < 2*offset) return ROLLOFF(i); else if (i > blen-1 - 2*offset) return ROLLOFF(blen-1 - i); return 8; } static void init_obmc_weight_row(Plane *p, uint8_t *obmc_weight, int stride, int left, int right, int wy) { int x; for (x = 0; left && x < p->xblen >> 1; x++) obmc_weight[x] = wy*8; for (; x < p->xblen >> right; x++) obmc_weight[x] = wy*weight(x, p->xblen, p->xoffset); for (; x < p->xblen; x++) obmc_weight[x] = wy*8; for (; x < stride; x++) obmc_weight[x] = 0; } static void init_obmc_weight(Plane *p, uint8_t *obmc_weight, int stride, int left, int right, int top, int bottom) { int y; for (y = 0; top && y < p->yblen >> 1; y++) { init_obmc_weight_row(p, obmc_weight, stride, left, right, 8); obmc_weight += stride; } for (; y < p->yblen >> bottom; y++) { int wy = weight(y, p->yblen, p->yoffset); init_obmc_weight_row(p, obmc_weight, stride, left, right, wy); obmc_weight += stride; } for (; y < p->yblen; y++) { init_obmc_weight_row(p, obmc_weight, stride, left, right, 8); obmc_weight += stride; } } static void init_obmc_weights(DiracContext *s, Plane *p, int by) { int top = !by; int bottom = by == s->blheight-1; /* don't bother re-initing for rows 2 to blheight-2, the weights don't change */ if (top || bottom || by == 1) { init_obmc_weight(p, s->obmc_weight[0], MAX_BLOCKSIZE, 1, 0, top, bottom); init_obmc_weight(p, s->obmc_weight[1], MAX_BLOCKSIZE, 0, 0, top, bottom); init_obmc_weight(p, s->obmc_weight[2], MAX_BLOCKSIZE, 0, 1, top, bottom); } } static const uint8_t epel_weights[4][4][4] = { {{ 16, 0, 0, 0 }, { 12, 4, 0, 0 }, { 8, 8, 0, 0 }, { 4, 12, 0, 0 }}, {{ 12, 0, 4, 0 }, { 9, 3, 3, 1 }, { 6, 6, 2, 2 }, { 3, 9, 1, 3 }}, {{ 8, 0, 8, 0 }, { 6, 2, 6, 2 }, { 4, 4, 4, 4 }, { 2, 6, 2, 6 }}, {{ 4, 0, 12, 0 }, { 3, 1, 9, 3 }, { 2, 2, 6, 6 }, { 1, 3, 3, 9 }} }; /** * For block x,y, determine which of the hpel planes to do bilinear * interpolation from and set src[] to the location in each hpel plane * to MC from. * * @return the index of the put_dirac_pixels_tab function to use * 0 for 1 plane (fpel,hpel), 1 for 2 planes (qpel), 2 for 4 planes (qpel), and 3 for epel */ static int mc_subpel(DiracContext *s, DiracBlock *block, const uint8_t *src[5], int x, int y, int ref, int plane) { Plane *p = &s->plane[plane]; uint8_t **ref_hpel = s->ref_pics[ref]->hpel[plane]; int motion_x = block->u.mv[ref][0]; int motion_y = block->u.mv[ref][1]; int mx, my, i, epel, nplanes = 0; if (plane) { motion_x >>= s->chroma_x_shift; motion_y >>= s->chroma_y_shift; } mx = motion_x & ~(-1 << s->mv_precision); my = motion_y & ~(-1 << s->mv_precision); motion_x >>= s->mv_precision; motion_y >>= s->mv_precision; /* normalize subpel coordinates to epel */ /* TODO: template this function? */ mx <<= 3 - s->mv_precision; my <<= 3 - s->mv_precision; x += motion_x; y += motion_y; epel = (mx|my)&1; /* hpel position */ if (!((mx|my)&3)) { nplanes = 1; src[0] = ref_hpel[(my>>1)+(mx>>2)] + y*p->stride + x; } else { /* qpel or epel */ nplanes = 4; for (i = 0; i < 4; i++) src[i] = ref_hpel[i] + y*p->stride + x; /* if we're interpolating in the right/bottom halves, adjust the planes as needed we increment x/y because the edge changes for half of the pixels */ if (mx > 4) { src[0] += 1; src[2] += 1; x++; } if (my > 4) { src[0] += p->stride; src[1] += p->stride; y++; } /* hpel planes are: [0]: F [1]: H [2]: V [3]: C */ if (!epel) { /* check if we really only need 2 planes since either mx or my is a hpel position. (epel weights of 0 handle this there) */ if (!(mx&3)) { /* mx == 0: average [0] and [2] mx == 4: average [1] and [3] */ src[!mx] = src[2 + !!mx]; nplanes = 2; } else if (!(my&3)) { src[0] = src[(my>>1) ]; src[1] = src[(my>>1)+1]; nplanes = 2; } } else { /* adjust the ordering if needed so the weights work */ if (mx > 4) { FFSWAP(const uint8_t *, src[0], src[1]); FFSWAP(const uint8_t *, src[2], src[3]); } if (my > 4) { FFSWAP(const uint8_t *, src[0], src[2]); FFSWAP(const uint8_t *, src[1], src[3]); } src[4] = epel_weights[my&3][mx&3]; } } /* fixme: v/h _edge_pos */ if ((unsigned)x > FFMAX(p->width +EDGE_WIDTH/2 - p->xblen, 0) || (unsigned)y > FFMAX(p->height+EDGE_WIDTH/2 - p->yblen, 0)) { for (i = 0; i < nplanes; i++) { ff_emulated_edge_mc(s->edge_emu_buffer[i], src[i], p->stride, p->xblen, p->yblen, x, y, p->width+EDGE_WIDTH/2, p->height+EDGE_WIDTH/2); src[i] = s->edge_emu_buffer[i]; } } return (nplanes>>1) + epel; } static void add_dc(uint16_t *dst, int dc, int stride, uint8_t *obmc_weight, int xblen, int yblen) { int x, y; dc += 128; for (y = 0; y < yblen; y++) { for (x = 0; x < xblen; x += 2) { dst[x ] += dc * obmc_weight[x ]; dst[x+1] += dc * obmc_weight[x+1]; } dst += stride; obmc_weight += MAX_BLOCKSIZE; } } static void block_mc(DiracContext *s, DiracBlock *block, uint16_t *mctmp, uint8_t *obmc_weight, int plane, int dstx, int dsty) { Plane *p = &s->plane[plane]; const uint8_t *src[5]; int idx; switch (block->ref&3) { case 0: /* DC */ add_dc(mctmp, block->u.dc[plane], p->stride, obmc_weight, p->xblen, p->yblen); return; case 1: case 2: idx = mc_subpel(s, block, src, dstx, dsty, (block->ref&3)-1, plane); s->put_pixels_tab[idx](s->mcscratch, src, p->stride, p->yblen); if (s->weight_func) s->weight_func(s->mcscratch, p->stride, s->weight_log2denom, s->weight[0] + s->weight[1], p->yblen); break; case 3: idx = mc_subpel(s, block, src, dstx, dsty, 0, plane); s->put_pixels_tab[idx](s->mcscratch, src, p->stride, p->yblen); idx = mc_subpel(s, block, src, dstx, dsty, 1, plane); if (s->biweight_func) { /* fixme: +32 is a quick hack */ s->put_pixels_tab[idx](s->mcscratch + 32, src, p->stride, p->yblen); s->biweight_func(s->mcscratch, s->mcscratch+32, p->stride, s->weight_log2denom, s->weight[0], s->weight[1], p->yblen); } else s->avg_pixels_tab[idx](s->mcscratch, src, p->stride, p->yblen); break; } s->add_obmc(mctmp, s->mcscratch, p->stride, obmc_weight, p->yblen); } static void mc_row(DiracContext *s, DiracBlock *block, uint16_t *mctmp, int plane, int dsty) { Plane *p = &s->plane[plane]; int x, dstx = p->xbsep - p->xoffset; block_mc(s, block, mctmp, s->obmc_weight[0], plane, -p->xoffset, dsty); mctmp += p->xbsep; for (x = 1; x < s->blwidth-1; x++) { block_mc(s, block+x, mctmp, s->obmc_weight[1], plane, dstx, dsty); dstx += p->xbsep; mctmp += p->xbsep; } block_mc(s, block+x, mctmp, s->obmc_weight[2], plane, dstx, dsty); } static void select_dsp_funcs(DiracContext *s, int width, int height, int xblen, int yblen) { int idx = 0; if (xblen > 8) idx = 1; if (xblen > 16) idx = 2; memcpy(s->put_pixels_tab, s->diracdsp.put_dirac_pixels_tab[idx], sizeof(s->put_pixels_tab)); memcpy(s->avg_pixels_tab, s->diracdsp.avg_dirac_pixels_tab[idx], sizeof(s->avg_pixels_tab)); s->add_obmc = s->diracdsp.add_dirac_obmc[idx]; if (s->weight_log2denom > 1 || s->weight[0] != 1 || s->weight[1] != 1) { s->weight_func = s->diracdsp.weight_dirac_pixels_tab[idx]; s->biweight_func = s->diracdsp.biweight_dirac_pixels_tab[idx]; } else { s->weight_func = NULL; s->biweight_func = NULL; } } static void interpolate_refplane(DiracContext *s, DiracFrame *ref, int plane, int width, int height) { /* chroma allocates an edge of 8 when subsampled which for 4:2:2 means an h edge of 16 and v edge of 8 just use 8 for everything for the moment */ int i, edge = EDGE_WIDTH/2; ref->hpel[plane][0] = ref->avframe.data[plane]; s->dsp.draw_edges(ref->hpel[plane][0], ref->avframe.linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM); /* EDGE_TOP | EDGE_BOTTOM values just copied to make it build, this needs to be ensured */ /* no need for hpel if we only have fpel vectors */ if (!s->mv_precision) return; for (i = 1; i < 4; i++) { if (!ref->hpel_base[plane][i]) ref->hpel_base[plane][i] = av_malloc((height+2*edge) * ref->avframe.linesize[plane] + 32); /* we need to be 16-byte aligned even for chroma */ ref->hpel[plane][i] = ref->hpel_base[plane][i] + edge*ref->avframe.linesize[plane] + 16; } if (!ref->interpolated[plane]) { s->diracdsp.dirac_hpel_filter(ref->hpel[plane][1], ref->hpel[plane][2], ref->hpel[plane][3], ref->hpel[plane][0], ref->avframe.linesize[plane], width, height); s->dsp.draw_edges(ref->hpel[plane][1], ref->avframe.linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM); s->dsp.draw_edges(ref->hpel[plane][2], ref->avframe.linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM); s->dsp.draw_edges(ref->hpel[plane][3], ref->avframe.linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM); } ref->interpolated[plane] = 1; } /** * Dirac Specification -> * 13.0 Transform data syntax. transform_data() */ static int dirac_decode_frame_internal(DiracContext *s) { DWTContext d; int y, i, comp, dsty; if (s->low_delay) { /* [DIRAC_STD] 13.5.1 low_delay_transform_data() */ for (comp = 0; comp < 3; comp++) { Plane *p = &s->plane[comp]; memset(p->idwt_buf, 0, p->idwt_stride * p->idwt_height * sizeof(IDWTELEM)); } if (!s->zero_res) decode_lowdelay(s); } for (comp = 0; comp < 3; comp++) { Plane *p = &s->plane[comp]; uint8_t *frame = s->current_picture->avframe.data[comp]; /* FIXME: small resolutions */ for (i = 0; i < 4; i++) s->edge_emu_buffer[i] = s->edge_emu_buffer_base + i*FFALIGN(p->width, 16); if (!s->zero_res && !s->low_delay) { memset(p->idwt_buf, 0, p->idwt_stride * p->idwt_height * sizeof(IDWTELEM)); decode_component(s, comp); /* [DIRAC_STD] 13.4.1 core_transform_data() */ } if (ff_spatial_idwt_init2(&d, p->idwt_buf, p->idwt_width, p->idwt_height, p->idwt_stride, s->wavelet_idx+2, s->wavelet_depth, p->idwt_tmp)) return -1; if (!s->num_refs) { /* intra */ for (y = 0; y < p->height; y += 16) { ff_spatial_idwt_slice2(&d, y+16); /* decode */ s->diracdsp.put_signed_rect_clamped(frame + y*p->stride, p->stride, p->idwt_buf + y*p->idwt_stride, p->idwt_stride, p->width, 16); } } else { /* inter */ int rowheight = p->ybsep*p->stride; select_dsp_funcs(s, p->width, p->height, p->xblen, p->yblen); for (i = 0; i < s->num_refs; i++) interpolate_refplane(s, s->ref_pics[i], comp, p->width, p->height); memset(s->mctmp, 0, 4*p->yoffset*p->stride); dsty = -p->yoffset; for (y = 0; y < s->blheight; y++) { int h = 0, start = FFMAX(dsty, 0); uint16_t *mctmp = s->mctmp + y*rowheight; DiracBlock *blocks = s->blmotion + y*s->blwidth; init_obmc_weights(s, p, y); if (y == s->blheight-1 || start+p->ybsep > p->height) h = p->height - start; else h = p->ybsep - (start - dsty); if (h < 0) break; memset(mctmp+2*p->yoffset*p->stride, 0, 2*rowheight); mc_row(s, blocks, mctmp, comp, dsty); mctmp += (start - dsty)*p->stride + p->xoffset; ff_spatial_idwt_slice2(&d, start + h); /* decode */ s->diracdsp.add_rect_clamped(frame + start*p->stride, mctmp, p->stride, p->idwt_buf + start*p->idwt_stride, p->idwt_stride, p->width, h); dsty += p->ybsep; } } } return 0; } /** * Dirac Specification -> * 11.1.1 Picture Header. picture_header() */ static int dirac_decode_picture_header(DiracContext *s) { int retire, picnum; int i, j, refnum, refdist; GetBitContext *gb = &s->gb; /* [DIRAC_STD] 11.1.1 Picture Header. picture_header() PICTURE_NUM */ picnum = s->current_picture->avframe.display_picture_number = get_bits_long(gb, 32); av_log(s->avctx,AV_LOG_DEBUG,"PICTURE_NUM: %d\n",picnum); /* if this is the first keyframe after a sequence header, start our reordering from here */ if (s->frame_number < 0) s->frame_number = picnum; s->ref_pics[0] = s->ref_pics[1] = NULL; for (i = 0; i < s->num_refs; i++) { refnum = picnum + dirac_get_se_golomb(gb); refdist = INT_MAX; /* find the closest reference to the one we want */ /* Jordi: this is needed if the referenced picture hasn't yet arrived */ for (j = 0; j < MAX_REFERENCE_FRAMES && refdist; j++) if (s->ref_frames[j] && FFABS(s->ref_frames[j]->avframe.display_picture_number - refnum) < refdist) { s->ref_pics[i] = s->ref_frames[j]; refdist = FFABS(s->ref_frames[j]->avframe.display_picture_number - refnum); } if (!s->ref_pics[i] || refdist) av_log(s->avctx, AV_LOG_DEBUG, "Reference not found\n"); /* if there were no references at all, allocate one */ if (!s->ref_pics[i]) for (j = 0; j < MAX_FRAMES; j++) if (!s->all_frames[j].avframe.data[0]) { s->ref_pics[i] = &s->all_frames[j]; s->avctx->get_buffer(s->avctx, &s->ref_pics[i]->avframe); break; } } /* retire the reference frames that are not used anymore */ if (s->current_picture->avframe.reference) { retire = picnum + dirac_get_se_golomb(gb); if (retire != picnum) { DiracFrame *retire_pic = remove_frame(s->ref_frames, retire); if (retire_pic) retire_pic->avframe.reference &= DELAYED_PIC_REF; else av_log(s->avctx, AV_LOG_DEBUG, "Frame to retire not found\n"); } /* if reference array is full, remove the oldest as per the spec */ while (add_frame(s->ref_frames, MAX_REFERENCE_FRAMES, s->current_picture)) { av_log(s->avctx, AV_LOG_ERROR, "Reference frame overflow\n"); remove_frame(s->ref_frames, s->ref_frames[0]->avframe.display_picture_number)->avframe.reference &= DELAYED_PIC_REF; } } if (s->num_refs) { if (dirac_unpack_prediction_parameters(s)) /* [DIRAC_STD] 11.2 Picture Prediction Data. picture_prediction() */ return -1; if (dirac_unpack_block_motion_data(s)) /* [DIRAC_STD] 12. Block motion data syntax */ return -1; } if (dirac_unpack_idwt_params(s)) /* [DIRAC_STD] 11.3 Wavelet transform data */ return -1; init_planes(s); return 0; } static int get_delayed_pic(DiracContext *s, AVFrame *picture, int *data_size) { DiracFrame *out = s->delay_frames[0]; int i, out_idx = 0; /* find frame with lowest picture number */ for (i = 1; s->delay_frames[i]; i++) if (s->delay_frames[i]->avframe.display_picture_number < out->avframe.display_picture_number) { out = s->delay_frames[i]; out_idx = i; } for (i = out_idx; s->delay_frames[i]; i++) s->delay_frames[i] = s->delay_frames[i+1]; if (out) { out->avframe.reference ^= DELAYED_PIC_REF; *data_size = sizeof(AVFrame); *(AVFrame *)picture = out->avframe; } return 0; } /** * Dirac Specification -> * 9.6 Parse Info Header Syntax. parse_info() * 4 byte start code + byte parse code + 4 byte size + 4 byte previous size */ #define DATA_UNIT_HEADER_SIZE 13 /* [DIRAC_STD] dirac_decode_data_unit makes reference to the while defined in 9.3 inside the function parse_sequence() */ static int dirac_decode_data_unit(AVCodecContext *avctx, const uint8_t *buf, int size) { DiracContext *s = avctx->priv_data; DiracFrame *pic = NULL; int i, parse_code = buf[4]; unsigned tmp; if (size < DATA_UNIT_HEADER_SIZE) return -1; init_get_bits(&s->gb, &buf[13], 8*(size - DATA_UNIT_HEADER_SIZE)); if (parse_code == pc_seq_header) { if (s->seen_sequence_header) return 0; /* [DIRAC_STD] 10. Sequence header */ if (avpriv_dirac_parse_sequence_header(avctx, &s->gb, &s->source)) return -1; avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift); if (alloc_sequence_buffers(s)) return -1; s->seen_sequence_header = 1; } else if (parse_code == pc_eos) { /* [DIRAC_STD] End of Sequence */ free_sequence_buffers(s); s->seen_sequence_header = 0; } else if (parse_code == pc_aux_data) { if (buf[13] == 1) { /* encoder implementation/version */ int ver[3]; /* versions older than 1.0.8 don't store quant delta for subbands with only one codeblock */ if (sscanf(buf+14, "Schroedinger %d.%d.%d", ver, ver+1, ver+2) == 3) if (ver[0] == 1 && ver[1] == 0 && ver[2] <= 7) s->old_delta_quant = 1; } } else if (parse_code & 0x8) { /* picture data unit */ if (!s->seen_sequence_header) { av_log(avctx, AV_LOG_DEBUG, "Dropping frame without sequence header\n"); return -1; } /* find an unused frame */ for (i = 0; i < MAX_FRAMES; i++) if (s->all_frames[i].avframe.data[0] == NULL) pic = &s->all_frames[i]; if (!pic) { av_log(avctx, AV_LOG_ERROR, "framelist full\n"); return -1; } avcodec_get_frame_defaults(&pic->avframe); /* [DIRAC_STD] Defined in 9.6.1 ... */ tmp = parse_code & 0x03; /* [DIRAC_STD] num_refs() */ if (tmp > 2) { av_log(avctx, AV_LOG_ERROR, "num_refs of 3\n"); return -1; } s->num_refs = tmp; s->is_arith = (parse_code & 0x48) == 0x08; /* [DIRAC_STD] using_ac() */ s->low_delay = (parse_code & 0x88) == 0x88; /* [DIRAC_STD] is_low_delay() */ pic->avframe.reference = (parse_code & 0x0C) == 0x0C; /* [DIRAC_STD] is_reference() */ pic->avframe.key_frame = s->num_refs == 0; /* [DIRAC_STD] is_intra() */ pic->avframe.pict_type = s->num_refs + 1; /* Definition of AVPictureType in avutil.h */ if (avctx->get_buffer(avctx, &pic->avframe) < 0) { av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); return -1; } s->current_picture = pic; s->plane[0].stride = pic->avframe.linesize[0]; s->plane[1].stride = pic->avframe.linesize[1]; s->plane[2].stride = pic->avframe.linesize[2]; /* [DIRAC_STD] 11.1 Picture parse. picture_parse() */ if (dirac_decode_picture_header(s)) return -1; /* [DIRAC_STD] 13.0 Transform data syntax. transform_data() */ if (dirac_decode_frame_internal(s)) return -1; } return 0; } static int dirac_decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *pkt) { DiracContext *s = avctx->priv_data; DiracFrame *picture = data; uint8_t *buf = pkt->data; int buf_size = pkt->size; int i, data_unit_size, buf_idx = 0; /* release unused frames */ for (i = 0; i < MAX_FRAMES; i++) if (s->all_frames[i].avframe.data[0] && !s->all_frames[i].avframe.reference) { avctx->release_buffer(avctx, &s->all_frames[i].avframe); memset(s->all_frames[i].interpolated, 0, sizeof(s->all_frames[i].interpolated)); } s->current_picture = NULL; *data_size = 0; /* end of stream, so flush delayed pics */ if (buf_size == 0) return get_delayed_pic(s, (AVFrame *)data, data_size); for (;;) { /*[DIRAC_STD] Here starts the code from parse_info() defined in 9.6 [DIRAC_STD] PARSE_INFO_PREFIX = "BBCD" as defined in ISO/IEC 646 BBCD start code search */ for (; buf_idx + DATA_UNIT_HEADER_SIZE < buf_size; buf_idx++) { if (buf[buf_idx ] == 'B' && buf[buf_idx+1] == 'B' && buf[buf_idx+2] == 'C' && buf[buf_idx+3] == 'D') break; } /* BBCD found or end of data */ if (buf_idx + DATA_UNIT_HEADER_SIZE >= buf_size) break; data_unit_size = AV_RB32(buf+buf_idx+5); if (buf_idx + data_unit_size > buf_size || !data_unit_size) { if(buf_idx + data_unit_size > buf_size) av_log(s->avctx, AV_LOG_ERROR, "Data unit with size %d is larger than input buffer, discarding\n", data_unit_size); buf_idx += 4; continue; } /* [DIRAC_STD] dirac_decode_data_unit makes reference to the while defined in 9.3 inside the function parse_sequence() */ if (dirac_decode_data_unit(avctx, buf+buf_idx, data_unit_size)) { av_log(s->avctx, AV_LOG_ERROR,"Error in dirac_decode_data_unit\n"); return -1; } buf_idx += data_unit_size; } if (!s->current_picture) return buf_size; if (s->current_picture->avframe.display_picture_number > s->frame_number) { DiracFrame *delayed_frame = remove_frame(s->delay_frames, s->frame_number); s->current_picture->avframe.reference |= DELAYED_PIC_REF; if (add_frame(s->delay_frames, MAX_DELAY, s->current_picture)) { int min_num = s->delay_frames[0]->avframe.display_picture_number; /* Too many delayed frames, so we display the frame with the lowest pts */ av_log(avctx, AV_LOG_ERROR, "Delay frame overflow\n"); delayed_frame = s->delay_frames[0]; for (i = 1; s->delay_frames[i]; i++) if (s->delay_frames[i]->avframe.display_picture_number < min_num) min_num = s->delay_frames[i]->avframe.display_picture_number; delayed_frame = remove_frame(s->delay_frames, min_num); add_frame(s->delay_frames, MAX_DELAY, s->current_picture); } if (delayed_frame) { delayed_frame->avframe.reference ^= DELAYED_PIC_REF; *(AVFrame*)data = delayed_frame->avframe; *data_size = sizeof(AVFrame); } } else if (s->current_picture->avframe.display_picture_number == s->frame_number) { /* The right frame at the right time :-) */ *(AVFrame*)data = s->current_picture->avframe; *data_size = sizeof(AVFrame); } if (*data_size) s->frame_number = picture->avframe.display_picture_number + 1; return buf_idx; } AVCodec ff_dirac_decoder = { .name = "dirac", .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_DIRAC, .priv_data_size = sizeof(DiracContext), .init = dirac_decode_init, .close = dirac_decode_end, .decode = dirac_decode_frame, .capabilities = CODEC_CAP_DELAY, .flush = dirac_decode_flush, .long_name = NULL_IF_CONFIG_SMALL("BBC Dirac VC-2"), };
svn2github/MPlayer-SB
ffmpeg/libavcodec/diracdec.c
C
gpl-2.0
67,639
using System; using System.Collections.Generic; using System.Text; using Server.Commands; using Server.Gumps; using Server.Items; using Server.Network; using Server.Prompts; using System.IO; using Server.Engines.CityLoyalty; using Server.ContextMenus; using Server.Services.TownCryer; namespace Server.Mobiles { public interface ITownCrierEntryList { List<TownCrierEntry> Entries { get; } TownCrierEntry GetRandomEntry(); TownCrierEntry AddEntry(string[] lines, TimeSpan duration); void RemoveEntry(TownCrierEntry entry); } public class GlobalTownCrierEntryList : ITownCrierEntryList { private static GlobalTownCrierEntryList m_Instance; private List<TownCrierEntry> m_Entries; public GlobalTownCrierEntryList() { } public static GlobalTownCrierEntryList Instance { get { if (m_Instance == null) m_Instance = new GlobalTownCrierEntryList(); return m_Instance; } } public bool IsEmpty { get { return (m_Entries == null || m_Entries.Count == 0); } } public List<TownCrierEntry> Entries { get { return m_Entries; } } public static void Initialize() { CommandSystem.Register("TownCriers", AccessLevel.GameMaster, new CommandEventHandler(TownCriers_OnCommand)); } [Usage("TownCriers")] [Description("Manages the global town crier list.")] public static void TownCriers_OnCommand(CommandEventArgs e) { e.Mobile.SendGump(new TownCrierGump(e.Mobile, Instance)); } public TownCrierEntry GetRandomEntry() { if (m_Entries == null || m_Entries.Count == 0) return null; for (int i = m_Entries.Count - 1; m_Entries != null && i >= 0; --i) { if (i >= m_Entries.Count) continue; TownCrierEntry tce = m_Entries[i]; if (tce.Expired) RemoveEntry(tce); } if (m_Entries == null || m_Entries.Count == 0) return null; return m_Entries[Utility.Random(m_Entries.Count)]; } public TownCrierEntry AddEntry(string[] lines, TimeSpan duration) { if (m_Entries == null) m_Entries = new List<TownCrierEntry>(); TownCrierEntry tce = new TownCrierEntry(lines, duration); m_Entries.Add(tce); List<TownCrier> instances = TownCrier.Instances; for (int i = 0; i < instances.Count; ++i) instances[i].ForceBeginAutoShout(); return tce; } public void AddEntry(TownCrierEntry entry) { if (m_Entries == null) m_Entries = new List<TownCrierEntry>(); m_Entries.Add(entry); List<TownCrier> instances = TownCrier.Instances; for (int i = 0; i < instances.Count; ++i) instances[i].ForceBeginAutoShout(); } public void RemoveEntry(TownCrierEntry tce) { if (m_Entries == null) return; m_Entries.Remove(tce); if (m_Entries.Count == 0) m_Entries = null; } #region Serialization public static string FilePath = Path.Combine("Saves/Misc", "TownCrierGlobalEntries.bin"); public static void Configure() { EventSink.WorldSave += OnSave; EventSink.WorldLoad += OnLoad; } public static void OnSave(WorldSaveEventArgs e) { Persistence.Serialize( FilePath, writer => { writer.Write(1); TownCryerSystem.Save(writer); writer.Write(Instance.Entries == null ? 0 : Instance.Entries.Count); if (Instance.Entries != null) { Instance.Entries.ForEach(entry => entry.Serialize(writer)); } }); } public static void OnLoad() { Persistence.Deserialize( FilePath, reader => { int version = reader.ReadInt(); switch (version) { case 1: { TownCryerSystem.Load(reader); goto case 0; } case 0: { int count = reader.ReadInt(); for (int i = 0; i < count; i++) { var entry = new TownCrierEntry(reader); if (!entry.Expired) { Instance.AddEntry(entry); } } } break; } }); } #endregion } public class TownCrierEntry { private readonly string[] m_Lines; private readonly DateTime m_ExpireTime; public TownCrierEntry(string[] lines, TimeSpan duration) { m_Lines = lines; if (duration < TimeSpan.Zero) duration = TimeSpan.Zero; else if (duration > TimeSpan.FromDays(365.0)) duration = TimeSpan.FromDays(365.0); m_ExpireTime = DateTime.UtcNow + duration; } public string[] Lines { get { return m_Lines; } } public DateTime ExpireTime { get { return m_ExpireTime; } } public bool Expired { get { return (DateTime.UtcNow >= m_ExpireTime); } } public TownCrierEntry(GenericReader reader) { int version = reader.ReadInt(); int count = reader.ReadInt(); m_Lines = new string[count]; for (int i = 0; i < count; i++) { m_Lines[i] = reader.ReadString(); } m_ExpireTime = reader.ReadDateTime(); } public void Serialize(GenericWriter writer) { writer.Write(0); writer.Write(Lines.Length); foreach (var str in Lines) { writer.Write(str); } writer.Write(m_ExpireTime); } } public class TownCrierDurationPrompt : Prompt { private readonly ITownCrierEntryList m_Owner; public TownCrierDurationPrompt(ITownCrierEntryList owner) { m_Owner = owner; } public override void OnResponse(Mobile from, string text) { TimeSpan ts; if (!TimeSpan.TryParse(text, out ts)) { from.SendMessage("Value was not properly formatted. Use: <hours:minutes:seconds>"); from.SendGump(new TownCrierGump(from, m_Owner)); return; } if (ts < TimeSpan.Zero) ts = TimeSpan.Zero; from.SendMessage("Duration set to: {0}", ts); from.SendMessage("Enter the first line to shout:"); from.Prompt = new TownCrierLinesPrompt(m_Owner, null, new List<String>(), ts); } public override void OnCancel(Mobile from) { from.SendLocalizedMessage(502980); // Message entry cancelled. from.SendGump(new TownCrierGump(from, m_Owner)); } } public class TownCrierLinesPrompt : Prompt { private readonly ITownCrierEntryList m_Owner; private readonly TownCrierEntry m_Entry; private readonly List<String> m_Lines; private readonly TimeSpan m_Duration; public TownCrierLinesPrompt(ITownCrierEntryList owner, TownCrierEntry entry, List<String> lines, TimeSpan duration) { m_Owner = owner; m_Entry = entry; m_Lines = lines; m_Duration = duration; } public override void OnResponse(Mobile from, string text) { m_Lines.Add(text); from.SendMessage("Enter the next line to shout, or press <ESC> if the message is finished."); from.Prompt = new TownCrierLinesPrompt(m_Owner, m_Entry, m_Lines, m_Duration); } public override void OnCancel(Mobile from) { if (m_Entry != null) m_Owner.RemoveEntry(m_Entry); if (m_Lines.Count > 0) { m_Owner.AddEntry(m_Lines.ToArray(), m_Duration); from.SendMessage("Message has been set."); } else { if (m_Entry != null) from.SendMessage("Message deleted."); else from.SendLocalizedMessage(502980); // Message entry cancelled. } from.SendGump(new TownCrierGump(from, m_Owner)); } } public class TownCrierGump : Gump { private readonly Mobile m_From; private readonly ITownCrierEntryList m_Owner; public TownCrierGump(Mobile from, ITownCrierEntryList owner) : base(50, 50) { m_From = from; m_Owner = owner; from.CloseGump(typeof(TownCrierGump)); AddPage(0); List<TownCrierEntry> entries = owner.Entries; owner.GetRandomEntry(); // force expiration checks int count = 0; if (entries != null) count = entries.Count; AddImageTiled(0, 0, 300, 38 + (count == 0 ? 20 : (count * 85)), 0xA40); AddAlphaRegion(1, 1, 298, 36 + (count == 0 ? 20 : (count * 85))); if (owner is GlobalTownCrierEntryList) { AddHtml(8, 8, 300 - 8 - 30, 20, "<basefont color=#FFFFFF><center>GLOBAL TOWN CRIER MESSAGES</center></basefont>", false, false); } else { AddHtml(8, 8, 300 - 8 - 30, 20, "<basefont color=#FFFFFF><center>TOWN CRIER MESSAGES</center></basefont>", false, false); } AddButton(300 - 8 - 30, 8, 0xFAB, 0xFAD, 1, GumpButtonType.Reply, 0); AddTooltip(3000161); // New Message if (count == 0) { AddHtml(8, 30, 284, 20, "<basefont color=#FFFFFF>The crier has no news.</basefont>", false, false); } else { for (int i = 0; i < entries.Count; ++i) { TownCrierEntry tce = (TownCrierEntry)entries[i]; TimeSpan toExpire = tce.ExpireTime - DateTime.UtcNow; if (toExpire < TimeSpan.Zero) toExpire = TimeSpan.Zero; StringBuilder sb = new StringBuilder(); sb.Append("[Expires: "); if (toExpire.TotalHours >= 1) { sb.Append((int)toExpire.TotalHours); sb.Append(':'); sb.Append(toExpire.Minutes.ToString("D2")); } else { sb.Append(toExpire.Minutes); } sb.Append(':'); sb.Append(toExpire.Seconds.ToString("D2")); sb.Append("] "); for (int j = 0; j < tce.Lines.Length; ++j) { if (j > 0) sb.Append("<br>"); sb.Append(tce.Lines[j]); } AddHtml(8, 35 + (i * 85), 254, 80, sb.ToString(), true, true); AddButton(300 - 8 - 26, 35 + (i * 85), 0x15E1, 0x15E5, 2 + i, GumpButtonType.Reply, 0); AddTooltip(3005101); // Edit } } } public override void OnResponse(NetState sender, RelayInfo info) { if (info.ButtonID == 1) { m_From.SendMessage("Enter the duration for the new message. Format: <hours:minutes:seconds>"); m_From.Prompt = new TownCrierDurationPrompt(m_Owner); } else if (info.ButtonID > 1) { List<TownCrierEntry> entries = m_Owner.Entries; int index = info.ButtonID - 2; if (entries != null && index < entries.Count) { TownCrierEntry tce = entries[index]; TimeSpan ts = tce.ExpireTime - DateTime.UtcNow; if (ts < TimeSpan.Zero) ts = TimeSpan.Zero; m_From.SendMessage("Editing entry #{0}.", index + 1); m_From.SendMessage("Push <ESC> to delete this entry."); m_From.SendMessage("Enter the first line to shout:"); m_From.Prompt = new TownCrierLinesPrompt(m_Owner, tce, new List<String>(), ts); } } } } public class TownCrier : Mobile, ITownCrierEntryList { private static readonly List<TownCrier> m_Instances = new List<TownCrier>(); private List<TownCrierEntry> m_Entries; private Timer m_NewsTimer; private Timer m_AutoShoutTimer; [Constructable] public TownCrier() { m_Instances.Add(this); InitStats(100, 100, 25); Title = "the town crier"; Hue = Utility.RandomSkinHue(); if (!Core.AOS) NameHue = 0x35; if (Female = Utility.RandomBool()) { Body = 0x191; Name = NameList.RandomName("female"); } else { Body = 0x190; Name = NameList.RandomName("male"); } AddItem(new FancyShirt(Utility.RandomBlueHue())); Item skirt; switch ( Utility.Random(2) ) { case 0: skirt = new Skirt(); break; default: case 1: skirt = new Kilt(); break; } skirt.Hue = Utility.RandomGreenHue(); AddItem(skirt); AddItem(new FeatheredHat(Utility.RandomGreenHue())); Item boots; switch ( Utility.Random(2) ) { case 0: boots = new Boots(); break; default: case 1: boots = new ThighBoots(); break; } AddItem(boots); Utility.AssignRandomHair(this); } public TownCrier(Serial serial) : base(serial) { m_Instances.Add(this); } public static List<TownCrier> Instances { get { return m_Instances; } } public List<TownCrierEntry> Entries { get { return m_Entries; } } public TownCrierEntry GetRandomEntry() { if (m_Entries == null || m_Entries.Count == 0) return GlobalTownCrierEntryList.Instance.GetRandomEntry(); for (int i = m_Entries.Count - 1; m_Entries != null && i >= 0; --i) { if (i >= m_Entries.Count) continue; TownCrierEntry tce = m_Entries[i]; if (tce.Expired) RemoveEntry(tce); } if (m_Entries == null || m_Entries.Count == 0) return GlobalTownCrierEntryList.Instance.GetRandomEntry(); TownCrierEntry entry = GlobalTownCrierEntryList.Instance.GetRandomEntry(); if (entry == null || Utility.RandomBool()) entry = m_Entries[Utility.Random(m_Entries.Count)]; return entry; } public void ForceBeginAutoShout() { if (m_AutoShoutTimer == null) m_AutoShoutTimer = Timer.DelayCall(TimeSpan.FromSeconds(5.0), TimeSpan.FromMinutes(1.0), new TimerCallback(AutoShout_Callback)); } public TownCrierEntry AddEntry(string[] lines, TimeSpan duration) { if (m_Entries == null) m_Entries = new List<TownCrierEntry>(); TownCrierEntry tce = new TownCrierEntry(lines, duration); m_Entries.Add(tce); if (m_AutoShoutTimer == null) m_AutoShoutTimer = Timer.DelayCall(TimeSpan.FromSeconds(5.0), TimeSpan.FromMinutes(1.0), new TimerCallback(AutoShout_Callback)); return tce; } public void AddEntry(TownCrierEntry entry) { if (m_Entries == null) m_Entries = new List<TownCrierEntry>(); m_Entries.Add(entry); if (m_AutoShoutTimer == null) m_AutoShoutTimer = Timer.DelayCall(TimeSpan.FromSeconds(5.0), TimeSpan.FromMinutes(1.0), new TimerCallback(AutoShout_Callback)); } public void RemoveEntry(TownCrierEntry tce) { if (m_Entries == null) return; m_Entries.Remove(tce); if (m_Entries.Count == 0) m_Entries = null; if (m_Entries == null && GlobalTownCrierEntryList.Instance.IsEmpty) { if (m_AutoShoutTimer != null) m_AutoShoutTimer.Stop(); m_AutoShoutTimer = null; } } public override void OnDoubleClick(Mobile from) { if (from is PlayerMobile && TownCryerSystem.Enabled) { BaseGump.SendGump(new TownCryerGump((PlayerMobile)from, this)); } if (from.AccessLevel >= AccessLevel.GameMaster) { from.SendGump(new TownCrierGump(from, this)); } else { base.OnDoubleClick(from); } } public override void GetContextMenuEntries(Mobile from, List<ContextMenuEntry> list) { base.GetContextMenuEntries(from, list); if (TownCryerSystem.Enabled) { TownCryerSystem.GetContextMenus(this, from, list); } } public override bool HandlesOnSpeech(Mobile from) { return (m_NewsTimer == null && from.Alive && InRange(from, 12)); } public override void OnSpeech(SpeechEventArgs e) { if (m_NewsTimer == null && e.HasKeyword(0x30) && e.Mobile.Alive && InRange(e.Mobile, 12)) // *news* { Direction = GetDirectionTo(e.Mobile); TownCrierEntry tce = GetRandomEntry(); if (tce == null) { PublicOverheadMessage(MessageType.Regular, 0x3B2, 1005643); // I have no news at this time. } else { m_NewsTimer = Timer.DelayCall(TimeSpan.FromSeconds(1.0), TimeSpan.FromSeconds(3.0), new TimerStateCallback(ShoutNews_Callback), new object[] { tce, 0 }); PublicOverheadMessage(MessageType.Regular, 0x3B2, 502978); // Some of the latest news! } if (e.Mobile is PlayerMobile && TownCryerSystem.Enabled) { BaseGump.SendGump(new TownCryerGump((PlayerMobile)e.Mobile, this)); } } } public override bool CanBeDamaged() { return false; } public override void OnDelete() { m_Instances.Remove(this); base.OnDelete(); } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)1); // version writer.Write(m_Entries == null ? 0 : m_Entries.Count); if (m_Entries != null) { m_Entries.ForEach(e => e.Serialize(writer)); } } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); switch (version) { case 1: { int count = reader.ReadInt(); for (int i = 0; i < count; i++) { var entry = new TownCrierEntry(reader); if (!entry.Expired) { AddEntry(entry); } } break; } } if (Core.AOS && NameHue == 0x35) NameHue = -1; } private void AutoShout_Callback() { TownCrierEntry tce = GetRandomEntry(); if (tce == null) { if (m_AutoShoutTimer != null) m_AutoShoutTimer.Stop(); m_AutoShoutTimer = null; } else if (m_NewsTimer == null) { m_NewsTimer = Timer.DelayCall(TimeSpan.FromSeconds(1.0), TimeSpan.FromSeconds(3.0), new TimerStateCallback(ShoutNews_Callback), new object[] { tce, 0 }); PublicOverheadMessage(MessageType.Regular, 0x3B2, 502976); // Hear ye! Hear ye! } } private void ShoutNews_Callback(object state) { object[] states = (object[])state; TownCrierEntry tce = (TownCrierEntry)states[0]; int index = (int)states[1]; if (index < 0 || index >= tce.Lines.Length) { if (m_NewsTimer != null) m_NewsTimer.Stop(); m_NewsTimer = null; } else { PublicOverheadMessage(MessageType.Regular, 0x3B2, false, tce.Lines[index]); states[1] = index + 1; } } } }
Frazurbluu/ServUO
Scripts/Mobiles/NPCs/TownCrier.cs
C#
gpl-2.0
23,076
package com.yh.hr.res.pt.queryhelper; import com.yh.hr.res.pt.bo.PtEducationTrainingInfo; import com.yh.hr.res.pt.dto.PtEducationTrainingInfoDTO; import jade.workflow.utils.ObjectUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; import com.yh.component.taglib.TableTagBean; import com.yh.platform.core.dao.DaoUtil; import com.yh.platform.core.exception.ServiceException; import com.yh.platform.core.util.BeanHelper; import com.yh.platform.core.util.StringMap; /** * @desc 教育培训业务信息查询工具类 * @author liul * @createDate 2017-2-17 */ public class PtEducationTrainingInfoQueryHelper { public static List<PtEducationTrainingInfoDTO> list(TableTagBean ttb) throws ServiceException { StringBuilder hql = new StringBuilder(); HashMap<String, Object> hqlParams = new HashMap<String, Object>(); buildHQL(ttb.getCondition(), hql, hqlParams); String order = ttb.getOrderBy(); if (order != null) { if (ttb.getAsc()) { hql.append(" order by " + order + " asc"); } else { hql.append(" order by " + order + " desc"); } }else{ //教育培训信息默认排序,起始时间倒序 hql.append(" order by trainingBeginDate desc "); } List<PtEducationTrainingInfo> list = DaoUtil.listByCondition(hql.toString(), hqlParams, ttb.getPage() * ttb.getPageSize(), ttb.getPageSize()); List<PtEducationTrainingInfoDTO> listDTO = new ArrayList<PtEducationTrainingInfoDTO>(); for(PtEducationTrainingInfo bo: list){ PtEducationTrainingInfoDTO dto = new PtEducationTrainingInfoDTO(); BeanHelper.copyProperties(bo, dto); listDTO.add(dto); } ttb.setList(listDTO); ttb.setTotal(DaoUtil.countByCondition("select count(*) "+hql, hqlParams)); return listDTO; } private static void buildHQL(StringMap params, StringBuilder hql, HashMap<String, Object> hqlParams) throws ServiceException { hql.append("from PtEducationTrainingInfo where 1=1"); String bizPersonOid = params.getAsStringEmptyNull("bizPersonOid"); if (bizPersonOid != null){ hql.append(" and bizPersonOid = :bizPersonOid"); try{ hqlParams.put("bizPersonOid", ObjectUtil.getValue(bizPersonOid, java.lang.Long.class)); } catch (jade.workflow.exception.ServiceException e) { e.printStackTrace(); } } String educationTrainingKinkCode = params.getAsStringEmptyNull("educationTrainingKinkCode"); if (educationTrainingKinkCode != null){ hql.append(" and educationTrainingKinkCode like :educationTrainingKinkCode"); hqlParams.put("educationTrainingKinkCode", "%"+educationTrainingKinkCode.trim()+"%"); } String trainingStatus = params.getAsStringEmptyNull("trainingStatus"); if (trainingStatus != null){ hql.append(" and trainingStatus like :trainingStatus"); hqlParams.put("trainingStatus", "%"+trainingStatus.trim()+"%"); } String trainingUnitName = params.getAsStringEmptyNull("trainingUnitName"); if (trainingUnitName != null){ hql.append(" and trainingUnitName like :trainingUnitName"); hqlParams.put("trainingUnitName", "%"+trainingUnitName.trim()+"%"); } } /** * 通过业务人员OID查找该人员的教育培训业务信息 * @param bizPersonOid * @return * @throws ServiceException */ public static List<PtEducationTrainingInfoDTO> listPtEducationTrainingInfoByBizPersonOid(Long bizPersonOid) throws ServiceException { String hql = "from PtEducationTrainingInfo ei where ei.bizPersonOid = :bizPersonOid order by ei.trainingBeginDate desc"; Map<String, Object> params = new HashMap<String, Object>(); params.put("bizPersonOid", bizPersonOid); List<PtEducationTrainingInfo> boList = DaoUtil.find(hql, params); List<PtEducationTrainingInfoDTO> dtoList = new ArrayList<PtEducationTrainingInfoDTO>(); if(CollectionUtils.isNotEmpty(boList)) { dtoList = BeanHelper.copyProperties(boList, PtEducationTrainingInfoDTO.class); } return dtoList; } /** * 通过基础OID查找该人员的教育培训业务信息 * @param baseEducationTrainingOid * @return * @throws ServiceException */ public static List<PtEducationTrainingInfoDTO> listPtEducationTrainingInfoByBaseEducationTrainingOid(Long baseEducationTrainingOid) throws ServiceException { List<PtEducationTrainingInfo> list = DaoUtil.findByNamed("from PtEducationTrainingInfo ei where ei.baseEducationTrainingOid = :baseEducationTrainingOid order by ei.trainingBeginDate desc", "baseEducationTrainingOid", baseEducationTrainingOid); return BeanHelper.copyProperties(list, PtEducationTrainingInfoDTO.class); } /** * 通过业务人员OID删除该人员的所有教育培训业务信息 * @param bizPersonOid * @throws ServiceException */ public static void deleteByBizPersonOid(Long bizPersonOid) throws ServiceException { DaoUtil.executeUpdate("delete from PtEducationTrainingInfo where bizPersonOid='"+bizPersonOid+"'"); } }
meijmOrg/Repo-test
freelance-hr-res/src/java/com/yh/hr/res/pt/queryhelper/PtEducationTrainingInfoQueryHelper.java
Java
gpl-2.0
5,295
// * This makes emacs happy -*-Mode: C++;-*- #ifndef _CURSESW_H #define _CURSESW_H // $Id: cursesw.h,v 1.1.1.1 2004/03/24 19:53:04 sure Exp $ #include <etip.h> #include <stdio.h> #include <stdarg.h> #ifdef __MWERKS__ /* This is a bogus check, stringstream is actually ANSI C++ standard, * but old compilers like GCC don't have it, and new compilers like Metrowerks * don't have strstream */ #include <sstream> #else #include <strstream.h> #endif extern "C" { # include <curses.h> } /* SCO 3.2v4 curses.h includes term.h, which defines lines as a macro. Undefine it here, because NCursesWindow uses lines as a method. */ #undef lines /* "Convert" macros to inlines. We'll define it as another symbol to avoid * conflict with library symbols. */ #undef UNDEF #define UNDEF(name) CUR_ ##name #ifdef addch inline int UNDEF(addch)(chtype ch) { return addch(ch); } #undef addch #define addch UNDEF(addch) #endif #ifdef echochar inline int UNDEF(echochar)(chtype ch) { return echochar(ch); } #undef echochar #define echochar UNDEF(echochar) #endif #ifdef insdelln inline int UNDEF(insdelln)(int n) { return insdelln(n); } #undef insdelln #define insdelln UNDEF(insdelln) #endif #ifdef addstr /* The (char*) cast is to hack around missing const's */ inline int UNDEF(addstr)(const char * str) { return addstr((char*)str); } #undef addstr #define addstr UNDEF(addstr) #endif #ifdef attron inline int UNDEF(attron)(chtype at) { return attron(at); } #undef attron #define attron UNDEF(attron) #endif #ifdef attroff inline int UNDEF(attroff)(chtype at) { return attroff(at); } #undef attroff #define attroff UNDEF(attroff) #endif #ifdef attrset inline chtype UNDEF(attrset)(chtype at) { return attrset(at); } #undef attrset #define attrset UNDEF(attrset) #endif #ifdef color_set inline chtype UNDEF(color_set)(short p,void* opts) { return color_set(p,opts); } #undef color_set #define color_set UNDEF(color_set) #endif #ifdef border inline int UNDEF(border)(chtype ls, chtype rs, chtype ts, chtype bs, chtype tl, chtype tr, chtype bl, chtype br) { return border(ls,rs,ts,bs,tl,tr,bl,br); } #undef border #define border UNDEF(border) #endif #ifdef box inline int UNDEF(box)(WINDOW *win, int v, int h) { return box(win, v, h); } #undef box #define box UNDEF(box) #endif #ifdef mvwhline inline int UNDEF(mvwhline)(WINDOW *win,int y,int x,chtype c,int n) { return mvwhline(win,y,x,c,n); } #undef mvwhline #define mvwhline UNDEF(mvwhline) #endif #ifdef mvwvline inline int UNDEF(mvwvline)(WINDOW *win,int y,int x,chtype c,int n) { return mvwvline(win,y,x,c,n); } #undef mvwvline #define mvwvline UNDEF(mvwvline) #endif #ifdef clear inline int UNDEF(clear)() { return clear(); } #undef clear #define clear UNDEF(clear) #endif #ifdef clearok inline int UNDEF(clearok)(WINDOW* win, bool bf) { return clearok(win, bf); } #undef clearok #define clearok UNDEF(clearok) #else extern "C" int clearok(WINDOW*, bool); #endif #ifdef clrtobot inline int UNDEF(clrtobot)() { return clrtobot(); } #undef clrtobot #define clrtobot UNDEF(clrtobot) #endif #ifdef clrtoeol inline int UNDEF(clrtoeol)() { return clrtoeol(); } #undef clrtoeol #define clrtoeol UNDEF(clrtoeol) #endif #ifdef delch inline int UNDEF(delch)() { return delch(); } #undef delch #define delch UNDEF(delch) #endif #ifdef deleteln inline int UNDEF(deleteln)() { return deleteln(); } #undef deleteln #define deleteln UNDEF(deleteln) #endif #ifdef erase inline int UNDEF(erase)() { return erase(); } #undef erase #define erase UNDEF(erase) #endif #ifdef flushok inline int UNDEF(flushok)(WINDOW* _win, bool _bf) { return flushok(_win, _bf); } #undef flushok #define flushok UNDEF(flushok) #else #define _no_flushok #endif #ifdef getch inline int UNDEF(getch)() { return getch(); } #undef getch #define getch UNDEF(getch) #endif #ifdef getstr inline int UNDEF(getstr)(char *_str) { return getstr(_str); } #undef getstr #define getstr UNDEF(getstr) #endif #ifdef instr inline int UNDEF(instr)(char *_str) { return instr(_str); } #undef instr #define instr UNDEF(instr) #endif #ifdef innstr inline int UNDEF(innstr)(char *_str, int n) { return innstr(_str,n); } #undef innstr #define innstr UNDEF(innstr) #endif #ifdef mvwinnstr inline int UNDEF(mvwinnstr)(WINDOW *win, int y, int x, char *_str, int n) { return mvwinnstr(win,y,x,_str,n); } #undef mvwinnstr #define mvwinnstr UNDEF(mvwinnstr) #endif #ifdef mvinnstr inline int UNDEF(mvinnstr)(int y, int x, char *_str, int n) { return mvinnstr(y,x,_str,n); } #undef mvinnstr #define mvinnstr UNDEF(mvinnstr) #endif #ifdef winsstr inline int UNDEF(winsstr)(WINDOW *w, const char *_str) { return winsstr(w,_str); } #undef winsstr #define winsstr UNDEF(winsstr) #endif #ifdef mvwinsstr inline int UNDEF(mvwinsstr)(WINDOW *w, int y, int x, const char *_str) { return mvwinsstr(w,y,x,_str); } #undef mvwinsstr #define mvwinsstr UNDEF(mvwinsstr) #endif #ifdef insstr inline int UNDEF(insstr)(const char *_str) { return insstr(_str); } #undef insstr #define insstr UNDEF(insstr) #endif #ifdef mvinsstr inline int UNDEF(mvinsstr)(int y, int x,const char *_str) { return mvinsstr(y,x,_str); } #undef mvinsstr #define mvinsstr UNDEF(mvinsstr) #endif #ifdef insnstr inline int UNDEF(insnstr)(const char *_str, int n) { return insnstr(_str,n); } #undef insnstr #define insnstr UNDEF(insnstr) #endif #ifdef mvwinsnstr inline int UNDEF(mvwinsnstr)(WINDOW *w, int y, int x,const char *_str, int n) { return mvwinsnstr(w,y,x,_str,n); } #undef mvwinsnstr #define mvwinsnstr UNDEF(mvwinsnstr) #endif #ifdef mvinsnstr inline int UNDEF(mvinsnstr)(int y, int x,const char *_str, int n) { return mvinsnstr(y,x,_str,n); } #undef mvinsnstr #define mvinsnstr UNDEF(mvinsnstr) #endif #ifdef getnstr inline int UNDEF(getnstr)(char *_str, int n) { return getnstr(_str,n); } #undef getnstr #define getnstr UNDEF(getnstr) #endif #ifdef getyx inline void UNDEF(getyx)(const WINDOW* win, int& y, int& x) { getyx(win, y, x); } #undef getyx #define getyx UNDEF(getyx) #endif #ifdef getbegyx inline void UNDEF(getbegyx)(WINDOW* win, int& y, int& x) { getbegyx(win, y, x); } #undef getbegyx #define getbegyx UNDEF(getbegyx) #endif #ifdef getmaxyx inline void UNDEF(getmaxyx)(WINDOW* win, int& y, int& x) { getmaxyx(win, y, x); } #undef getmaxyx #define getmaxyx UNDEF(getmaxyx) #endif #ifdef hline inline int UNDEF(hline)(chtype ch, int n) { return hline(ch, n); } #undef hline #define hline UNDEF(hline) #endif #ifdef inch inline chtype UNDEF(inch)() { return inch(); } #undef inch #define inch UNDEF(inch) #endif #ifdef insch inline int UNDEF(insch)(char c) { return insch(c); } #undef insch #define insch UNDEF(insch) #endif #ifdef insertln inline int UNDEF(insertln)() { return insertln(); } #undef insertln #define insertln UNDEF(insertln) #endif #ifdef leaveok inline int UNDEF(leaveok)(WINDOW* win, bool bf) { return leaveok(win, bf); } #undef leaveok #define leaveok UNDEF(leaveok) #else extern "C" int leaveok(WINDOW* win, bool bf); #endif #ifdef move inline int UNDEF(move)(int x, int y) { return move(x, y); } #undef move #define move UNDEF(move) #endif #ifdef refresh inline int UNDEF(refresh)() { return refresh(); } #undef refresh #define refresh UNDEF(refresh) #endif #ifdef redrawwin inline int UNDEF(redrawwin)(WINDOW *win) { return redrawwin(win); } #undef redrawwin #define redrawwin UNDEF(redrawwin) #endif #ifdef scrl inline int UNDEF(scrl)(int l) { return scrl(l); } #undef scrl #define scrl UNDEF(scrl) #endif #ifdef scroll inline int UNDEF(scroll)(WINDOW *win) { return scroll(win); } #undef scroll #define scroll UNDEF(scroll) #endif #ifdef scrollok inline int UNDEF(scrollok)(WINDOW* win, bool bf) { return scrollok(win, bf); } #undef scrollok #define scrollok UNDEF(scrollok) #else #if defined(__NCURSES_H) extern "C" int scrollok(WINDOW*, bool); #else extern "C" int scrollok(WINDOW*, char); #endif #endif #ifdef setscrreg inline int UNDEF(setscrreg)(int t, int b) { return setscrreg(t, b); } #undef setscrreg #define setscrreg UNDEF(setscrreg) #endif #ifdef standend inline int UNDEF(standend)() { return standend(); } #undef standend #define standend UNDEF(standend) #endif #ifdef standout inline int UNDEF(standout)() { return standout(); } #undef standout #define standout UNDEF(standout) #endif #ifdef subpad inline WINDOW *UNDEF(subpad)(WINDOW *p, int l, int c, int y, int x) { return derwin(p,l,c,y,x); } #undef subpad #define subpad UNDEF(subpad) #endif #ifdef timeout inline void UNDEF(timeout)(int delay) { timeout(delay); } #undef timeout #define timeout UNDEF(timeout) #endif #ifdef touchline inline int UNDEF(touchline)(WINDOW *win, int s, int c) { return touchline(win,s,c); } #undef touchline #define touchline UNDEF(touchline) #endif #ifdef touchwin inline int UNDEF(touchwin)(WINDOW *win) { return touchwin(win); } #undef touchwin #define touchwin UNDEF(touchwin) #endif #ifdef untouchwin inline int UNDEF(untouchwin)(WINDOW *win) { return untouchwin(win); } #undef untouchwin #define untouchwin UNDEF(untouchwin) #endif #ifdef vline inline int UNDEF(vline)(chtype ch, int n) { return vline(ch, n); } #undef vline #define vline UNDEF(vline) #endif #ifdef waddstr inline int UNDEF(waddstr)(WINDOW *win, char *str) { return waddstr(win, str); } #undef waddstr #define waddstr UNDEF(waddstr) #endif #ifdef waddchstr inline int UNDEF(waddchstr)(WINDOW *win, chtype *at) { return waddchstr(win, at); } #undef waddchstr #define waddchstr UNDEF(waddchstr) #endif #ifdef wstandend inline int UNDEF(wstandend)(WINDOW *win) { return wstandend(win); } #undef wstandend #define wstandend UNDEF(wstandend) #endif #ifdef wstandout inline int UNDEF(wstandout)(WINDOW *win) { return wstandout(win); } #undef wstandout #define wstandout UNDEF(wstandout) #endif #ifdef wattroff inline int UNDEF(wattroff)(WINDOW *win, int att) { return wattroff(win, att); } #undef wattroff #define wattroff UNDEF(wattroff) #endif #ifdef chgat inline int UNDEF(chgat)(int n,attr_t attr, short color, const void *opts) { return chgat(n,attr,color,opts); } #undef chgat #define chgat UNDEF(chgat) #endif #ifdef mvchgat inline int UNDEF(mvchgat)(int y, int x, int n, attr_t attr, short color, const void *opts) { return mvchgat(y,x,n,attr,color,opts); } #undef mvchgat #define mvchgat UNDEF(mvchgat) #endif #ifdef mvwchgat inline int UNDEF(mvwchgat)(WINDOW *win, int y, int x, int n, attr_t attr, short color, const void *opts) { return mvwchgat(win,y,x,n,attr,color,opts); } #undef mvwchgat #define mvwchgat UNDEF(mvwchgat) #endif #ifdef wattrset inline int UNDEF(wattrset)(WINDOW *win, int att) { return wattrset(win, att); } #undef wattrset #define wattrset UNDEF(wattrset) #endif #ifdef winch inline chtype UNDEF(winch)(const WINDOW* win) { return winch(win); } #undef winch #define winch UNDEF(winch) #endif #ifdef mvwaddch inline int UNDEF(mvwaddch)(WINDOW *win, int y, int x, const chtype ch) { return mvwaddch(win, y, x, ch); } #undef mvwaddch #define mvwaddch UNDEF(mvwaddch) #endif #ifdef mvwaddchnstr inline int UNDEF(mvwaddchnstr)(WINDOW *win, int y, int x, chtype *str, int n) { return mvwaddchnstr(win, y, x, str, n); } #undef mvwaddchnstr #define mvwaddchnstr UNDEF(mvwaddchnstr) #endif #ifdef mvwaddchstr inline int UNDEF(mvwaddchstr)(WINDOW *win, int y, int x, chtype *str) { return mvwaddchstr(win, y, x, str); } #undef mvwaddchstr #define mvwaddchstr UNDEF(mvwaddchstr) #endif #ifdef addnstr inline int UNDEF(addnstr)(const char *str, int n) { return addnstr((char*)str, n); } #undef addnstr #define addnstr UNDEF(addnstr) #endif #ifdef mvwaddnstr inline int UNDEF(mvwaddnstr)(WINDOW *win, int y, int x, const char *str, int n) { return mvwaddnstr(win, y, x, (char*)str, n); } #undef mvwaddnstr #define mvwaddnstr UNDEF(mvwaddnstr) #endif #ifdef mvwaddstr inline int UNDEF(mvwaddstr)(WINDOW *win, int y, int x, const char * str) { return mvwaddstr(win, y, x, (char*)str); } #undef mvwaddstr #define mvwaddstr UNDEF(mvwaddstr) #endif #ifdef mvwdelch inline int UNDEF(mvwdelch)(WINDOW *win, int y, int x) { return mvwdelch(win, y, x); } #undef mvwdelch #define mvwdelch UNDEF(mvwdelch) #endif #ifdef mvwgetch inline int UNDEF(mvwgetch)(WINDOW *win, int y, int x) { return mvwgetch(win, y, x);} #undef mvwgetch #define mvwgetch UNDEF(mvwgetch) #endif #ifdef mvwgetstr inline int UNDEF(mvwgetstr)(WINDOW *win, int y, int x, char *str) {return mvwgetstr(win,y,x, str);} #undef mvwgetstr #define mvwgetstr UNDEF(mvwgetstr) #endif #ifdef mvwgetnstr inline int UNDEF(mvwgetnstr)(WINDOW *win, int y, int x, char *str, int n) {return mvwgetnstr(win,y,x, str,n);} #undef mvwgetnstr #define mvwgetnstr UNDEF(mvwgetnstr) #endif #ifdef mvwinch inline chtype UNDEF(mvwinch)(WINDOW *win, int y, int x) { return mvwinch(win, y, x);} #undef mvwinch #define mvwinch UNDEF(mvwinch) #endif #ifdef mvwinsch inline int UNDEF(mvwinsch)(WINDOW *win, int y, int x, char c) { return mvwinsch(win, y, x, c); } #undef mvwinsch #define mvwinsch UNDEF(mvwinsch) #endif #ifdef mvaddch inline int UNDEF(mvaddch)(int y, int x, chtype ch) { return mvaddch(y, x, ch); } #undef mvaddch #define mvaddch UNDEF(mvaddch) #endif #ifdef mvaddnstr inline int UNDEF(mvaddnstr)(int y, int x, const char *str, int n) { return mvaddnstr(y, x, (char*)str, n); } #undef mvaddnstr #define mvaddnstr UNDEF(mvaddnstr) #endif #ifdef mvaddstr inline int UNDEF(mvaddstr)(int y, int x, const char * str) { return mvaddstr(y, x, (char*)str); } #undef mvaddstr #define mvaddstr UNDEF(mvaddstr) #endif #ifdef mvdelch inline int UNDEF(mvdelch)(int y, int x) { return mvdelch(y, x);} #undef mvdelch #define mvdelch UNDEF(mvdelch) #endif #ifdef mvgetch inline int UNDEF(mvgetch)(int y, int x) { return mvgetch(y, x);} #undef mvgetch #define mvgetch UNDEF(mvgetch) #endif #ifdef mvgetstr inline int UNDEF(mvgetstr)(int y, int x, char *str) {return mvgetstr(y, x, str);} #undef mvgetstr #define mvgetstr UNDEF(mvgetstr) #endif #ifdef mvgetnstr inline int UNDEF(mvgetnstr)(int y, int x, char *str, int n) { return mvgetnstr(y, x, str,n);} #undef mvgetnstr #define mvgetnstr UNDEF(mvgetnstr) #endif #ifdef mvinch inline chtype UNDEF(mvinch)(int y, int x) { return mvinch(y, x);} #undef mvinch #define mvinch UNDEF(mvinch) #endif #ifdef mvinsch inline int UNDEF(mvinsch)(int y, int x, char c) { return mvinsch(y, x, c); } #undef mvinsch #define mvinsch UNDEF(mvinsch) #endif #ifdef napms inline void UNDEF(napms)(unsigned long x) { napms(x); } #undef napms #define napms UNDEF(napms) #endif #ifdef fixterm inline int UNDEF(fixterm)(void) { return fixterm(); } #undef fixterm #define fixterm UNDEF(fixterm) #endif #ifdef resetterm inline int UNDEF(resetterm)(void) { return resetterm(); } #undef resetterm #define resetterm UNDEF(resetterm) #endif #ifdef saveterm inline int UNDEF(saveterm)(void) { return saveterm(); } #undef saveterm #define saveterm UNDEF(saveterm) #endif #ifdef crmode inline int UNDEF(crmode)(void) { return crmode(); } #undef crmode #define crmode UNDEF(crmode) #endif #ifdef nocrmode inline int UNDEF(nocrmode)(void) { return nocrmode(); } #undef nocrmode #define nocrmode UNDEF(nocrmode) #endif #ifdef getbkgd inline chtype UNDEF(getbkgd)(const WINDOW *win) { return getbkgd(win); } #undef getbkgd #define getbkgd UNDEF(getbkgd) #endif #ifdef bkgd inline int UNDEF(bkgd)(chtype ch) { return bkgd(ch); } #undef bkgd #define bkgd UNDEF(bkgd) #endif #ifdef bkgdset inline void UNDEF(bkgdset)(chtype ch) { bkgdset(ch); } #undef bkgdset #define bkgdset UNDEF(bkgdset) #endif /* * * C++ class for windows. * * */ class NCursesWindow { friend class NCursesMenu; friend class NCursesForm; private: static bool b_initialized; static void initialize(); static int ripoff_init(WINDOW *,int); void init(); short getcolor(int getback) const; static int setpalette(short fore, short back, short pair); static int colorInitialized; // This private constructor is only used during the initialization // of windows generated by ripoffline() calls. NCursesWindow(WINDOW* win, int cols); protected: void err_handler(const char *) const THROWS(NCursesException); // Signal an error with the given message text. static long count; // count of all active windows: // We rely on the c++ promise that // all otherwise uninitialized // static class vars are set to 0 WINDOW* w; // the curses WINDOW bool alloced; // TRUE if we own the WINDOW NCursesWindow* par; // parent, if subwindow NCursesWindow* subwins; // head of subwindows list NCursesWindow* sib; // next subwindow of parent void kill_subwindows(); // disable all subwindows // Destroy all subwindows. /* Only for use by derived classes. They are then in charge to fill the member variables correctly. */ NCursesWindow(); public: NCursesWindow(WINDOW* &window); // useful only for stdscr NCursesWindow(int lines, // number of lines int cols, // number of columns int begin_y, // line origin int begin_x); // col origin NCursesWindow(NCursesWindow& par,// parent window int lines, // number of lines int cols, // number of columns int begin_y, // absolute or relative int begin_x, // origins: char absrel = 'a');// if `a', by & bx are // absolute screen pos, else if `r', they are relative to par origin NCursesWindow(NCursesWindow& par,// parent window bool do_box = TRUE); // this is the very common case that we want to create the subwindow that // is two lines and two columns smaller and begins at (1,1). // We may automatically request the box around it. virtual ~NCursesWindow(); NCursesWindow Clone(); // Make an exact copy of the window. // Initialization. static void useColors(void); // Call this routine very early if you want to have colors. static int ripoffline(int ripoff_lines, int (*init)(NCursesWindow& win)); // This function is used to generate a window of ripped-of lines. // If the argument is positive, lines are removed from the top, if it // is negative lines are removed from the bottom. This enhances the // lowlevel ripoffline() function because it uses the internal // implementation that allows to remove more than just a single line. // This function must be called before any other ncurses function. The // creation of the window is defered until ncurses gets initialized. // The initialization function is then called. // ------------------------------------------------------------------------- // terminal status // ------------------------------------------------------------------------- int lines() const { return LINES; } // Number of lines on terminal, *not* window int cols() const { return COLS; } // Number of cols on terminal, *not* window int tabsize() const { return TABSIZE; } // Size of a tab on terminal, *not* window static int NumberOfColors(); // Number of available colors int colors() const { return NumberOfColors(); } // Number of available colors // ------------------------------------------------------------------------- // window status // ------------------------------------------------------------------------- int height() const { return maxy() + 1; } // Number of lines in this window int width() const { return maxx() + 1; } // Number of columns in this window int begx() const { return w->_begx; } // Column of top left corner relative to stdscr int begy() const { return w->_begy; } // Line of top left corner relative to stdscr int maxx() const { return w->_maxx; } // Largest x coord in window int maxy() const { return w->_maxy; } // Largest y coord in window short getcolor() const; // Actual color pair short foreground() const { return getcolor(0); } // Actual foreground color short background() const { return getcolor(1); } // Actual background color int setpalette(short fore, short back); // Set color palette entry int setcolor(short pair); // Set actually used palette entry // ------------------------------------------------------------------------- // window positioning // ------------------------------------------------------------------------- virtual int mvwin(int begin_y, int begin_x) { return ::mvwin(w,begin_y,begin_x); } // Move window to new position with the new position as top left corner. // This is virtual because it is redefined in NCursesPanel. // ------------------------------------------------------------------------- // coordinate positioning // ------------------------------------------------------------------------- int move(int y, int x) { return ::wmove(w, y, x); } // Move cursor the this position void getyx(int& y, int& x) const { ::getyx(w, y, x); } // Get current position of the cursor int mvcur(int oldrow, int oldcol, int newrow, int newcol) const { return ::mvcur(oldrow, oldcol, newrow, newcol); } // Perform lowlevel cursor motion that takes effect immediately. // ------------------------------------------------------------------------- // input // ------------------------------------------------------------------------- int getch() { return ::wgetch(w); } // Get a keystroke from the window. int getch(int y, int x) { return ::mvwgetch(w,y,x); } // Move cursor to position and get a keystroke from the window int getstr(char* str, int n=-1) { return ::wgetnstr(w, str,n); } // Read a series of characters into str until a newline or carriage return // is received. Read at most n characters. If n is negative, the limit is // ignored. int getstr(int y, int x, char* str, int n=-1) { return ::mvwgetnstr(w,y,x,str,n); } // Move the cursor to the requested position and then perform the getstr() // as described above. int instr(char *s, int n=-1) { return ::winnstr(w,s,n); } // Get a string of characters from the window into the buffer s. Retrieve // at most n characters, if n is negative retrieve all characters up to the // end of the current line. Attributes are stripped from the characters. int instr(int y, int x, char *s, int n=-1) { return ::mvwinnstr(w,y,x,s,n); } // Move the cursor to the requested position and then perform the instr() // as described above. int scanw(const char* fmt, ...) // Perform a scanw function from the window. This only works if you're // using the GNU C++ compiler. #if __GNUG__ >= 2 __attribute__ ((format (scanf, 2, 3))); #else ; #endif int scanw(int y, int x, const char* fmt, ...) // Move the cursor to the requested position and then perform a scanw // from the window. This nly works if you're using the GNU C++ compiler. #if __GNUG__ >= 2 __attribute__ ((format (scanf, 4, 5))); #else ; #endif // ------------------------------------------------------------------------- // output // ------------------------------------------------------------------------- int addch(const chtype ch) { return ::waddch(w, ch); } // Put attributed character to the window. int addch(int y, int x, const chtype ch) { return ::mvwaddch(w,y,x,ch); } // Move cursor to the requested position and then put attributed character // to the window. int echochar(const chtype ch) { return ::wechochar(w,ch); } // Put attributed character to the window and refresh it immediately. int addstr(const char* str, int n=-1) { return ::waddnstr(w, (char*)str,n); } // Write the string str to the window, stop writing if the terminating // NUL or the limit n is reached. If n is negative, it is ignored. int addstr(int y, int x, const char * str, int n=-1) { return ::mvwaddnstr(w,y,x,(char*)str,n); } // Move the cursor to the requested position and then perform the addstr // as described above. int printw(const char* fmt, ...) // Do a formatted print to the window. #if __GNUG__ >= 2 __attribute__ ((format (printf, 2, 3))); #else ; #endif int printw(int y, int x, const char * fmt, ...) // Move the cursor and then do a formatted print to the window. #if __GNUG__ >= 2 __attribute__ ((format (printf, 4, 5))); #else ; #endif chtype inch() const { return ::winch(w); } // Retrieve attributed character under the current cursor position. chtype inch(int y, int x) { return ::mvwinch(w,y,x); } // Move cursor to requested position and then retrieve attributed character // at this position. int insch(chtype ch) { return ::winsch(w, ch); } // Insert attributed character into the window before current cursor // position. int insch(int y, int x, chtype ch) { return ::mvwinsch(w,y,x,(char)ch); } // Move cursor to requested position and then insert the attributed // character before that position. int insertln() { return ::winsdelln(w,1); } // Insert an empty line above the current line. int insdelln(int n=1) { return ::winsdelln(w,n); } // If n>0 insert that many lines above the current line. If n<0 delete // that many lines beginning with the current line. int insstr(const char *s, int n=-1) { return ::winsnstr(w,s,n); } // Insert the string into the window before the current cursor position. // Insert stops at end of string or when the limit n is reached. If n is // negative, it is ignored. int insstr(int y, int x, const char *s, int n=-1) { return ::mvwinsnstr(w,y,x,s,n); } // Move the cursor to the requested position and then perform the insstr() // as described above. int attron (chtype at) { return ::wattron (w, at); } // Switch on the window attributes; int attroff(chtype at) { return ::wattroff(w, (int) at); } // Switch off the window attributes; int attrset(chtype at) { return ::wattrset(w, (int) at); } // Set the window attributes; int color_set(short color_pair_number, void* opts=NULL) { return ::wcolor_set(w, color_pair_number, opts); } // Set the window color attribute; int chgat(int n,attr_t attr, short color, const void *opts=NULL) { return ::wchgat(w,n,attr,color,opts); } // Change the attributes of the next n characters in the current line. If // n is negative or greater than the number of remaining characters in the // line, the attributes will be changed up to the end of the line. int chgat(int y, int x, int n,attr_t attr, short color, const void *opts=NULL) { return ::mvwchgat(w,y,x,n,attr,color,opts); } // Move the cursor to the requested position and then perform chgat() as // described above. // ------------------------------------------------------------------------- // background // ------------------------------------------------------------------------- chtype getbkgd() const { return ::getbkgd(w); } // Get current background setting. int bkgd(const chtype ch) { return ::wbkgd(w,ch); } // Set the background property and apply it to the window. void bkgdset(chtype ch) { ::wbkgdset(w,ch); } // Set the background property. // ------------------------------------------------------------------------- // borders // ------------------------------------------------------------------------- int box(chtype vert=0, chtype hor=0) { return ::wborder(w, vert, vert, hor, hor, 0, 0 ,0, 0); } // Draw a box around the window with the given vertical and horizontal // drawing characters. If you specifiy a zero as character, curses will try // to find a "nice" character. int border(chtype left=0, chtype right=0, chtype top =0, chtype bottom=0, chtype top_left =0, chtype top_right=0, chtype bottom_left =0, chtype bottom_right=0) { return ::wborder(w,left,right,top,bottom,top_left,top_right, bottom_left,bottom_right); } // Draw a border around the window with the given characters for the // various parts of the border. If you pass zero for a character, curses // will try to find "nice" characters. // ------------------------------------------------------------------------- // lines and boxes // ------------------------------------------------------------------------- int hline(int len, chtype ch=0) { return ::whline(w, ch, len); } // Draw a horizontal line of len characters with the given character. If // you pass zero for the character, curses will try to find a "nice" one. int hline(int y, int x, int len, chtype ch=0) { return ::mvwhline(w,y,x,ch,len); } // Move the cursor to the requested position and then draw a horizontal line. int vline(int len, chtype ch=0) { return ::wvline(w, ch, len); } // Draw a vertical line of len characters with the given character. If // you pass zero for the character, curses will try to find a "nice" one. int vline(int y, int x, int len, chtype ch=0) { return ::mvwvline(w,y,x,ch,len); } // Move the cursor to the requested position and then draw a vertical line. // ------------------------------------------------------------------------- // erasure // ------------------------------------------------------------------------- int erase() { return ::werase(w); } // Erase the window. int clear() { return ::wclear(w); } // Clear the window. int clearok(bool bf) { return ::clearok(w, bf); } // Set/Reset the clear flag. If set, the next refresh() will clear the // screen. int clrtobot() { return ::wclrtobot(w); } // Clear to the end of the window. int clrtoeol() { return ::wclrtoeol(w); } // Clear to the end of the line. int delch() { return ::wdelch(w); } // Delete character under the cursor. int delch(int y, int x) { return ::mvwdelch(w,y,x); } // Move cursor to requested position and delete the character under the // cursor. int deleteln() { return ::winsdelln(w,-1); } // Delete the current line. // ------------------------------------------------------------------------- // screen control // ------------------------------------------------------------------------- int scroll(int amount=1) { return ::wscrl(w,amount); } // Scroll amount lines. If amount is positive, scroll up, otherwise // scroll down. int scrollok(bool bf) { return ::scrollok(w, bf); } // If bf is TRUE, window scrolls if cursor is moved off the bottom // edge of the window or a scrolling region, otherwise the cursor is left // at the bottom line. int setscrreg(int from, int to) { return ::wsetscrreg(w,from,to); } // Define a soft scrolling region. int idlok(bool bf) { return ::idlok(w, bf); } // If bf is TRUE, use insert/delete line hardware support if possible. // Otherwise do it in software. void idcok(bool bf) { ::idcok(w, bf); } // If bf is TRUE, use insert/delete character hardware support if possible. // Otherwise do it in software. int touchwin() { return ::wtouchln(w,0,height(),1); } // Mark the whole window as modified. int untouchwin() { return ::wtouchln(w,0,height(),0); } // Mark the whole window as unmodified. int touchln(int s, int cnt, bool changed=TRUE) { return ::wtouchln(w,s,cnt,(int)(changed?1:0)); } // Mark cnt lines beginning from line s as changed or unchanged, depending // on the value of the changed flag. bool is_linetouched(int line) const { return (::is_linetouched(w,line) ? TRUE:FALSE); } // Return TRUE if line is marked as changed, FALSE otherwise bool is_wintouched() const { return (::is_wintouched(w) ? TRUE:FALSE); } // Return TRUE if window is marked as changed, FALSE otherwise int leaveok(bool bf) { return ::leaveok(w, bf); } // If bf is TRUE, curses will leave the cursor after an update whereever // it is after the update. int redrawln(int from, int n) { return ::wredrawln(w,from,n); } // Redraw n lines starting from the requested line int redrawwin() { return ::wredrawln(w,0,height()); } // Redraw the whole window int doupdate() { return ::doupdate(); } // Do all outputs to make the physical screen looking like the virtual one void syncdown() { ::wsyncdown(w); } // Propagate the changes down to all descendant windows void syncup() { ::wsyncup(w); } // Propagate the changes up in the hierarchy void cursyncup() { ::wcursyncup(w); } // Position the cursor in all ancestor windows corresponding to our setting int syncok(bool bf) { return ::syncok(w,bf); } // If called with bf=TRUE, syncup() is called whenever the window is changed #ifndef _no_flushok int flushok(bool bf) { return ::flushok(w, bf); } #endif void immedok(bool bf) { ::immedok(w,bf); } // If called with bf=TRUE, any change in the window will cause an // automatic immediate refresh() int keypad(bool bf) { return ::keypad(w, bf); } // If called with bf=TRUE, the application will interpret function keys. int meta(bool bf) { return ::meta(w,bf); } // If called with bf=TRUE, keys may generate 8-Bit characters. Otherwise // 7-Bit characters are generated. int standout() { return ::wstandout(w); } // Enable "standout" attributes int standend() { return ::wstandend(w); } // Disable "standout" attributes // ------------------------------------------------------------------------- // The next two are virtual, because we redefine them in the // NCursesPanel class. // ------------------------------------------------------------------------- virtual int refresh() { return ::wrefresh(w); } // Propagate the changes in this window to the virtual screen and call // doupdate(). This is redefined in NCursesPanel. virtual int noutrefresh() { return ::wnoutrefresh(w); } // Propagate the changes in this window to the virtual screen. This is // redefined in NCursesPanel. // ------------------------------------------------------------------------- // multiple window control // ------------------------------------------------------------------------- int overlay(NCursesWindow& win) { return ::overlay(w, win.w); } // Overlay this window over win. int overwrite(NCursesWindow& win) { return ::overwrite(w, win.w); } // Overwrite win with this window. int copywin(NCursesWindow& win, int sminrow, int smincol, int dminrow, int dmincol, int dmaxrow, int dmaxcol, bool overlay=TRUE) { return ::copywin(w,win.w,sminrow,smincol,dminrow,dmincol, dmaxrow,dmaxcol,(int)(overlay?1:0)); } // Overlay or overwrite the rectangle in win given by dminrow,dmincol, // dmaxrow,dmaxcol with the rectangle in this window beginning at // sminrow,smincol. // ------------------------------------------------------------------------- // Mouse related // ------------------------------------------------------------------------- bool has_mouse() const; // Return TRUE if terminal supports a mouse, FALSE otherwise // ------------------------------------------------------------------------- // traversal support // ------------------------------------------------------------------------- NCursesWindow* child() { return subwins; } // Get the first child window. NCursesWindow* sibling() { return sib; } // Get the next child of my parent. NCursesWindow* parent() { return par; } // Get my parent. bool isDescendant(NCursesWindow& win); // Return TRUE if win is a descendant of this. }; // ------------------------------------------------------------------------- // We leave this here for compatibility reasons. // ------------------------------------------------------------------------- class NCursesColorWindow : public NCursesWindow { public: NCursesColorWindow(WINDOW* &window) // useful only for stdscr : NCursesWindow(window) { useColors(); } NCursesColorWindow(int lines, // number of lines int cols, // number of columns int begin_y, // line origin int begin_x) // col origin : NCursesWindow(lines,cols,begin_y,begin_x) { useColors(); } NCursesColorWindow(NCursesWindow& par,// parent window int lines, // number of lines int cols, // number of columns int begin_y, // absolute or relative int begin_x, // origins: char absrel = 'a') // if `a', by & bx are : NCursesWindow(par,lines,cols, // absolute screen pos, begin_y,begin_x, // else if `r', they are absrel ) { // relative to par origin useColors(); } }; // These enum definitions really belong inside the NCursesPad class, but only // recent compilers support that feature. typedef enum { REQ_PAD_REFRESH = KEY_MAX + 1, REQ_PAD_UP, REQ_PAD_DOWN, REQ_PAD_LEFT, REQ_PAD_RIGHT, REQ_PAD_EXIT } Pad_Request; const Pad_Request PAD_LOW = REQ_PAD_REFRESH; // lowest op-code const Pad_Request PAD_HIGH = REQ_PAD_EXIT; // highest op-code // ------------------------------------------------------------------------- // Pad Support. We allow an association of a pad with a "real" window // through which the pad may be viewed. // ------------------------------------------------------------------------- class NCursesPad : public NCursesWindow { private: NCursesWindow* viewWin; // the "viewport" window NCursesWindow* viewSub; // the "viewport" subwindow int h_gridsize, v_gridsize; protected: int min_row, min_col; // top left row/col of the pads display area NCursesWindow* Win(void) const { // Get the window into which the pad should be copied (if any) return (viewSub?viewSub:(viewWin?viewWin:0)); } NCursesWindow* getWindow(void) const { return viewWin; } NCursesWindow* getSubWindow(void) const { return viewSub; } virtual int driver (int key); // Virtualize keystroke key // The driver translates the keystroke c into an Pad_Request virtual void OnUnknownOperation(int pad_req) { ::beep(); } // This is called if the driver returns an unknown op-code virtual void OnNavigationError(int pad_req) { ::beep(); } // This is called if a navigation request couldn't be satisfied virtual void OnOperation(int pad_req) { }; // OnOperation is called if a Pad_Operation was executed and just before // the refresh() operation is done. public: NCursesPad(int lines, int cols); // create a pad with the given size virtual ~NCursesPad() {} int echochar(const chtype ch) { return ::pechochar(w,ch); } // Put the attributed character onto the pad and immediately do a // prefresh(). int refresh(); // If a viewport is defined the pad is displayed in this window, otherwise // this is a noop. int refresh(int pminrow, int pmincol, int sminrow, int smincol, int smaxrow, int smaxcol) { return ::prefresh(w,pminrow,pmincol, sminrow,smincol,smaxrow,smaxcol); } // The coordinates sminrow,smincol,smaxrow,smaxcol describe a rectangle // on the screen. <b>refresh</b> copies a rectangle of this size beginning // with top left corner pminrow,pmincol onto the screen and calls doupdate(). int noutrefresh(); // If a viewport is defined the pad is displayed in this window, otherwise // this is a noop. int noutrefresh(int pminrow, int pmincol, int sminrow, int smincol, int smaxrow, int smaxcol) { return ::pnoutrefresh(w,pminrow,pmincol, sminrow,smincol,smaxrow,smaxcol); } // Does the same like refresh() but without calling doupdate(). virtual void setWindow(NCursesWindow& view, int v_grid = 1, int h_grid = 1); // Add the window "view" as viewing window to the pad. virtual void setSubWindow(NCursesWindow& sub); // Use the subwindow "sub" of the viewport window for the actual viewing. // The full viewport window is usually used to provide some decorations // like frames, titles etc. virtual void operator() (void); // Perform Pad's operation }; // A FramedPad is constructed always with a viewport window. This viewport // will be framed (by a box() command) and the interior of the box is the // viewport subwindow. On the frame we display scrollbar sliders. class NCursesFramedPad : public NCursesPad { protected: virtual void OnOperation(int pad_req); public: NCursesFramedPad(NCursesWindow& win, int lines, int cols, int v_grid = 1, int h_grid = 1) : NCursesPad(lines,cols) { NCursesPad::setWindow(win,v_grid,h_grid); NCursesPad::setSubWindow(*(new NCursesWindow(win))); } // Construct the FramedPad with the given Window win as viewport. virtual ~NCursesFramedPad() { delete getSubWindow(); } void setWindow(NCursesWindow& view, int v_grid = 1, int h_grid = 1) { err_handler("Operation not allowed"); } // Disable this call; the viewport is already defined void setSubWindow(NCursesWindow& sub) { err_handler("Operation not allowed"); } // Disable this call; the viewport subwindow is already defined }; #endif // _CURSESW_H
nslu2/glibc
ncurses/c++/cursesw.h
C
gpl-2.0
41,968
// // DiEdge.h // AbstractGraph // // Created by Jiageng Li on 4/8/12. // Copyright (c) 2012 University of Illinois at Urbana-Champaign. All rights reserved. // #ifndef _DIEDGE_H_ #define _DIEDGE_H_ #include "../Nodes/DiNode.h" #include "AbstractEdge.h" #include "../incl.h" class DiNode; class AGRAPH_EXPORT DiEdge : public AbstractEdge{ public: DiEdge(int id, DiNode * s, DiNode * t); DiEdge(int id, DiNode * s, DiNode * t, int v); ~DiEdge(); AbstractNode* getFrom(); AbstractNode* getTo(); void printEdge(); private: DiNode * from; DiNode * to; }; #endif
DeathByTape/OldWork
abstract-graph/AbstractGraph/include/Edges/DiEdge.h
C
gpl-2.0
596
const root = 'https://support.wordpress.com'; export default { ADDING_GOOGLE_APPS_TO_YOUR_SITE: `${root}/add-email/adding-google-apps-to-your-site`, ADDING_USERS: `${root}/adding-users`, ALL_ABOUT_DOMAINS: `${root}/all-about-domains`, AUTO_RENEWAL: `${root}/auto-renewal`, BANDPAGE_WIDGET: `${root}/widgets/bandpage-widget`, CATEGORIES_VS_TAGS: `${root}/posts/categories-vs-tags`, CHANGE_NAME_SERVERS: `${root}/domains/change-name-servers`, CHANGE_NAME_SERVERS_FINDING_OUT_NEW_NS: `${root}/domains/change-name-servers/#finding-out-your-new-name-server`, COMMENTS: `${root}/category/comments`, COMMUNITY_TRANSLATOR: `${root}/community-translator`, CONTACT: `https://wordpress.com/help/contact`, CUSTOM_DNS: `${root}/domains/custom-dns`, DOMAINS: `${root}/domains`, EMAIL_FORWARDING: `${root}/email-forwarding`, ENABLE_DISABLE_COMMENTS: `${root}/enable-disable-comments`, EVENTBRITE: `${root}/eventbrite`, EVENTBRITE_EVENT_CALENDARLISTING_WIDGET: `${root}/widgets/eventbrite-event-calendarlisting-widget`, EXPORT: `${root}/export`, FACEBOOK_EMBEDS: `${root}/facebook-integration/facebook-embeds`, FACEBOOK_LIKE_BOX: `${root}/facebook-integration/#facebook-like-box`, FOLLOWERS: `${root}/followers`, GETTING_MORE_VIEWS_AND_TRAFFIC: `${root}/getting-more-views-and-traffic`, GOOGLE_ANALYTICS: `${root}/google-analytics`, GOOGLE_PLUS_EMBEDS: `${root}/google-plus-embeds`, GRAVATAR_HOVERCARDS: `${root}/gravatar-hovercards`, IMPORT: `${root}/import`, INSTAGRAM_WIDGET: `${root}/instagram/instagram-widget`, LIVE_CHAT: `${root}/live-chat`, MANAGE_PURCHASES: `${root}/manage-purchases`, MAP_EXISTING_DOMAIN: `${root}/domains/map-existing-domain`, MAP_SUBDOMAIN: `${root}/domains/map-subdomain`, MEDIA: `${root}/media`, PUBLICIZE: `${root}/publicize`, PUBLIC_VS_PRIVATE: `${root}/domains/register-domain/#public-versus-private`, REFUNDS: `${root}/refunds`, SEO_TAGS: `${root}/getting-more-views-and-traffic/#use-appropriate-tags`, SETTING_PRIMARY_DOMAIN: `${root}/domains/#setting-the-primary-domain`, SETTING_UP_PREMIUM_SERVICES: `${root}/setting-up-premium-services`, SHARING: `${root}/sharing`, START: `${root}/start`, STATS_CLICKS: `${root}/stats/#clicks`, STATS_REFERRERS: `${root}/stats/#referrers`, STATS_SEO_TERMS: `${root}/stats/#search-engine-terms`, STATS_SPAM_REFERRER: `${root}/stats/#marking-spam-referrers`, STATS_TOP_POSTS_PAGES: `${root}/stats/#top-posts-pages`, STATS_VIEWS_BY_COUNTRY: `${root}/stats/#views-by-country`, SUPPORT_ROOT: `${root}/`, TRANSFER_DOMAIN_REGISTRATION: `${root}/transfer-domain-registration`, TWITTER_TIMELINE_WIDGET: `${root}/widgets/twitter-timeline-widget`, USERS: `${root}/category/users`, USER_ROLES: `${root}/user-roles`, VIDEOS: `${root}/videos` };
Kimsangcheon/wp-calypso
client/lib/url/support.js
JavaScript
gpl-2.0
2,742
<?php /** * @package com_zoo * @author YOOtheme http://www.yootheme.com * @copyright Copyright (C) YOOtheme GmbH * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only */ // no direct access defined('_JEXEC') or die('Restricted access'); // include assets css/js if (strtolower(substr($GLOBALS[($this->app->joomla->isVersion('1.5') ? 'mainframe' : 'app')]->getTemplate(), 0, 3)) != 'yoo') { $this->app->document->addStylesheet('assets:css/reset.css'); } $this->app->document->addStylesheet($this->template->resource.'assets/css/zoo.css'); // show description only if it has content if (!$this->application->description) { $this->params->set('template.show_description', 0); } // show title only if it has content if (!$this->application->getParams()->get('content.title')) { $this->params->set('template.show_title', 0); } // show image only if an image is selected if (!($image = $this->application->getImage('content.image'))) { $this->params->set('template.show_image', 0); } $css_class = $this->application->getGroup().'-'.$this->template->name; ?> <div id="yoo-zoo" class="yoo-zoo <?php echo $css_class; ?> <?php echo $css_class.'-frontpage'; ?>"> <?php if ($this->params->get('template.show_alpha_index')) : ?> <?php echo $this->partial('alphaindex'); ?> <?php endif; ?> <?php if ($this->params->get('template.show_title') || $this->params->get('template.show_description') || $this->params->get('template.show_image')) : ?> <div class="details <?php echo 'alignment-'.$this->params->get('template.alignment'); ?>"> <?php if ($this->params->get('template.show_title')) : ?> <h1 class="title"><?php echo $this->application->getParams()->get('content.title'); ?></h1> <?php if ($this->application->getParams()->get('content.subtitle')) : ?> <h2 class="subtitle"><?php echo $this->application->getParams()->get('content.subtitle'); ?></h2> <?php endif; ?> <?php endif; ?> <?php if ($this->params->get('template.show_description') || $this->params->get('template.show_image')) : ?> <div class="description"> <?php if ($this->params->get('template.show_image')) : ?> <img class="image" src="<?php echo $image['src']; ?>" title="<?php echo $this->application->getParams()->get('content.title'); ?>" alt="<?php echo $this->application->getParams()->get('content.title'); ?>" <?php echo $image['width_height']; ?>/> <?php endif; ?> <?php if ($this->params->get('template.show_description')) echo $this->application->getText($this->application->description); ?> </div> <?php endif; ?> </div> <?php endif; ?> <?php // render categories $has_categories = false; if ($this->category->childrenHaveItems()) { $has_categories = true; echo '<div class="frontpage-categories">'; // create rows foreach($this->selected_categories as $category) { if ($category && !$category->totalItemCount()) continue; echo '<div class="row">'; echo $this->partial('frontpage_category', compact('category')); echo '</div>'; } echo '</div>'; } ?> <?php // render items if (count($this->items)) { $itemstitle = ''; $itemstitle = $this->application->getParams()->get('content.items_title'); echo $this->partial('items', compact('itemstitle', 'has_categories')); } ?> </div>
yozzh/vet-help
media/zoo/applications/cookbook/templates/default/frontpage.php
PHP
gpl-2.0
3,297
<?php namespace MustBeSanta\Ensemble; class Sidekick { /** @var String */ private $firstName; /** * @return String */ public function getFirstName() { return $this->firstName; } /** * @param String $firstName */ public function setFirstName($firstName) { $this->firstName = $firstName; } }
kler/MustBeSanta
src/MustBeSanta/Ensemble/Sidekick.php
PHP
gpl-2.0
371
/* * Copyright (c) 2020, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, as published by the * Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package io.mycat.server; import java.io.IOException; import java.nio.channels.NetworkChannel; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.mycat.MycatServer; import io.mycat.backend.mysql.listener.DefaultSqlExecuteStageListener; import io.mycat.backend.mysql.listener.SqlExecuteStageListener; import io.mycat.config.ErrorCode; import io.mycat.config.model.SchemaConfig; import io.mycat.config.model.SystemConfig; import io.mycat.net.FrontendConnection; import io.mycat.route.RouteResultset; import io.mycat.server.handler.MysqlProcHandler; import io.mycat.server.parser.ServerParse; import io.mycat.server.response.Heartbeat; import io.mycat.server.response.InformationSchemaProfiling; import io.mycat.server.response.InformationSchemaProfilingSqlyog; import io.mycat.server.response.Ping; import io.mycat.server.util.SchemaUtil; import io.mycat.util.SplitUtil; import io.mycat.util.TimeUtil; /** * @author mycat */ public class ServerConnection extends FrontendConnection { private static final Logger LOGGER = LoggerFactory .getLogger(ServerConnection.class); private long authTimeout = SystemConfig.DEFAULT_AUTH_TIMEOUT; /** 保存SET SQL_SELECT_LIMIT的值, default 解析为-1. */ private volatile int sqlSelectLimit = -1; private volatile boolean txReadonly; private volatile int txIsolation; private volatile boolean autocommit; private volatile boolean preAcStates; //上一个ac状态,默认为true private volatile boolean txInterrupted; private volatile String txInterrputMsg = ""; private long lastInsertId; private NonBlockingSession session; /** * 标志是否执行了lock tables语句,并处于lock状态 */ private volatile boolean isLocked = false; private Queue<SqlEntry> executeSqlQueue; private SqlExecuteStageListener listener; public ServerConnection(NetworkChannel channel) throws IOException { super(channel); this.txInterrupted = false; this.autocommit = true; this.preAcStates = true; this.txReadonly = false; this.executeSqlQueue = new LinkedBlockingQueue<>(); this.listener = new DefaultSqlExecuteStageListener(this); } @Override public boolean isIdleTimeout() { if (isAuthenticated) { return super.isIdleTimeout(); } else { return TimeUtil.currentTimeMillis() > Math.max(lastWriteTime, lastReadTime) + this.authTimeout; } } public long getAuthTimeout() { return authTimeout; } public void setAuthTimeout(long authTimeout) { this.authTimeout = authTimeout; } public int getTxIsolation() { return txIsolation; } public void setTxIsolation(int txIsolation) { this.txIsolation = txIsolation; } public boolean isAutocommit() { return autocommit; } public void setAutocommit(boolean autocommit) { this.autocommit = autocommit; } public boolean isTxReadonly() { return txReadonly; } public void setTxReadonly(boolean txReadonly) { this.txReadonly = txReadonly; } public int getSqlSelectLimit() { return sqlSelectLimit; } public void setSqlSelectLimit(int sqlSelectLimit) { this.sqlSelectLimit = sqlSelectLimit; } public long getLastInsertId() { return lastInsertId; } public void setLastInsertId(long lastInsertId) { this.lastInsertId = lastInsertId; } /** * 设置是否需要中断当前事务 */ public void setTxInterrupt(String txInterrputMsg) { if (!autocommit && !txInterrupted) { txInterrupted = true; this.txInterrputMsg = txInterrputMsg; } } /** * * 清空食事务中断 * */ public void clearTxInterrupt() { if (!autocommit && txInterrupted) { txInterrupted = false; this.txInterrputMsg = ""; } } public boolean isTxInterrupted() { return txInterrupted; } public NonBlockingSession getSession2() { return session; } public void setSession2(NonBlockingSession session2) { this.session = session2; } public boolean isLocked() { return isLocked; } public void setLocked(boolean isLocked) { this.isLocked = isLocked; } @Override public void ping() { Ping.response(this); } @Override public void heartbeat(byte[] data) { Heartbeat.response(this, data); } public void execute(String sql, int type) { //连接状态检查 if (this.isClosed()) { LOGGER.warn("ignore execute ,server connection is closed " + this); return; } // 事务状态检查 if (txInterrupted) { writeErrMessage(ErrorCode.ER_YES, "Transaction error, need to rollback." + txInterrputMsg); return; } // 检查当前使用的DB String db = this.schema; boolean isDefault = true; if (db == null) { db = SchemaUtil.detectDefaultDb(sql, type); if (db == null) { db = MycatServer.getInstance().getConfig().getUsers().get(user).getDefaultSchema(); if (db == null) { writeErrMessage(ErrorCode.ERR_BAD_LOGICDB, "No MyCAT Database selected"); return ; } } isDefault = false; } // 兼容PhpAdmin's, 支持对MySQL元数据的模拟返回 //// TODO: 2016/5/20 支持更多information_schema特性 // if (ServerParse.SELECT == type // && db.equalsIgnoreCase("information_schema") ) { // MysqlInformationSchemaHandler.handle(sql, this); // return; // } if (ServerParse.SELECT == type && sql.contains("mysql") && sql.contains("proc")) { SchemaUtil.SchemaInfo schemaInfo = SchemaUtil.parseSchema(sql); if (schemaInfo != null && "mysql".equalsIgnoreCase(schemaInfo.schema) && "proc".equalsIgnoreCase(schemaInfo.table)) { // 兼容MySQLWorkbench MysqlProcHandler.handle(sql, this); return; } } SchemaConfig schema = MycatServer.getInstance().getConfig().getSchemas().get(db); if (schema == null) { writeErrMessage(ErrorCode.ERR_BAD_LOGICDB, "Unknown MyCAT Database '" + db + "'"); return; } //fix navicat SELECT STATE AS `State`, ROUND(SUM(DURATION),7) AS `Duration`, CONCAT(ROUND(SUM(DURATION)/*100,3), '%') AS `Percentage` FROM INFORMATION_SCHEMA.PROFILING WHERE QUERY_ID= GROUP BY STATE ORDER BY SEQ if(ServerParse.SELECT == type &&sql.contains(" INFORMATION_SCHEMA.PROFILING ")&&sql.contains("CONCAT(ROUND(SUM(DURATION)/")) { InformationSchemaProfiling.response(this); return; } //fix sqlyog select state, round(sum(duration),5) as `duration (summed) in sec` from information_schema.profiling where query_id = 0 group by state order by `duration (summed) in sec` desc if(ServerParse.SELECT == type &&sql.contains(" information_schema.profiling ")&&sql.contains("duration (summed) in sec")) { InformationSchemaProfilingSqlyog.response(this); return; } /* 当已经设置默认schema时,可以通过在sql中指定其它schema的方式执行 * 相关sql,已经在mysql客户端中验证。 * 所以在此处增加关于sql中指定Schema方式的支持。 */ if (isDefault && schema.isCheckSQLSchema() && isNormalSql(type)) { SchemaUtil.SchemaInfo schemaInfo = SchemaUtil.parseSchema(sql); if (schemaInfo != null && schemaInfo.schema != null && !schemaInfo.schema.equals(db)) { SchemaConfig schemaConfig = MycatServer.getInstance().getConfig().getSchemas().get(schemaInfo.schema); if (schemaConfig != null) schema = schemaConfig; } } routeEndExecuteSQL(sql, type, schema); } private boolean isNormalSql(int type) { return ServerParse.SELECT==type||ServerParse.INSERT==type||ServerParse.UPDATE==type||ServerParse.DELETE==type||ServerParse.DDL==type; } public RouteResultset routeSQL(String sql, int type) { // 检查当前使用的DB String db = this.schema; if (db == null) { db = SchemaUtil.detectDefaultDb(sql, type); if (db == null){ db = MycatServer.getInstance().getConfig().getUsers().get(user).getDefaultSchema(); if (db == null) { writeErrMessage(ErrorCode.ERR_BAD_LOGICDB, "No MyCAT Database selected"); return null; } } } SchemaConfig schema = MycatServer.getInstance().getConfig() .getSchemas().get(db); if (schema == null) { writeErrMessage(ErrorCode.ERR_BAD_LOGICDB, "Unknown MyCAT Database '" + db + "'"); return null; } // 路由计算 RouteResultset rrs = null; try { rrs = MycatServer .getInstance() .getRouterservice() .route(MycatServer.getInstance().getConfig().getSystem(), schema, type, sql, this.charset, this); } catch (Exception e) { StringBuilder s = new StringBuilder(); LOGGER.warn(s.append(this).append(sql).toString() + " err:" + e.toString(),e); String msg = e.getMessage(); writeErrMessage(ErrorCode.ER_PARSE_ERROR, msg == null ? e.getClass().getSimpleName() : msg); return null; } return rrs; } public void routeEndExecuteSQL(String sql, final int type, final SchemaConfig schema) { // 路由计算 RouteResultset rrs = null; try { rrs = MycatServer .getInstance() .getRouterservice() .route(MycatServer.getInstance().getConfig().getSystem(), schema, type, sql, this.charset, this); } catch (Exception e) { StringBuilder s = new StringBuilder(); LOGGER.warn(s.append(this).append(sql).toString() + " err:" + e.toString(),e); String msg = e.getMessage(); writeErrMessage(ErrorCode.ER_PARSE_ERROR, msg == null ? e.getClass().getSimpleName() : msg); return; } if (rrs != null) { // #支持mariadb驱动useBatchMultiSend=true,连续接收到的sql先放入队列,等待前面处理完成后再继续处理。 // 参考https://mariadb.com/kb/en/option-batchmultisend-description/ boolean executeNow = false; synchronized (this.executeSqlQueue) { executeNow = this.executeSqlQueue.isEmpty(); this.executeSqlQueue.add(new SqlEntry(sql, type, rrs)); if (LOGGER.isDebugEnabled()) { LOGGER.debug("add queue,executeSqlQueue size {}", executeSqlQueue.size()); } } if (executeNow) { this.executeSqlId++; session.execute(rrs, rrs.isSelectForUpdate() ? ServerParse.UPDATE : type); } } } /** * 提交事务 */ public void commit() { if (txInterrupted) { LOGGER.warn("receive commit ,but found err message in Transaction {}",this); this.rollback(); // writeErrMessage(ErrorCode.ER_YES, // "Transaction error, need to rollback."); } else { session.commit(); } } /** * 回滚事务 */ public void rollback() { // 状态检查 if (txInterrupted) { txInterrupted = false; } // 执行回滚 session.rollback(); } /** * 执行lock tables语句方法 * @param sql */ public void lockTable(String sql) { // 事务中不允许执行lock table语句 if (!autocommit) { writeErrMessage(ErrorCode.ER_YES, "can't lock table in transaction!"); return; } // 已经执行了lock table且未执行unlock table之前的连接不能再次执行lock table命令 if (isLocked) { writeErrMessage(ErrorCode.ER_YES, "can't lock multi-table"); return; } RouteResultset rrs = routeSQL(sql, ServerParse.LOCK); if (rrs != null) { session.lockTable(rrs); } } /** * 执行unlock tables语句方法 * @param sql */ public void unLockTable(String sql) { sql = sql.replaceAll("\n", " ").replaceAll("\t", " "); String[] words = SplitUtil.split(sql, ' ', true); if (words.length==2 && ("table".equalsIgnoreCase(words[1]) || "tables".equalsIgnoreCase(words[1]))) { isLocked = false; session.unLockTable(sql); } else { writeErrMessage(ErrorCode.ER_UNKNOWN_COM_ERROR, "Unknown command"); } } /** * 撤销执行中的语句 * * @param sponsor * 发起者为null表示是自己 */ public void cancel(final FrontendConnection sponsor) { processor.getExecutor().execute(new Runnable() { @Override public void run() { session.cancel(sponsor); } }); } @Override public void close(String reason) { super.close(reason); session.terminate(); if(getLoadDataInfileHandler()!=null) { getLoadDataInfileHandler().clear(); } } /** * add huangyiming 检测字符串中某字符串出现次数 * @param srcText * @param findText * @return */ public static int appearNumber(String srcText, String findText) { int count = 0; Pattern p = Pattern.compile(findText); Matcher m = p.matcher(srcText); while (m.find()) { count++; } return count; } @Override public String toString() { return "ServerConnection [id=" + id + ", schema=" + schema + ", host=" + host + ", user=" + user + ",txIsolation=" + txIsolation + ", autocommit=" + autocommit + ", schema=" + schema+ ", executeSql=" + executeSql + "]" + this.getSession2(); } public boolean isPreAcStates() { return preAcStates; } public void setPreAcStates(boolean preAcStates) { this.preAcStates = preAcStates; } public SqlExecuteStageListener getListener() { return listener; } public void setListener(SqlExecuteStageListener listener) { this.listener = listener; } @Override public void checkQueueFlow() { RouteResultset rrs = session.getRrs(); if (rrs != null && rrs.getNodes().length > 1 && session.getRrs().needMerge()) { // 多节点合并结果集语句需要拉取所有数据,无法流控 return; } else { // 非合并结果集语句进行流量控制检查。 flowController.check(session.getTargetMap()); } } @Override public void resetConnection() { // 1 简单点直接关闭后端连接。若按照mysql官方的提交事务或回滚事务,mycat都会回包给应用,引发包乱序。 session.closeAndClearResources("receive com_reset_connection"); // 2 重置用户变量 this.txInterrupted = false; this.autocommit = true; this.preAcStates = true; this.txReadonly = false; this.lastInsertId = 0; super.resetConnection(); } /** * sql执行完成后回调函数 */ public void onEventSqlCompleted() { SqlEntry sqlEntry = null; synchronized (this.executeSqlQueue) { this.executeSqlQueue.poll();// 弹出已经执行成功的 sqlEntry = this.executeSqlQueue.peek(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("poll queue,executeSqlQueue size {}", this.executeSqlQueue.size()); } } if (sqlEntry != null) { this.executeSqlId++; session.execute(sqlEntry.rrs, sqlEntry.rrs.isSelectForUpdate() ? ServerParse.UPDATE : sqlEntry.type); } } private class SqlEntry { public String sql; public int type; public RouteResultset rrs; public SqlEntry(String sql, int type, RouteResultset rrs) { this.sql = sql; this.type = type; this.rrs = rrs; } } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/server/ServerConnection.java
Java
gpl-2.0
16,219
/* * GPAC - Multimedia Framework C SDK * * Copyright (c) Jean Le Feuvre 2000-2005 * All rights reserved * * This file is part of GPAC / Events management * * GPAC 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, or (at your option) * any later version. * * GPAC 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; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #ifndef _GF_EVENTS_H_ #define _GF_EVENTS_H_ #ifdef __cplusplus extern "C" { #endif #include <gpac/math.h> #include <gpac/tools.h> /* minimal event system DO NOT CHANGE THEIR POSITION IN THE LIST, USED TO SPEED UP FILTERING OF USER INPUT EVENTS */ /*events*/ enum { /****************************************************** Events used for both GPAC internals and DOM Events *******************************************************/ /*MouseEvents*/ GF_EVENT_CLICK, GF_EVENT_MOUSEUP, GF_EVENT_MOUSEDOWN, GF_EVENT_MOUSEOVER, GF_EVENT_MOUSEOUT, /*!! ALL MOUSE EVENTS SHALL BE DECLARED BEFORE MOUSEMOVE !! */ GF_EVENT_MOUSEMOVE, /*mouse wheel event*/ GF_EVENT_MOUSEWHEEL, /*Key Events*/ GF_EVENT_KEYUP, GF_EVENT_KEYDOWN, /* covers KeyDown, KeyPress and AccessKey */ GF_EVENT_LONGKEYPRESS, /*character input*/ GF_EVENT_TEXTINPUT, /****************************************************** Events used for DOM Events only *******************************************************/ GF_EVENT_TEXTSELECT, /*DOM UIEvents*/ GF_EVENT_FOCUSIN, GF_EVENT_FOCUSOUT, GF_EVENT_ACTIVATE, GF_EVENT_CHANGE, GF_EVENT_FOCUS, GF_EVENT_BLUR, /*SVG (HTML) Events*/ GF_EVENT_LOAD, GF_EVENT_UNLOAD, GF_EVENT_ABORT, GF_EVENT_ERROR, GF_EVENT_RESIZE, GF_EVENT_SCROLL, GF_EVENT_ZOOM, GF_EVENT_BEGIN, /*this is a fake event, it is NEVER fired, only used in SMIL begin*/ GF_EVENT_BEGIN_EVENT, GF_EVENT_END, /*this is a fake event, it is NEVER fired, only used in SMIL end*/ GF_EVENT_END_EVENT, GF_EVENT_REPEAT, /*this is a fake event, it is NEVER fired, only used in SMIL repeat*/ GF_EVENT_REPEAT_EVENT, /*DOM MutationEvents - NOT SUPPORTED YET*/ GF_EVENT_TREE_MODIFIED, GF_EVENT_NODE_INSERTED, GF_EVENT_NODE_REMOVED, GF_EVENT_NODE_INSERTED_DOC, GF_EVENT_NODE_REMOVED_DOC, GF_EVENT_ATTR_MODIFIED, GF_EVENT_CHAR_DATA_MODIFIED, GF_EVENT_NODE_NAME_CHANGED, GF_EVENT_ATTR_NAME_CHANGED, GF_EVENT_DCCI_PROP_CHANGE, /*LASeR events*/ GF_EVENT_ACTIVATED, GF_EVENT_DEACTIVATED, GF_EVENT_PAUSE, GF_EVENT_PAUSED_EVENT, GF_EVENT_PLAY, GF_EVENT_REPEAT_KEY, GF_EVENT_RESUME_EVENT, GF_EVENT_SHORT_ACCESSKEY, /*pseudo-event, only used in LASeR coding*/ GF_EVENT_EXECUTION_TIME, /*MediaAccess events - cf http://www.w3.org/TR/MediaAccessEvents*/ GF_EVENT_MEDIA_BEGIN_SESSION_SETUP, GF_EVENT_MEDIA_END_SESSION_SETUP, GF_EVENT_MEDIA_DATA_REQUEST, GF_EVENT_MEDIA_PLAYABLE, GF_EVENT_MEDIA_NOT_PLAYABLE, GF_EVENT_MEDIA_DATA_PROGRESS, GF_EVENT_MEDIA_END_OF_DATA, GF_EVENT_MEDIA_STOP, GF_EVENT_MEDIA_ERROR, GF_EVENT_BATTERY, GF_EVENT_CPU, GF_EVENT_UNKNOWN, /****************************************************** Events used for GPAC internals only *******************************************************/ /*same as mousedown, generated internally by GPAC*/ GF_EVENT_DBLCLICK, /*window events*/ /*size has changed - indicate new w & h in .x end .y fields of event. When sent from gpac to a video plugin, indicates the output size should be changed. This is only sent when the plugin manages the output video himself When sent from a video plugin to gpac, indicates the output size has been changed. This is only sent when the plugin manages the output video himself */ GF_EVENT_SIZE, /*signals the scene size (if indicated in scene) upon connection (sent to the user event proc only) if scene size hasn't changed (seeking or other) this event is not sent */ GF_EVENT_SCENE_SIZE, GF_EVENT_SHOWHIDE, /*window show/hide (minimized or other). This is also sent to the user to signal focus switch in fullscreen*/ GF_EVENT_SET_CURSOR, /*set mouse cursor*/ GF_EVENT_SET_CAPTION, /*set window caption*/ GF_EVENT_MOVE, /*move window*/ GF_EVENT_REFRESH, /*window needs repaint (whenever needed, eg restore, hide->show, background refresh, paint)*/ GF_EVENT_QUIT, /*window is being closed*/ /*video hw setup message: - when sent from gpac to plugin, indicates that the plugin should re-setup hardware context due to a window resize: * for 2D output, this means resizing the backbuffer if needed (depending on HW constraints) * for 3D output, this means re-setup of OpenGL context (depending on HW constraints). Depending on windowing systems and implementations, it could be possible to resize a window without destroying the GL context. - when sent from plugin to gpac, indicates that hardware resources must be resetup before next render step (this is mainly due to discard all openGL textures and cached objects) */ GF_EVENT_VIDEO_SETUP, /*terminal events*/ GF_EVENT_CONNECT, /*signal URL is connected*/ GF_EVENT_DURATION, /*signal duration of presentation*/ GF_EVENT_AUTHORIZATION, /*indicates a user and pass is queried*/ GF_EVENT_NAVIGATE, /*indicates the user app should load or jump to the given URL.*/ GF_EVENT_NAVIGATE_INFO, /*indicates the link or its description under the mouse pointer*/ GF_EVENT_MESSAGE, /*message from the MPEG-4 terminal*/ GF_EVENT_PROGRESS, /*progress message from the MPEG-4 terminal*/ GF_EVENT_VIEWPOINTS, /*indicates viewpoint list has changed - no struct associated*/ GF_EVENT_STREAMLIST, /*indicates stream list has changed - no struct associated - only used when no scene info is present*/ GF_EVENT_METADATA, /*indicates a change in associated metadata*/ GF_EVENT_MIGRATE, /*indicates a session migration request*/ GF_EVENT_DISCONNECT, /*indicates the current url should be disconnected*/ GF_EVENT_SYS_COLORS, /*queries the list of system colors*/ }; /*GPAC/DOM3 key codes*/ enum { GF_KEY_UNIDENTIFIED = 0, GF_KEY_ACCEPT = 1, /* "Accept" The Accept (Commit) key.*/ GF_KEY_AGAIN, /* "Again" The Again key.*/ GF_KEY_ALLCANDIDATES, /* "AllCandidates" The All Candidates key.*/ GF_KEY_ALPHANUM, /*"Alphanumeric" The Alphanumeric key.*/ GF_KEY_ALT, /*"Alt" The Alt (Menu) key.*/ GF_KEY_ALTGRAPH, /*"AltGraph" The Alt-Graph key.*/ GF_KEY_APPS, /*"Apps" The Application key.*/ GF_KEY_ATTN, /*"Attn" The ATTN key.*/ GF_KEY_BROWSERBACK, /*"BrowserBack" The Browser Back key.*/ GF_KEY_BROWSERFAVORITES, /*"BrowserFavorites" The Browser Favorites key.*/ GF_KEY_BROWSERFORWARD, /*"BrowserForward" The Browser Forward key.*/ GF_KEY_BROWSERHOME, /*"BrowserHome" The Browser Home key.*/ GF_KEY_BROWSERREFRESH, /*"BrowserRefresh" The Browser Refresh key.*/ GF_KEY_BROWSERSEARCH, /*"BrowserSearch" The Browser Search key.*/ GF_KEY_BROWSERSTOP, /*"BrowserStop" The Browser Stop key.*/ GF_KEY_CAPSLOCK, /*"CapsLock" The Caps Lock (Capital) key.*/ GF_KEY_CLEAR, /*"Clear" The Clear key.*/ GF_KEY_CODEINPUT, /*"CodeInput" The Code Input key.*/ GF_KEY_COMPOSE, /*"Compose" The Compose key.*/ GF_KEY_CONTROL, /*"Control" The Control (Ctrl) key.*/ GF_KEY_CRSEL, /*"Crsel" The Crsel key.*/ GF_KEY_CONVERT, /*"Convert" The Convert key.*/ GF_KEY_COPY, /*"Copy" The Copy key.*/ GF_KEY_CUT, /*"Cut" The Cut key.*/ GF_KEY_DOWN, /*"Down" The Down Arrow key.*/ GF_KEY_END, /*"End" The End key.*/ GF_KEY_ENTER, /*"Enter" The Enter key. Note: This key identifier is also used for the Return (Macintosh numpad) key.*/ GF_KEY_ERASEEOF, /*"EraseEof" The Erase EOF key.*/ GF_KEY_EXECUTE, /*"Execute" The Execute key.*/ GF_KEY_EXSEL, /*"Exsel" The Exsel key.*/ GF_KEY_F1, /*"F1" The F1 key.*/ GF_KEY_F2, /*"F2" The F2 key.*/ GF_KEY_F3, /*"F3" The F3 key.*/ GF_KEY_F4, /*"F4" The F4 key.*/ GF_KEY_F5, /*"F5" The F5 key.*/ GF_KEY_F6, /*"F6" The F6 key.*/ GF_KEY_F7, /*"F7" The F7 key.*/ GF_KEY_F8, /*"F8" The F8 key.*/ GF_KEY_F9, /*"F9" The F9 key.*/ GF_KEY_F10, /*"F10" The F10 key.*/ GF_KEY_F11, /*"F11" The F11 key.*/ GF_KEY_F12, /*"F12" The F12 key.*/ GF_KEY_F13, /*"F13" The F13 key.*/ GF_KEY_F14, /*"F14" The F14 key.*/ GF_KEY_F15, /*"F15" The F15 key.*/ GF_KEY_F16, /*"F16" The F16 key.*/ GF_KEY_F17, /*"F17" The F17 key.*/ GF_KEY_F18, /*"F18" The F18 key.*/ GF_KEY_F19, /*"F19" The F19 key.*/ GF_KEY_F20, /*"F20" The F20 key.*/ GF_KEY_F21, /*"F21" The F21 key.*/ GF_KEY_F22, /*"F22" The F22 key.*/ GF_KEY_F23, /*"F23" The F23 key.*/ GF_KEY_F24, /*"F24" The F24 key.*/ GF_KEY_FINALMODE, /*"FinalMode" The Final Mode (Final) key used on some asian keyboards.*/ GF_KEY_FIND, /*"Find" The Find key.*/ GF_KEY_FULLWIDTH, /*"FullWidth" The Full-Width Characters key.*/ GF_KEY_HALFWIDTH, /*"HalfWidth" The Half-Width Characters key.*/ GF_KEY_HANGULMODE, /*"HangulMode" The Hangul (Korean characters) Mode key.*/ GF_KEY_HANJAMODE, /*"HanjaMode" The Hanja (Korean characters) Mode key.*/ GF_KEY_HELP, /*"Help" The Help key.*/ GF_KEY_HIRAGANA, /*"Hiragana" The Hiragana (Japanese Kana characters) key.*/ GF_KEY_HOME, /*"Home" The Home key.*/ GF_KEY_INSERT, /*"Insert" The Insert (Ins) key.*/ GF_KEY_JAPANESEHIRAGANA, /*"JapaneseHiragana" The Japanese-Hiragana key.*/ GF_KEY_JAPANESEKATAKANA, /*"JapaneseKatakana" The Japanese-Katakana key.*/ GF_KEY_JAPANESEROMAJI, /*"JapaneseRomaji" The Japanese-Romaji key.*/ GF_KEY_JUNJAMODE, /*"JunjaMode" The Junja Mode key.*/ GF_KEY_KANAMODE, /*"KanaMode" The Kana Mode (Kana Lock) key.*/ GF_KEY_KANJIMODE, /*"KanjiMode" The Kanji (Japanese name for ideographic characters of Chinese origin) Mode key.*/ GF_KEY_KATAKANA, /*"Katakana" The Katakana (Japanese Kana characters) key.*/ GF_KEY_LAUNCHAPPLICATION1, /*"LaunchApplication1" The Start Application One key.*/ GF_KEY_LAUNCHAPPLICATION2, /*"LaunchApplication2" The Start Application Two key.*/ GF_KEY_LAUNCHMAIL, /*"LaunchMail" The Start Mail key.*/ GF_KEY_LEFT, /*"Left" The Left Arrow key.*/ GF_KEY_META, /*"Meta" The Meta key.*/ GF_KEY_MEDIANEXTTRACK, /*"MediaNextTrack" The Media Next Track key.*/ GF_KEY_MEDIAPLAYPAUSE, /*"MediaPlayPause" The Media Play Pause key.*/ GF_KEY_MEDIAPREVIOUSTRACK, /*"MediaPreviousTrack" The Media Previous Track key.*/ GF_KEY_MEDIASTOP, /*"MediaStop" The Media Stok key.*/ GF_KEY_MODECHANGE, /*"ModeChange" The Mode Change key.*/ GF_KEY_NONCONVERT, /*"Nonconvert" The Nonconvert (Don't Convert) key.*/ GF_KEY_NUMLOCK, /*"NumLock" The Num Lock key.*/ GF_KEY_PAGEDOWN, /*"PageDown" The Page Down (Next) key.*/ GF_KEY_PAGEUP, /*"PageUp" The Page Up key.*/ GF_KEY_PASTE, /*"Paste" The Paste key.*/ GF_KEY_PAUSE, /*"Pause" The Pause key.*/ GF_KEY_PLAY, /*"Play" The Play key.*/ GF_KEY_PREVIOUSCANDIDATE, /*"PreviousCandidate" The Previous Candidate function key.*/ GF_KEY_PRINTSCREEN, /*"PrintScreen" The Print Screen (PrintScrn, SnapShot) key.*/ GF_KEY_PROCESS, /*"Process" The Process key.*/ GF_KEY_PROPS, /*"Props" The Props key.*/ GF_KEY_RIGHT, /*"Right" The Right Arrow key.*/ GF_KEY_ROMANCHARACTERS, /*"RomanCharacters" The Roman Characters function key.*/ GF_KEY_SCROLL, /*"Scroll" The Scroll Lock key.*/ GF_KEY_SELECT, /*"Select" The Select key.*/ GF_KEY_SELECTMEDIA, /*"SelectMedia" The Select Media key.*/ GF_KEY_SHIFT, /*"Shift" The Shift key.*/ GF_KEY_STOP, /*"Stop" The Stop key.*/ GF_KEY_UP, /*"Up" The Up Arrow key.*/ GF_KEY_UNDO, /*"Undo" The Undo key.*/ GF_KEY_VOLUMEDOWN, /*"VolumeDown" The Volume Down key.*/ GF_KEY_VOLUMEMUTE, /*"VolumeMute" The Volume Mute key.*/ GF_KEY_VOLUMEUP, /*"VolumeUp" The Volume Up key.*/ GF_KEY_WIN, /*"Win" The Windows Logo key.*/ GF_KEY_ZOOM, /*"Zoom" The Zoom key.*/ GF_KEY_BACKSPACE, /*"U+0008" The Backspace (Back) key.*/ GF_KEY_TAB, /*"U+0009" The Horizontal Tabulation (Tab) key.*/ GF_KEY_CANCEL, /*"U+0018" The Cancel key.*/ GF_KEY_ESCAPE, /*"U+001B" The Escape (Esc) key.*/ GF_KEY_SPACE, /*"U+0020" The Space (Spacebar) key.*/ GF_KEY_EXCLAMATION, /*"U+0021" The Exclamation Mark (Factorial, Bang) key (!).*/ GF_KEY_QUOTATION, /*"U+0022" The Quotation Mark (Quote Double) key (").*/ GF_KEY_NUMBER, /*"U+0023" The Number Sign (Pound Sign, Hash, Crosshatch, Octothorpe) key (#).*/ GF_KEY_DOLLAR, /*"U+0024" The Dollar Sign (milreis, escudo) key ($).*/ GF_KEY_AMPERSAND, /*"U+0026" The Ampersand key (&).*/ GF_KEY_APOSTROPHE, /*"U+0027" The Apostrophe (Apostrophe-Quote, APL Quote) key (').*/ GF_KEY_LEFTPARENTHESIS, /*"U+0028" The Left Parenthesis (Opening Parenthesis) key (().*/ GF_KEY_RIGHTPARENTHESIS, /*"U+0029" The Right Parenthesis (Closing Parenthesis) key ()).*/ GF_KEY_STAR, /*"U+002A" The Asterix (Star) key (*).*/ GF_KEY_PLUS, /*"U+002B" The Plus Sign (Plus) key (+).*/ GF_KEY_COMMA, /*"U+002C" The Comma (decimal separator) sign key (,).*/ GF_KEY_HYPHEN, /*"U+002D" The Hyphen-minus (hyphen or minus sign) key (-).*/ GF_KEY_FULLSTOP, /*"U+002E" The Full Stop (period, dot, decimal point) key (.).*/ GF_KEY_SLASH, /*"U+002F" The Solidus (slash, virgule, shilling) key (/).*/ GF_KEY_0, /*"U+0030" The Digit Zero key (0).*/ GF_KEY_1, /*"U+0031" The Digit One key (1).*/ GF_KEY_2, /*"U+0032" The Digit Two key (2).*/ GF_KEY_3, /*"U+0033" The Digit Three key (3).*/ GF_KEY_4, /*"U+0034" The Digit Four key (4).*/ GF_KEY_5, /*"U+0035" The Digit Five key (5).*/ GF_KEY_6, /*"U+0036" The Digit Six key (6).*/ GF_KEY_7, /*"U+0037" The Digit Seven key (7).*/ GF_KEY_8, /*"U+0038" The Digit Eight key (8).*/ GF_KEY_9, /*"U+0039" The Digit Nine key (9).*/ GF_KEY_COLON, /*"U+003A" The Colon key (:).*/ GF_KEY_SEMICOLON, /*"U+003B" The Semicolon key (;).*/ GF_KEY_LESSTHAN, /*"U+003C" The Less-Than Sign key (<).*/ GF_KEY_EQUALS, /*"U+003D" The Equals Sign key (=).*/ GF_KEY_GREATERTHAN, /*"U+003E" The Greater-Than Sign key (>).*/ GF_KEY_QUESTION, /*"U+003F" The Question Mark key (?).*/ GF_KEY_AT, /*"U+0040" The Commercial At (@) key.*/ GF_KEY_A, /*"U+0041" The Latin Capital Letter A key (A).*/ GF_KEY_B, /*"U+0042" The Latin Capital Letter B key (B).*/ GF_KEY_C, /*"U+0043" The Latin Capital Letter C key (C).*/ GF_KEY_D, /*"U+0044" The Latin Capital Letter D key (D).*/ GF_KEY_E, /*"U+0045" The Latin Capital Letter E key (E).*/ GF_KEY_F, /*"U+0046" The Latin Capital Letter F key (F).*/ GF_KEY_G, /*"U+0047" The Latin Capital Letter G key (G).*/ GF_KEY_H, /*"U+0048" The Latin Capital Letter H key (H).*/ GF_KEY_I, /*"U+0049" The Latin Capital Letter I key (I).*/ GF_KEY_J, /*"U+004A" The Latin Capital Letter J key (J).*/ GF_KEY_K, /*"U+004B" The Latin Capital Letter K key (K).*/ GF_KEY_L, /*"U+004C" The Latin Capital Letter L key (L).*/ GF_KEY_M, /*"U+004D" The Latin Capital Letter M key (M).*/ GF_KEY_N, /*"U+004E" The Latin Capital Letter N key (N).*/ GF_KEY_O, /*"U+004F" The Latin Capital Letter O key (O).*/ GF_KEY_P, /*"U+0050" The Latin Capital Letter P key (P).*/ GF_KEY_Q, /*"U+0051" The Latin Capital Letter Q key (Q).*/ GF_KEY_R, /*"U+0052" The Latin Capital Letter R key (R).*/ GF_KEY_S, /*"U+0053" The Latin Capital Letter S key (S).*/ GF_KEY_T, /*"U+0054" The Latin Capital Letter T key (T).*/ GF_KEY_U, /*"U+0055" The Latin Capital Letter U key (U).*/ GF_KEY_V, /*"U+0056" The Latin Capital Letter V key (V).*/ GF_KEY_W, /*"U+0057" The Latin Capital Letter W key (W).*/ GF_KEY_X, /*"U+0058" The Latin Capital Letter X key (X).*/ GF_KEY_Y, /*"U+0059" The Latin Capital Letter Y key (Y).*/ GF_KEY_Z, /*"U+005A" The Latin Capital Letter Z key (Z).*/ GF_KEY_LEFTSQUAREBRACKET, /*"U+005B" The Left Square Bracket (Opening Square Bracket) key ([).*/ GF_KEY_BACKSLASH, /*"U+005C" The Reverse Solidus (Backslash) key (\).*/ GF_KEY_RIGHTSQUAREBRACKET, /*"U+005D" The Right Square Bracket (Closing Square Bracket) key (]).*/ GF_KEY_CIRCUM, /*"U+005E" The Circumflex Accent key (^).*/ GF_KEY_UNDERSCORE, /*"U+005F" The Low Sign (Spacing Underscore, Underscore) key (_).*/ GF_KEY_GRAVEACCENT, /*"U+0060" The Grave Accent (Back Quote) key (`).*/ GF_KEY_LEFTCURLYBRACKET, /*"U+007B" The Left Curly Bracket (Opening Curly Bracket, Opening Brace, Brace Left) key ({).*/ GF_KEY_PIPE, /*"U+007C" The Vertical Line (Vertical Bar, Pipe) key (|).*/ GF_KEY_RIGHTCURLYBRACKET, /*"U+007D" The Right Curly Bracket (Closing Curly Bracket, Closing Brace, Brace Right) key (}).*/ GF_KEY_DEL, /*"U+007F" The Delete (Del) Key.*/ GF_KEY_INVERTEXCLAMATION, /*"U+00A1" The Inverted Exclamation Mark key (�).*/ GF_KEY_DEADGRAVE, /*"U+0300" The Combining Grave Accent (Greek Varia, Dead Grave) key.*/ GF_KEY_DEADEACUTE, /*"U+0301" The Combining Acute Accent (Stress Mark, Greek Oxia, Tonos, Dead Eacute) key.*/ GF_KEY_DEADCIRCUM, /*"U+0302" The Combining Circumflex Accent (Hat, Dead Circumflex) key.*/ GF_KEY_DEADTILDE, /*"U+0303" The Combining Tilde (Dead Tilde) key.*/ GF_KEY_DEADMACRON, /*"U+0304" The Combining Macron (Long, Dead Macron) key.*/ GF_KEY_DEADBREVE, /*"U+0306" The Combining Breve (Short, Dead Breve) key.*/ GF_KEY_DEADABOVEDOT, /*"U+0307" The Combining Dot Above (Derivative, Dead Above Dot) key.*/ GF_KEY_DEADDIARESIS, /*"U+0308" The Combining Diaeresis (Double Dot Abode, Umlaut, Greek Dialytika, Double Derivative, Dead Diaeresis) key.*/ GF_KEY_DEADRINGABOVE, /*"U+030A" The Combining Ring Above (Dead Above Ring) key.*/ GF_KEY_DEADDOUBLEACUTE, /*"U+030B" The Combining Double Acute Accent (Dead Doubleacute) key.*/ GF_KEY_DEADCARON, /*"U+030C" The Combining Caron (Hacek, V Above, Dead Caron) key.*/ GF_KEY_DEADCEDILLA, /*"U+0327" The Combining Cedilla (Dead Cedilla) key.*/ GF_KEY_DEADOGONEK, /*"U+0328" The Combining Ogonek (Nasal Hook, Dead Ogonek) key.*/ GF_KEY_DEADIOTA, /*"U+0345" The Combining Greek Ypogegrammeni (Greek Non-Spacing Iota Below, Iota Subscript, Dead Iota) key.*/ GF_KEY_EURO, /*"U+20AC" The Euro Currency Sign key (�).*/ GF_KEY_DEADVOICESOUND, /*"U+3099" The Combining Katakana-Hiragana Voiced Sound Mark (Dead Voiced Sound) key.*/ GF_KEY_DEADSEMIVOICESOUND, /*"U+309A" The Combining Katakana-Hiragana Semi-Voiced Sound Mark (Dead Semivoiced Sound) key. */ /*non-dom keys, used in LASeR*/ GF_KEY_CELL_SOFT1, /*soft1 key of cell phones*/ GF_KEY_CELL_SOFT2, /*soft2 key of cell phones*/ /*for joystick handling*/ GF_KEY_JOYSTICK }; /*key modifiers state - set by terminal (not set by video driver)*/ enum { GF_KEY_MOD_SHIFT = (1), GF_KEY_MOD_CTRL = (1<<2), GF_KEY_MOD_ALT = (1<<3), GF_KEY_EXT_NUMPAD = (1<<4), GF_KEY_EXT_LEFT = (1<<5), GF_KEY_EXT_RIGHT = (1<<6) }; /*mouse button modifiers*/ enum { GF_MOUSE_LEFT = 0, GF_MOUSE_MIDDLE, GF_MOUSE_RIGHT }; /*event proc return value: ignored*/ typedef struct { /*GF_EVENT_MOUSEMOVE, GF_EVENT_MOUSEWHEEL, GF_EVENT_MOUSEDOWN, GF_EVENT_MOUSEUP*/ u8 type; /*mouse location in output window, 2D-like: top-left (0,0), increasing y towards bottom*/ s32 x, y; /*wheel position (wheel current delta / wheel absolute delta) for GF_EVENT_MouseWheel*/ Fixed wheel_pos; /*0: left - 1: middle, 2- right*/ u32 button; /*key modifier*/ u32 key_states; } GF_EventMouse; /*event proc return value: ignored*/ typedef struct { /*GF_EVENT_KEYDOWN and GF_EVENT_KEYUP*/ u8 type; /*above GPAC/DOM key code*/ u32 key_code; /* hadrware key value (matching ASCI) */ u32 hw_code; /*key modifier*/ u32 flags; } GF_EventKey; /*event proc return value: ignored*/ typedef struct { /*GF_EVENT_TEXTINPUT*/ u8 type; /*above virtual key code*/ u32 unicode_char; } GF_EventChar; /*event proc return value: ignored*/ typedef struct { /*GF_EVENT_SIZE*/ u8 type; /*width and height*/ u16 width, height; } GF_EventSize; /*event proc return value: ignored*/ typedef struct { /*GF_EVENT_VIDEO_SETUP*/ u8 type; /*width and height of visual surface to allocate*/ u16 width, height; /*indicates whether double buffering is desired*/ Bool back_buffer; /*indicates whether system memory for the backbuffer is desired (no video blitting)*/ Bool system_memory; /*indicates whether opengl context shall be created. Values are: 0: no opengl context shall be created 1: opengl context shall be created for the main window and set as the current one 2: an extra opengl context shall be created for offscreen rendering and set as the current one if not supported, mix of 2D (raster) and 3D (openGL) will be disabled */ u32 opengl_mode; } GF_EventVideoSetup; /*event proc return value: ignored this event may be triggered by the compositor if owning window or if shortcut fullscreen is detected*/ typedef struct { /*GF_EVENT_SHOWHIDE*/ u8 type; /*0: hidden - 1: visible - 2: fullscreen*/ u32 show_type; } GF_EventShow; /*sensor signaling*/ enum { GF_CURSOR_NORMAL = 0x00, GF_CURSOR_ANCHOR, GF_CURSOR_TOUCH, /*discSensor, cylinderSensor, sphereSensor*/ GF_CURSOR_ROTATE, /*proximitySensor & proximitySensor2D*/ GF_CURSOR_PROXIMITY, /*planeSensor & planeSensor2D*/ GF_CURSOR_PLANE, /*collision*/ GF_CURSOR_COLLIDE, GF_CURSOR_HIDE, }; /*event proc return value: ignored*/ typedef struct { /*GF_EVENT_SET_CURSOR*/ u8 type; /*set if is visible*/ u32 cursor_type; } GF_EventCursor; /*event proc return value: ignored*/ typedef struct { /*GF_EVENT_SET_CAPTION*/ u8 type; /*window style flags - NOT USED YET*/ const char *caption; } GF_EventCaption; /*event proc: never posted*/ typedef struct { /*GF_EVENT_MOVE*/ u8 type; s32 x, y; /*0: absolute positionning, 1: relative move, 2: use alignment constraints*/ Bool relative; /*0: left/top, 1: middle, 2: right/bottom*/ u8 align_x, align_y; } GF_EventMove; /*duration may be signaled several times: it may change when setting up streams event proc return value: ignored*/ typedef struct { /*GF_EVENT_DURATION*/ u8 type; /*duration in seconds*/ Double duration; /*is seeking supported for service*/ Bool can_seek; } GF_EventDuration; /*event proc return value: 0 if URL not supported, 1 if accepted (it is the user responsability to load the url) YOU SHALL NOT DIRECTLY OPEN THE NEW URL IN THE EVENT PROC, THIS WOULD DEADLOCK THE TERMINAL */ typedef struct { /*GF_EVENT_NAVIGATE and GF_EVENT_NAVIGATE_INFO*/ u8 type; /*new url to open / data to handle*/ const char *to_url; /*parameters (cf vrml spec) - UNUSED for GF_EVENT_NAVIGATE_INFO*/ u32 param_count; const char **parameters; } GF_EventNavigate; /*event proc return value: ignored*/ typedef struct { /*GF_EVENT_MESSAGE*/ u8 type; /*name of service issuing the message*/ const char *service; /*message*/ const char *message; /*error if any*/ GF_Err error; } GF_EventMessage; /*event proc return value: ignored*/ typedef struct { /*GF_EVENT_PROGRESS*/ u8 type; /*name of service issuing the progress notif*/ const char *service; /*progress type: 0: buffering, 1: downloading, 2: importing (BT/VRML/...)*/ u32 progress_type; /*amount done and total amount of operation. For buffer events, expresses current and total desired stream buffer in scene in milliseconds For download events, expresses current and total size of download in bytes For import events, no units defined (depends on importers) */ u32 done, total; } GF_EventProgress; /*event proc return value: ignored*/ typedef struct { /*GF_EVENT_CONNECT*/ u8 type; /*sent upon connection/deconnection completion. if any error, it is signaled through message event*/ Bool is_connected; } GF_EventConnect; /*event proc return value: 1 if info has been completed, 0 otherwise (and operation this request was for will then fail)*/ typedef struct { /*GF_EVENT_AUTHORIZATION*/ u8 type; /*the URL the auth request is for*/ const char *site_url; /*user name (provided buffer can hold 50 bytes). It may already be formated, or an empty ("") string*/ char *user; /*password (provided buffer can hold 50 bytes)*/ char *password; } GF_EventAuthorize; /*event proc return value: 1 if info has been completed, 0 otherwise */ typedef struct { /*GF_EVENT_SYS_COLORS*/ u8 type; /*ARGB colors, in order: ActiveBorder, ActiveCaption, AppWorkspace, Background, ButtonFace, ButtonHighlight, ButtonShadow, ButtonText, CaptionText, GrayText, Highlight, HighlightText, InactiveBorder, InactiveCaption, InactiveCaptionText, InfoBackground, InfoText, Menu, MenuText, Scrollbar, ThreeDDarkShadow, ThreeDFace, ThreeDHighlight, ThreeDLightShadow, ThreeDShadow, Window, WindowFrame, WindowText */ u32 sys_colors[28]; } GF_EventSysColors; /*Mutation AttrChangeType Signaling*/ enum { GF_MUTATION_ATTRCHANGE_MODIFICATION = 0x01, GF_MUTATION_ATTRCHANGE_ADDITION = 0x02, GF_MUTATION_ATTRCHANGE_REMOVAL = 0x03, }; typedef struct { /* GF_EVENT_TREE_MODIFIED, GF_EVENT_NODE_INSERTED, GF_EVENT_NODE_REMOVED, GF_EVENT_NODE_INSERTED_DOC, GF_EVENT_NODE_REMOVED_DOC, GF_EVENT_ATTR_MODIFIED, GF_EVENT_CHAR_DATA_MODIFIED */ u8 type; void *relatedNode; void *prevValue; void *newValue; void *attrName; u8 attrChange; } GF_EventMutation; typedef union { u8 type; GF_EventMouse mouse; GF_EventKey key; GF_EventChar character; GF_EventSize size; GF_EventShow show; GF_EventDuration duration; GF_EventNavigate navigate; GF_EventMessage message; GF_EventProgress progress; GF_EventConnect connect; GF_EventCaption caption; GF_EventCursor cursor; GF_EventAuthorize auth; GF_EventSysColors sys_cols; GF_EventMove move; GF_EventVideoSetup setup; GF_EventMutation mutation; } GF_Event; #ifdef __cplusplus } #endif #endif /*_GF_EVENTS_H_*/
upyzl/direct264umod
GPAC/events.h
C
gpl-2.0
26,279
public class Hello { public static void main(String args[]) { System.out.println("Hello Josh!, welcome to Java"); } }
williamsjoshua005/Java_Codes
OOpHello/Hello.java
Java
gpl-2.0
132
/* * athena-file-info.h - Information about a file * * Copyright (C) 2003 Novell, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ /* AthenaFileInfo is an interface to the AthenaFile object. It * provides access to the asynchronous data in the AthenaFile. * Extensions are passed objects of this type for operations. */ #ifndef ATHENA_FILE_INFO_H #define ATHENA_FILE_INFO_H #include <glib-object.h> #include <gio/gio.h> G_BEGIN_DECLS #define ATHENA_TYPE_FILE_INFO (athena_file_info_get_type ()) #define ATHENA_FILE_INFO(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), ATHENA_TYPE_FILE_INFO, AthenaFileInfo)) #define ATHENA_IS_FILE_INFO(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), ATHENA_TYPE_FILE_INFO)) #define ATHENA_FILE_INFO_GET_IFACE(obj) (G_TYPE_INSTANCE_GET_INTERFACE ((obj), ATHENA_TYPE_FILE_INFO, AthenaFileInfoIface)) #ifndef ATHENA_FILE_DEFINED #define ATHENA_FILE_DEFINED /* Using AthenaFile for the vtable to make implementing this in * AthenaFile easier */ typedef struct AthenaFile AthenaFile; #endif typedef AthenaFile AthenaFileInfo; typedef struct _AthenaFileInfoIface AthenaFileInfoIface; struct _AthenaFileInfoIface { GTypeInterface g_iface; gboolean (*is_gone) (AthenaFileInfo *file); char * (*get_name) (AthenaFileInfo *file); char * (*get_uri) (AthenaFileInfo *file); char * (*get_parent_uri) (AthenaFileInfo *file); char * (*get_uri_scheme) (AthenaFileInfo *file); char * (*get_mime_type) (AthenaFileInfo *file); gboolean (*is_mime_type) (AthenaFileInfo *file, const char *mime_Type); gboolean (*is_directory) (AthenaFileInfo *file); void (*add_emblem) (AthenaFileInfo *file, const char *emblem_name); char * (*get_string_attribute) (AthenaFileInfo *file, const char *attribute_name); void (*add_string_attribute) (AthenaFileInfo *file, const char *attribute_name, const char *value); void (*invalidate_extension_info) (AthenaFileInfo *file); char * (*get_activation_uri) (AthenaFileInfo *file); GFileType (*get_file_type) (AthenaFileInfo *file); GFile * (*get_location) (AthenaFileInfo *file); GFile * (*get_parent_location) (AthenaFileInfo *file); AthenaFileInfo* (*get_parent_info) (AthenaFileInfo *file); GMount * (*get_mount) (AthenaFileInfo *file); gboolean (*can_write) (AthenaFileInfo *file); }; GList *athena_file_info_list_copy (GList *files); void athena_file_info_list_free (GList *files); GType athena_file_info_get_type (void); /* Return true if the file has been deleted */ gboolean athena_file_info_is_gone (AthenaFileInfo *file); /* Name and Location */ GFileType athena_file_info_get_file_type (AthenaFileInfo *file); GFile * athena_file_info_get_location (AthenaFileInfo *file); char * athena_file_info_get_name (AthenaFileInfo *file); char * athena_file_info_get_uri (AthenaFileInfo *file); char * athena_file_info_get_activation_uri (AthenaFileInfo *file); GFile * athena_file_info_get_parent_location (AthenaFileInfo *file); char * athena_file_info_get_parent_uri (AthenaFileInfo *file); GMount * athena_file_info_get_mount (AthenaFileInfo *file); char * athena_file_info_get_uri_scheme (AthenaFileInfo *file); /* It's not safe to call this recursively multiple times, as it works * only for files already cached by Athena. */ AthenaFileInfo* athena_file_info_get_parent_info (AthenaFileInfo *file); /* File Type */ char * athena_file_info_get_mime_type (AthenaFileInfo *file); gboolean athena_file_info_is_mime_type (AthenaFileInfo *file, const char *mime_type); gboolean athena_file_info_is_directory (AthenaFileInfo *file); gboolean athena_file_info_can_write (AthenaFileInfo *file); /* Modifying the AthenaFileInfo */ void athena_file_info_add_emblem (AthenaFileInfo *file, const char *emblem_name); char * athena_file_info_get_string_attribute (AthenaFileInfo *file, const char *attribute_name); void athena_file_info_add_string_attribute (AthenaFileInfo *file, const char *attribute_name, const char *value); /* Invalidating file info */ void athena_file_info_invalidate_extension_info (AthenaFileInfo *file); AthenaFileInfo *athena_file_info_lookup (GFile *location); AthenaFileInfo *athena_file_info_create (GFile *location); AthenaFileInfo *athena_file_info_lookup_for_uri (const char *uri); AthenaFileInfo *athena_file_info_create_for_uri (const char *uri); G_END_DECLS #endif
SolusOS-discontinued/athena
libathena-extension/athena-file-info.h
C
gpl-2.0
5,967
/* Copyright (C) 2014 Red Hat, Inc. This file is part of IcedTea. IcedTea is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2. IcedTea 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 IcedTea; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package net.sourceforge.jnlp.util.docprovider.formatters.formatters; import org.junit.Assert; import org.junit.Test; public class ReplacingTextFormatterTest { Formatter tr = new ReplacingTextFormatter() { @Override public String wrapParagraph(String s) { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getHeaders(String id, String encoding) { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getNewLine() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getBoldOpening() { return "OPEN"; } @Override public String getBoldClosing() { return "CLOSE"; } @Override public String getBreakAndBold() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getCloseBoldAndBreak() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getBoldCloseNwlineBoldOpen() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getTitle(String name) { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getUrl(String url, String appearence) { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getOption(String key, String value) { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getSeeAlso(String s) { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getTail() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getFileSuffix() { throw new UnsupportedOperationException("Not supported yet."); } }; @Test public void upperCaseNoSpaces() { String s = tr.process("aaa <B> bbb </B> ccc"); Assert.assertEquals("aaa OPEN bbb CLOSE ccc", s); } @Test public void lowercaseNoSpaces() { String s = tr.process("aaa <b> bbb </b> ccc"); Assert.assertEquals("aaa OPEN bbb CLOSE ccc", s); } @Test public void lowercaseSpaces() { String s = tr.process("aaa < b > bbb < / b > ccc"); Assert.assertEquals("aaa OPEN bbb CLOSE ccc", s); } @Test public void uppercaseSpaces() { String s = tr.process("aaa < B > bbb < / B > ccc"); Assert.assertEquals("aaa OPEN bbb CLOSE ccc", s); } @Test public void mixedCases1() { String s = tr.process("aaa <B> bbb </b> ccc"); Assert.assertEquals("aaa OPEN bbb CLOSE ccc", s); } @Test public void mixedSpace2() { String s = tr.process("aaa <b> bbb </B> ccc"); Assert.assertEquals("aaa OPEN bbb CLOSE ccc", s); } @Test public void illegal1() { String s = tr.process("aaa <b style=\"blah\"> bbb </B> ccc"); Assert.assertFalse(s.contains("OPEN")); Assert.assertTrue(s.contains("CLOSE")); } @Test public void illegal2() { String s = tr.process("</B abc> ccc <b>"); Assert.assertFalse(s.contains("CLOSE")); Assert.assertTrue(s.contains("OPEN")); } }
GITNE/icedtea-web
tests/netx/unit/net/sourceforge/jnlp/util/docprovider/formatters/formatters/ReplacingTextFormatterTest.java
Java
gpl-2.0
5,586
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.roshin.gallery.support.widget; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.support.v4.util.ArrayMap; import android.support.v4.util.LongSparseArray; import android.support.v4.util.Pools; import static com.roshin.gallery.support.widget.RecyclerView.ItemAnimator.ItemHolderInfo; import static com.roshin.gallery.support.widget.RecyclerView.ViewHolder; import static com.roshin.gallery.support.widget.ViewInfoStore.InfoRecord.FLAG_APPEAR; import static com.roshin.gallery.support.widget.ViewInfoStore.InfoRecord.FLAG_APPEAR_AND_DISAPPEAR; import static com.roshin.gallery.support.widget.ViewInfoStore.InfoRecord.FLAG_APPEAR_PRE_AND_POST; import static com.roshin.gallery.support.widget.ViewInfoStore.InfoRecord.FLAG_DISAPPEARED; import static com.roshin.gallery.support.widget.ViewInfoStore.InfoRecord.FLAG_POST; import static com.roshin.gallery.support.widget.ViewInfoStore.InfoRecord.FLAG_PRE; import static com.roshin.gallery.support.widget.ViewInfoStore.InfoRecord.FLAG_PRE_AND_POST; /** * This class abstracts all tracking for Views to run animations * * @hide */ class ViewInfoStore { private static final boolean DEBUG = false; /** * View data records for pre-layout */ @VisibleForTesting final ArrayMap<ViewHolder, InfoRecord> mLayoutHolderMap = new ArrayMap<>(); @VisibleForTesting final LongSparseArray<ViewHolder> mOldChangedHolders = new LongSparseArray<>(); /** * Clears the state and all existing tracking data */ void clear() { mLayoutHolderMap.clear(); mOldChangedHolders.clear(); } /** * Adds the item information to the prelayout tracking * @param holder The ViewHolder whose information is being saved * @param info The information to save */ void addToPreLayout(ViewHolder holder, ItemHolderInfo info) { InfoRecord record = mLayoutHolderMap.get(holder); if (record == null) { record = InfoRecord.obtain(); mLayoutHolderMap.put(holder, record); } record.preInfo = info; record.flags |= FLAG_PRE; } boolean isDisappearing(ViewHolder holder) { final InfoRecord record = mLayoutHolderMap.get(holder); return record != null && ((record.flags & FLAG_DISAPPEARED) != 0); } /** * Finds the ItemHolderInfo for the given ViewHolder in preLayout list and removes it. * * @param vh The ViewHolder whose information is being queried * @return The ItemHolderInfo for the given ViewHolder or null if it does not exist */ @Nullable ItemHolderInfo popFromPreLayout(ViewHolder vh) { return popFromLayoutStep(vh, FLAG_PRE); } /** * Finds the ItemHolderInfo for the given ViewHolder in postLayout list and removes it. * * @param vh The ViewHolder whose information is being queried * @return The ItemHolderInfo for the given ViewHolder or null if it does not exist */ @Nullable ItemHolderInfo popFromPostLayout(ViewHolder vh) { return popFromLayoutStep(vh, FLAG_POST); } private ItemHolderInfo popFromLayoutStep(ViewHolder vh, int flag) { int index = mLayoutHolderMap.indexOfKey(vh); if (index < 0) { return null; } final InfoRecord record = mLayoutHolderMap.valueAt(index); if (record != null && (record.flags & flag) != 0) { record.flags &= ~flag; final ItemHolderInfo info; if (flag == FLAG_PRE) { info = record.preInfo; } else if (flag == FLAG_POST) { info = record.postInfo; } else { throw new IllegalArgumentException("Must provide flag PRE or POST"); } // if not pre-post flag is left, clear. if ((record.flags & (FLAG_PRE | FLAG_POST)) == 0) { mLayoutHolderMap.removeAt(index); InfoRecord.recycle(record); } return info; } return null; } /** * Adds the given ViewHolder to the oldChangeHolders list * @param key The key to identify the ViewHolder. * @param holder The ViewHolder to store */ void addToOldChangeHolders(long key, ViewHolder holder) { mOldChangedHolders.put(key, holder); } /** * Adds the given ViewHolder to the appeared in pre layout list. These are Views added by the * LayoutManager during a pre-layout pass. We distinguish them from other views that were * already in the pre-layout so that ItemAnimator can choose to run a different animation for * them. * * @param holder The ViewHolder to store * @param info The information to save */ void addToAppearedInPreLayoutHolders(ViewHolder holder, ItemHolderInfo info) { InfoRecord record = mLayoutHolderMap.get(holder); if (record == null) { record = InfoRecord.obtain(); mLayoutHolderMap.put(holder, record); } record.flags |= FLAG_APPEAR; record.preInfo = info; } /** * Checks whether the given ViewHolder is in preLayout list * @param viewHolder The ViewHolder to query * * @return True if the ViewHolder is present in preLayout, false otherwise */ boolean isInPreLayout(ViewHolder viewHolder) { final InfoRecord record = mLayoutHolderMap.get(viewHolder); return record != null && (record.flags & FLAG_PRE) != 0; } /** * Queries the oldChangeHolder list for the given key. If they are not tracked, simply returns * null. * @param key The key to be used to find the ViewHolder. * * @return A ViewHolder if exists or null if it does not exist. */ ViewHolder getFromOldChangeHolders(long key) { return mOldChangedHolders.get(key); } /** * Adds the item information to the post layout list * @param holder The ViewHolder whose information is being saved * @param info The information to save */ void addToPostLayout(ViewHolder holder, ItemHolderInfo info) { InfoRecord record = mLayoutHolderMap.get(holder); if (record == null) { record = InfoRecord.obtain(); mLayoutHolderMap.put(holder, record); } record.postInfo = info; record.flags |= FLAG_POST; } /** * A ViewHolder might be added by the LayoutManager just to animate its disappearance. * This list holds such items so that we can animate / recycle these ViewHolders properly. * * @param holder The ViewHolder which disappeared during a layout. */ void addToDisappearedInLayout(ViewHolder holder) { InfoRecord record = mLayoutHolderMap.get(holder); if (record == null) { record = InfoRecord.obtain(); mLayoutHolderMap.put(holder, record); } record.flags |= FLAG_DISAPPEARED; } /** * Removes a ViewHolder from disappearing list. * @param holder The ViewHolder to be removed from the disappearing list. */ void removeFromDisappearedInLayout(ViewHolder holder) { InfoRecord record = mLayoutHolderMap.get(holder); if (record == null) { return; } record.flags &= ~FLAG_DISAPPEARED; } void process(ProcessCallback callback) { for (int index = mLayoutHolderMap.size() - 1; index >= 0; index --) { final ViewHolder viewHolder = mLayoutHolderMap.keyAt(index); final InfoRecord record = mLayoutHolderMap.removeAt(index); if ((record.flags & FLAG_APPEAR_AND_DISAPPEAR) == FLAG_APPEAR_AND_DISAPPEAR) { // Appeared then disappeared. Not useful for animations. callback.unused(viewHolder); } else if ((record.flags & FLAG_DISAPPEARED) != 0) { // Set as "disappeared" by the LayoutManager (addDisappearingView) if (record.preInfo == null) { // similar to appear disappear but happened between different layout passes. // this can happen when the layout manager is using auto-measure callback.unused(viewHolder); } else { callback.processDisappeared(viewHolder, record.preInfo, record.postInfo); } } else if ((record.flags & FLAG_APPEAR_PRE_AND_POST) == FLAG_APPEAR_PRE_AND_POST) { // Appeared in the layout but not in the adapter (e.g. entered the viewport) callback.processAppeared(viewHolder, record.preInfo, record.postInfo); } else if ((record.flags & FLAG_PRE_AND_POST) == FLAG_PRE_AND_POST) { // Persistent in both passes. Animate persistence callback.processPersistent(viewHolder, record.preInfo, record.postInfo); } else if ((record.flags & FLAG_PRE) != 0) { // Was in pre-layout, never been added to post layout callback.processDisappeared(viewHolder, record.preInfo, null); } else if ((record.flags & FLAG_POST) != 0) { // Was not in pre-layout, been added to post layout callback.processAppeared(viewHolder, record.preInfo, record.postInfo); } else if ((record.flags & FLAG_APPEAR) != 0) { // Scrap view. RecyclerView will handle removing/recycling this. } else if (DEBUG) { throw new IllegalStateException("record without any reasonable flag combination:/"); } InfoRecord.recycle(record); } } /** * Removes the ViewHolder from all list * @param holder The ViewHolder which we should stop tracking */ void removeViewHolder(ViewHolder holder) { for (int i = mOldChangedHolders.size() - 1; i >= 0; i--) { if (holder == mOldChangedHolders.valueAt(i)) { mOldChangedHolders.removeAt(i); break; } } final InfoRecord info = mLayoutHolderMap.remove(holder); if (info != null) { InfoRecord.recycle(info); } } void onDetach() { InfoRecord.drainCache(); } public void onViewDetached(ViewHolder viewHolder) { removeFromDisappearedInLayout(viewHolder); } interface ProcessCallback { void processDisappeared(ViewHolder viewHolder, @NonNull ItemHolderInfo preInfo, @Nullable ItemHolderInfo postInfo); void processAppeared(ViewHolder viewHolder, @Nullable ItemHolderInfo preInfo, ItemHolderInfo postInfo); void processPersistent(ViewHolder viewHolder, @NonNull ItemHolderInfo preInfo, @NonNull ItemHolderInfo postInfo); void unused(ViewHolder holder); } static class InfoRecord { // disappearing list static final int FLAG_DISAPPEARED = 1; // appear in pre layout list static final int FLAG_APPEAR = 1 << 1; // pre layout, this is necessary to distinguish null item info static final int FLAG_PRE = 1 << 2; // post layout, this is necessary to distinguish null item info static final int FLAG_POST = 1 << 3; static final int FLAG_APPEAR_AND_DISAPPEAR = FLAG_APPEAR | FLAG_DISAPPEARED; static final int FLAG_PRE_AND_POST = FLAG_PRE | FLAG_POST; static final int FLAG_APPEAR_PRE_AND_POST = FLAG_APPEAR | FLAG_PRE | FLAG_POST; int flags; @Nullable ItemHolderInfo preInfo; @Nullable ItemHolderInfo postInfo; static Pools.Pool<InfoRecord> sPool = new Pools.SimplePool<>(20); private InfoRecord() { } static InfoRecord obtain() { InfoRecord record = sPool.acquire(); return record == null ? new InfoRecord() : record; } static void recycle(InfoRecord record) { record.flags = 0; record.preInfo = null; record.postInfo = null; sPool.release(record); } static void drainCache() { //noinspection StatementWithEmptyBody while (sPool.acquire() != null); } } }
minobilis/Picca
app/src/main/java/com/roshin/gallery/support/widget/ViewInfoStore.java
Java
gpl-2.0
12,963
var Rect = require("utils/rect"); /** Resize a window * * @param options Options for resize * @param callback */ function resize(options,callback) { var winId = options.window.id, info = options.updateInfo, os = options.os, updateInfo = {}; // The target rect // $.extend(updateInfo,viewport.size().toData()); /* if (rect.__proto__.constructor.name == "Rect"){ $.extend(updateInfo,rect.toData()); } else { $.extend(updateInfo,rect); } */ $.extend(updateInfo,info); updateInfo.state = "normal"; /* Remarks: * * Sometimes Chrome on Ubuntu/Unity may not report the current state correctly. * So set to "normal" by default. Otherwise, it may not be able to resize maximized window * */ if (os == "MacOS") { delete updateInfo.state; // Don't set normal in MacOS. The animation will be mad } if (os == "Linux") { _resizeOnLinux(winId,updateInfo,callback); } else { chrome.windows.update(winId, updateInfo , callback); } } /** A special resize function for Linux due to the #72369 bug for Chrome on Linux * */ function _resizeOnLinux(winId,updateInfo,callback){ var lastSize = new Rect(); var newSize = new Rect(); var targetSize = new Rect(updateInfo); function checker() { // Check is the resize frozen? chrome.windows.get(winId,function(result) { newSize = new Rect(result); // console.log("checker",winId,lastSize,newSize,targetSize); if (lastSize.equal(newSize) || newSize.equal(targetSize)) { // Done! if (callback) callback(result); } else { lastSize = newSize; setTimeout(checker,100); } }); } lastSize = new Rect(); chrome.windows.update(winId, updateInfo , checker); }; module.exports = resize;
benlau/dualless
src/chrome/sys/toolbox/resize.js
JavaScript
gpl-2.0
1,910
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Oliorga\GeneratorBundle\Command; use Doctrine\Bundle\DoctrineBundle\Mapping\MetadataFactory; abstract class GenerateDoctrineCommand extends GeneratorCommand { public function isEnabled() { return class_exists('Doctrine\\Bundle\\DoctrineBundle\\DoctrineBundle'); } protected function parseShortcutNotation($shortcut) { $entity = str_replace('/', '\\', $shortcut); if (false === $pos = strpos($entity, ':')) { throw new \InvalidArgumentException(sprintf('The entity name must contain a : ("%s" given, expecting something like AcmeBlogBundle:Blog/Post)', $entity)); } return array(substr($entity, 0, $pos), substr($entity, $pos + 1)); } protected function getEntityMetadata($entity) { $factory = new MetadataFactory($this->getContainer()->get('doctrine')); return $factory->getClassMetadata($entity)->getMetadata(); } }
blacksad12/oliorga
src/Oliorga/GeneratorBundle/Command/GenerateDoctrineCommand.php
PHP
gpl-2.0
1,176
/* * Copyright (c) 2008-2009 Atheros Communications Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef ATH_H #define ATH_H #include <linux/skbuff.h> #include <linux/if_ether.h> <<<<<<< HEAD #include <linux/spinlock.h> ======= >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a #include <net/mac80211.h> /* * The key cache is used for h/w cipher state and also for * tracking station state such as the current tx antenna. * We also setup a mapping table between key cache slot indices * and station state to short-circuit node lookups on rx. * Different parts have different size key caches. We handle * up to ATH_KEYMAX entries (could dynamically allocate state). */ #define ATH_KEYMAX 128 /* max key cache size we handle */ static const u8 ath_bcast_mac[ETH_ALEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; struct ath_ani { bool caldone; <<<<<<< HEAD ======= int16_t noise_floor; >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a unsigned int longcal_timer; unsigned int shortcal_timer; unsigned int resetcal_timer; unsigned int checkani_timer; struct timer_list timer; }; <<<<<<< HEAD struct ath_cycle_counters { u32 cycles; u32 rx_busy; u32 rx_frame; u32 tx_frame; }; ======= >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a enum ath_device_state { ATH_HW_UNAVAILABLE, ATH_HW_INITIALIZED, }; enum ath_bus_type { ATH_PCI, ATH_AHB, ATH_USB, }; struct reg_dmn_pair_mapping { u16 regDmnEnum; u16 reg_5ghz_ctl; u16 reg_2ghz_ctl; }; struct ath_regulatory { char alpha2[2]; u16 country_code; u16 max_power_level; u32 tp_scale; u16 current_rd; u16 current_rd_ext; int16_t power_limit; struct reg_dmn_pair_mapping *regpair; }; <<<<<<< HEAD enum ath_crypt_caps { ATH_CRYPT_CAP_CIPHER_AESCCM = BIT(0), ATH_CRYPT_CAP_MIC_COMBINED = BIT(1), }; struct ath_keyval { u8 kv_type; u8 kv_pad; u16 kv_len; u8 kv_val[16]; /* TK */ u8 kv_mic[8]; /* Michael MIC key */ u8 kv_txmic[8]; /* Michael MIC TX key (used only if the hardware * supports both MIC keys in the same key cache entry; * in that case, kv_mic is the RX key) */ }; enum ath_cipher { ATH_CIPHER_WEP = 0, ATH_CIPHER_AES_OCB = 1, ATH_CIPHER_AES_CCM = 2, ATH_CIPHER_CKIP = 3, ATH_CIPHER_TKIP = 4, ATH_CIPHER_CLR = 5, ATH_CIPHER_MIC = 127 }; ======= >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a /** * struct ath_ops - Register read/write operations * * @read: Register read <<<<<<< HEAD * @multi_read: Multiple register read * @write: Register write * @enable_write_buffer: Enable multiple register writes * @write_flush: flush buffered register writes and disable buffering */ struct ath_ops { unsigned int (*read)(void *, u32 reg_offset); void (*multi_read)(void *, u32 *addr, u32 *val, u16 count); void (*write)(void *, u32 val, u32 reg_offset); void (*enable_write_buffer)(void *); void (*write_flush) (void *); u32 (*rmw)(void *, u32 reg_offset, u32 set, u32 clr); }; struct ath_common; struct ath_bus_ops; ======= * @write: Register write * @enable_write_buffer: Enable multiple register writes * @disable_write_buffer: Disable multiple register writes * @write_flush: Flush buffered register writes */ struct ath_ops { unsigned int (*read)(void *, u32 reg_offset); void (*write)(void *, u32 val, u32 reg_offset); void (*enable_write_buffer)(void *); void (*disable_write_buffer)(void *); void (*write_flush) (void *); }; struct ath_common; struct ath_bus_ops { enum ath_bus_type ath_bus_type; void (*read_cachesize)(struct ath_common *common, int *csz); bool (*eeprom_read)(struct ath_common *common, u32 off, u16 *data); void (*bt_coex_prep)(struct ath_common *common); }; >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a struct ath_common { void *ah; void *priv; struct ieee80211_hw *hw; int debug_mask; enum ath_device_state state; struct ath_ani ani; u16 cachelsz; u16 curaid; u8 macaddr[ETH_ALEN]; u8 curbssid[ETH_ALEN]; u8 bssidmask[ETH_ALEN]; u8 tx_chainmask; u8 rx_chainmask; u32 rx_bufsize; u32 keymax; DECLARE_BITMAP(keymap, ATH_KEYMAX); <<<<<<< HEAD DECLARE_BITMAP(tkip_keymap, ATH_KEYMAX); enum ath_crypt_caps crypt_caps; unsigned int clockrate; spinlock_t cc_lock; struct ath_cycle_counters cc_ani; struct ath_cycle_counters cc_survey; ======= u8 splitmic; >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a struct ath_regulatory regulatory; const struct ath_ops *ops; const struct ath_bus_ops *bus_ops; <<<<<<< HEAD bool btcoex_enabled; ======= >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a }; struct sk_buff *ath_rxbuf_alloc(struct ath_common *common, u32 len, gfp_t gfp_mask); void ath_hw_setbssidmask(struct ath_common *common); <<<<<<< HEAD void ath_key_delete(struct ath_common *common, struct ieee80211_key_conf *key); int ath_key_config(struct ath_common *common, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct ieee80211_key_conf *key); bool ath_hw_keyreset(struct ath_common *common, u16 entry); void ath_hw_cycle_counters_update(struct ath_common *common); int32_t ath_hw_get_listen_time(struct ath_common *common); extern __attribute__ ((format (printf, 3, 4))) int ath_printk(const char *level, struct ath_common *common, const char *fmt, ...); #define ath_emerg(common, fmt, ...) \ ath_printk(KERN_EMERG, common, fmt, ##__VA_ARGS__) #define ath_alert(common, fmt, ...) \ ath_printk(KERN_ALERT, common, fmt, ##__VA_ARGS__) #define ath_crit(common, fmt, ...) \ ath_printk(KERN_CRIT, common, fmt, ##__VA_ARGS__) #define ath_err(common, fmt, ...) \ ath_printk(KERN_ERR, common, fmt, ##__VA_ARGS__) #define ath_warn(common, fmt, ...) \ ath_printk(KERN_WARNING, common, fmt, ##__VA_ARGS__) #define ath_notice(common, fmt, ...) \ ath_printk(KERN_NOTICE, common, fmt, ##__VA_ARGS__) #define ath_info(common, fmt, ...) \ ath_printk(KERN_INFO, common, fmt, ##__VA_ARGS__) /** * enum ath_debug_level - atheros wireless debug level * * @ATH_DBG_RESET: reset processing * @ATH_DBG_QUEUE: hardware queue management * @ATH_DBG_EEPROM: eeprom processing * @ATH_DBG_CALIBRATE: periodic calibration * @ATH_DBG_INTERRUPT: interrupt processing * @ATH_DBG_REGULATORY: regulatory processing * @ATH_DBG_ANI: adaptive noise immunitive processing * @ATH_DBG_XMIT: basic xmit operation * @ATH_DBG_BEACON: beacon handling * @ATH_DBG_CONFIG: configuration of the hardware * @ATH_DBG_FATAL: fatal errors, this is the default, DBG_DEFAULT * @ATH_DBG_PS: power save processing * @ATH_DBG_HWTIMER: hardware timer handling * @ATH_DBG_BTCOEX: bluetooth coexistance * @ATH_DBG_BSTUCK: stuck beacons * @ATH_DBG_ANY: enable all debugging * * The debug level is used to control the amount and type of debugging output * we want to see. Each driver has its own method for enabling debugging and * modifying debug level states -- but this is typically done through a * module parameter 'debug' along with a respective 'debug' debugfs file * entry. */ enum ATH_DEBUG { ATH_DBG_RESET = 0x00000001, ATH_DBG_QUEUE = 0x00000002, ATH_DBG_EEPROM = 0x00000004, ATH_DBG_CALIBRATE = 0x00000008, ATH_DBG_INTERRUPT = 0x00000010, ATH_DBG_REGULATORY = 0x00000020, ATH_DBG_ANI = 0x00000040, ATH_DBG_XMIT = 0x00000080, ATH_DBG_BEACON = 0x00000100, ATH_DBG_CONFIG = 0x00000200, ATH_DBG_FATAL = 0x00000400, ATH_DBG_PS = 0x00000800, ATH_DBG_HWTIMER = 0x00001000, ATH_DBG_BTCOEX = 0x00002000, ATH_DBG_WMI = 0x00004000, ATH_DBG_BSTUCK = 0x00008000, ATH_DBG_ANY = 0xffffffff }; #define ATH_DBG_DEFAULT (ATH_DBG_FATAL) #ifdef CONFIG_ATH_DEBUG #define ath_dbg(common, dbg_mask, fmt, ...) \ ({ \ int rtn; \ if ((common)->debug_mask & dbg_mask) \ rtn = ath_printk(KERN_DEBUG, common, fmt, \ ##__VA_ARGS__); \ else \ rtn = 0; \ \ rtn; \ }) #define ATH_DBG_WARN(foo, arg...) WARN(foo, arg) #define ATH_DBG_WARN_ON_ONCE(foo) WARN_ON_ONCE(foo) #else static inline __attribute__ ((format (printf, 3, 4))) int ath_dbg(struct ath_common *common, enum ATH_DEBUG dbg_mask, const char *fmt, ...) { return 0; } #define ATH_DBG_WARN(foo, arg...) do {} while (0) #define ATH_DBG_WARN_ON_ONCE(foo) ({ \ int __ret_warn_once = !!(foo); \ unlikely(__ret_warn_once); \ }) #endif /* CONFIG_ATH_DEBUG */ /** Returns string describing opmode, or NULL if unknown mode. */ #ifdef CONFIG_ATH_DEBUG const char *ath_opmode_to_string(enum nl80211_iftype opmode); #else static inline const char *ath_opmode_to_string(enum nl80211_iftype opmode) { return "UNKNOWN"; } #endif ======= >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a #endif /* ATH_H */
Core2idiot/Kernel-Samsung-3.0...-
drivers/net/wireless/ath/ath.h
C
gpl-2.0
9,286
<?php namespace Drupal\spectre_mautic\Tests; use Drupal\Core\Url; use Drupal\simpletest\WebTestBase; /** * Simple test to ensure that main page loads with module enabled. * * @group spectre_mautic */ class LoadTest extends WebTestBase{ /** * Modules to enable. * * @var array */ public static $modules = ['spectre_mautic']; /** * A user with permission to administer site configuration. * * @var \Drupal\user\UserInterface */ protected $user; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->user = $this->drupalCreateUser(['administer site configuration']); $this->drupalLogin($this->user); } /** * Tests that the home page loads with a 200 response. */ public function testLoad() { $this->drupalGet(Url::fromRoute('<front>')); $this->assertResponse(200); } }
tannguyen04/99mobile
web/modules/custom/spectre_mautic/src/Tests/LoadTest.php
PHP
gpl-2.0
876
/* * arch/arm/mach-rpc/include/mach/io.h * * Copyright (C) 1997 Russell King * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Modifications: * 06-Dec-1997 RMK Created. */ #ifndef __ASM_ARM_ARCH_IO_H #define __ASM_ARM_ARCH_IO_H #include <mach/hardware.h> #define IO_SPACE_LIMIT 0xffffffff /* * We use two different types of addressing - PC style addresses, and ARM * addresses. PC style accesses the PC hardware with the normal PC IO * addresses, eg 0x3f8 for serial#1. ARM addresses are 0x80000000+ * and are translated to the start of IO. Note that all addresses are * shifted left! */ #define __PORT_PCIO(x) (!((x) & 0x80000000)) /* * Dynamic IO functions. */ static inline void __outb (unsigned int value, unsigned int port) { unsigned long temp; __asm__ __volatile__( "tst %2, #0x80000000\n\t" "mov %0, %4\n\t" "addeq %0, %0, %3\n\t" "strb %1, [%0, %2, lsl #2] @ outb" : "=&r" (temp) : "r" (value), "r" (port), "Ir" (PCIO_BASE - IO_BASE), "Ir" (IO_BASE) : "cc"); } static inline void __outw (unsigned int value, unsigned int port) { unsigned long temp; __asm__ __volatile__( "tst %2, #0x80000000\n\t" "mov %0, %4\n\t" "addeq %0, %0, %3\n\t" "str %1, [%0, %2, lsl #2] @ outw" : "=&r" (temp) : "r" (value|value<<16), "r" (port), "Ir" (PCIO_BASE - IO_BASE), "Ir" (IO_BASE) : "cc"); } static inline void __outl (unsigned int value, unsigned int port) { unsigned long temp; __asm__ __volatile__( "tst %2, #0x80000000\n\t" "mov %0, %4\n\t" "addeq %0, %0, %3\n\t" "str %1, [%0, %2, lsl #2] @ outl" : "=&r" (temp) : "r" (value), "r" (port), "Ir" (PCIO_BASE - IO_BASE), "Ir" (IO_BASE) : "cc"); } #define DECLARE_DYN_IN(sz,fnsuffix,instr) \ static inline unsigned sz __in##fnsuffix (unsigned int port) \ { \ unsigned long temp, value; \ __asm__ __volatile__( \ "tst %2, #0x80000000\n\t" \ "mov %0, %4\n\t" \ "addeq %0, %0, %3\n\t" \ "ldr" instr " %1, [%0, %2, lsl #2] @ in" #fnsuffix \ : "=&r" (temp), "=r" (value) \ : "r" (port), "Ir" (PCIO_BASE - IO_BASE), "Ir" (IO_BASE) \ : "cc"); \ return (unsigned sz)value; \ } static inline void __iomem *__deprecated __ioaddr(unsigned int port) { void __iomem *ret; if (__PORT_PCIO(port)) ret = PCIO_BASE; else ret = IO_BASE; return ret + (port << 2); } #define DECLARE_IO(sz,fnsuffix,instr) \ DECLARE_DYN_IN(sz,fnsuffix,instr) DECLARE_IO(char,b,"b") DECLARE_IO(short,w,"") DECLARE_IO(int,l,"") #undef DECLARE_IO #undef DECLARE_DYN_IN /* * Constant address IO functions * * These have to be macros for the 'J' constraint to work - * +/-4096 immediate operand. */ #define __outbc(value,port) \ ({ \ if (__PORT_PCIO((port))) \ __asm__ __volatile__( \ "strb %0, [%1, %2] @ outbc" \ : : "r" (value), "r" (PCIO_BASE), "Jr" ((port) << 2)); \ else \ __asm__ __volatile__( \ "strb %0, [%1, %2] @ outbc" \ : : "r" (value), "r" (IO_BASE), "r" ((port) << 2)); \ }) #define __inbc(port) \ ({ \ unsigned char result; \ if (__PORT_PCIO((port))) \ __asm__ __volatile__( \ "ldrb %0, [%1, %2] @ inbc" \ : "=r" (result) : "r" (PCIO_BASE), "Jr" ((port) << 2)); \ else \ __asm__ __volatile__( \ "ldrb %0, [%1, %2] @ inbc" \ : "=r" (result) : "r" (IO_BASE), "r" ((port) << 2)); \ result; \ }) #define __outwc(value,port) \ ({ \ unsigned long __v = value; \ if (__PORT_PCIO((port))) \ __asm__ __volatile__( \ "str %0, [%1, %2] @ outwc" \ : : "r" (__v|__v<<16), "r" (PCIO_BASE), "Jr" ((port) << 2)); \ else \ __asm__ __volatile__( \ "str %0, [%1, %2] @ outwc" \ : : "r" (__v|__v<<16), "r" (IO_BASE), "r" ((port) << 2)); \ }) #define __inwc(port) \ ({ \ unsigned short result; \ if (__PORT_PCIO((port))) \ __asm__ __volatile__( \ "ldr %0, [%1, %2] @ inwc" \ : "=r" (result) : "r" (PCIO_BASE), "Jr" ((port) << 2)); \ else \ __asm__ __volatile__( \ "ldr %0, [%1, %2] @ inwc" \ : "=r" (result) : "r" (IO_BASE), "r" ((port) << 2)); \ result & 0xffff; \ }) #define __outlc(value,port) \ ({ \ unsigned long __v = value; \ if (__PORT_PCIO((port))) \ __asm__ __volatile__( \ "str %0, [%1, %2] @ outlc" \ : : "r" (__v), "r" (PCIO_BASE), "Jr" ((port) << 2)); \ else \ __asm__ __volatile__( \ "str %0, [%1, %2] @ outlc" \ : : "r" (__v), "r" (IO_BASE), "r" ((port) << 2)); \ }) #define __inlc(port) \ ({ \ unsigned long result; \ if (__PORT_PCIO((port))) \ __asm__ __volatile__( \ "ldr %0, [%1, %2] @ inlc" \ : "=r" (result) : "r" (PCIO_BASE), "Jr" ((port) << 2)); \ else \ __asm__ __volatile__( \ "ldr %0, [%1, %2] @ inlc" \ : "=r" (result) : "r" (IO_BASE), "r" ((port) << 2)); \ result; \ }) #define inb(p) (__builtin_constant_p((p)) ? __inbc(p) : __inb(p)) #define inw(p) (__builtin_constant_p((p)) ? __inwc(p) : __inw(p)) #define inl(p) (__builtin_constant_p((p)) ? __inlc(p) : __inl(p)) #define outb(v,p) (__builtin_constant_p((p)) ? __outbc(v,p) : __outb(v,p)) #define outw(v,p) (__builtin_constant_p((p)) ? __outwc(v,p) : __outw(v,p)) #define outl(v,p) (__builtin_constant_p((p)) ? __outlc(v,p) : __outl(v,p)) /* the following macro is deprecated */ #define ioaddr(port) ((unsigned long)__ioaddr((port))) #define insb(p,d,l) __raw_readsb(__ioaddr(p),d,l) #define insw(p,d,l) __raw_readsw(__ioaddr(p),d,l) #define outsb(p,d,l) __raw_writesb(__ioaddr(p),d,l) #define outsw(p,d,l) __raw_writesw(__ioaddr(p),d,l) #endif
leftrepo/Owl-Kernel-for-Xperia-Sola
arch/arm/mach-rpc/include/mach/io.h
C
gpl-2.0
5,865
CREATE TABLE [dbo].[Customer_User] ( UserID uniqueidentifier NOT NULL, CustomerID INT NOT NULL CONSTRAINT pk_UserID_CustomerID PRIMARY KEY (UserID,CustomerID), CONSTRAINT fk_UserID FOREIGN KEY (UserID) REFERENCES [dbo].[aspnet_Users](UserId), CONSTRAINT fk_CustomerID FOREIGN KEY (CustomerID) REFERENCES [dbo].[Customer](CustomerID) )
sarychuk/MIS418GroupProject
Database/MIS418 DB/CustomerUser.table.sql
SQL
gpl-2.0
344
/** * Select2 Spanish translation */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "No se encontraron resultados"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Por favor, introduzca " + n + " car" + (n == 1? "ácter" : "acteres"); }, formatInputTooLong: function (input, max) { var n = input.length - max; return "Por favor, elimine " + n + " car" + (n == 1? "ácter" : "acteres"); }, formatSelectionTooBig: function (limit) { return "Sólo puede seleccionar " + limit + " elemento" + (limit == 1 ? "" : "s"); }, formatLoadMore: function (pageNumber) { return "Cargando más resultados…"; }, formatSearching: function () { return "Buscando…"; } }); })(jQuery);
sadpiglet20/ninesouthestates
wp-content/themes/real-spaces/includes/ReduxCore/assets/js/vendor/select2/select2_locale_es.js
JavaScript
gpl-2.0
822
<html> <body> /*Create table and test all DML Operation on the table */ <?php $conn=odbc_connect('mycsql','root','manager'); if (!$conn) { echo "Connection Failed"; exit(1); } $sth = odbc_prepare($conn,"CREATE TABLE t1(f1 INT, f2 CHAR(20));"); $res = odbc_execute($sth); if (!$res) { echo "Error in Creation"; exit(2); } echo "Table Created"; $sth = odbc_prepare($conn, "INSERT INTO t1(f1, f2) VALUES(12,'Lakshye');"); $res = odbc_execute($sth); if (!$res) { echo "Error in Insertion"; exit(3); } echo "\nRecord Inserted"; $sth = odbc_prepare($conn, "INSERT INTO t1(f1, f2) VALUES(13,'CSQL');"); $res = odbc_execute($sth); if (!$res) { echo "Error in Insertion"; exit(3); } echo "\nRecord Inserted"; $sth = 'select * from t1;'; $rs = odbc_exec($conn, $sth); if (!$rs) { echo "Error in selection"; exit(4); } echo "\nselect executed\n"; echo "<table><tr>"; echo "<th>ROLL</th>"; echo "<th>NAME</th></tr>"; echo "\nfetch started\n"; while (odbc_fetch_row($rs)) { $roll=preg_replace('/[\x00-\x09\x0B-\x19\x7F]/', '',odbc_result($rs, 1)); $name=preg_replace('/[\x00-\x09\x0B-\x19\x7F]/', '',odbc_result($rs, 2)); echo "<tr><td>$roll</td>"; echo "<td>$name</td></tr>\n"; } echo "</table>"; $sth = odbc_prepare($conn, "UPDATE t1 SET f2='TWELVE' WHERE f1=12;"); $res = odbc_execute($sth); if (!$res) { echo "\nError in Updation\n"; exit(5); } echo "\nRecord Updated\n"; $sth = 'select * from t1;'; $rs = odbc_exec($conn, $sth); while (odbc_fetch_row($rs)) { $roll=preg_replace('/[\x00-\x09\x0B-\x19\x7F]/', '',odbc_result($rs, 1)); $name=preg_replace('/[\x00-\x09\x0B-\x19\x7F]/', '',odbc_result($rs, 2)); echo "<tr><td>$roll</td>"; echo "<td>$name</td></tr>\n"; } echo "</table>"; $sth = odbc_prepare($conn, "DELETE FROM t1 WHERE f1=13;"); $res = odbc_execute($sth); if (!$res) { echo "\nError in Deletion\n"; exit(6); } echo "\nRecord Deleted\n"; $sth = 'select * from t1;'; $rs = odbc_exec($conn, $sth); while (odbc_fetch_row($rs)) { $roll=preg_replace('/[\x00-\x09\x0B-\x19\x7F]/', '',odbc_result($rs, 1)); $name=preg_replace('/[\x00-\x09\x0B-\x19\x7F]/', '',odbc_result($rs, 2)); echo "<tr><td>$roll</td>"; echo "<td>$name</td></tr>\n"; } echo "</table>"; $sth=odbc_prepare($conn,"DROP TABLE t1;"); $res = odbc_execute($sth); if (!$res) { echo "\nError in Drop Table"; exit(7); } echo "\nTable Dropped \nTest Passed"; odbc_close($conn); ?> </body> </html>
mattibickel/csql
examples/php/phpexample.php
PHP
gpl-2.0
2,436
#include <dcc/RosDccData.h> #include <dcc/History.h> #include <dcc/ClearFreq.h> #include <std_srvs/Empty.h> #include <ros/ros.h> #include <pthread.h> #include <map> #include <vector> #include <list> std::map<int, int> counts; std::map<int, int> nonzero; ros::Subscriber dccSub; ros::Publisher outgoing; ros::ServiceServer clearall; ros::ServiceServer clearind; pthread_mutex_t dcclock; std::list<int> my_freqs; void loadParams(){ } bool contains(std::list<int> l, int test){ for (std::list<int>::iterator it = my_freqs.begin();it!=my_freqs.end();it++){ if (*it==test){ return true; } } return false; } bool clearIndService(dcc::ClearFreq::Request &req, dcc::ClearFreq::Response &res){ pthread_mutex_lock(&dcclock); counts[req.freq]=0; nonzero[req.freq]=0; pthread_mutex_unlock(&dcclock); return true; } bool clearService(std_srvs::Empty::Request &req ,std_srvs::Empty::Response &res){ pthread_mutex_lock(&dcclock); my_freqs.clear(); counts.clear(); nonzero.clear(); pthread_mutex_unlock(&dcclock); return true; } void dccIn(const dcc::RosDccData::ConstPtr &msg){ int str = msg->strength; int f = msg->frequency; pthread_mutex_lock(&dcclock); if (!contains(my_freqs,f)){ my_freqs.push_back(f); my_freqs.sort(); } counts[f]++; if (str>0){ nonzero[f]++; } dcc::History omsg; std::list<int>::iterator it; for (it = my_freqs.begin();it!=my_freqs.end();it++){ omsg.frequencies.push_back(*it); omsg.counts.push_back(counts[*it]); omsg.nonzeros.push_back(nonzero[*it]); } outgoing.publish(omsg); pthread_mutex_unlock(&dcclock); ROS_INFO("Have: %Zu freqs",my_freqs.size()); } void launch(){ ros::NodeHandle nh("dcc"); dccSub = nh.subscribe<dcc::RosDccData>("signal",10,&dccIn); outgoing = nh.advertise<dcc::History>("history",10); clearall = nh.advertiseService("clear_counts",&clearService); clearind = nh.advertiseService("clear_single",&clearIndService); } int main(int argc,char** argv){ if (!ros::isInitialized()){ ros::init(argc,argv,"dcchistory"); } ROS_INFO("Starting history..."); pthread_mutex_init(&dcclock,NULL); loadParams(); launch(); ROS_INFO("Publishing history of /dcc/signal to /dcc/history"); ros::spin(); pthread_mutex_destroy(&dcclock); return EXIT_SUCCESS; }
jodavaho/sig_client
ROSSH/src/cpp/sampler.cpp
C++
gpl-2.0
2,248
// -*- C++ -*- // Class which controls what tasks are executed. // Copyright (C) 2004 David Dooling <banjo@users.sourceforge.net> // // This file is part of CHIMP. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. // #ifndef CH_MANAGER_H #define CH_MANAGER_H 1 #include <map> #include <string> #include <vector> #include "except.h" #include "mechanism.h" #include "unique.h" #include "task.h" // set namespace to avoid possible clashes CH_BEGIN_NAMESPACE // set of tasks for a specific mechanism typedef CH_STD::map<mechanism*,task::seq> mechanism_tasks; typedef mechanism_tasks::iterator mechanism_tasks_iter; typedef mechanism_tasks::const_iterator mechanism_tasks_citer; typedef CH_STD::vector<CH_STD::string> input_seq; typedef input_seq::iterator input_seq_iter; typedef input_seq::const_iterator input_seq_citer; // class to parse input file and perform tasks class task_manager { static task_manager master; // singleton instance of task_manager mechanism::seq mechanisms; // all mechanisms in correct order mechanism_tasks tasks; // the to do list for each mechanism mechanism* current; // current active mechanism private: // ctor: (default) make private for singleton task_manager(); // prevent copy construction and assignment task_manager(const task_manager&); task_manager& operator=(const task_manager&); // parse a single control file void parse_control(CH_STD::string path) throw (bad_file, bad_input, bad_pointer, bad_request, bad_value, bad_type); // this, tokenizer(), file_name(), // parameter_file(), task_file(), // new_mechanism() // create an empty mechanism, put it into list, make current void new_mechanism(const CH_STD::string& name) throw (bad_file, bad_input, bad_request); // mechanism(), // mechanism::parse() // create a new parameter task and parse input void parameter_file(const CH_STD::string& path) throw (bad_pointer, bad_file, bad_input); // this, parameter_task(), // parameter_task::parse() // send the file to the task parser and insert return values void task_file(const CH_STD::string& file_name) throw (bad_pointer, bad_file, bad_input, bad_request, bad_value, bad_type); // this, task::parse_file() public: // dtor: erase name from list and delete tasks ~task_manager(); // return a reference to the singleton static task_manager& get(); // parse a list of control files void parse_control(const input_seq& input_files) throw (bad_file, bad_input, bad_pointer, bad_request, bad_value, bad_type); // parse_control() // return pointer to current mechanism mechanism* get_current_mechanism() const throw (bad_pointer); // this // find the task of the given name for current mechanism const task* find_task(const CH_STD::string& name) throw (bad_pointer); // this // perform the given tasks void perform() throw (bad_pointer, bad_file, bad_input, bad_value, bad_type, bad_request); // this, model_reaction(), model_task::perform() }; // end class task_manager CH_END_NAMESPACE #endif // not CH_MANAGER_H /* $Id: manager.h,v 1.1.1.1 2004/11/25 20:24:05 banjo Exp $ */
ddgenome/chimp
src/manager.h
C
gpl-2.0
3,813
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html lang="en"> <head> <meta name="generator" content="AWStats 6.95 (build 1.943) from config file awstats.ckbran.ru.conf (http://awstats.sourceforge.net)"> <meta name="robots" content="noindex,nofollow"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="description" content="Awstats - Advanced Web Statistics for ckbran.ru (2013-09) - downloads"> <title>Statistics for ckbran.ru (2013-09) - downloads</title> <style type="text/css"> <!-- body { font: 11px verdana, arial, helvetica, sans-serif; background-color: #FFFFFF; margin-top: 0; margin-bottom: 0; } .aws_bodyl { } .aws_border { border-collapse: collapse; background-color: #CCCCDD; padding: 1px 1px 1px 1px; margin-top: 0px; margin-bottom: 0px; } .aws_title { font: 13px verdana, arial, helvetica, sans-serif; font-weight: bold; background-color: #CCCCDD; text-align: center; margin-top: 0; margin-bottom: 0; padding: 1px 1px 1px 1px; color: #000000; } .aws_blank { font: 13px verdana, arial, helvetica, sans-serif; background-color: #FFFFFF; text-align: center; margin-bottom: 0; padding: 1px 1px 1px 1px; } .aws_data { background-color: #FFFFFF; border-top-width: 1px; border-left-width: 0px; border-right-width: 0px; border-bottom-width: 0px; } .aws_formfield { font: 13px verdana, arial, helvetica; } .aws_button { font-family: arial,verdana,helvetica, sans-serif; font-size: 12px; border: 1px solid #ccd7e0; background-image : url(/awstatsicons/other/button.gif); } th { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; padding: 1px 2px 1px 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:center; color: #000000; } th.aws { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; padding: 1px 2px 1px 1px; font-size: 13px; font-weight: bold; } td { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:center; color: #000000; } td.aws { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:left; color: #000000; padding: 0px;} td.awsm { border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; font: 11px verdana, arial, helvetica, sans-serif; text-align:left; color: #000000; padding: 0px; } b { font-weight: bold; } a { font: 11px verdana, arial, helvetica, sans-serif; } a:link { color: #0011BB; text-decoration: none; } a:visited { color: #0011BB; text-decoration: none; } a:hover { color: #605040; text-decoration: underline; } .currentday { font-weight: bold; } //--> </style> </head> <body style="margin-top: 0px"> <a name="top"></a> <a name="menu">&nbsp;</a> <form name="FormDateFilter" action="/cgi-bin/awstats.pl?config=ckbran.ru&amp;output=downloads" style="padding: 0px 0px 0px 0px; margin-top: 0"> <table class="aws_border" border="0" cellpadding="2" cellspacing="0" width="100%"> <tr><td> <table class="aws_data sortable" border="0" cellpadding="1" cellspacing="0" width="100%"> <tr><td class="aws" valign="middle"><b>Statistics for:</b>&nbsp;</td><td class="aws" valign="middle"><span style="font-size: 14px;">ckbran.ru</span></td><td align="right" rowspan="3"><a href="http://awstats.sourceforge.net" target="awstatshome"><img src="/awstatsicons/other/awstats_logo6.png" border="0" alt='Awstats Web Site' title='Awstats Web Site' /></a></td></tr> <tr valign="middle"><td class="aws" valign="middle" width="150"><b>Last Update:</b>&nbsp;</td><td class="aws" valign="middle"><span style="font-size: 12px;">30 Oct 2013 - 00:01</span></td></tr> <tr><td class="aws" valign="middle"><b>Reported period:</b></td><td class="aws" valign="middle"><span style="font-size: 14px;">Month Sep 2013</span></td></tr> </table> </td></tr></table> </form> <table> <tr><td class="aws"><a href="javascript:parent.window.close();">Close window</a></td></tr> </table>
AxelFG/ckbran-inf
old/webstat/awstats.ckbran.ru.downloads.092013.html
HTML
gpl-2.0
4,211
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_25) on Wed Aug 07 11:50:46 BRT 2013 --> <title>Uses of Class br.com.dazen.main.App</title> <meta name="date" content="2013-08-07"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class br.com.dazen.main.App"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../br/com/dazen/main/App.html" title="class in br.com.dazen.main">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?br/com/dazen/main/class-use/App.html" target="_top">Frames</a></li> <li><a href="App.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class br.com.dazen.main.App" class="title">Uses of Class<br>br.com.dazen.main.App</h2> </div> <div class="classUseContainer">No usage of br.com.dazen.main.App</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../br/com/dazen/main/App.html" title="class in br.com.dazen.main">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?br/com/dazen/main/class-use/App.html" target="_top">Frames</a></li> <li><a href="App.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
CharlesQueiroz/NFValidator
doc/br/com/dazen/main/class-use/App.html
HTML
gpl-2.0
3,976
package edu.stanford.nlp.classify; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import edu.stanford.nlp.ling.Datum; import edu.stanford.nlp.math.ADMath; import edu.stanford.nlp.math.ArrayMath; import edu.stanford.nlp.math.DoubleAD; import edu.stanford.nlp.optimization.AbstractStochasticCachingDiffUpdateFunction; import edu.stanford.nlp.optimization.StochasticCalculateMethods; import edu.stanford.nlp.util.Index; /** * Maximizes the conditional likelihood with a given prior. * * @author Dan Klein * @author Galen Andrew * @author Chris Cox (merged w/ SumConditionalObjectiveFunction, 2/16/05) * @author Sarah Spikes (Templatization, allowing an Iterable<Datum<L, F>> to be passed in instead of a GeneralDataset<L, F>) * @author Angel Chang (support in place SGD - extend AbstractStochasticCachingDiffUpdateFunction) */ public class LogConditionalObjectiveFunction<L, F> extends AbstractStochasticCachingDiffUpdateFunction { public void setPrior(LogPrior prior) { this.prior = prior; clearCache(); } protected LogPrior prior; protected int numFeatures = 0; protected int numClasses = 0; protected int[][] data = null; protected Iterable<Datum<L, F>> dataIterable = null; protected double[][] values = null; protected int[] labels = null; protected float[] dataweights = null; protected double[] derivativeNumerator = null; protected DoubleAD[] xAD = null; protected double [] priorDerivative = null; //The only reason this is around is because the Prior Functions don't handle stochastic calculations yet. protected DoubleAD[] derivativeAD = null; protected DoubleAD[] sums = null; protected DoubleAD[] probs = null; protected Index<L> labelIndex = null; protected Index<F> featureIndex = null; protected boolean useIterable = false; protected boolean useSummedConditionalLikelihood = false; //whether to use sumConditional or logConditional @Override public int domainDimension() { return numFeatures * numClasses; } @Override public int dataDimension(){ return data.length; } int classOf(int index) { return index % numClasses; } int featureOf(int index) { return index / numClasses; } protected int indexOf(int f, int c) { return f * numClasses + c; } public double[][] to2D(double[] x) { double[][] x2 = new double[numFeatures][numClasses]; for (int i = 0; i < numFeatures; i++) { for (int j = 0; j < numClasses; j++) { x2[i][j] = x[indexOf(i, j)]; } } return x2; } /** * Calculate the conditional likelihood. * If <code>useSummedConditionalLikelihood</code> is <code>false</code> (the default), * this calculates standard(product) CL, otherwise this calculates summed CL. * What's the difference? See Klein and Manning's 2002 EMNLP paper. */ @Override protected void calculate(double[] x) { //If the batchSize is 0 then use the regular calculate methods if (useSummedConditionalLikelihood) { calculateSCL(x); } else { calculateCL(x); } } /* * This function is used to comme up with an estimate of the value / gradient based on only a small * portion of the data (refered to as the batchSize for lack of a better term. In this case batch does * not mean All!! It should be thought of in the sense of "a small batch of the data". */ @Override public void calculateStochastic(double[] x, double[] v, int[] batch){ if(method.calculatesHessianVectorProduct() && v != null){ // This is used for Stochastic Methods that involve second order information (SMD for example) if(method.equals(StochasticCalculateMethods.AlgorithmicDifferentiation)){ calculateStochasticAlgorithmicDifferentiation(x,v,batch); }else if(method.equals(StochasticCalculateMethods.IncorporatedFiniteDifference)){ calculateStochasticFiniteDifference(x,v,finiteDifferenceStepSize,batch); } } else{ //This is used for Stochastic Methods that don't need anything but the gradient (SGD) calculateStochasticGradientOnly(x,batch); } } /** * Calculate the summed conditional likelihood of this data by summing * conditional estimates. * */ private void calculateSCL(double[] x) { //System.out.println("Checking at: "+x[0]+" "+x[1]+" "+x[2]); value = 0.0; Arrays.fill(derivative, 0.0); double[] sums = new double[numClasses]; double[] probs = new double[numClasses]; double[] counts = new double[numClasses]; Arrays.fill(counts, 0.0); for (int d = 0; d < data.length; d++) { // if (d == testMin) { // d = testMax - 1; // continue; // } int[] features = data[d]; // activation Arrays.fill(sums, 0.0); for (int c = 0; c < numClasses; c++) { for (int f = 0; f < features.length; f++) { int i = indexOf(features[f], c); sums[c] += x[i]; } } // expectation (slower routine replaced by fast way) // double total = Double.NEGATIVE_INFINITY; // for (int c=0; c<numClasses; c++) { // total = SloppyMath.logAdd(total, sums[c]); // } double total = ArrayMath.logSum(sums); int ld = labels[d]; for (int c = 0; c < numClasses; c++) { probs[c] = Math.exp(sums[c] - total); for (int f = 0; f < features.length; f++) { int i = indexOf(features[f], c); derivative[i] += probs[ld] * probs[c]; } } // observed for (int f = 0; f < features.length; f++) { int i = indexOf(features[f], labels[d]); derivative[i] -= probs[ld]; } value -= probs[ld]; } // priors if (true) { for (int i = 0; i < x.length; i++) { double k = 1.0; double w = x[i]; value += k * w * w / 2.0; derivative[i] += k * w; } } } /** * Calculate the conditional likelihood of this data by multiplying * conditional estimates. * */ private void calculateCL(double[] x) { if (values != null) { rvfcalculate(x); return; } //System.out.println("Checking at: "+x[0]+" "+x[1]+" "+x[2]); value = 0.0; if (derivative == null) { derivative = new double[x.length]; } else { Arrays.fill(derivative, 0.0); } if (derivativeNumerator == null) { derivativeNumerator = new double[x.length]; //use dataIterable if data is null & vice versa if(data != null) { for (int d = 0; d < data.length; d++) { // if (d == testMin) { // d = testMax - 1; // continue; // } int[] features = data[d]; for (int f = 0; f < features.length; f++) { int i = indexOf(features[f], labels[d]); if (dataweights == null) { derivativeNumerator[i] -= 1; } else { derivativeNumerator[i] -= dataweights[d]; } } } } //TODO: Make sure this work as expected!! else if(dataIterable != null) { //int index = 0; for (Datum<L, F> datum : dataIterable) { // if (d == testMin) { // d = testMax - 1; // continue; // } Collection<F> features = datum.asFeatures(); for (F feature : features) { int i = indexOf(featureIndex.indexOf(feature), labelIndex.indexOf(datum.label())); if (dataweights == null) { derivativeNumerator[i] -= 1; } /*else { derivativeNumerator[i] -= dataweights[index]; }*/ } } } else { System.err.println("Both were null! Couldn't calculate."); System.exit(-1); } } copy(derivative, derivativeNumerator); // Arrays.fill(derivative, 0.0); double[] sums = new double[numClasses]; double[] probs = new double[numClasses]; // double[] counts = new double[numClasses]; // Arrays.fill(counts, 0.0); Iterator<Datum<L, F>> iter = null; int d = -1; if(useIterable) iter = dataIterable.iterator(); Datum<L, F> datum = null; while(true){ if(useIterable) { if(!iter.hasNext()) break; datum = iter.next(); } else { d++; if(d >= data.length) break; } // if (d == testMin) { // d = testMax - 1; // continue; // } // activation Arrays.fill(sums, 0.0); double total = 0; if(!useIterable) { int[] featuresArr = data[d]; for (int c = 0; c < numClasses; c++) { for (int f = 0; f < featuresArr.length; f++) { int i = indexOf(featuresArr[f], c); sums[c] += x[i]; } } // expectation (slower routine replaced by fast way) // double total = Double.NEGATIVE_INFINITY; // for (int c=0; c<numClasses; c++) { // total = SloppyMath.logAdd(total, sums[c]); // } total = ArrayMath.logSum(sums); for (int c = 0; c < numClasses; c++) { probs[c] = Math.exp(sums[c] - total); if (dataweights != null) { probs[c] *= dataweights[d]; } for (int f = 0; f < featuresArr.length; f++) { int i = indexOf(featuresArr[f], c); derivative[i] += probs[c]; } } } else { Collection<F> features = datum.asFeatures(); for (int c = 0; c < numClasses; c++) { for (F feature : features) { int i = indexOf(featureIndex.indexOf(feature), c); sums[c] += x[i]; } } // expectation (slower routine replaced by fast way) // double total = Double.NEGATIVE_INFINITY; // for (int c=0; c<numClasses; c++) { // total = SloppyMath.logAdd(total, sums[c]); // } total = ArrayMath.logSum(sums); for (int c = 0; c < numClasses; c++) { probs[c] = Math.exp(sums[c] - total); if (dataweights != null) { probs[c] *= dataweights[d]; } for (F feature : features) { int i = indexOf(featureIndex.indexOf(feature), c); derivative[i] += probs[c]; } } } int labelindex; if(useIterable) labelindex = labelIndex.indexOf(datum.label()); else labelindex = labels[d]; double dV = sums[labelindex] - total; if (dataweights != null) { dV *= dataweights[d]; } value -= dV; } value += prior.compute(x, derivative); } public void calculateStochasticFiniteDifference(double[] x,double[] v, double h, int[] batch){ // THOUGHTS: // does applying the renormalization (g(x+hv)-g(x)) / h at each step along the way // introduce too much error to makes this method numerically accurate? // akleeman Feb 23 2007 // Answer to my own question: Feb 25th // Doesn't look like it!! With h = 1e-4 it seems like the Finite Difference makes almost // exactly the same step as the exact hessian vector product calculated through AD. // That said it's probably (in the case of the Log Conditional Objective function) logical // to only use finite difference. Unless of course the function is somehow nearly singular, // in which case finite difference could turn what is a convex problem into a singular proble... NOT GOOD. if (values != null) { rvfcalculate(x); return; } value = 0.0; if (priorDerivative == null) { priorDerivative = new double[x.length]; } double priorFactor = batch.length/(data.length*prior.getSigma()*prior.getSigma()); derivative = ArrayMath.multiply(x,priorFactor); HdotV = ArrayMath.multiply(v,priorFactor); //Arrays.fill(derivative, 0.0); double[] sums = new double[numClasses]; double[] sumsV = new double[numClasses]; double[] probs = new double[numClasses]; double[] probsV = new double[numClasses]; for (int d = 0; d <batch.length; d++) { //Sets the index based on the current batch int m = batch[d]; int[] features = data[m]; // activation Arrays.fill(sums, 0.0); Arrays.fill(sumsV,0.0); for (int c = 0; c < numClasses; c++) { for (int f = 0; f < features.length; f++) { int i = indexOf(features[f], c); sums[c] += x[i]; sumsV[c] += x[i] + h*v[i]; } } double total = ArrayMath.logSum(sums); double totalV = ArrayMath.logSum(sumsV); for (int c = 0; c < numClasses; c++) { probs[c] = Math.exp(sums[c] - total); probsV[c] = Math.exp(sumsV[c]- totalV); if (dataweights != null) { probs[c] *= dataweights[m]; probsV[c] *= dataweights[m]; } for (int f = 0; f < features.length; f++) { int i = indexOf(features[f], c); //derivative[i] += (-1); derivative[i] += probs[c]; HdotV[i] += (probsV[c] - probs[c])/h; if( c == labels[m]) {derivative[i] -= 1;} } } double dV = sums[labels[m]] - total; if (dataweights != null) { dV *= dataweights[m]; } value -= dV; } //Why was this being copied? -akleeman //double[] tmpDeriv = new double[derivative.length]; //System.arraycopy(derivative,0,tmpDeriv,0,derivative.length); value += ((double) batch.length)/((double) data.length)*prior.compute(x,priorDerivative); } public void calculateStochasticGradientOnly(double[] x, int[] batch) { if (values != null) { rvfcalculate(x); return; } value = 0.0; int batchSize = batch.length; if (priorDerivative == null) { priorDerivative = new double[x.length]; } double priorFactor = batchSize/(data.length*prior.getSigma()*prior.getSigma()); derivative = ArrayMath.multiply(x,priorFactor); //Arrays.fill(derivative, 0.0); double[] sums = new double[numClasses]; //double[] sumsV = new double[numClasses]; double[] probs = new double[numClasses]; //double[] probsV = new double[numClasses]; for (int d = 0; d <batchSize; d++) { //Sets the index based on the current batch int m = batch[d]; int[] features = data[m]; // activation Arrays.fill(sums, 0.0); //Arrays.fill(sumsV,0.0); for (int c = 0; c < numClasses; c++) { for (int f = 0; f < features.length; f++) { int i = indexOf(features[f], c); sums[c] += x[i]; } } double total = ArrayMath.logSum(sums); //double totalV = ArrayMath.logSum(sumsV); for (int c = 0; c < numClasses; c++) { probs[c] = Math.exp(sums[c] - total); //probsV[c] = Math.exp(sumsV[c]- totalV); if (dataweights != null) { probs[c] *= dataweights[m]; //probsV[c] *= dataweights[m]; } for (int f = 0; f < features.length; f++) { int i = indexOf(features[f], c); //derivative[i] += (-1); derivative[i] += probs[c]; if( c == labels[m]) {derivative[i] -= 1;} } } double dV = sums[labels[m]] - total; if (dataweights != null) { dV *= dataweights[m]; } value -= dV; } value += ((double) batchSize)/((double) data.length)*prior.compute(x,priorDerivative); } public double valueAt(double[] x, double xscale, int[] batch) { value = 0.0; int batchSize = batch.length; double[] sums = new double[numClasses]; for (int d = 0; d <batchSize; d++) { //Sets the index based on the current batch int m = batch[d]; int[] features = data[m]; Arrays.fill(sums, 0.0); for (int c = 0; c < numClasses; c++) { for (int f = 0; f < features.length; f++) { int i = indexOf(features[f], c); if (values != null) { sums[c] += x[i]*xscale*values[m][f]; } else { sums[c] += x[i]*xscale; } } } double total = ArrayMath.logSum(sums); double dV = sums[labels[m]] - total; if (dataweights != null) { dV *= dataweights[m]; } value -= dV; } return value; } public double calculateStochasticUpdate(double[] x, double xscale, int[] batch, double gain) { value = 0.0; int batchSize = batch.length; double[] sums = new double[numClasses]; double[] probs = new double[numClasses]; for (int d = 0; d <batchSize; d++) { //Sets the index based on the current batch int m = batch[d]; int[] features = data[m]; // activation Arrays.fill(sums, 0.0); for (int c = 0; c < numClasses; c++) { for (int f = 0; f < features.length; f++) { int i = indexOf(features[f], c); if (values != null) { sums[c] += x[i]*xscale*values[m][f]; } else { sums[c] += x[i]*xscale; } } } for (int f = 0; f < features.length; f++) { int i = indexOf(features[f], labels[m]); double v = (values != null)? values[m][f]:1; double delta = (dataweights != null)? dataweights[m]*v:v; x[i] += delta*gain; } double total = ArrayMath.logSum(sums); for (int c = 0; c < numClasses; c++) { probs[c] = Math.exp(sums[c] - total); if (dataweights != null) { probs[c] *= dataweights[m]; } for (int f = 0; f < features.length; f++) { int i = indexOf(features[f], c); double v = (values != null)? values[m][f]:1; double delta = probs[c]*v; x[i] -= delta*gain; } } double dV = sums[labels[m]] - total; if (dataweights != null) { dV *= dataweights[m]; } value -= dV; } return value; } protected void calculateStochasticAlgorithmicDifferentiation(double[] x, double[] v, int[] batch) { System.err.print("*"); //Initialize value = 0.0; if(derivativeAD == null){ //initialize any variables derivativeAD = new DoubleAD[x.length]; for (int i = 0; i < x.length;i++){ derivativeAD[i] = new DoubleAD(0.0,0.0); } } if(xAD == null){ xAD = new DoubleAD[x.length]; for (int i = 0; i < x.length;i++){ xAD[i] = new DoubleAD(x[i],v[i]); } } // Initialize the sums if(sums == null){ sums = new DoubleAD[numClasses]; for (int c = 0; c<numClasses;c++){ sums[c] = new DoubleAD(0,0); } } if(probs == null) { probs = new DoubleAD[numClasses]; for (int c = 0; c<numClasses;c++){ probs[c] = new DoubleAD(0,0); } } //long curTime = System.currentTimeMillis(); // Copy the Derivative numerator, and set up the vector V to be used for Hess*V for (int i = 0; i < x.length;i++){ xAD[i].set(x[i],v[i]); derivativeAD[i].set(0.0,0.0); } //System.err.print(System.currentTimeMillis() - curTime + " - "); //curTime = System.currentTimeMillis(); for (int d = 0; d <batch.length ; d++) { //Sets the index based on the current batch int m = (curElement + d) % data.length; int[] features = data[m]; for (int c = 0; c<numClasses;c++){ sums[c].set(0.0,0.0); } for (int c = 0; c < numClasses; c++) { for (int f = 0; f < features.length; f++) { int i = indexOf(features[f], c); sums[c] = ADMath.plus(sums[c],xAD[i]); } } DoubleAD total = ADMath.logSum(sums); for (int c = 0; c < numClasses; c++) { probs[c] = ADMath.exp( ADMath.minus(sums[c], total) ); if (dataweights != null) { probs[c] = ADMath.multConst(probs[c], dataweights[d]); } for (int f = 0; f < features.length; f++) { int i = indexOf(features[f], c); if (c == labels[m]){derivativeAD[i].plusEqualsConst(-1.0);} derivativeAD[i].plusEquals(probs[c]); } } double dV = sums[labels[m]].getval() - total.getval(); if (dataweights != null) { dV *= dataweights[d]; } value -= dV; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // DANGEROUS!!!!!!! Divide by Zero possible!!!!!!!!!! // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Need to modify the prior class to handle AD -akleeman //System.err.print(System.currentTimeMillis() - curTime + " - "); //curTime = System.currentTimeMillis(); double[] tmp = new double[x.length]; for(int i = 0; i < x.length; i++){ tmp[i] = derivativeAD[i].getval(); derivativeAD[i].plusEquals(ADMath.multConst(xAD[i], batch.length/(data.length * prior.getSigma()*prior.getSigma()))); derivative[i] = derivativeAD[i].getval(); HdotV[i] = derivativeAD[i].getdot(); } value += ((double) batch.length)/((double) data.length)*prior.compute(x, tmp); //System.err.print(System.currentTimeMillis() - curTime + " - "); //System.err.println(""); } /** * Calculate conditional likelihood for datasets with real-valued features. * Currently this can calculate CL only (no support for SCL). * TODO: sum-conditional obj. fun. with RVFs. * */ protected void rvfcalculate(double[] x) { value = 0.0; if (derivativeNumerator == null) { derivativeNumerator = new double[x.length]; for (int d = 0; d < data.length; d++) { // if (d == testMin) { // d = testMax - 1; // continue; // } int[] features = data[d]; for (int f = 0; f < features.length; f++) { int i = indexOf(features[f], labels[d]); if (dataweights == null) { derivativeNumerator[i] -= values[d][f]; } else { derivativeNumerator[i] -= dataweights[d]*values[d][f]; } } } } copy(derivative, derivativeNumerator); // Arrays.fill(derivative, 0.0); double[] sums = new double[numClasses]; double[] probs = new double[numClasses]; // double[] counts = new double[numClasses]; // Arrays.fill(counts, 0.0); for (int d = 0; d < data.length; d++) { // if (d == testMin) { // d = testMax - 1; // continue; // } int[] features = data[d]; // activation Arrays.fill(sums, 0.0); for (int c = 0; c < numClasses; c++) { for (int f = 0; f < features.length; f++) { int i = indexOf(features[f], c); sums[c] += x[i] * values[d][f]; } } // expectation (slower routine replaced by fast way) // double total = Double.NEGATIVE_INFINITY; // for (int c=0; c<numClasses; c++) { // total = SloppyMath.logAdd(total, sums[c]); // } double total = ArrayMath.logSum(sums); for (int c = 0; c < numClasses; c++) { probs[c] = Math.exp(sums[c] - total); if (dataweights != null) { probs[c] *= dataweights[d]; } for (int f = 0; f < features.length; f++) { int i = indexOf(features[f], c); derivative[i] += probs[c] * values[d][f]; } } double dV = sums[labels[d]] - total; if (dataweights != null) { dV *= dataweights[d]; } value -= dV; } value += prior.compute(x, derivative); } // public void setTestMinMax(int testMin, int testMax) { // this.testMin = testMin; // this.testMax = testMax; // } public void setUseSumCondObjFun(boolean value) { this.useSummedConditionalLikelihood = value; } public LogConditionalObjectiveFunction(GeneralDataset<L, F> dataset) { this(dataset, new LogPrior(LogPrior.LogPriorType.QUADRATIC)); } public LogConditionalObjectiveFunction(GeneralDataset<L, F> dataset, LogPrior prior) { this(dataset, prior, false); } public LogConditionalObjectiveFunction(GeneralDataset<L, F> dataset, float[] dataWeights, LogPrior prior) { this(dataset, prior, false); this.dataweights = dataWeights; System.err.println("correct constructor"); } public LogConditionalObjectiveFunction(GeneralDataset<L, F> dataset, LogPrior prior, boolean useSumCondObjFun) { setPrior(prior); setUseSumCondObjFun(useSumCondObjFun); this.numFeatures = dataset.numFeatures(); this.numClasses = dataset.numClasses(); this.data = dataset.getDataArray(); this.labels = dataset.getLabelsArray(); this.values = dataset.getValuesArray(); if (dataset instanceof WeightedDataset<?,?>) { this.dataweights = ((WeightedDataset<L, F>)dataset).getWeights(); } } //TODO: test this public LogConditionalObjectiveFunction(Iterable<Datum<L, F>> dataIterable, LogPrior logPrior, Index<F> featureIndex, Index<L> labelIndex) { setPrior(prior); setUseSumCondObjFun(false); this.useIterable = true; this.numFeatures = featureIndex.size(); this.numClasses = labelIndex.size(); this.data = null; this.dataIterable = dataIterable; this.labelIndex = labelIndex; this.featureIndex = featureIndex; this.labels = null;//dataset.getLabelsArray(); this.values = null;//dataset.getValuesArray(); //this.dataweights //leave it null? } public LogConditionalObjectiveFunction(int numFeatures, int numClasses, int[][] data, int[] labels, boolean useSumCondObjFun) { this(numFeatures, numClasses, data, labels); this.useSummedConditionalLikelihood = useSumCondObjFun; } public LogConditionalObjectiveFunction(int numFeatures, int numClasses, int[][] data, int[] labels) { this(numFeatures, numClasses, data, labels, new LogPrior(LogPrior.LogPriorType.QUADRATIC)); } public LogConditionalObjectiveFunction(int numFeatures, int numClasses, int[][] data, int[] labels, LogPrior prior) { this(numFeatures, numClasses, data, labels, null, prior); } public LogConditionalObjectiveFunction(int numFeatures, int numClasses, int[][] data, int[] labels, float[] dataweights) { this(numFeatures, numClasses, data, labels, dataweights, new LogPrior(LogPrior.LogPriorType.QUADRATIC)); } public LogConditionalObjectiveFunction(int numFeatures, int numClasses, int[][] data, int[] labels, float[] dataweights, LogPrior prior) { this.numFeatures = numFeatures; this.numClasses = numClasses; this.data = data; this.labels = labels; this.prior = prior; this.dataweights = dataweights; // this.testMin = data.length; // this.testMax = data.length; } public LogConditionalObjectiveFunction(int numFeatures, int numClasses, int[][] data, int[] labels, int intPrior, double sigma, double epsilon) { this(numFeatures, numClasses, data, null, labels, intPrior, sigma, epsilon); } public LogConditionalObjectiveFunction(int numFeatures, int numClasses, int[][] data, double[][] values, int[] labels, int intPrior, double sigma, double epsilon) { this.numFeatures = numFeatures; this.numClasses = numClasses; this.data = data; this.values = values; this.labels = labels; this.prior = new LogPrior(intPrior, sigma, epsilon); // this.testMin = data.length; // this.testMax = data.length; } }
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/classify/LogConditionalObjectiveFunction.java
Java
gpl-2.0
28,501
using System; using Server; using Server.Gumps; using Server.Mobiles; using Server.Commands; using System.Collections; using System.Collections.Generic; using Kaltar.Habilidades; namespace Kaltar.Talentos { public class AprenderHabilidadeTalento : AprenderHabilidadeGump { public static void Initialize() { CommandSystem.Register("aTalento", AccessLevel.Player, new CommandEventHandler(AprenderHabilidadeTalentos)); CommandSystem.Register("rTalento", AccessLevel.Player, new CommandEventHandler(RemoverHabilidadeTalentos)); } private static void RemoverHabilidadeTalentos(CommandEventArgs e) { Jogador jogador = (Jogador)e.Mobile; jogador.getSistemaTalento().removerTotalHabilidades(); jogador.UpdateResistances(); } private static void AprenderHabilidadeTalentos(CommandEventArgs e) { Jogador jogador = (Jogador)e.Mobile; List<int> habilidades = new List<int>(); habilidades.Add((int)IdHabilidadeTalento.bloquear); habilidades.Add((int)IdHabilidadeTalento.flanquear); habilidades.Add((int)IdHabilidadeTalento.poderDaFe); habilidades.Add((int)IdHabilidadeTalento.peleDeferro); jogador.SendGump(new AprenderHabilidadeTalento(jogador, habilidades)); } public AprenderHabilidadeTalento(Jogador jogador, List<int> habilidades) : base(jogador, habilidades) { } /** * Recupera a habilidade apartir do seu Id. */ public override Habilidade getHabilidade(int idHabilidade) { try { return HabilidadeTalento.getHabilidadeTalento((IdHabilidadeTalento)idHabilidade); } catch(Exception e) { Console.WriteLine(e.StackTrace); jogador.SendMessage("Não foi possível encontrar habilidade com o id informado. " + idHabilidade); return null; } } /** * Quando confirmado o aprendizado, esse método será invocado pelo gump de Confirmação. */ public override bool aprenderHabilidade(Jogador jogador, int idHabilidade) { try { return jogador.getSistemaTalento().aprender((IdHabilidadeTalento)idHabilidade); } catch (Exception e) { Console.WriteLine(e.StackTrace); jogador.SendMessage("Não foi possível encontrar habilidade com o id informado. " + idHabilidade); return false; } } /** * Recupera o número de pontos de habilidade. */ public override string totalPontosHabilidade(Jogador jogador) { return jogador.getSistemaTalento().pontosDisponiveis() + ""; } /** * Recupera o nome do tipo de habilidade. ex.: habilidade Talento, talento etc. */ public override string getTipoHabilidade() { return "talento"; } } }
alucardxlx/kaltar
Scripts/Kaltar/Jogador/Talento/Gump/AprenderHabilidadeTalento.cs
C#
gpl-2.0
3,242
<!DOCTYPE html> <html lang="en-US"> <!-- Mirrored from www.w3schools.com/bootstrap/tryit.asp?filename=trybs_case_jumbotron&stacked=h by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 07:34:12 GMT --> <head> <title>Tryit Editor v2.3</title> <meta id="viewport" name='viewport'> <script> (function() { if ( navigator.userAgent.match(/iPad/i) ) { document.getElementById('viewport').setAttribute("content", "width=device-width, initial-scale=0.9"); } }()); </script> <link rel="stylesheet" href="../trycss.css"> <!--[if lt IE 8]> <style> .textareacontainer, .iframecontainer {width:48%;} .textarea, .iframe {height:800px;} #textareaCode, #iframeResult {height:700px;} .menu img {display:none;} </style> <![endif]--> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','../../www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-3855518-1', 'auto'); ga('require', 'displayfeatures'); ga('send', 'pageview'); </script> <script> var googletag = googletag || {}; googletag.cmd = googletag.cmd || []; (function() { var gads = document.createElement('script'); gads.async = true; gads.type = 'text/javascript'; var useSSL = 'https:' == document.location.protocol; gads.src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js'; var node = document.getElementsByTagName('script')[0]; node.parentNode.insertBefore(gads, node); })(); </script> <script> googletag.cmd.push(function() { googletag.defineSlot('/16833175/TryitLeaderboard', [[728, 90], [970, 90]], 'div-gpt-ad-1383036313516-0').addService(googletag.pubads()); googletag.pubads().setTargeting("content","trybootstrap"); googletag.pubads().enableSingleRequest(); googletag.enableServices(); }); </script> <script type="text/javascript"> function submitTryit() { var t=document.getElementById("textareaCode").value; t=t.replace(/=/gi,"w3equalsign"); var pos=t.search(/script/i) while (pos>0) { t=t.substring(0,pos) + "w3" + t.substr(pos,3) + "w3" + t.substr(pos+3,3) + "tag" + t.substr(pos+6); pos=t.search(/script/i); } if ( navigator.userAgent.match(/Safari/i) ) { t=escape(t); document.getElementById("bt").value="1"; } document.getElementById("code").value=t; document.getElementById("tryitform").action="tryit_view52a0.html?x=" + Math.random(); validateForm(); document.getElementById("iframeResult").contentWindow.name = "view"; document.getElementById("tryitform").submit(); } function validateForm() { var code=document.getElementById("code").value; if (code.length>8000) { document.getElementById("code").value="<h1>Error</h1>"; } } </script> <style> .resultHeader { padding-top:15px; } .textareacontainer, .iframecontainer { height:49%; float:none; width:98%; } .textarea, .iframe { position:relative; width:100%; margin:0; height:99%; } .container { min-width:260px; } </style> </head> <body> <div id="ads"> <div style="position:relative;width:100%;margin-top:0px;margin-bottom:0px;"> <div style="width:974px;height:94px;position:relative;margin:0px;margin-top:5px;margin-bottom:5px;margin-right:auto;margin-left:auto;padding:0px;overflow:hidden;"> <!-- TryitLeaderboard --> <div id='div-gpt-ad-1383036313516-0' style='width:970px; height:90px;'> <script type='text/javascript'> googletag.cmd.push(function() { googletag.display('div-gpt-ad-1383036313516-0'); }); </script> </div> <div style="clear:both"></div> </div> </div> </div> <div class="container"> <div class="textareacontainer"> <div class="textarea"> <div class="headerText" style="width:auto;float:left;">Edit This Code:</div> <div class="headerBtnDiv" style="width:auto;float:right;margin-top:8px;margin-right:2.4%;"><button class="submit" type="button" onclick="submitTryit()">See Result &raquo;</button></div> <div class="textareawrapper"> <textarea autocomplete="off" class="code_input" id="textareaCode" wrap="logical" xrows="30" xcols="50"><!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Case</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="../../maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <script src="../../ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="jumbotron"> <h1>My first Bootstrap website!</h1> <p>This page will grow as we add more and more components from Bootstrap...</p> </div> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <p>This is a paragraph.</p> <p>This is another paragraph.</p> </div> </body> <!-- Mirrored from www.w3schools.com/bootstrap/tryit.asp?filename=trybs_case_jumbotron&stacked=h by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 07:34:12 GMT --> </html> </textarea> <form autocomplete="off" style="margin:0px;display:none;" action="http://www.w3schools.com/bootstrap/tryit_view.asp" method="post" target="view" id="tryitform" name="tryitform" onsubmit="validateForm();"> <input type="hidden" name="code" id="code" /> <input type="hidden" id="bt" name="bt" /> </form> </div> </div> </div> <div class="iframecontainer"> <div class="iframe"> <div class="headerText resultHeader">Result:</div> <div class="iframewrapper"> <iframe id="iframeResult" class="result_output" frameborder="0" name="view" xsrc="trybs_case_jumbotron.html"></iframe> </div> <div class="footerText">Try it Yourself - &copy; <a href="../index.html">w3schools.com</a></div> </div> </div> </div> <script>submitTryit()</script> </body> </html>
platinhom/ManualHom
Coding/W3School/W3Schools_Offline_2015/www.w3schools.com/bootstrap/tryit476d.html
HTML
gpl-2.0
6,049
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="pt"> <head> <!-- Generated by javadoc (1.8.0_25) on Tue Mar 24 10:53:23 BRT 2015 --> <title>testes</title> <meta name="date" content="2015-03-24"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <script type="text/javascript" src="../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="testes"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-files/index-1.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../model/automovel/package-summary.html">Prev&nbsp;Package</a></li> <li>Next&nbsp;Package</li> </ul> <ul class="navList"> <li><a href="../index.html?testes/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Package" class="title">Package&nbsp;testes</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../testes/CarroTest.html" title="class in testes">CarroTest</a></td> <td class="colLast"> <div class="block">Aqui será feito os testes referentes ao carro.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../testes/MotoTest.html" title="class in testes">MotoTest</a></td> <td class="colLast"> <div class="block">Testes referentes a <a href="../model/automovel/Moto.html" title="class in model.automovel"><code>Moto</code></a></div> </td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-files/index-1.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../model/automovel/package-summary.html">Prev&nbsp;Package</a></li> <li>Next&nbsp;Package</li> </ul> <ul class="navList"> <li><a href="../index.html?testes/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
fabinhodsouza/metodos_avancados_uepb
doc/testes/package-summary.html
HTML
gpl-2.0
4,793
#ifndef RNGSUPPORT_H #define RNGSUPPORT_H #ifdef __cplusplus #if __cplusplus >= 201103L || (defined _MSC_VER && _MSC_VER >= 1600) #define NYQ_USE_RANDOM_HEADER #endif #if defined NYQ_USE_RANDOM_HEADER #include <vector> #include <random> namespace Nyq { typedef std::mt19937 nyq_generator; const int nyq_generator_state_size = nyq_generator::state_size; typedef std::seed_seq nyq_seed_seq; typedef std::uniform_real_distribution<float> nyq_uniform_float_distribution; typedef std::normal_distribution<float> nyq_normal_float_distribution; typedef std::uniform_real_distribution<double> nyq_uniform_double_distribution; typedef std::normal_distribution<double> nyq_normal_double_distribution; typedef std::uniform_int_distribution<int> nyq_uniform_int_distribution; class RngSupportBase { protected: static std::vector<unsigned int> CreateRootSeedVector(); }; template <class RNG = nyq_generator> class RngSupport : RngSupportBase { private: friend std::vector<unsigned int> CreateRootSeedVector(); static RNG CreateRootGenerator() { auto seed_data = CreateRootSeedVector(); std::seed_seq seed(begin(seed_data), end(seed_data)); RNG generator(seed); return generator; } static RNG& GetRootGenerator() { static thread_local auto generator = CreateRootGenerator(); return generator; } public: template<class RealFwdIt, class Real> static void RandomFillUniform(RealFwdIt first, RealFwdIt last, Real low, Real high) { RNG& generator = GetRootGenerator(); std::uniform_real_distribution<Real> uniform{ low, high }; for (; first != last; ++first) *first = uniform(generator); } template<class RealFwdIt, class Real> static void RandomFillNormal(RealFwdIt first, RealFwdIt last, Real mean, Real stDev) { RNG& generator = GetRootGenerator(); std::normal_distribution<Real> uniform{ mean, stDev }; for (; first != last; ++first) *first = uniform(generator); } template<class RealFwdIt, class Real> static bool RandomFillClampedNormal(RealFwdIt first, RealFwdIt last, Real mean, Real stDev, Real low, Real high) { RNG& generator = GetRootGenerator(); std::normal_distribution<Real> uniform{ mean, stDev }; for (; first != last; ++first) { int retry = 10; for (;;) { Real x = uniform(generator); if (x <= high && x >= low) { *first = x; break; } if (--retry <= 0) return false; } } return true; } template<class Real> static Real RandomUniformReal(Real low, Real high) { auto& generator = GetRootGenerator(); std::uniform_real_distribution<Real> uniform{ low, high }; return uniform(generator); } template<class Int> static Int RandomUniformInt(Int low, Int high) { auto& generator = GetRootGenerator(); std::uniform_int_distribution<Int> uniform{ low, high }; return uniform(generator); } static std::vector<unsigned int> CreateSeedVector(std::vector<unsigned int>::size_type size) { std::vector<unsigned int> seed; seed.reserve(size); auto rng = GetRootGenerator(); for (; size > 0; --size) seed.push_back(rng()); return seed; } }; // class RngSupport template <class RNG = nyq_generator> static RNG CreateGenerator(int size = 32) { auto seed_data = RngSupport<RNG>::CreateSeedVector(size); nyq_seed_seq seq(begin(seed_data), end(seed_data)); RNG generator(seq); return generator; } template <class RNG = nyq_generator> static void ReseedGenerator(RNG& generator, int size = 32) { auto seed_data = RngSupport<RNG>::CreateSeedVector(size); nyq_seed_seq seq(begin(seed_data), end(seed_data)); generator.seed(seq); } template <class RNG = nyq_generator> class NyqEngine : public RNG { public: explicit NyqEngine(int size = 32) : RNG(CreateGenerator(size)) { } }; } // namespace Nyq #endif // NYQ_USE_RANDOM_HEADER extern "C" { #endif // __cplusplus void RandomFillUniformFloat(float* p, size_t count, float low, float high); void RandomFillNormalFloat(float* p, size_t count, float mean, float stDev); int RandomFillClampedNormalFloat(float* p, size_t count, float mean, float stDev, float low, float high); float RandomUniformFloat(float low, float high); void RandomFillUniformDouble(double* p, size_t count, double low, double high); void RandomFillNormalDouble(double* p, size_t count, double mean, double stDev); int RandomFillClampedNormalDouble(double* p, size_t count, double mean, double stDev, double low, double high); double RandomUniformDouble(double low, double high); int RandomUniformInt(int lowInclusive, int highExclusive); #ifdef __cplusplus } // extern "C" #endif #endif // RNGSUPPORT_H
ShanghaiTimes/Audacity2015
lib-src/libnyquist/RngSupport.h
C
gpl-2.0
5,102
/* * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "AreaBoundary.h" #include "CellImpl.h" #include "GridNotifiersImpl.h" #include "InstanceScript.h" #include "MotionMaster.h" #include "MoveSplineInit.h" #include "ObjectAccessor.h" #include "Player.h" #include "ScriptedCreature.h" #include "SpellAuraEffects.h" #include "SpellMgr.h" #include "SpellScript.h" #include "ulduar.h" #include <G3D/Vector3.h> enum Spells { // Thorim SPELL_SHEATH_OF_LIGHTNING = 62276, SPELL_STORMHAMMER = 62042, SPELL_STORMHAMMER_SIF = 64767, SPELL_STORMHAMMER_BOOMERANG = 64909, SPELL_DEAFENING_THUNDER = 62470, SPELL_CHARGE_ORB = 62016, SPELL_SUMMON_LIGHTNING_ORB = 62391, SPELL_LIGHTNING_DESTRUCTION = 62393, SPELL_TOUCH_OF_DOMINION = 62507, SPELL_TOUCH_OF_DOMINION_TRIGGERED = 62565, SPELL_CHAIN_LIGHTNING = 62131, SPELL_LIGHTNING_ORB_CHARGED = 62186, // wrong duration, triggered spell should handle lightning release SPELL_LIGHTNING_CHARGE = 62279, SPELL_LIGHTNING_RELEASE = 62466, SPELL_LIGHTNING_PILLAR_2 = 62976, // caster high position, target low position SPELL_LIGHTNING_PILLAR_1 = 63238, // caster high position, target low position SPELL_UNBALANCING_STRIKE = 62130, SPELL_BERSERK_PHASE_1 = 62560, SPELL_BERSERK_PHASE_2 = 62555, SPELL_ACTIVATE_LIGHTNING_ORB_PERIODIC = 62184, // Credits SPELL_CREDIT_SIFFED = 64980, SPELL_CREDIT_KILL = 64985, // Lightning Field SPELL_LIGHTNING_FIELD = 64972, SPELL_LIGHTNING_BEAM_CHANNEL = 45537, // Sif SPELL_BLIZZARD = 62577, SPELL_BLINK = 62578, SPELL_FROSTBOLT_VOLLEY = 62580, SPELL_FROSTBOLT = 62583, SPELL_FROSTNOVA = 62597, SPELL_SIF_TRANSFORM = 64778, // Runic Colossus SPELL_SMASH = 62339, SPELL_RUNIC_BARRIER = 62338, SPELL_RUNIC_CHARGE = 62613, SPELL_RUNIC_SMASH = 62465, SPELL_RUNIC_SMASH_RIGHT = 62057, SPELL_RUNIC_SMASH_LEFT = 62058, // Ancient Rune Giant SPELL_RUNIC_FORTIFICATION = 62942, SPELL_RUNE_DETONATION = 62526, SPELL_STOMP = 62411 }; enum Phases { PHASE_NULL, PHASE_1, PHASE_2 }; enum Events { // Thorim EVENT_SAY_AGGRO_2 = 1, EVENT_SAY_SIF_START, EVENT_START_SIF_CHANNEL, EVENT_STORMHAMMER, EVENT_CHARGE_ORB, EVENT_SUMMON_ADDS, EVENT_BERSERK, EVENT_JUMPDOWN, EVENT_UNBALANCING_STRIKE, EVENT_CHAIN_LIGHTNING, EVENT_START_PERIODIC_CHARGE, EVENT_LIGHTNING_CHARGE, EVENT_ACTIVATE_LIGHTNING_FIELD, EVENT_OUTRO_1, EVENT_OUTRO_2, EVENT_OUTRO_3, // Runic Colossus EVENT_RUNIC_BARRIER, EVENT_SMASH, EVENT_RUNIC_CHARGE, EVENT_RUNIC_SMASH, // Ancient Rune Giant EVENT_RUNIC_FORTIFICATION, EVENT_STOMP, EVENT_RUNE_DETONATION, // Arena NPC EVENT_PRIMARY_ABILITY, EVENT_SECONDARY_ABILITY, EVENT_THIRD_ABILITY, EVENT_ABILITY_CHARGE, // Sif EVENT_BLINK, EVENT_FROST_NOVA, EVENT_FROSTBOLT, EVENT_FROSTBOLT_VOLLEY, EVENT_BLIZZARD }; enum Yells { // Thorim SAY_AGGRO_1 = 0, SAY_AGGRO_2 = 1, SAY_SPECIAL = 2, SAY_JUMPDOWN = 3, SAY_SLAY = 4, SAY_BERSERK = 5, SAY_WIPE = 6, SAY_DEATH = 7, SAY_END_NORMAL_1 = 8, SAY_END_NORMAL_2 = 9, SAY_END_NORMAL_3 = 10, SAY_END_HARD_1 = 11, SAY_END_HARD_2 = 12, SAY_END_HARD_3 = 13, // Runic Colossus EMOTE_RUNIC_BARRIER = 0, // Ancient Rune Giant EMOTE_RUNIC_MIGHT = 0, // Sif SAY_SIF_START = 0, SAY_SIF_DESPAWN = 1, SAY_SIF_EVENT = 2 }; enum PreAddSpells { SPELL_ACID_BREATH = 62315, SPELL_SWEEP = 62316, SPELL_DEVASTATE = 62317, SPELL_HEROIC_SWIPE = 62444, SPELL_SUNDER_ARMOR = 57807, SPELL_BARBED_SHOT = 62318, SPELL_SHOOT = 16496, SPELL_RENEW = 62333, SPELL_GREATER_HEAL = 62334, /// 61965 SPELL_CIRCLE_OF_HEALING = 61964, SPELL_HOLY_SMITE = 62335, SPELL_LEAP = 61934, SPELL_CHARGE = 32323, SPELL_MORTAL_STRIKE = 35054, SPELL_WHIRLWIND = 33500, SPELL_LOW_BLOW = 62326, SPELL_PUMMEL = 38313, SPELL_RUNIC_LIGHTNING = 62327, SPELL_RUNIC_MENDING = 62328, SPELL_RUNIC_SHIELD = 62321, SPELL_RUNIC_STRIKE = 62322, SPELL_AURA_OF_CELERITY = 62320, SPELL_IMPALE = 62331, SPELL_WHIRLING_TRIP = 64151, SPELL_CLEAVE = 42724, SPELL_HAMSTRING = 48639, SPELL_SHIELD_SMASH = 62332, }; enum TrashTypes { // Pre Phase Trash BEHEMOTH, MERCENARY_CAPTAIN, MERCENARY_SOLDIER, // Arena Phase Trash DARK_RUNE_CHAMPION, DARK_RUNE_WARBRINGER, DARK_RUNE_COMMONER, DARK_RUNE_EVOKER, // Hall Way Trash IRON_RING_GUARD, IRON_HONOR_GUARD, // Shared DARK_RUNE_ACOLYTE }; struct ThorimTrashInfo { uint32 Type; uint32 Entry; uint32 PrimaryAbility; uint32 SecondaryAbility; uint32 ThirdAbility; }; uint8 const ThorimTrashCount = 13; ThorimTrashInfo const StaticThorimTrashInfo[ThorimTrashCount] = { // Pre Phase { BEHEMOTH, NPC_JORMUNGAR_BEHEMOTH, SPELL_ACID_BREATH, SPELL_SWEEP, 0 }, { MERCENARY_CAPTAIN, NPC_MERCENARY_CAPTAIN_A, SPELL_DEVASTATE, SPELL_HEROIC_SWIPE, SPELL_SUNDER_ARMOR }, { MERCENARY_SOLDIER, NPC_MERCENARY_SOLDIER_A, SPELL_BARBED_SHOT, SPELL_SHOOT, 0 }, { DARK_RUNE_ACOLYTE, NPC_DARK_RUNE_ACOLYTE_PRE, SPELL_RENEW, SPELL_GREATER_HEAL, SPELL_CIRCLE_OF_HEALING }, { MERCENARY_CAPTAIN, NPC_MERCENARY_CAPTAIN_H, SPELL_DEVASTATE, SPELL_HEROIC_SWIPE, SPELL_SUNDER_ARMOR }, { MERCENARY_SOLDIER, NPC_MERCENARY_SOLDIER_H, SPELL_BARBED_SHOT, SPELL_SHOOT, 0 }, // Arena Phase { DARK_RUNE_CHAMPION, NPC_DARK_RUNE_CHAMPION, SPELL_MORTAL_STRIKE, SPELL_WHIRLWIND, 0 }, { DARK_RUNE_WARBRINGER, NPC_DARK_RUNE_WARBRINGER, SPELL_RUNIC_STRIKE, 0, 0 }, { DARK_RUNE_EVOKER, NPC_DARK_RUNE_EVOKER, SPELL_RUNIC_LIGHTNING, SPELL_RUNIC_SHIELD, SPELL_RUNIC_MENDING }, { DARK_RUNE_COMMONER, NPC_DARK_RUNE_COMMONER, SPELL_LOW_BLOW, SPELL_PUMMEL, 0 }, // Hall Way { IRON_RING_GUARD, NPC_IRON_RING_GUARD, SPELL_WHIRLING_TRIP, SPELL_IMPALE, 0 }, { IRON_HONOR_GUARD, NPC_IRON_HONOR_GUARD, SPELL_CLEAVE, SPELL_SHIELD_SMASH, 0 }, { DARK_RUNE_ACOLYTE, NPC_DARK_RUNE_ACOLYTE, SPELL_RENEW, SPELL_GREATER_HEAL, 0 } }; enum Actions { ACTION_INCREASE_PREADDS_COUNT, ACTION_ACTIVATE_RUNIC_SMASH, ACTION_ACTIVATE_ADDS, ACTION_PILLAR_CHARGED, ACTION_START_HARD_MODE, ACTION_BERSERK }; struct SummonLocation { Position pos; uint32 entry; }; SummonLocation const PreAddLocations[] = { { { 2149.68f, -263.477f, 419.679f, 3.120f }, NPC_JORMUNGAR_BEHEMOTH }, { { 2131.31f, -271.640f, 419.840f, 2.188f }, NPC_MERCENARY_CAPTAIN_A }, { { 2127.24f, -259.182f, 419.974f, 5.917f }, NPC_MERCENARY_SOLDIER_A }, { { 2123.32f, -254.770f, 419.840f, 6.170f }, NPC_MERCENARY_SOLDIER_A }, { { 2120.10f, -258.990f, 419.840f, 6.250f }, NPC_MERCENARY_SOLDIER_A }, { { 2129.09f, -277.142f, 419.756f, 1.222f }, NPC_DARK_RUNE_ACOLYTE_PRE } }; SummonLocation const ColossusAddLocations[] = { { { 2218.38f, -297.50f, 412.18f, 1.030f }, NPC_IRON_RING_GUARD }, { { 2235.07f, -297.98f, 412.18f, 1.613f }, NPC_IRON_RING_GUARD }, { { 2235.26f, -338.34f, 412.18f, 1.589f }, NPC_IRON_RING_GUARD }, { { 2217.69f, -337.39f, 412.18f, 1.241f }, NPC_IRON_RING_GUARD }, { { 2227.58f, -308.30f, 412.18f, 1.591f }, NPC_DARK_RUNE_ACOLYTE }, { { 2227.47f, -345.37f, 412.18f, 1.566f }, NPC_DARK_RUNE_ACOLYTE } }; SummonLocation const GiantAddLocations[] = { { { 2198.05f, -428.77f, 419.95f, 6.056f }, NPC_IRON_HONOR_GUARD }, { { 2220.31f, -436.22f, 412.26f, 1.064f }, NPC_IRON_HONOR_GUARD }, { { 2158.88f, -441.73f, 438.25f, 0.127f }, NPC_IRON_HONOR_GUARD }, { { 2198.29f, -436.92f, 419.95f, 0.261f }, NPC_DARK_RUNE_ACOLYTE }, { { 2230.93f, -434.27f, 412.26f, 1.931f }, NPC_DARK_RUNE_ACOLYTE } }; Position const SifSpawnPosition = { 2148.301f, -297.8453f, 438.3308f, 2.687807f }; enum Data { DATA_CHARGED_PILLAR = 1 }; enum DisplayIds { THORIM_WEAPON_DISPLAY_ID = 45900 }; Position const LightningOrbPath[] = { { 2134.889893f, -298.632996f, 438.247467f }, { 2134.570068f, -440.317993f, 438.247467f }, { 2167.820312f, -440.330261f, 438.247589f }, { 2213.394287f, -433.318298f, 412.665863f }, { 2227.766113f, -433.275818f, 412.177032f }, { 2227.551270f, -263.081085f, 412.176880f }, { 2202.208008f, -262.939270f, 412.168976f }, { 2182.310059f, -263.233093f, 414.739410f } }; std::size_t const LightningOrbPathSize = std::extent<decltype(LightningOrbPath)>::value; // used for trash jump calculation Position const ArenaCenter = { 2134.77f, -262.307f }; // used for lightning field calculation Position const LightningFieldCenter = { 2135.178f, -321.122f }; CircleBoundary const ArenaFloorCircle(ArenaCenter, 45.4); CircleBoundary const InvertedBalconyCircle(LightningFieldCenter, 32.0, true); CreatureBoundary const ArenaBoundaries = { &ArenaFloorCircle, &InvertedBalconyCircle }; class HeightPositionCheck { public: HeightPositionCheck(bool ret) : _ret(ret) { } bool operator()(Position const* pos) const { return (pos->GetPositionZ() > THORIM_BALCONY_Z_CHECK) == _ret; } private: bool _ret; static float const THORIM_BALCONY_Z_CHECK; }; float const HeightPositionCheck::THORIM_BALCONY_Z_CHECK = 428.0f; class RunicSmashExplosionEvent : public BasicEvent { public: RunicSmashExplosionEvent(Creature* owner) : _owner(owner) { } bool Execute(uint64 /*eventTime*/, uint32 /*updateTime*/) override { _owner->CastSpell(nullptr, SPELL_RUNIC_SMASH); return true; } private: Creature* _owner; }; class TrashJumpEvent : public BasicEvent { public: TrashJumpEvent(Creature* owner) : _owner(owner), _stage(0) { } bool Execute(uint64 eventTime, uint32 /*updateTime*/) override { switch (_stage) { case 0: _owner->CastSpell(nullptr, SPELL_LEAP); ++_stage; _owner->m_Events.AddEvent(this, Milliseconds(eventTime) + 2s); return false; case 1: _owner->SetReactState(REACT_AGGRESSIVE); _owner->AI()->DoZoneInCombat(_owner); _owner->AI()->SetBoundary(&ArenaBoundaries); return true; default: break; } return true; } private: Creature* _owner; uint8 _stage; }; class LightningFieldEvent : public BasicEvent { public: LightningFieldEvent(Creature* owner) : _owner(owner) { } bool Execute(uint64 eventTime, uint32 /*updateTime*/) override { if (InstanceScript* instance = _owner->GetInstanceScript()) { if (instance->GetBossState(BOSS_THORIM) == IN_PROGRESS) { _owner->CastSpell(nullptr, SPELL_LIGHTNING_FIELD); _owner->m_Events.AddEvent(this, Milliseconds(eventTime) + 1s); return false; } } _owner->InterruptNonMeleeSpells(false); _owner->AI()->EnterEvadeMode(); return true; } private: Creature* _owner; }; class boss_thorim : public CreatureScript { public: boss_thorim() : CreatureScript("boss_thorim") { } struct boss_thorimAI : public BossAI { boss_thorimAI(Creature* creature) : BossAI(creature, BOSS_THORIM) { _encounterFinished = false; Initialize(); } void Initialize() { _killedCount = 0; _waveType = 0; _hardMode = true; _orbSummoned = false; _dontStandInTheLightning = true; } void Reset() override { if (_encounterFinished) return; SetBoundary(nullptr); _Reset(); Initialize(); me->SetReactState(REACT_PASSIVE); me->SetDisableGravity(true); me->SetControlled(true, UNIT_STATE_ROOT); me->SetImmuneToPC(true); events.SetPhase(PHASE_NULL); // Respawn Mini Bosses for (uint8 i = DATA_RUNIC_COLOSSUS; i <= DATA_RUNE_GIANT; ++i) if (Creature* miniBoss = ObjectAccessor::GetCreature(*me, instance->GetGuidData(i))) miniBoss->Respawn(true); // Spawn Pre Phase Adds for (SummonLocation const& s : PreAddLocations) me->SummonCreature(s.entry, s.pos, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 3s); if (GameObject* lever = instance->GetGameObject(DATA_THORIM_LEVER)) lever->AddFlag(GO_FLAG_NOT_SELECTABLE); // Remove trigger auras if (Creature* pillar = ObjectAccessor::GetCreature(*me, _activePillarGUID)) pillar->RemoveAllAuras(); if (Creature* controller = instance->GetCreature(DATA_THORIM_CONTROLLER)) controller->RemoveAllAuras(); _activePillarGUID.Clear(); } void EnterEvadeMode(EvadeReason /*why*/) override { summons.DespawnAll(); _DespawnAtEvade(); } void SetGUID(ObjectGuid const& guid, int32 id) override { if (id == DATA_CHARGED_PILLAR) { _activePillarGUID = guid; if (Creature* pillar = ObjectAccessor::GetCreature(*me, _activePillarGUID)) { pillar->CastSpell(pillar, SPELL_LIGHTNING_ORB_CHARGED, true); pillar->CastSpell(nullptr, SPELL_LIGHTNING_PILLAR_2); events.ScheduleEvent(EVENT_LIGHTNING_CHARGE, 8s, 0, PHASE_2); } } } void KilledUnit(Unit* who) override { if (who->GetTypeId() == TYPEID_PLAYER) Talk(SAY_SLAY); } void SpellHit(WorldObject* /*caster*/, SpellInfo const* spellInfo) override { if (spellInfo->Id == SPELL_TOUCH_OF_DOMINION_TRIGGERED) { if (Creature* sif = instance->GetCreature(DATA_SIF)) { sif->AI()->Talk(SAY_SIF_DESPAWN); sif->DespawnOrUnsummon(6s); _hardMode = false; } } } void SpellHitTarget(WorldObject* target, SpellInfo const* spellInfo) override { if (target->GetTypeId() == TYPEID_PLAYER && spellInfo->Id == SPELL_LIGHTNING_RELEASE) _dontStandInTheLightning = false; } void FinishEncounter() { if (_encounterFinished) return; _encounterFinished = true; DoCastAOE(SPELL_CREDIT_KILL, true); // before change faction me->SetReactState(REACT_PASSIVE); me->InterruptNonMeleeSpells(true); me->RemoveAllAttackers(); me->AttackStop(); me->SetFaction(FACTION_FRIENDLY); me->AddUnitFlag(UNIT_FLAG_RENAME); if (Creature* controller = instance->GetCreature(DATA_THORIM_CONTROLLER)) controller->RemoveAllAuras(); if (Creature* pillar = ObjectAccessor::GetCreature(*me, _activePillarGUID)) pillar->RemoveAllAuras(); if (_hardMode) { if (Creature* sif = instance->GetCreature(DATA_SIF)) { summons.Despawn(sif); sif->DespawnOrUnsummon(10s); } } _JustDied(); Talk(SAY_DEATH); events.ScheduleEvent(EVENT_OUTRO_1, 4s); events.ScheduleEvent(EVENT_OUTRO_2, _hardMode ? 8s : 11s); events.ScheduleEvent(EVENT_OUTRO_3, _hardMode ? 19s : 21s); me->m_Events.AddEvent(new UlduarKeeperDespawnEvent(me), me->m_Events.CalculateTime(35s)); } void MovementInform(uint32 type, uint32 id) override { if (type != EFFECT_MOTION_TYPE || id != EVENT_JUMP) return; ResetThreatList(); SetBoundary(&ArenaBoundaries); } void JustEngagedWith(Unit* who) override { BossAI::JustEngagedWith(who); Talk(SAY_AGGRO_1); events.SetPhase(PHASE_1); events.ScheduleEvent(EVENT_SAY_AGGRO_2, 9s, 0, PHASE_1); events.ScheduleEvent(EVENT_SAY_SIF_START, 16500ms, 0, PHASE_1); events.ScheduleEvent(EVENT_START_SIF_CHANNEL, 22500ms, 0, PHASE_1); events.ScheduleEvent(EVENT_STORMHAMMER, 40s, 0, PHASE_1); events.ScheduleEvent(EVENT_CHARGE_ORB, 30s, 0, PHASE_1); events.ScheduleEvent(EVENT_SUMMON_ADDS, 15s, 0, PHASE_1); events.ScheduleEvent(EVENT_BERSERK, 369s); DoCast(me, SPELL_SHEATH_OF_LIGHTNING); if (Creature* runicColossus = instance->GetCreature(DATA_RUNIC_COLOSSUS)) { runicColossus->SetImmuneToPC(false); runicColossus->AI()->DoAction(ACTION_ACTIVATE_ADDS); } if (GameObject* lever = instance->GetGameObject(DATA_THORIM_LEVER)) lever->RemoveFlag(GO_FLAG_NOT_SELECTABLE); // Summon Sif me->SummonCreature(NPC_SIF, SifSpawnPosition); } void JustSummoned(Creature* summon) override { switch (summon->GetEntry()) { case NPC_LIGHTNING_ORB: { summon->SetReactState(REACT_PASSIVE); summon->CastSpell(summon, SPELL_LIGHTNING_DESTRUCTION, true); Movement::PointsArray path; path.reserve(LightningOrbPathSize); std::transform(std::begin(LightningOrbPath), std::end(LightningOrbPath), std::back_inserter(path), [](Position const& pos) { return G3D::Vector3(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ()); }); Movement::MoveSplineInit init(summon); init.MovebyPath(path); summon->GetMotionMaster()->LaunchMoveSpline(std::move(init), 0, MOTION_PRIORITY_NORMAL, POINT_MOTION_TYPE); break; } case NPC_DARK_RUNE_CHAMPION: case NPC_DARK_RUNE_WARBRINGER: case NPC_DARK_RUNE_EVOKER: case NPC_DARK_RUNE_COMMONER: summon->SetReactState(REACT_PASSIVE); summon->m_Events.AddEvent(new TrashJumpEvent(summon), summon->m_Events.CalculateTime(3s)); break; case NPC_SIF: summon->SetReactState(REACT_PASSIVE); break; default: break; } BossAI::JustSummoned(summon); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_SAY_AGGRO_2: Talk(SAY_AGGRO_2); break; case EVENT_SAY_SIF_START: if (Creature* sif = instance->GetCreature(DATA_SIF)) sif->AI()->Talk(SAY_SIF_START); break; case EVENT_START_SIF_CHANNEL: if (Creature* sif = instance->GetCreature(DATA_SIF)) sif->CastSpell(me, SPELL_TOUCH_OF_DOMINION); break; case EVENT_STORMHAMMER: DoCast(SPELL_STORMHAMMER); events.Repeat(15s, 20s); break; case EVENT_CHARGE_ORB: DoCastAOE(SPELL_CHARGE_ORB); events.Repeat(15s, 20s); break; case EVENT_SUMMON_ADDS: SummonWave(); events.Repeat(_orbSummoned ? 3s : 10s); break; case EVENT_JUMPDOWN: if (_hardMode) if (Creature* sif = instance->GetCreature(DATA_SIF)) sif->AI()->DoAction(ACTION_START_HARD_MODE); me->RemoveAurasDueToSpell(SPELL_SHEATH_OF_LIGHTNING); me->SetReactState(REACT_AGGRESSIVE); me->SetDisableGravity(false); me->SetControlled(false, UNIT_STATE_ROOT); me->GetMotionMaster()->MoveJump(2134.8f, -263.056f, 419.983f, me->GetOrientation(), 30.0f, 20.0f); events.ScheduleEvent(EVENT_START_PERIODIC_CHARGE, 2s, 0, PHASE_2); events.ScheduleEvent(EVENT_UNBALANCING_STRIKE, 15s, 0, PHASE_2); events.ScheduleEvent(EVENT_CHAIN_LIGHTNING, 20s, 0, PHASE_2); break; case EVENT_UNBALANCING_STRIKE: DoCastVictim(SPELL_UNBALANCING_STRIKE); events.Repeat(15s, 20s); break; case EVENT_CHAIN_LIGHTNING: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 100.0f, true)) DoCast(target, SPELL_CHAIN_LIGHTNING); events.Repeat(7s, 15s); break; case EVENT_START_PERIODIC_CHARGE: if (Creature* controller = instance->GetCreature(DATA_THORIM_CONTROLLER)) controller->CastSpell(controller, SPELL_ACTIVATE_LIGHTNING_ORB_PERIODIC, true); break; case EVENT_LIGHTNING_CHARGE: if (Creature* pillar = ObjectAccessor::GetCreature(*me, _activePillarGUID)) DoCast(pillar, SPELL_LIGHTNING_RELEASE); break; case EVENT_BERSERK: if (events.IsInPhase(PHASE_1)) { Talk(SAY_WIPE); DoCastAOE(SPELL_BERSERK_PHASE_1, true); DoCast(me, SPELL_SUMMON_LIGHTNING_ORB, true); } else { Talk(SAY_BERSERK); DoCast(me, SPELL_BERSERK_PHASE_2, true); } break; case EVENT_ACTIVATE_LIGHTNING_FIELD: { std::list<Creature*> triggers; me->GetCreatureListWithEntryInGrid(triggers, NPC_THORIM_EVENT_BUNNY, 100.0f); triggers.remove_if([](Creature* bunny) { if (HeightPositionCheck(false)(bunny)) return true; return LightningFieldCenter.GetExactDist2dSq(bunny) > 1296.0f; }); Milliseconds timer = 1s; for (Creature* bunny : triggers) bunny->m_Events.AddEvent(new LightningFieldEvent(bunny), bunny->m_Events.CalculateTime(timer += 100ms)); triggers.remove_if([](Creature* bunny) { return LightningFieldCenter.GetExactDist2dSq(bunny) < 576.0f; }); triggers.sort([](Creature* a, Creature* b) { return a->GetPositionX() < b->GetPositionX(); }); for (auto itr = triggers.cbegin(); itr != triggers.cend();) { auto prev = itr++; if (itr != triggers.cend()) (*prev)->CastSpell(*itr, SPELL_LIGHTNING_BEAM_CHANNEL); } break; } case EVENT_OUTRO_1: Talk(_hardMode ? SAY_END_HARD_1 : SAY_END_NORMAL_1); if (_hardMode) DoCast(me, SPELL_STORMHAMMER_SIF); break; case EVENT_OUTRO_2: Talk(_hardMode ? SAY_END_HARD_2 : SAY_END_NORMAL_2); if (_hardMode) if (Creature* sif = instance->GetCreature(DATA_SIF)) sif->SetStandState(UNIT_STAND_STATE_DEAD); break; case EVENT_OUTRO_3: Talk(_hardMode ? SAY_END_HARD_3 : SAY_END_NORMAL_3); break; default: break; } if (me->HasUnitState(UNIT_STATE_CASTING)) return; } DoMeleeAttackIfReady(); } void DoAction(int32 action) override { switch (action) { case ACTION_BERSERK: if (events.IsInPhase(PHASE_2)) return; if (!_orbSummoned) { _orbSummoned = true; events.RescheduleEvent(EVENT_BERSERK, 1s); } return; case ACTION_INCREASE_PREADDS_COUNT: if (++_killedCount >= 6) { // Event starts me->SetImmuneToPC(false); DoZoneInCombat(me); } break; default: break; } } void GetTrashSpawnTriggers(std::list<Creature*>& triggerList, uint32 count = 1) { me->GetCreatureListWithEntryInGrid(triggerList, NPC_THORIM_EVENT_BUNNY, 100.0f); triggerList.remove_if([](Creature* bunny) { if (HeightPositionCheck(false)(bunny)) return true; return ArenaCenter.GetExactDist2dSq(bunny) < 3025.0f; }); if (triggerList.empty()) return; if (count == 1) { Creature* bunny = Trinity::Containers::SelectRandomContainerElement(triggerList); triggerList.clear(); triggerList.push_back(bunny); } else Trinity::Containers::RandomResize(triggerList, count); } void SummonWave() { switch (_waveType) { case 0: { // Dark Rune Commoner std::list<Creature*> triggers; GetTrashSpawnTriggers(triggers, urand(5, 6)); for (Creature* bunny : triggers) me->SummonCreature(StaticThorimTrashInfo[6 + 3].Entry, *bunny, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 3s); ++_waveType; break; } case 1: if (urand(0, 1)) { // Dark Rune Champion or Dark Rune Evoker std::list<Creature*> triggers; GetTrashSpawnTriggers(triggers, urand(2, 4)); for (Creature* bunny : triggers) me->SummonCreature(StaticThorimTrashInfo[6 + RAND(0, 2)].Entry, *bunny, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 3s); } else { // Dark Rune Warbringer std::list<Creature*> triggers; GetTrashSpawnTriggers(triggers); for (Creature* bunny : triggers) me->SummonCreature(StaticThorimTrashInfo[6 + 1].Entry, *bunny, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 3s); } --_waveType; break; } } bool CanStartPhase2(Unit* actor) const { if (!actor || actor->GetTypeId() != TYPEID_PLAYER || !me->IsWithinDistInMap(actor, 10.0f)) return false; Creature* runicColossus = instance->GetCreature(DATA_RUNIC_COLOSSUS); Creature* runeGiant = instance->GetCreature(DATA_RUNE_GIANT); return runicColossus && !runicColossus->IsAlive() && runeGiant && !runeGiant->IsAlive(); } void DamageTaken(Unit* attacker, uint32& damage) override { if (events.IsInPhase(PHASE_1) && CanStartPhase2(attacker)) { Talk(SAY_JUMPDOWN); events.SetPhase(PHASE_2); events.ScheduleEvent(EVENT_JUMPDOWN, 8s); events.ScheduleEvent(EVENT_ACTIVATE_LIGHTNING_FIELD, 15s); events.RescheduleEvent(EVENT_BERSERK, 300s, 0, PHASE_2); if (Creature* sif = instance->GetCreature(DATA_SIF)) sif->InterruptNonMeleeSpells(false); // Hard Mode if (_hardMode) DoCastAOE(SPELL_CREDIT_SIFFED, true); } else if (me->HealthBelowPctDamaged(1, damage)) { damage = 0; FinishEncounter(); } } private: ObjectGuid _activePillarGUID; uint8 _killedCount; uint8 _waveType; bool _hardMode; bool _encounterFinished; bool _orbSummoned; bool _dontStandInTheLightning; }; CreatureAI* GetAI(Creature* creature) const override { return GetUlduarAI<boss_thorimAI>(creature); } }; struct npc_thorim_trashAI : public ScriptedAI { npc_thorim_trashAI(Creature* creature) : ScriptedAI(creature) { _instance = creature->GetInstanceScript(); for (uint8 i = 0; i < ThorimTrashCount; ++i) if (me->GetEntry() == StaticThorimTrashInfo[i].Entry) _info = &StaticThorimTrashInfo[i]; ASSERT(_info); } struct AIHelper { /// returns heal amount of the given spell including hots static uint32 GetTotalHeal(SpellInfo const* spellInfo, Unit const* caster) { uint32 heal = 0; for (SpellEffectInfo const& spellEffectInfo : spellInfo->GetEffects()) { if (spellEffectInfo.IsEffect(SPELL_EFFECT_HEAL)) heal += spellEffectInfo.CalcValue(caster); if (spellEffectInfo.IsEffect(SPELL_EFFECT_APPLY_AURA) && spellEffectInfo.IsAura(SPELL_AURA_PERIODIC_HEAL)) heal += spellInfo->GetMaxTicks() * spellEffectInfo.CalcValue(caster); } return heal; } /// returns remaining heal amount on given target static uint32 GetRemainingHealOn(Unit* target) { uint32 heal = 0; Unit::AuraEffectList const& auras = target->GetAuraEffectsByType(SPELL_AURA_PERIODIC_HEAL); for (AuraEffect const* aurEff : auras) heal += aurEff->GetAmount() * aurEff->GetRemainingTicks(); return heal; } class MostHPMissingInRange { public: MostHPMissingInRange(Unit const* referer, float range, uint32 hp, uint32 exclAura = 0, bool exclSelf = false) : _referer(referer), _range(range), _hp(hp), _exclAura(exclAura), _exclSelf(exclSelf) { } bool operator()(Unit* u) { if (_exclSelf && u == _referer) return false; if (_exclAura && u->HasAura(_exclAura)) return false; if ((u->GetHealth() + GetRemainingHealOn(u) + _hp) > u->GetMaxHealth()) return false; uint32 missingHP = u->GetMaxHealth() - u->GetHealth(); if (u->IsAlive() && _referer->IsFriendlyTo(u) && _referer->IsWithinDistInMap(u, _range) && missingHP > _hp) { _hp = missingHP; return true; } return false; } private: Unit const* _referer; float _range; uint32 _hp; uint32 _exclAura; bool _exclSelf; }; static Unit* GetUnitWithMostMissingHp(SpellInfo const* spellInfo, Unit* caster) { // use positive range, it's a healing spell float const range = spellInfo->GetMaxRange(true); uint32 const heal = GetTotalHeal(spellInfo, caster); Unit* target = nullptr; Trinity::MostHPMissingInRange checker(caster, range, heal); Trinity::UnitLastSearcher<Trinity::MostHPMissingInRange> searcher(caster, target, checker); Cell::VisitGridObjects(caster, searcher, 60.0f); return target; } static Unit* GetHealTarget(SpellInfo const* spellInfo, Unit* caster) { Unit* healTarget = nullptr; if (!spellInfo->HasAttribute(SPELL_ATTR1_CANT_TARGET_SELF) && !roll_chance_f(caster->GetHealthPct()) && ((caster->GetHealth() + GetRemainingHealOn(caster) + GetTotalHeal(spellInfo, caster)) <= caster->GetMaxHealth())) healTarget = caster; else healTarget = GetUnitWithMostMissingHp(spellInfo, caster); return healTarget; } }; bool UseAbility(uint32 spellId) { SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId, GetDifficulty()); if (!spellInfo) return false; Unit* target = nullptr; if (AIHelper::GetTotalHeal(spellInfo, me)) target = AIHelper::GetHealTarget(spellInfo, me); else target = me->GetVictim(); if (!target) return false; if (_info->Type == MERCENARY_SOLDIER) { bool allowMove = true; if (me->IsInRange(target, spellInfo->GetMinRange(), spellInfo->GetMaxRange())) allowMove = false; if (IsCombatMovementAllowed() != allowMove) { SetCombatMovement(allowMove); // need relaunch movement ScriptedAI::AttackStart(target); // give some time to allow reposition, try again in a second if (allowMove) return false; } } DoCast(target, spellId); return true; } void UpdateAI(uint32 diff) final override { if (!UpdateVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = _events.ExecuteEvent()) { ExecuteEvent(eventId); if (me->HasUnitState(UNIT_STATE_CASTING)) return; } if (_info->Type == DARK_RUNE_ACOLYTE) DoSpellAttackIfReady(SPELL_HOLY_SMITE); else DoMeleeAttackIfReady(); } virtual void ExecuteEvent(uint32 eventId) = 0; protected: InstanceScript* _instance; EventMap _events; ThorimTrashInfo const* _info = nullptr; }; class npc_thorim_pre_phase : public CreatureScript { public: npc_thorim_pre_phase() : CreatureScript("npc_thorim_pre_phase") { } struct npc_thorim_pre_phaseAI : public npc_thorim_trashAI { npc_thorim_pre_phaseAI(Creature* creature) : npc_thorim_trashAI(creature) { me->setActive(true); // prevent grid unload me->SetFarVisible(true); } void Reset() override { _events.Reset(); if (_info->PrimaryAbility) _events.ScheduleEvent(EVENT_PRIMARY_ABILITY, 3s, 6s); if (_info->SecondaryAbility) { if (_info->SecondaryAbility == SPELL_SHOOT) _events.ScheduleEvent(EVENT_SECONDARY_ABILITY, 2s); else _events.ScheduleEvent(EVENT_SECONDARY_ABILITY, 12s, 15s); } if (_info->ThirdAbility) _events.ScheduleEvent(EVENT_THIRD_ABILITY, 6s, 8s); if (_info->Type == MERCENARY_SOLDIER) SetCombatMovement(false); } void JustDied(Unit* /*killer*/) override { if (Creature* thorim = _instance->GetCreature(BOSS_THORIM)) thorim->AI()->DoAction(ACTION_INCREASE_PREADDS_COUNT); } bool ShouldSparWith(Unit const* target) const override { return !target->GetAffectingPlayer(); } void DamageTaken(Unit* attacker, uint32& damage) override { // nullify spell damage if (!attacker || !attacker->GetAffectingPlayer()) damage = 0; } void ExecuteEvent(uint32 eventId) override { switch (eventId) { case EVENT_PRIMARY_ABILITY: if (UseAbility(_info->PrimaryAbility)) _events.ScheduleEvent(eventId, 15s, 20s); else _events.ScheduleEvent(eventId, 1s); break; case EVENT_SECONDARY_ABILITY: if (UseAbility(_info->SecondaryAbility)) { if (_info->SecondaryAbility == SPELL_SHOOT) _events.ScheduleEvent(eventId, 2s); else _events.ScheduleEvent(eventId, 4s, 8s); } else _events.ScheduleEvent(eventId, 1s); break; case EVENT_THIRD_ABILITY: if (UseAbility(_info->ThirdAbility)) _events.ScheduleEvent(eventId, 6s, 8s); else _events.ScheduleEvent(eventId, 1s); break; default: break; } } }; CreatureAI* GetAI(Creature* creature) const override { return GetUlduarAI<npc_thorim_pre_phaseAI>(creature); } }; class npc_thorim_arena_phase : public CreatureScript { public: npc_thorim_arena_phase() : CreatureScript("npc_thorim_arena_phase") { } struct npc_thorim_arena_phaseAI : public npc_thorim_trashAI { npc_thorim_arena_phaseAI(Creature* creature) : npc_thorim_trashAI(creature) { switch (_info->Type) { case DARK_RUNE_CHAMPION: case DARK_RUNE_WARBRINGER: case DARK_RUNE_COMMONER: case DARK_RUNE_EVOKER: _isInArena = true; break; case DARK_RUNE_ACOLYTE: { _isInArena = (_info->Entry == NPC_DARK_RUNE_ACOLYTE_PRE); SetBoundary(&ArenaBoundaries, !_isInArena); break; } default: _isInArena = false; break; } } bool CanAIAttack(Unit const* who) const override { // don't try to attack players in balcony if (_isInArena && HeightPositionCheck(true)(who)) return false; return IsInBoundary(who); } void Reset() override { _events.Reset(); if (_info->PrimaryAbility) _events.ScheduleEvent(EVENT_PRIMARY_ABILITY, 3s, 6s); if (_info->SecondaryAbility) _events.ScheduleEvent(EVENT_SECONDARY_ABILITY, 7s, 9s); if (_info->ThirdAbility) _events.ScheduleEvent(EVENT_THIRD_ABILITY, 6s, 8s); if (_info->Type == DARK_RUNE_CHAMPION) _events.ScheduleEvent(EVENT_ABILITY_CHARGE, 8s); } void JustEngagedWith(Unit* /*who*/) override { if (_info->Type == DARK_RUNE_WARBRINGER) DoCast(me, SPELL_AURA_OF_CELERITY); if (!_isInArena) if (Creature* colossus = _instance->GetCreature(DATA_RUNIC_COLOSSUS)) colossus->AI()->DoAction(ACTION_ACTIVATE_RUNIC_SMASH); } void EnterEvadeMode(EvadeReason why) override { if (why != EVADE_REASON_NO_HOSTILES && why != EVADE_REASON_BOUNDARY) return; // this should only happen if theres no alive player in the arena -> summon orb if (Creature* thorim = _instance->GetCreature(BOSS_THORIM)) thorim->AI()->DoAction(ACTION_BERSERK); ScriptedAI::EnterEvadeMode(why); } void ExecuteEvent(uint32 eventId) override { switch (eventId) { case EVENT_PRIMARY_ABILITY: if (UseAbility(_info->PrimaryAbility)) _events.Repeat(3s, 6s); else _events.Repeat(1s); break; case EVENT_SECONDARY_ABILITY: if (UseAbility(_info->SecondaryAbility)) _events.Repeat(12s, 16s); else _events.Repeat(1s); break; case EVENT_THIRD_ABILITY: if (UseAbility(_info->ThirdAbility)) _events.Repeat(6s, 8s); else _events.Repeat(1s); break; case EVENT_ABILITY_CHARGE: { Unit* referer = me; if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, [referer](Unit* unit){ return unit->GetTypeId() == TYPEID_PLAYER && unit->IsInRange(referer, 8.0f, 25.0f); })) DoCast(target, SPELL_CHARGE); _events.ScheduleEvent(eventId, 12s); break; } default: break; } } private: bool _isInArena; }; CreatureAI* GetAI(Creature* creature) const override { return GetUlduarAI<npc_thorim_arena_phaseAI>(creature); } }; struct npc_thorim_minibossAI : public ScriptedAI { npc_thorim_minibossAI(Creature* creature) : ScriptedAI(creature), _summons(me) { _instance = creature->GetInstanceScript(); SetBoundary(&ArenaBoundaries, true); } bool CanAIAttack(Unit const* who) const final override { return IsInBoundary(who); } void JustSummoned(Creature* summon) final override { _summons.Summon(summon); } void SummonedCreatureDespawn(Creature* summon) final override { _summons.Despawn(summon); } void DoAction(int32 action) override { if (action == ACTION_ACTIVATE_ADDS) { for (ObjectGuid const& guid : _summons) if (Creature* summon = ObjectAccessor::GetCreature(*me, guid)) summon->SetImmuneToPC(false); } } protected: InstanceScript* _instance; EventMap _events; SummonList _summons; }; class npc_runic_colossus : public CreatureScript { public: npc_runic_colossus() : CreatureScript("npc_runic_colossus") { } struct npc_runic_colossusAI : public npc_thorim_minibossAI { npc_runic_colossusAI(Creature* creature) : npc_thorim_minibossAI(creature) { Initialize(); } void Initialize() { _runicActive = false; } void Reset() override { Initialize(); _events.Reset(); // close the Runic Door _instance->HandleGameObject(_instance->GetGuidData(DATA_RUNIC_DOOR), false); // Spawn trashes _summons.DespawnAll(); for (SummonLocation const& s : ColossusAddLocations) me->SummonCreature(s.entry, s.pos, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 3s); } void MoveInLineOfSight(Unit* /*who*/) override { // don't enter combat } void DoAction(int32 action) override { npc_thorim_minibossAI::DoAction(action); if (_runicActive) return; if (action == ACTION_ACTIVATE_RUNIC_SMASH) { _runicActive = true; _events.ScheduleEvent(EVENT_RUNIC_SMASH, 7s); } } void JustDied(Unit* /*killer*/) override { // open the Runic Door _instance->HandleGameObject(_instance->GetGuidData(DATA_RUNIC_DOOR), true); if (Creature* thorim = _instance->GetCreature(BOSS_THORIM)) thorim->AI()->Talk(SAY_SPECIAL); if (Creature* giant = _instance->GetCreature(DATA_RUNE_GIANT)) { giant->SetImmuneToPC(false); giant->AI()->DoAction(ACTION_ACTIVATE_ADDS); } } void JustEngagedWith(Unit* /*who*/) override { DoZoneInCombat(); _events.Reset(); _events.ScheduleEvent(EVENT_RUNIC_BARRIER, 12s, 15s); _events.ScheduleEvent(EVENT_SMASH, 15s, 18s); _events.ScheduleEvent(EVENT_RUNIC_CHARGE, 20s, 24s); } void UpdateAI(uint32 diff) override { _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_RUNIC_BARRIER: Talk(EMOTE_RUNIC_BARRIER); DoCastAOE(SPELL_RUNIC_BARRIER); _events.Repeat(35s, 45s); break; case EVENT_SMASH: DoCastAOE(SPELL_SMASH); _events.Repeat(15s, 18s); break; case EVENT_RUNIC_CHARGE: { Unit* referer = me; if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, [referer](Unit* unit){ return unit->GetTypeId() == TYPEID_PLAYER && unit->IsInRange(referer, 8.0f, 40.0f); })) DoCast(target, SPELL_RUNIC_CHARGE); _events.Repeat(20s); break; } case EVENT_RUNIC_SMASH: DoCast(me, RAND(SPELL_RUNIC_SMASH_LEFT, SPELL_RUNIC_SMASH_RIGHT)); _events.Repeat(6s); break; default: break; } if (me->HasUnitState(UNIT_STATE_CASTING)) return; } if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } private: bool _runicActive; }; CreatureAI* GetAI(Creature* creature) const override { return GetUlduarAI<npc_runic_colossusAI>(creature); } }; class npc_ancient_rune_giant : public CreatureScript { public: npc_ancient_rune_giant() : CreatureScript("npc_ancient_rune_giant") { } struct npc_ancient_rune_giantAI : public npc_thorim_minibossAI { npc_ancient_rune_giantAI(Creature* creature) : npc_thorim_minibossAI(creature) { } void Reset() override { _events.Reset(); // close the Stone Door _instance->HandleGameObject(_instance->GetGuidData(DATA_STONE_DOOR), false); // Spawn trashes _summons.DespawnAll(); for (SummonLocation const& s : GiantAddLocations) me->SummonCreature(s.entry, s.pos, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 3s); } void JustEngagedWith(Unit* /*who*/) override { DoZoneInCombat(); _events.Reset(); _events.ScheduleEvent(EVENT_RUNIC_FORTIFICATION, 1ms); _events.ScheduleEvent(EVENT_STOMP, 10s, 12s); _events.ScheduleEvent(EVENT_RUNE_DETONATION, 25s); } void JustDied(Unit* /*killer*/) override { // opem the Stone Door _instance->HandleGameObject(_instance->GetGuidData(DATA_STONE_DOOR), true); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_RUNIC_FORTIFICATION: Talk(EMOTE_RUNIC_MIGHT); DoCastAOE(SPELL_RUNIC_FORTIFICATION); break; case EVENT_STOMP: DoCastAOE(SPELL_STOMP); _events.Repeat(10s, 12s); break; case EVENT_RUNE_DETONATION: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 60.0f, true)) DoCast(target, SPELL_RUNE_DETONATION); _events.Repeat(10s, 12s); break; default: break; } if (me->HasUnitState(UNIT_STATE_CASTING)) return; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return GetUlduarAI<npc_ancient_rune_giantAI>(creature); } }; class npc_sif : public CreatureScript { public: npc_sif() : CreatureScript("npc_sif") { } struct npc_sifAI : public ScriptedAI { npc_sifAI(Creature* creature) : ScriptedAI(creature) { SetCombatMovement(false); _instance = creature->GetInstanceScript(); } void Reset() override { _events.Reset(); } void SpellHit(WorldObject* /*caster*/, SpellInfo const* spellInfo) override { if (spellInfo->Id == SPELL_STORMHAMMER_SIF) { me->InterruptSpell(CURRENT_GENERIC_SPELL); me->SetReactState(REACT_PASSIVE); me->AttackStop(); } } void DoAction(int32 action) override { if (action == ACTION_START_HARD_MODE) { me->SetReactState(REACT_AGGRESSIVE); DoZoneInCombat(me); Talk(SAY_SIF_EVENT); _events.Reset(); _events.ScheduleEvent(EVENT_FROSTBOLT, 2s); _events.ScheduleEvent(EVENT_FROSTBOLT_VOLLEY, 15s); _events.ScheduleEvent(EVENT_BLINK, 20s, 25s); _events.ScheduleEvent(EVENT_BLIZZARD, 30s); } } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_BLINK: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 100.0f, true)) DoCast(target, SPELL_BLINK); _events.ScheduleEvent(EVENT_FROST_NOVA, 0s); _events.Repeat(20s, 25s); return; case EVENT_FROST_NOVA: DoCastAOE(SPELL_FROSTNOVA); return; case EVENT_FROSTBOLT: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 100.0f, true)) DoCast(target, SPELL_FROSTBOLT); _events.Repeat(2s); return; case EVENT_FROSTBOLT_VOLLEY: DoCastAOE(SPELL_FROSTBOLT_VOLLEY); _events.Repeat(15s, 20s); return; case EVENT_BLIZZARD: DoCastAOE(SPELL_BLIZZARD); _events.Repeat(35s, 45s); return; default: break; } if (me->HasUnitState(UNIT_STATE_CASTING)) return; } // no melee attack } private: EventMap _events; InstanceScript* _instance; }; CreatureAI* GetAI(Creature* creature) const override { return GetUlduarAI<npc_sifAI>(creature); } }; // 62576 - Blizzard // 62602 - Blizzard class spell_thorim_blizzard_effect : public SpellScriptLoader { public: spell_thorim_blizzard_effect() : SpellScriptLoader("spell_thorim_blizzard_effect") { } class spell_thorim_blizzard_effect_AuraScript : public AuraScript { PrepareAuraScript(spell_thorim_blizzard_effect_AuraScript); bool CheckAreaTarget(Unit* target) { /// @todo: fix this for all dynobj auras if (target != GetOwner()) { // check if not stacking aura already on target // this one prevents overriding auras periodically by 2 near area aura owners Unit::AuraApplicationMap const& auraMap = target->GetAppliedAuras(); for (Unit::AuraApplicationMap::const_iterator iter = auraMap.begin(); iter != auraMap.end(); ++iter) { Aura const* aura = iter->second->GetBase(); if (GetId() == aura->GetId() && GetOwner() != aura->GetOwner() /*!GetAura()->CanStackWith(aura)*/) return false; } } return true; } void Register() override { DoCheckAreaTarget += AuraCheckAreaTargetFn(spell_thorim_blizzard_effect_AuraScript::CheckAreaTarget); } }; AuraScript* GetAuraScript() const override { return new spell_thorim_blizzard_effect_AuraScript(); } }; // 62580, 62604 - Frostbolt Volley class spell_thorim_frostbolt_volley : public SpellScriptLoader { public: spell_thorim_frostbolt_volley() : SpellScriptLoader("spell_thorim_frostbolt_volley") { } class spell_thorim_frostbolt_volley_SpellScript : public SpellScript { PrepareSpellScript(spell_thorim_frostbolt_volley_SpellScript); void FilterTargets(std::list<WorldObject*>& targets) { targets.remove_if([](WorldObject* object) -> bool { if (object->GetTypeId() == TYPEID_PLAYER) return false; if (Creature* creature = object->ToCreature()) return !creature->IsPet(); return true; }); } void Register() override { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_thorim_frostbolt_volley_SpellScript::FilterTargets, EFFECT_ALL, TARGET_UNIT_SRC_AREA_ENEMY); } }; SpellScript* GetSpellScript() const override { return new spell_thorim_frostbolt_volley_SpellScript(); } }; // 62016 - Charge Orb class spell_thorim_charge_orb : public SpellScriptLoader { public: spell_thorim_charge_orb() : SpellScriptLoader("spell_thorim_charge_orb") { } class spell_thorim_charge_orb_SpellScript : public SpellScript { PrepareSpellScript(spell_thorim_charge_orb_SpellScript); bool Validate(SpellInfo const* /*spellInfo*/) override { return ValidateSpellInfo({ SPELL_LIGHTNING_PILLAR_1 }); } void FilterTargets(std::list<WorldObject*>& targets) { targets.remove_if(HeightPositionCheck(false)); if (targets.empty()) return; WorldObject* target = Trinity::Containers::SelectRandomContainerElement(targets); targets.clear(); targets.push_back(target); } void HandleScript() { if (Unit* target = GetHitUnit()) target->CastSpell(nullptr, SPELL_LIGHTNING_PILLAR_1, true); } void Register() override { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_thorim_charge_orb_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENTRY); AfterHit += SpellHitFn(spell_thorim_charge_orb_SpellScript::HandleScript); } }; SpellScript* GetSpellScript() const override { return new spell_thorim_charge_orb_SpellScript(); } }; // 62466 - Lightning Charge class spell_thorim_lightning_charge : public SpellScriptLoader { public: spell_thorim_lightning_charge() : SpellScriptLoader("spell_thorim_lightning_charge") { } class spell_thorim_lightning_charge_SpellScript : public SpellScript { PrepareSpellScript(spell_thorim_lightning_charge_SpellScript); bool Validate(SpellInfo const* /*spellInfo*/) override { return ValidateSpellInfo({ SPELL_LIGHTNING_CHARGE }); } void HandleFocus() { /// @workaround: focus target is not working because spell is triggered and instant if (Creature* creature = GetCaster()->ToCreature()) creature->SetSpellFocus(GetSpell(), GetExplTargetWorldObject()); } void HandleCharge() { GetCaster()->CastSpell(GetCaster(), SPELL_LIGHTNING_CHARGE); } void Register() override { BeforeCast += SpellCastFn(spell_thorim_lightning_charge_SpellScript::HandleFocus); AfterCast += SpellCastFn(spell_thorim_lightning_charge_SpellScript::HandleCharge); } }; SpellScript* GetSpellScript() const override { return new spell_thorim_lightning_charge_SpellScript(); } }; // 61934 - Leap class spell_thorim_arena_leap : public SpellScriptLoader { public: spell_thorim_arena_leap() : SpellScriptLoader("spell_thorim_arena_leap") { } class spell_thorim_arena_leap_SpellScript : public SpellScript { PrepareSpellScript(spell_thorim_arena_leap_SpellScript); bool Load() override { return GetCaster()->GetTypeId() == TYPEID_UNIT; } void HandleScript(SpellEffIndex /*effIndex*/) { if (Position const* pos = GetHitDest()) GetCaster()->ToCreature()->SetHomePosition(*pos); } void Register() override { OnEffectLaunch += SpellEffectFn(spell_thorim_arena_leap_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_JUMP_DEST); } }; SpellScript* GetSpellScript() const override { return new spell_thorim_arena_leap_SpellScript(); } }; struct OutOfArenaCheck { bool operator()(Position const* who) const { return !CreatureAI::IsInBounds(ArenaBoundaries, who); } }; // 62042 - Stormhammer class spell_thorim_stormhammer : public SpellScriptLoader { public: spell_thorim_stormhammer() : SpellScriptLoader("spell_thorim_stormhammer") { } class spell_thorim_stormhammer_SpellScript : public SpellScript { PrepareSpellScript(spell_thorim_stormhammer_SpellScript); bool Validate(SpellInfo const* /*spellInfo*/) override { return ValidateSpellInfo({ SPELL_STORMHAMMER_BOOMERANG, SPELL_DEAFENING_THUNDER }); } void FilterTargets(std::list<WorldObject*>& targets) { targets.remove_if([](WorldObject* target) -> bool { return HeightPositionCheck(true)(target) || OutOfArenaCheck()(target); }); if (targets.empty()) { FinishCast(SPELL_FAILED_NO_VALID_TARGETS); return; } WorldObject* target = Trinity::Containers::SelectRandomContainerElement(targets); targets.clear(); targets.push_back(target); } void HandleScript(SpellEffIndex /*effIndex*/) { if (Unit* target = GetHitUnit()) { target->CastSpell(target, SPELL_DEAFENING_THUNDER, true); target->CastSpell(GetCaster(), SPELL_STORMHAMMER_BOOMERANG, true); } } void LoseHammer() { GetCaster()->SetVirtualItem(0, 0); } void Register() override { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_thorim_stormhammer_SpellScript::FilterTargets, EFFECT_ALL, TARGET_UNIT_SRC_AREA_ENEMY); AfterCast += SpellCastFn(spell_thorim_stormhammer_SpellScript::LoseHammer); OnEffectHitTarget += SpellEffectFn(spell_thorim_stormhammer_SpellScript::HandleScript, EFFECT_2, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const override { return new spell_thorim_stormhammer_SpellScript(); } }; // 64767 - Stormhammer class spell_thorim_stormhammer_sif : public SpellScriptLoader { public: spell_thorim_stormhammer_sif() : SpellScriptLoader("spell_thorim_stormhammer_sif") { } class spell_thorim_stormhammer_sif_SpellScript : public SpellScript { PrepareSpellScript(spell_thorim_stormhammer_sif_SpellScript); bool Validate(SpellInfo const* /*spellInfo*/) override { return ValidateSpellInfo({ SPELL_STORMHAMMER_BOOMERANG, SPELL_SIF_TRANSFORM }); } void HandleScript(SpellEffIndex /*effIndex*/) { if (Unit* target = GetHitUnit()) { target->CastSpell(GetCaster(), SPELL_STORMHAMMER_BOOMERANG, true); target->CastSpell(target, SPELL_SIF_TRANSFORM, true); } } void LoseHammer() { GetCaster()->SetVirtualItem(0, 0); } void Register() override { AfterCast += SpellCastFn(spell_thorim_stormhammer_sif_SpellScript::LoseHammer); OnEffectHitTarget += SpellEffectFn(spell_thorim_stormhammer_sif_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const override { return new spell_thorim_stormhammer_sif_SpellScript(); } }; // 64909 - Stormhammer class spell_thorim_stormhammer_boomerang : public SpellScriptLoader { public: spell_thorim_stormhammer_boomerang() : SpellScriptLoader("spell_thorim_stormhammer_boomerang") { } class spell_thorim_stormhammer_boomerang_SpellScript : public SpellScript { PrepareSpellScript(spell_thorim_stormhammer_boomerang_SpellScript); void RecoverHammer(SpellEffIndex /*effIndex*/) { if (Unit* target = GetHitUnit()) target->SetVirtualItem(0, THORIM_WEAPON_DISPLAY_ID); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_thorim_stormhammer_boomerang_SpellScript::RecoverHammer, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const override { return new spell_thorim_stormhammer_boomerang_SpellScript(); } }; // 62057, 62058 - Runic Smash class spell_thorim_runic_smash : public SpellScriptLoader { public: spell_thorim_runic_smash() : SpellScriptLoader("spell_thorim_runic_smash") { } class spell_thorim_runic_smash_SpellScript : public SpellScript { PrepareSpellScript(spell_thorim_runic_smash_SpellScript); bool Validate(SpellInfo const* /*spellInfo*/) override { return ValidateSpellInfo({ SPELL_RUNIC_SMASH }); } void HandleScript(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); std::vector<Creature*> triggers; GetCaster()->GetCreatureListWithEntryInGrid(triggers, GetSpellInfo()->Id == SPELL_RUNIC_SMASH_LEFT ? NPC_GOLEM_LEFT_HAND_BUNNY : NPC_GOLEM_RIGHT_HAND_BUNNY, 150.0f); for (Creature* trigger : triggers) { Milliseconds time = Milliseconds(uint64(GetCaster()->GetExactDist(trigger) * 30.f)); trigger->m_Events.AddEvent(new RunicSmashExplosionEvent(trigger), trigger->m_Events.CalculateTime(time)); }; } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_thorim_runic_smash_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_TRIGGER_SPELL); } }; SpellScript* GetSpellScript() const override { return new spell_thorim_runic_smash_SpellScript(); } }; class UpperOrbCheck { public: UpperOrbCheck() : _check(true) { } bool operator() (Creature* target) const { return target->GetEntry() == NPC_THUNDER_ORB && _check(target); } private: HeightPositionCheck const _check; }; // 62184 - Activate Lightning Orb Periodic class spell_thorim_activate_lightning_orb_periodic : public SpellScriptLoader { public: spell_thorim_activate_lightning_orb_periodic() : SpellScriptLoader("spell_thorim_activate_lightning_orb_periodic") { } class spell_thorim_activate_lightning_orb_periodic_AuraScript : public AuraScript { PrepareAuraScript(spell_thorim_activate_lightning_orb_periodic_AuraScript); InstanceScript* instance = nullptr; void PeriodicTick(AuraEffect const* /*aurEff*/) { PreventDefaultAction(); Unit* caster = GetCaster(); std::vector<Creature*> triggers; UpperOrbCheck check; Trinity::CreatureListSearcher<UpperOrbCheck> searcher(caster, triggers, check); Cell::VisitGridObjects(caster, searcher, 100.f); if (!triggers.empty()) { Creature* target = Trinity::Containers::SelectRandomContainerElement(triggers); if (Creature* thorim = instance->GetCreature(BOSS_THORIM)) thorim->AI()->SetGUID(target->GetGUID(), DATA_CHARGED_PILLAR); } } bool Load() override { if (Unit* caster = GetCaster()) instance = caster->GetInstanceScript(); return instance != nullptr; } void Register() override { OnEffectPeriodic += AuraEffectPeriodicFn(spell_thorim_activate_lightning_orb_periodic_AuraScript::PeriodicTick, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL); } }; AuraScript* GetAuraScript() const override { return new spell_thorim_activate_lightning_orb_periodic_AuraScript(); } }; class condition_thorim_arena_leap : public ConditionScript { public: condition_thorim_arena_leap() : ConditionScript("condition_thorim_arena_leap"), _check(false) { } bool OnConditionCheck(Condition const* condition, ConditionSourceInfo& sourceInfo) override { WorldObject* target = sourceInfo.mConditionTargets[condition->ConditionTarget]; InstanceScript* instance = target->GetInstanceScript(); if (!instance) return false; return _check(target); } private: HeightPositionCheck _check; }; void AddSC_boss_thorim() { new boss_thorim(); new npc_thorim_pre_phase(); new npc_thorim_arena_phase(); new npc_runic_colossus(); new npc_ancient_rune_giant(); new npc_sif(); new spell_thorim_blizzard_effect(); new spell_thorim_frostbolt_volley(); new spell_thorim_charge_orb(); new spell_thorim_lightning_charge(); new spell_thorim_stormhammer(); new spell_thorim_stormhammer_sif(); new spell_thorim_stormhammer_boomerang(); new spell_thorim_arena_leap(); new spell_thorim_runic_smash(); new spell_thorim_activate_lightning_orb_periodic(); new condition_thorim_arena_leap(); }
Shauren/TrinityCore
src/server/scripts/Northrend/Ulduar/Ulduar/boss_thorim.cpp
C++
gpl-2.0
77,173
<p>This is the singleItem view.</p> {{item}} <form ng-submit="save()"> <input type="text" ng-model="item.name"> <input type="text" ng-model="item.weight"> <label> <input type="checkbox" ng-model="item.in_stock"> In stock </label> <button type="submit">Save</button> </form>
daniellowtw/angular-parse-crud
app/views/singleitem.html
HTML
gpl-2.0
313
<html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="assets/stylesheet-en.css" /> </head> <body class="eng"> <div class='verse' id='Ch_C05_S14_V02' type='mantra'> <div class='versetext'>atsyannaṁ paśyasi priyamattyannaṁ paśyati priyaṁ bhavatyasya brahmavarcasaṁ kulē ya ētamēvamātmānaṁ vaiśvānaramupāstē prāṇastvēṣa ātmana iti hōvāca prāṇasya udakramiṣyadyanmāṁ nāgamiṣya iti ॥ 2 ॥ </div> <div class='bhashya' id='Ch_C05_S14_V02_B01'>atsyannamityādi samānam । prāṇastvēṣa ātmana iti ha uvāca । prāṇastē tava udakramiṣyat utkrāntōऽbhaviṣyat , yanmāṁ nāgamiṣya iti ॥ </div> </div> </body> </html>
SrirangaDigital/shankara-android
app/src/main/assets/html/en/Ch_C05_S14_V02.html
HTML
gpl-2.0
691
JFLAGS = -O -Xlint JC = javac .SUFFIXES: .java .class .java.class: $(JC) $(JFLAGS) $*.java CLASSES = \ detector/Detector.java \ detector/DetectorCir.java \ detector/DetectorLin.java \ graphs/CList.java \ graphs/Graph.java \ graphs/GraphCir.java \ graphs/GraphLin.java \ order/GeneOrder.java \ order/GeneOrderCir.java \ order/GeneOrderLin.java \ scheduler/LoadBalancer.java \ solvers/ASMSolver.java \ solvers/ExactSolver.java \ solvers/ExactThread.java \ solvers/HeuSolver.java \ structs/Elem.java \ structs/ElemNoBuffer.java \ structs/ElemWithBuffer.java \ structs/SearchList.java \ tools/Const.java \ tools/Func.java \ tools/Info.java \ tools/Params.java \ gasts/Solution.java \ gasts/GraphXu.java \ gasts/GASTS.java \ gasts/GAS_Phylogeny.java \ gasts/Heuristic_min.java \ gasts/Linearalization.java \ gasts/Newick.java \ gasts/Node.java \ gasts/NodePair.java \ gasts/Poisson.java \ gasts/ReversalDistance.java \ gasts/SimulatedGenome.java \ gasts/Simulation.java \ gasts/SimuNode.java \ gasts/Solution.java \ gasts/WeightedASM.java \ gasts/Genome.java \ gasts/EF.java \ gasts/Constant.java \ gasts/ASM.java \ gasts/Adjacency.java \ gasts/AdjNode.java \ gasts/Adequate.java \ DCJ.java default: classes classes: $(CLASSES:.java=.class) clean: $(RM) *.class $(RM) detector/*.class $(RM) graphs/*.class $(RM) order/*.class $(RM) scheduler/*.class $(RM) solvers/*.class $(RM) structs/*.class $(RM) tools/*.class $(RM) gasts/*.class
stplaydog/DCJStream
Makefile
Makefile
gpl-2.0
1,657
import unittest import mock import blivet from pykickstart.constants import CLEARPART_TYPE_ALL, CLEARPART_TYPE_LINUX, CLEARPART_TYPE_NONE from parted import PARTITION_NORMAL from blivet.flags import flags DEVICE_CLASSES = [ blivet.devices.DiskDevice, blivet.devices.PartitionDevice ] @unittest.skipUnless(not any(x.unavailable_type_dependencies() for x in DEVICE_CLASSES), "some unsupported device classes required for this test") class ClearPartTestCase(unittest.TestCase): def setUp(self): flags.testing = True def test_should_clear(self): """ Test the Blivet.should_clear method. """ b = blivet.Blivet() DiskDevice = blivet.devices.DiskDevice PartitionDevice = blivet.devices.PartitionDevice # sda is a disk with an existing disklabel containing two partitions sda = DiskDevice("sda", size=100000, exists=True) sda.format = blivet.formats.get_format("disklabel", device=sda.path, exists=True) sda.format._parted_disk = mock.Mock() sda.format._parted_device = mock.Mock() sda.format._parted_disk.configure_mock(partitions=[]) b.devicetree._add_device(sda) # sda1 is a partition containing an existing ext4 filesystem sda1 = PartitionDevice("sda1", size=500, exists=True, parents=[sda]) sda1._parted_partition = mock.Mock(**{'type': PARTITION_NORMAL, 'getFlag.return_value': 0}) sda1.format = blivet.formats.get_format("ext4", mountpoint="/boot", device=sda1.path, exists=True) b.devicetree._add_device(sda1) # sda2 is a partition containing an existing vfat filesystem sda2 = PartitionDevice("sda2", size=10000, exists=True, parents=[sda]) sda2._parted_partition = mock.Mock(**{'type': PARTITION_NORMAL, 'getFlag.return_value': 0}) sda2.format = blivet.formats.get_format("vfat", mountpoint="/foo", device=sda2.path, exists=True) b.devicetree._add_device(sda2) # sdb is an unpartitioned disk containing an xfs filesystem sdb = DiskDevice("sdb", size=100000, exists=True) sdb.format = blivet.formats.get_format("xfs", device=sdb.path, exists=True) b.devicetree._add_device(sdb) # sdc is an unformatted/uninitialized/empty disk sdc = DiskDevice("sdc", size=100000, exists=True) b.devicetree._add_device(sdc) # sdd is a disk containing an existing disklabel with no partitions sdd = DiskDevice("sdd", size=100000, exists=True) sdd.format = blivet.formats.get_format("disklabel", device=sdd.path, exists=True) b.devicetree._add_device(sdd) # # clearpart type none # b.config.clear_part_type = CLEARPART_TYPE_NONE self.assertFalse(b.should_clear(sda1), msg="type none should not clear any partitions") self.assertFalse(b.should_clear(sda2), msg="type none should not clear any partitions") b.config.initialize_disks = False self.assertFalse(b.should_clear(sda), msg="type none should not clear non-empty disks") self.assertFalse(b.should_clear(sdb), msg="type none should not clear formatting from " "unpartitioned disks") self.assertFalse(b.should_clear(sdc), msg="type none should not clear empty disk without " "initlabel") self.assertFalse(b.should_clear(sdd), msg="type none should not clear empty partition table " "without initlabel") b.config.initialize_disks = True self.assertFalse(b.should_clear(sda), msg="type none should not clear non-empty disks even " "with initlabel") self.assertFalse(b.should_clear(sdb), msg="type non should not clear formatting from " "unpartitioned disks even with initlabel") self.assertTrue(b.should_clear(sdc), msg="type none should clear empty disks when initlabel " "is set") self.assertTrue(b.should_clear(sdd), msg="type none should clear empty partition table when " "initlabel is set") # # clearpart type linux # b.config.clear_part_type = CLEARPART_TYPE_LINUX self.assertTrue(b.should_clear(sda1), msg="type linux should clear partitions containing " "ext4 filesystems") self.assertFalse(b.should_clear(sda2), msg="type linux should not clear partitions " "containing vfat filesystems") b.config.initialize_disks = False self.assertFalse(b.should_clear(sda), msg="type linux should not clear non-empty disklabels") self.assertTrue(b.should_clear(sdb), msg="type linux should clear linux-native whole-disk " "formatting regardless of initlabel setting") self.assertFalse(b.should_clear(sdc), msg="type linux should not clear unformatted disks " "unless initlabel is set") self.assertFalse(b.should_clear(sdd), msg="type linux should not clear disks with empty " "partition tables unless initlabel is set") b.config.initialize_disks = True self.assertFalse(b.should_clear(sda), msg="type linux should not clear non-empty disklabels") self.assertTrue(b.should_clear(sdb), msg="type linux should clear linux-native whole-disk " "formatting regardless of initlabel setting") self.assertTrue(b.should_clear(sdc), msg="type linux should clear unformatted disks when " "initlabel is set") self.assertTrue(b.should_clear(sdd), msg="type linux should clear disks with empty " "partition tables when initlabel is set") sda1.protected = True self.assertFalse(b.should_clear(sda1), msg="protected devices should never be cleared") self.assertFalse(b.should_clear(sda), msg="disks containing protected devices should never " "be cleared") sda1.protected = False # # clearpart type all # b.config.clear_part_type = CLEARPART_TYPE_ALL self.assertTrue(b.should_clear(sda1), msg="type all should clear all partitions") self.assertTrue(b.should_clear(sda2), msg="type all should clear all partitions") b.config.initialize_disks = False self.assertTrue(b.should_clear(sda), msg="type all should initialize all disks") self.assertTrue(b.should_clear(sdb), msg="type all should initialize all disks") self.assertTrue(b.should_clear(sdc), msg="type all should initialize all disks") self.assertTrue(b.should_clear(sdd), msg="type all should initialize all disks") b.config.initialize_disks = True self.assertTrue(b.should_clear(sda), msg="type all should initialize all disks") self.assertTrue(b.should_clear(sdb), msg="type all should initialize all disks") self.assertTrue(b.should_clear(sdc), msg="type all should initialize all disks") self.assertTrue(b.should_clear(sdd), msg="type all should initialize all disks") sda1.protected = True self.assertFalse(b.should_clear(sda1), msg="protected devices should never be cleared") self.assertFalse(b.should_clear(sda), msg="disks containing protected devices should never " "be cleared") sda1.protected = False # # clearpart type list # # TODO def tearDown(self): flags.testing = False def test_initialize_disk(self): """ magic partitions non-empty partition table """ pass def test_recursive_remove(self): """ protected device at various points in stack """ pass
atodorov/blivet
tests/clearpart_test.py
Python
gpl-2.0
9,228
/* * linux/drivers/mmc/core/bus.c * * Copyright (C) 2003 Russell King, All Rights Reserved. * Copyright (C) 2007 Pierre Ossman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * MMC card bus driver model */ #include <linux/device.h> #include <linux/err.h> #include <linux/slab.h> <<<<<<< HEAD #include <linux/pm_runtime.h> ======= >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a #include <linux/mmc/card.h> #include <linux/mmc/host.h> #include "core.h" #include "sdio_cis.h" #include "bus.h" <<<<<<< HEAD ======= #define dev_to_mmc_card(d) container_of(d, struct mmc_card, dev) >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a #define to_mmc_driver(d) container_of(d, struct mmc_driver, drv) static ssize_t mmc_type_show(struct device *dev, struct device_attribute *attr, char *buf) { <<<<<<< HEAD struct mmc_card *card = mmc_dev_to_card(dev); ======= struct mmc_card *card = dev_to_mmc_card(dev); >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a switch (card->type) { case MMC_TYPE_MMC: return sprintf(buf, "MMC\n"); case MMC_TYPE_SD: return sprintf(buf, "SD\n"); case MMC_TYPE_SDIO: return sprintf(buf, "SDIO\n"); <<<<<<< HEAD case MMC_TYPE_SD_COMBO: return sprintf(buf, "SDcombo\n"); ======= >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a default: return -EFAULT; } } static struct device_attribute mmc_dev_attrs[] = { __ATTR(type, S_IRUGO, mmc_type_show, NULL), __ATTR_NULL, }; /* * This currently matches any MMC driver to any MMC card - drivers * themselves make the decision whether to drive this card in their * probe method. */ static int mmc_bus_match(struct device *dev, struct device_driver *drv) { return 1; } static int mmc_bus_uevent(struct device *dev, struct kobj_uevent_env *env) { <<<<<<< HEAD struct mmc_card *card = mmc_dev_to_card(dev); ======= struct mmc_card *card = dev_to_mmc_card(dev); >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a const char *type; int retval = 0; switch (card->type) { case MMC_TYPE_MMC: type = "MMC"; break; case MMC_TYPE_SD: type = "SD"; break; case MMC_TYPE_SDIO: type = "SDIO"; break; <<<<<<< HEAD case MMC_TYPE_SD_COMBO: type = "SDcombo"; break; ======= >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a default: type = NULL; } if (type) { retval = add_uevent_var(env, "MMC_TYPE=%s", type); if (retval) return retval; } retval = add_uevent_var(env, "MMC_NAME=%s", mmc_card_name(card)); if (retval) return retval; /* * Request the mmc_block device. Note: that this is a direct request * for the module it carries no information as to what is inserted. */ retval = add_uevent_var(env, "MODALIAS=mmc:block"); return retval; } static int mmc_bus_probe(struct device *dev) { struct mmc_driver *drv = to_mmc_driver(dev->driver); <<<<<<< HEAD struct mmc_card *card = mmc_dev_to_card(dev); ======= struct mmc_card *card = dev_to_mmc_card(dev); >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a return drv->probe(card); } static int mmc_bus_remove(struct device *dev) { struct mmc_driver *drv = to_mmc_driver(dev->driver); <<<<<<< HEAD struct mmc_card *card = mmc_dev_to_card(dev); ======= struct mmc_card *card = dev_to_mmc_card(dev); >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a drv->remove(card); return 0; } <<<<<<< HEAD static int mmc_bus_suspend(struct device *dev) { struct mmc_driver *drv = to_mmc_driver(dev->driver); struct mmc_card *card = mmc_dev_to_card(dev); int ret = 0; if (dev->driver && drv->suspend) ret = drv->suspend(card); ======= static int mmc_bus_suspend(struct device *dev, pm_message_t state) { struct mmc_driver *drv = to_mmc_driver(dev->driver); struct mmc_card *card = dev_to_mmc_card(dev); int ret = 0; if (dev->driver && drv->suspend) ret = drv->suspend(card, state); >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a return ret; } static int mmc_bus_resume(struct device *dev) { struct mmc_driver *drv = to_mmc_driver(dev->driver); <<<<<<< HEAD struct mmc_card *card = mmc_dev_to_card(dev); ======= struct mmc_card *card = dev_to_mmc_card(dev); >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a int ret = 0; if (dev->driver && drv->resume) ret = drv->resume(card); return ret; } <<<<<<< HEAD #ifdef CONFIG_PM_RUNTIME static int mmc_runtime_suspend(struct device *dev) { struct mmc_card *card = mmc_dev_to_card(dev); return mmc_power_save_host(card->host); } static int mmc_runtime_resume(struct device *dev) { struct mmc_card *card = mmc_dev_to_card(dev); return mmc_power_restore_host(card->host); } static int mmc_runtime_idle(struct device *dev) { return pm_runtime_suspend(dev); } #else /* !CONFIG_PM_RUNTIME */ #define mmc_runtime_suspend NULL #define mmc_runtime_resume NULL #define mmc_runtime_idle NULL #endif /* !CONFIG_PM_RUNTIME */ static const struct dev_pm_ops mmc_bus_pm_ops = { .runtime_suspend = mmc_runtime_suspend, .runtime_resume = mmc_runtime_resume, .runtime_idle = mmc_runtime_idle, .suspend = mmc_bus_suspend, .resume = mmc_bus_resume, }; ======= >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a static struct bus_type mmc_bus_type = { .name = "mmc", .dev_attrs = mmc_dev_attrs, .match = mmc_bus_match, .uevent = mmc_bus_uevent, .probe = mmc_bus_probe, .remove = mmc_bus_remove, <<<<<<< HEAD .pm = &mmc_bus_pm_ops, ======= .suspend = mmc_bus_suspend, .resume = mmc_bus_resume, >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a }; int mmc_register_bus(void) { return bus_register(&mmc_bus_type); } void mmc_unregister_bus(void) { bus_unregister(&mmc_bus_type); } /** * mmc_register_driver - register a media driver * @drv: MMC media driver */ int mmc_register_driver(struct mmc_driver *drv) { drv->drv.bus = &mmc_bus_type; return driver_register(&drv->drv); } EXPORT_SYMBOL(mmc_register_driver); /** * mmc_unregister_driver - unregister a media driver * @drv: MMC media driver */ void mmc_unregister_driver(struct mmc_driver *drv) { drv->drv.bus = &mmc_bus_type; driver_unregister(&drv->drv); } EXPORT_SYMBOL(mmc_unregister_driver); static void mmc_release_card(struct device *dev) { <<<<<<< HEAD struct mmc_card *card = mmc_dev_to_card(dev); ======= struct mmc_card *card = dev_to_mmc_card(dev); >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a sdio_free_common_cis(card); if (card->info) kfree(card->info); kfree(card); } /* * Allocate and initialise a new MMC card structure. */ struct mmc_card *mmc_alloc_card(struct mmc_host *host, struct device_type *type) { struct mmc_card *card; card = kzalloc(sizeof(struct mmc_card), GFP_KERNEL); if (!card) return ERR_PTR(-ENOMEM); card->host = host; device_initialize(&card->dev); card->dev.parent = mmc_classdev(host); card->dev.bus = &mmc_bus_type; card->dev.release = mmc_release_card; card->dev.type = type; return card; } /* * Register a new MMC card with the driver model. */ int mmc_add_card(struct mmc_card *card) { int ret; const char *type; dev_set_name(&card->dev, "%s:%04x", mmc_hostname(card->host), card->rca); <<<<<<< HEAD card->removed = 0; ======= >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a switch (card->type) { case MMC_TYPE_MMC: type = "MMC"; break; case MMC_TYPE_SD: type = "SD"; <<<<<<< HEAD if (mmc_card_blockaddr(card)) { if (mmc_card_ext_capacity(card)) type = "SDXC"; else type = "SDHC"; } ======= if (mmc_card_blockaddr(card)) type = "SDHC"; >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a break; case MMC_TYPE_SDIO: type = "SDIO"; break; <<<<<<< HEAD case MMC_TYPE_SD_COMBO: type = "SD-combo"; if (mmc_card_blockaddr(card)) type = "SDHC-combo"; break; ======= >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a default: type = "?"; break; } if (mmc_host_is_spi(card->host)) { <<<<<<< HEAD printk(KERN_INFO "%s: new %s%s%s card on SPI\n", mmc_hostname(card->host), mmc_card_highspeed(card) ? "high speed " : "", mmc_card_ddr_mode(card) ? "DDR " : "", type); } else { printk(KERN_INFO "%s: new %s%s%s card at address %04x\n", mmc_hostname(card->host), mmc_sd_card_uhs(card) ? "ultra high speed " : (mmc_card_highspeed(card) ? "high speed " : ""), mmc_card_ddr_mode(card) ? "DDR " : "", type, card->rca); } #ifdef CONFIG_DEBUG_FS mmc_add_card_debugfs(card); #endif ======= printk(KERN_INFO "%s: new %s%s card on SPI\n", mmc_hostname(card->host), mmc_card_highspeed(card) ? "high speed " : "", type); } else { printk(KERN_INFO "%s: new %s%s card at address %04x\n", mmc_hostname(card->host), mmc_card_highspeed(card) ? "high speed " : "", type, card->rca); } >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a ret = device_add(&card->dev); if (ret) return ret; <<<<<<< HEAD ======= #ifdef CONFIG_DEBUG_FS mmc_add_card_debugfs(card); #endif >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a mmc_card_set_present(card); return 0; } /* * Unregister a new MMC card with the driver model, and * (eventually) free it. */ void mmc_remove_card(struct mmc_card *card) { <<<<<<< HEAD if (mmc_card_sd(card)) card->removed = 1; ======= >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a #ifdef CONFIG_DEBUG_FS mmc_remove_card_debugfs(card); #endif if (mmc_card_present(card)) { if (mmc_host_is_spi(card->host)) { printk(KERN_INFO "%s: SPI card removed\n", mmc_hostname(card->host)); } else { printk(KERN_INFO "%s: card %04x removed\n", mmc_hostname(card->host), card->rca); } device_del(&card->dev); } put_device(&card->dev); }
Core2idiot/Kernel-Samsung-3.0...-
drivers/mmc/core/bus.c
C
gpl-2.0
9,637
// $HeadURL$ // $Id$ // // Copyright © 2006, 2010, 2011, 2012 by the President and Fellows of Harvard College. // // Screensaver is an open-source project developed by the ICCB-L and NSRB labs // at Harvard Medical School. This software is distributed under the terms of // the GNU General Public License. package edu.harvard.med.screensaver.ui.arch.datatable.column; import java.util.Comparator; import edu.harvard.med.screensaver.util.NullSafeComparator; import org.joda.time.LocalDate; public abstract class DateColumn<R> extends TableColumn<R,LocalDate> { abstract protected LocalDate getDate(R o); public DateColumn(String name, String description, String group) { super(name, description, ColumnType.DATE, group); } @Override public LocalDate getCellValue(R o) { return getDate(o); } @Override protected Comparator<R> getAscendingComparator() { return new NullSafeComparator<R>() { NullSafeComparator<LocalDate> _dateComparator = new NullSafeComparator<LocalDate>() { @Override protected int doCompare(LocalDate d1, LocalDate d2) { return d1.compareTo(d2); } }; @Override protected int doCompare(R o1, R o2) { return _dateComparator.compare(getDate(o1), getDate(o2)); } }; } }
hmsiccbl/screensaver
web/src/main/java/edu/harvard/med/screensaver/ui/arch/datatable/column/DateColumn.java
Java
gpl-2.0
1,302
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>ip::address_v6::to_string (1 of 2 overloads)</title> <link rel="stylesheet" href="../../../../boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.73.2"> <link rel="start" href="../../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../to_string.html" title="ip::address_v6::to_string"> <link rel="prev" href="../to_string.html" title="ip::address_v6::to_string"> <link rel="next" href="overload2.html" title="ip::address_v6::to_string (2 of 2 overloads)"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../to_string.html"><img src="../../../../../../doc/html/images/prev.png" alt="Prev"></a><a accesskey="u" href="../to_string.html"><img src="../../../../../../doc/html/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/html/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/html/images/next.png" alt="Next"></a> </div> <div class="section" lang="en"> <div class="titlepage"><div><div><h5 class="title"> <a name="boost_asio.reference.ip__address_v6.to_string.overload1"></a><a class="link" href="overload1.html" title="ip::address_v6::to_string (1 of 2 overloads)"> ip::address_v6::to_string (1 of 2 overloads)</a> </h5></div></div></div> <p> Get the address as a string. </p> <pre class="programlisting"><span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span> <span class="identifier">to_string</span><span class="special">()</span> <span class="keyword">const</span><span class="special">;</span> </pre> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright © 2003 - 2008 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../to_string.html"><img src="../../../../../../doc/html/images/prev.png" alt="Prev"></a><a accesskey="u" href="../to_string.html"><img src="../../../../../../doc/html/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/html/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/html/images/next.png" alt="Next"></a> </div> </body> </html>
scs/uclinux
lib/boost/boost_1_38_0/doc/html/boost_asio/reference/ip__address_v6/to_string/overload1.html
HTML
gpl-2.0
3,396
#!/bin/bash echo "....................................................." echo "Starting Build for S6-Flat Device" echo "....................................................." sleep 5 ./build_flat.sh sleep 3 ./repack_flat.sh sleep 3 clear echo "....................................................." echo "Starting Build for S6-Edge Device" echo "....................................................." sleep 5 ./build_edge.sh sleep 3 ./repack_edge.sh sleep 3 exit 1
Hybridmax/G92XF_Mystery_Kernel
build_all.sh
Shell
gpl-2.0
469
# SPDX-License-Identifier: GPL-2.0+ # Copyright (c) 2016 Google, Inc # Written by Simon Glass <sjg@chromium.org> # # Entry-type module for 'u-boot-nodtb.bin' # from entry import Entry from blob import Entry_blob class Entry_u_boot_spl_nodtb(Entry_blob): def __init__(self, image, etype, node): Entry_blob.__init__(self, image, etype, node) def GetDefaultFilename(self): return 'spl/u-boot-spl-nodtb.bin'
ev3dev/u-boot
tools/binman/etype/u_boot_spl_nodtb.py
Python
gpl-2.0
431
<?php //namespace Admin; /** * The admin-specific functionality of the plugin. * * @link http://eliseoeric.com * @since 1.0.0 * * @package Citrix_Connect * @subpackage Citrix_Connect/admin */ /** * The admin-specific functionality of the plugin. * * Defines the plugin name, version, and two examples hooks for how to * enqueue the admin-specific stylesheet and JavaScript. * * @package Citrix_Connect * @subpackage Citrix_Connect/admin * @author Eric Eliseo <eric.eliseo@gmail.com> */ class Citrix_Connect_Admin { /** * The ID of this plugin. * * @since 1.0.0 * @access private * @var string $plugin_name The ID of this plugin. */ private $plugin_name; /** * The version of this plugin. * * @since 1.0.0 * @access private * @var string $version The current version of this plugin. */ private $version; /** * Initialize the class and set its properties. * * @since 1.0.0 * @param string $plugin_name The name of this plugin. * @param string $version The version of this plugin. */ public function __construct( $plugin_name, $version ) { $this->plugin_name = $plugin_name; $this->version = $version; } /** * Register the stylesheets for the admin area. * * @since 1.0.0 */ public function enqueue_styles() { /** * This function is provided for demonstration purposes only. * * An instance of this class should be passed to the run() function * defined in Citrix_Connect_Loader as all of the hooks are defined * in that particular class. * * The Citrix_Connect_Loader will then create the relationship * between the defined hooks and the functions defined in this * class. */ wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/citrix-connect-admin.css', array(), $this->version, 'all' ); wp_register_style( 'datatables', '//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css' ); } /** * Register the JavaScript for the admin area. * * @since 1.0.0 */ public function enqueue_scripts() { /** * This function is provided for demonstration purposes only. * * An instance of this class should be passed to the run() function * defined in Citrix_Connect_Loader as all of the hooks are defined * in that particular class. * * The Citrix_Connect_Loader will then create the relationship * between the defined hooks and the functions defined in this * class. */ wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/citrix-connect-admin.js', array( 'jquery' ), $this->version, false ); wp_register_script( 'datatables', '//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js', array( 'jquery' ), '1.0', true ); wp_register_script( 'cc_datatables', plugin_dir_url( __FILE__ ) . 'js/citrix-connect-datatables.js', array(), '1.0', true ); } public function cmb2_render_callback_for_text_password( $field, $escaped_value, $object_id, $object_type, $field_type_object ) { echo $field_type_object->input( array( 'type' => 'password' ) ); } public function cmb2_sanitize_text_password_callback( $override_value, $value ) { return $value; } }
eliseoeric/citrix-connect
admin/class-citrix-connect-admin.php
PHP
gpl-2.0
3,244
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Framework\Authorization; /** * Responsible for internal authorization decision making based on provided role, resource and privilege * * @api */ interface PolicyInterface { /** * Check whether given role has access to given resource * * @abstract * @param string $roleId * @param string $resourceId * @param string|null $privilege * @return bool */ public function isAllowed($roleId, $resourceId, $privilege = null); }
kunj1988/Magento2
lib/internal/Magento/Framework/Authorization/PolicyInterface.php
PHP
gpl-2.0
595
package org.andork.jogl.uniform; import org.andork.jogl.shader.Uniform4fvLocation; import com.jogamp.opengl.GL2ES2; public class Uniform4fv implements Uniform { int count = 1; float[] value; int value_offset; public Uniform4fv count(int count) { this.count = count; return this; } @Override public void put(GL2ES2 gl, int location) { gl.glUniform4fv(location, count, value, value_offset); } public Uniform4fv value(float... value) { this.value = value; return this; } public float[] value() { return value; } public Uniform4fv value_offset(int value_offset) { this.value_offset = value_offset; return this; } public void put(GL2ES2 gl, Uniform4fvLocation location) { put(gl, location.location()); } }
jedwards1211/breakout
andork-jogl-gl2es2-utils/src/org/andork/jogl/uniform/Uniform4fv.java
Java
gpl-2.0
744
<?PHP // $Id$ // // Release $Name$ // // Copyright (c)2002-2003 Matthias Finck, Dirk Fust, Oliver Hankel, Iver Jackewitz, Michael Janneck, // Martti Jeenicke, Detlev Krause, Irina L. Marinescu, Timo Nolte, Bernd Pape, // Edouard Simon, Monique Strauss, José Manuel González Vázquez // // This file is part of CommSy. // // CommSy 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. // // CommSy 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 have received a copy of the GNU General Public License // along with CommSy. /** upper class of the dates item */ include_once('classes/cs_item.php'); /** class for a dates * this class implements a dates item */ class cs_dates_item extends cs_item { /** constructor * the only available constructor, initial values for internal variables * * @param object environment environment of commsy */ function __construct($environment) { cs_item::__construct($environment); $this->_type = CS_DATE_TYPE; } /** Checks and sets the data of the item. * * @param $data_array Is the prepared array from "_buildItemArray($db_array)" * * @author CommSy Development Group */ function _setItemData($data_array) { // check data before setting #if(!(isset($data_array['title']) and !empty($data_array['title']) # and isset($data_array['start_day']) and !empty($data_array['start_day']))) { # include_once('functions/error_functions.php');trigger_error("At least one mandatory field is not set for item ".$data_array['item_id'], E_USER_WARNING); # var_dump($data_array); #} $this->_data = $data_array; } /** get title of a dates * this method returns the title of the dates * * @return string title of a dates * * @author CommSy Development Group */ function getTitle () { if ($this->getPublic()=='-1'){ $translator = $this->_environment->getTranslationObject(); return $translator->getMessage('COMMON_AUTOMATIC_DELETE_TITLE'); }else{ return $this->_getValue('title'); } } /** set title of a dates * this method sets the title of the dates * * @param string value title of the dates * * @author CommSy Development Group */ function setTitle ($value) { // sanitize title $converter = $this->_environment->getTextConverter(); $value = htmlentities($value); $value = $converter->sanitizeHTML($value); $this->_setValue('title', $value); } /** set date and time of start in the database time format * this method sets the starting datetime of the dates * * @param string value starting datetime of the dates * * @author CommSy Development Group */ function setDateTime_start ($value) { $this->_setValue('datetime_start', $value); } /** get date and time of start in the database time format * this method returns the starting datetime of the dates * * @return string starting datetime of the dates * * @author CommSy Development Group */ function getDateTime_start () { return $this->_getValue('datetime_start'); } /** get date and time of start as a proper \DateTime object * this method returns the starting datetime of the dates * * @return \DateTime starting datetime of the dates * * @author CommSy Development Group */ public function getDateTimeObject_start () { return \DateTime::createFromFormat('Y-m-d H:i:s', $this->_getValue('datetime_start')); } /** set date and time of end in the database time format * this method sets the ending datetime of the dates * * @param string value ending datetime of the dates * * @author CommSy Development Group */ function setDateTime_end ($value) { $this->_setValue('datetime_end', $value); } /** get date and time of end in the database time format * this method returns the ending datetime of the dates * * @return string ending datetime of the dates * * @author CommSy Development Group */ function getDateTime_end () { return $this->_getValue('datetime_end'); } /** get date and time of end as a proper \DateTime object * this method returns the ending datetime of the dates * * @return \DateTime ending datetime of the dates * * @author CommSy Development Group */ public function getDateTimeObject_end () { return \DateTime::createFromFormat('Y-m-d H:i:s', $this->_getValue('datetime_end')); } /** get description of a dates * this method returns the description of the dates * * @return string description of a dates */ function getDescription () { if ($this->getPublic()=='-1'){ $translator = $this->_environment->getTranslationObject(); return $translator->getMessage('COMMON_AUTOMATIC_DELETE_DESCRIPTION'); }else{ return $this->_getValue('description'); } } /** set description of a dates * this method sets the description of the dates * * @param string value description of the dates * * @author CommSy Development Group */ function setDescription ($value) { // sanitize description $converter = $this->_environment->getTextConverter(); $value = $converter->sanitizeFullHTML($value); $this->_setValue('description', $value); } /** set ending day of a dates * this method sets the starting day of the dates * * @param string value starting day of the dates * * @author CommSy Development Group */ function setEndingDay($value) { $this->_setValue('end_day', $value); } /** get ending day of a dates * this method returns the ending day of the dates * * @return string ending day of a dates * * @author CommSy Development Group */ function getEndingDay() { return $this->_getValue('end_day'); } /** set ending time of a dates * this method sets the ending time of the dates * * @param string value ending time of the dates * * @author CommSy Development Group */ function setEndingTime($value) { $this->_setValue('end_time', $value); } /** get ending time of a dates * this method returns the ending time of the dates * * @return string ending time of a dates * * @author CommSy Development Group */ function getEndingTime() { return $this->_getValue('end_time'); } /** set starting day of a dates * this method sets the starting day of the dates * * @param string value starting day of the dates * * @author CommSy Development Group */ function setStartingDay($value) { $this->_setValue('start_day', $value); } /** get starting day of a dates * this method returns the starting day of the dates * * @return string starting day of a dates * * @author CommSy Development Group */ function getStartingDay() { return $this->_getValue('start_day'); } function setShownStartingDay($value) { $this->_setValue('shown_start_day', $value); } function getShownStartingDay() { return $this->_getValue('shown_start_day'); } function setShownStartingTime($value) { $this->_setValue('shown_start_time', $value); } function getShownStartingTime() { return $this->_getValue('shown_start_time'); } public function getStartingDayName() { return getDayNameFromInt( date('w', strtotime( $this->getStartingDay() ) ) ); } public function getEndingDayName() { return getDayNameFromInt(date('w', strtotime( $this->getEndingDay() ) ) ); } /** set starting time of a dates * this method sets the starting time of the dates * * @param string value starting time of the dates * * @author CommSy Development Group */ function setStartingTime($value) { $this->_setValue('start_time', $value); } /** get starting time of a dates * this method returns the starting time of the dates * * @return string starting time of a dates * * @author CommSy Development Group */ function getStartingTime() { return $this->_getValue('start_time'); } /** set place of a dates * this method sets the place of the dates * * @param string value place of the dates * * @author CommSy Development Group */ function setPlace($value) { $this->_setValue('place', $value); } /** get place of a dates * this method returns the place of the dates * * @return string place of a dates * * @author CommSy Development Group */ function getPlace() { if ($this->getPublic()=='-1'){ return ''; }else{ return $this->_getValue('place'); } } /** set date_mode status of a dates * this method sets the date_mode status of the dates * * @param string value date_mode status of the dates * * @author CommSy Development Group */ function setDateMode($value) { $this->_setValue('date_mode', $value); } /** get date_mode status of a dates * this method returns the date_mode status of the dates * * @return string date_mode status of a dates * * @author CommSy Development Group */ function getDateMode() { return $this->_getValue('date_mode'); } /** set color of a dates * this method sets the color of the dates * * @param string value color of the dates * * @author CommSy Development Group */ function setColor($value) { $this->_setValue('color', $value); } /** get color of a dates * this method returns the color of the dates * * @return string color of a dates * * @author CommSy Development Group */ function getColor() { return $this->_getValue('color'); } /** set calendar_id of a dates * this method sets the calendar_id of the dates * * @param string value calendar_id of the dates * * @author CommSy Development Group */ function setCalendarId($value) { $this->_setValue('calendar_id', $value); } /** get calendar_id of a dates * this method returns the calendar_id of the dates * * @return string calendar_id of a dates * * @author CommSy Development Group */ function getCalendarId() { return $this->_getValue('calendar_id'); } /** * @return \App\Entity\Calendars * @throws Exception */ function getCalendar() { global $symfonyContainer; $calendarsService = $symfonyContainer->get('commsy.calendars_service'); return $calendarsService->getCalendar($this->getCalendarId())[0]; } /** set recurrence_id of a date * this method sets the recurrence_id of the date * * @param string value recurrence_id of the date * * @author CommSy Development Group */ function setRecurrenceId($value) { $this->_setValue('recurrence_id', $value); } /** get recurrence_id of a date * this method returns the recurrence_id of the date * * @return string recurrence_id of a date * * @author CommSy Development Group */ function getRecurrenceId() { return $this->_getValue('recurrence_id'); } /** set recurrence_pattern of a date * this method sets the recurrence_pattern of the date * * @param string value recurrence_pattern of the date * * @author CommSy Development Group */ function setRecurrencePattern($value) { $this->_setValue('recurrence_pattern', $value); } /** get recurrence_pattern of a date * this method returns the recurrence_pattern of the date * * @return array recurrence_pattern of a date * * @author CommSy Development Group */ function getRecurrencePattern() { return $this->_getValue('recurrence_pattern'); } function issetPrivatDate(){ return $this->_getValue('date_mode')==1; } function getParticipantsItemList(){ $members = new cs_list(); $member_ids = $this->getLinkedItemIDArray(CS_USER_TYPE); if ( !empty($member_ids) ){ $user_manager = $this->_environment->getUserManager(); $user_manager->setIDArrayLimit($member_ids); $user_manager->select(); $members = $user_manager->get(); } // returns a cs_list of user_items return $members; } function isParticipant($user) { $link_member_list = $this->getLinkItemList(CS_USER_TYPE); $link_member_item = $link_member_list->getFirst(); $is_member = false; while ( $link_member_item ) { $linked_user_id = $link_member_item->getLinkedItemID($this); if ( $user->getItemID() == $linked_user_id ) { $is_member = true; break; } $link_member_item = $link_member_list->getNext(); } return $is_member; } function addParticipant ($user) { if ( !$this->isParticipant($user) ) { $link_manager = $this->_environment->getLinkItemManager(); $link_item = $link_manager->getNewItem(); $link_item->setFirstLinkedItem($this); $link_item->setSecondLinkedItem($user); $link_item->save(); } } function removeParticipant ($user) { $link_member_list = $this->getLinkItemList(CS_USER_TYPE); $link_member_item = $link_member_list->getFirst(); while ( $link_member_item ) { $linked_user_id = $link_member_item->getLinkedItemID($this); if ( $user->getItemID() == $linked_user_id ) { $link_member_item->delete(); } $link_member_item = $link_member_list->getNext(); } } /** Checks the data of the item. * * @return boolean TRUE if data is valid FALSE otherwise */ function isValid() { // mandatory fields set? $title = $this->getTitle(); $start_day = $this->getStartingDay(); return (parent::isValid() and !empty($title) and !empty($start_day)); } function save () { $dates_mananger = $this->_environment->getDatesManager(); $this->_save($dates_mananger); $this->_saveFiles(); // this must be done before saveFileLinks $this->_saveFileLinks(); // this must be done after saving so we can be sure to have an item id $this->updateElastic(); } public function updateElastic() { global $symfonyContainer; $objectPersister = $symfonyContainer->get('app.elastica.object_persister.commsy_date'); $em = $symfonyContainer->get('doctrine.orm.entity_manager'); $repository = $em->getRepository('App:Dates'); $this->replaceElasticItem($objectPersister, $repository); } public function delete() { global $symfonyContainer; /** @var \Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcer */ $eventDispatcer = $symfonyContainer->get('event_dispatcher'); $itemDeletedEvent = new \App\Event\ItemDeletedEvent($this); $eventDispatcer->dispatch($itemDeletedEvent, \App\Event\ItemDeletedEvent::NAME); $date_manager = $this->_environment->getDatesManager(); $this->_delete($date_manager); // delete associated annotations $this->deleteAssociatedAnnotations(); $objectPersister = $symfonyContainer->get('app.elastica.object_persister.commsy_date'); $em = $symfonyContainer->get('doctrine.orm.entity_manager'); $repository = $em->getRepository('App:Dates'); $this->deleteElasticItem($objectPersister, $repository); } /** asks if item is editable by everybody or just creator * * @param value * * @author CommSy Development Group */ function isPublic() { if ($this->_getValue('public')== 1) { return true; } else { return false; } } /** sets if announcement is editable by everybody or just creator * * @param value * * @author CommSy Development Group */ function setPublic ($value) { $this->_setValue('public', $value); } function copy() { $copy = $this->cloneCopy(); $copy->setItemID(''); $copy->setFileList($this->_copyFileList()); $copy->setContextID($this->_environment->getCurrentContextID()); $user = $this->_environment->getCurrentUserItem(); $copy->setCreatorItem($user); $copy->setModificatorItem($user); $list = new cs_list(); $copy->setGroupList($list); $copy->setTopicList($list); $copy->save(); return $copy; } function cloneCopy() { $clone_item = clone $this; // "clone" needed for php5 #if( !empty($this->_changed) ) { # include_once('functions/error_functions.php');trigger_error("attempt to clone unsaved / changed material; clone will match the persistent state of this item", E_USER_WARNING); #} $group_list = $this->getGroupList(); $clone_item->setGroupList($group_list); $topic_list = $this->getTopicList(); $clone_item->setTopicList($topic_list); return $clone_item; } /** get full description of date and time * * @author CommSy Development Group */ function getDateDescription() { $converter = $this->_environment->getTextConverter(); $translator = $this->_environment->getTranslationObject(); // description /* $desc = $this->getDescription(); if(!empty($desc)) { $converter->setFileArray($this->getItemFileList()); if ( $this->_with_old_text_formating ) { $desc = $converter->textFullHTMLFormatting($desc); } else { $desc = $converter->textFullHTMLFormatting($desc); } } */ // set up style of days and times // time $parse_time_start = convertTimeFromInput($this->getStartingTime()); $conforms = $parse_time_start['conforms']; if($conforms === true) { $start_time_print = getTimeLanguage($parse_time_start['datetime']); } else { // TODO: compareWithSearchText $start_time_print = $converter->text_as_html_short($this->getStartingTime()); } $parse_time_end = convertTimeFromInput($this->getEndingTime()); $conforms = $parse_time_end['conforms']; if($conforms === true) { $end_time_print = getTimeLanguage($parse_time_end['datetime']); } else { // TODO: compareWithSearchText $end_time_print = $converter->text_as_html_short($this->getEndingTime()); } // day $parse_day_start = convertDateFromInput($this->getStartingDay(), $this->_environment->getSelectedLanguage()); $conforms = $parse_day_start['conforms']; if($conforms === true) { $start_day_print = $this->getStartingDayName() . ', ' . $translator->getDateInLang($parse_day_start['datetime']); } else { // TODO: compareWithSearchText $start_day_print = $converter->text_as_html_short($this->getStartingDay()); } $parse_day_end = convertDateFromInput($this->getEndingDay(), $this->_environment->getSelectedLanguage()); $conforms = $parse_day_end['conforms']; if($conforms === true) { $end_day_print = $this->getEndingDayName() . ', ' . $translator->getDateInLang($parse_day_end['datetime']); } else { // TODO: compareWithSearchText $end_day_print = $converter->text_as_html_short($this->getEndingDay()); } // formate dates and times for displaying $date_print = ''; $time_print = ''; if($end_day_print !== '') { // with ending day $date_print = $translator->getMessage('DATES_AS_OF') . ' ' . $start_day_print . ' ' . $translator->getMessage('DATES_TILL') . ' ' . $end_day_print; if($parse_day_start['conforms'] && $parse_day_end['conforms']) { // start and end are dates, not string <- ??? $date_print .= ' (' . getDifference($parse_day_start['timestamp'], $parse_day_end['timestamp']) . ' ' . $translator->getMessage('DATES_DAYS') . ')'; } if($start_time_print !== '' && $end_time_print === '' && !$this->isWholeDay()) { // only start time given $time_print = $translator->getMessage('DATES_AS_OF_LOWER') . ' ' . $start_time_print; if($parse_time_start['conforms'] === true) { $time_print .= ' ' . $translator->getMessage('DATES_OCLOCK'); } } elseif($start_time_print === '' && $end_time_print !== '' && !$this->isWholeDay()) { // only end time given $time_print = $translator->getMessage('DATES_TILL') . ' ' . $end_time_print; if($parse_time_end['conforms'] === true) { $time_print .= ' ' . $translator->getMessage('DATES_OCLOCK'); } } elseif($start_time_print !== '' && $end_time_print !== '') { // all times given if (!$this->isWholeDay()) { if ($parse_time_end['conforms'] === true) { $end_time_print .= ' ' . $translator->getMessage('DATES_OCLOCK'); } if ($parse_time_start['conforms'] === true) { $start_time_print .= ' ' . $translator->getMessage('DATES_OCLOCK'); } $date_print = $translator->getMessage('DATES_AS_OF') . ' ' . $start_day_print . ', ' . $start_time_print . ' ' . $translator->getMessage('DATES_TILL') . ' ' . $end_day_print . ', ' . $end_time_print; } else { $date_print = $translator->getMessage('DATES_AS_OF') . ' ' . $start_day_print . ' ' . $translator->getMessage('DATES_TILL') . ' ' . $end_day_print; } if($parse_day_start['conforms'] && $parse_day_end['conforms']) { $date_print .= ' (' . getDifference($parse_day_start['timestamp'], $parse_day_end['timestamp']) . ' ' . $translator->getMessage('DATES_DAYS') . ')'; } } } else { // without ending day $date_print = $translator->getMessage('DATES_ON_DAY_UPPER') . ' ' . $start_day_print; if($start_time_print !== '' && $end_time_print == '' && !$this->isWholeDay()) { // starting time given $time_print = $translator->getMessage('DATES_AS_OF_LOWER') . ' ' . $start_time_print; if($parse_time_start['conforms'] === true) { $time_print .= ' ' . $translator->getMessage('DATES_OCLOCK'); } } elseif($start_time_print === '' && $end_time_print !== '' && !$this->isWholeDay()) { // end time given $time_print = $translator->getMessage('DATES_TILL') . ' ' . $end_time_print; if($parse_time_end['conforms'] === true) { $time_print .= ' ' . $translator->getMessage('DATES_OCLOCK'); } } elseif($start_time_print !== '' && $end_time_print !== '' && !$this->isWholeDay()) { // all times given if($parse_time_end['conforms'] === true) { $end_time_print .= ' ' . $translator->getMessage('DATES_OCLOCK'); } if($parse_time_start['conforms'] === true) { $start_time_print .= ' ' . $translator->getMessage('DATES_OCLOCK'); } $time_print = $translator->getMessage('DATES_FROM_TIME_LOWER') . ' ' . $start_time_print . ' ' . $translator->getMessage('DATES_TILL') . ' ' . $end_time_print; } } if($parse_day_start['timestamp'] === $parse_day_end['timestamp'] && $parse_day_start['conforms'] && $parse_day_end['conforms']) { $date_print = $translator->getMessage('DATES_ON_DAY_UPPER') . ' ' . $start_day_print; if (!$this->isWholeDay()) { if ($start_time_print !== '' && $end_time_print === '') { // starting time given $time_print = $translator->getMessage('DATES_AS_OF_LOWER') . ' ' . $start_time_print; } elseif ($start_time_print === '' && $end_time_print !== '') { // endtime given $time_print = $translator->getMessage('DATES_TILL') . ' ' . $end_time_print; } elseif ($start_time_print !== '' && $end_time_print !== '') { // all times given $time_print = $translator->getMessage('DATES_FROM_TIME_LOWER') . ' ' . $start_time_print . ' ' . $translator->getMessage('DATES_TILL') . ' ' . $end_time_print; } } } // date and time $datetime = $date_print; if($time_print !== '') { $datetime .= ' ' . $time_print; } return $datetime; } function getDateListDescription() { $converter = $this->_environment->getTextConverter(); $translator = $this->_environment->getTranslationObject(); // description /* $desc = $this->getDescription(); if(!empty($desc)) { $converter->setFileArray($this->getItemFileList()); if ( $this->_with_old_text_formating ) { $desc = $converter->textFullHTMLFormatting($desc); } else { $desc = $converter->textFullHTMLFormatting($desc); } } */ // set up style of days and times // time $parse_time_start = convertTimeFromInput($this->getStartingTime()); $conforms = $parse_time_start['conforms']; if($conforms === true) { $start_time_print = getTimeLanguage($parse_time_start['datetime']); } else { // TODO: compareWithSearchText $start_time_print = $converter->text_as_html_short($this->getStartingTime()); } $parse_time_end = convertTimeFromInput($this->getEndingTime()); $conforms = $parse_time_end['conforms']; if($conforms === true) { $end_time_print = getTimeLanguage($parse_time_end['datetime']); } else { // TODO: compareWithSearchText $end_time_print = $converter->text_as_html_short($this->getEndingTime()); } // day $parse_day_start = convertDateFromInput($this->getStartingDay(), $this->_environment->getSelectedLanguage()); $conforms = $parse_day_start['conforms']; if($conforms === true) { $start_day_print = $translator->getDateInLang($parse_day_start['datetime']); } else { // TODO: compareWithSearchText $start_day_print = $converter->text_as_html_short($this->getStartingDay()); } $parse_day_end = convertDateFromInput($this->getEndingDay(), $this->_environment->getSelectedLanguage()); $conforms = $parse_day_end['conforms']; if($conforms === true) { $end_day_print = $translator->getDateInLang($parse_day_end['datetime']); } else { // TODO: compareWithSearchText $end_day_print = $converter->text_as_html_short($this->getEndingDay()); } // formate dates and times for displaying $date_print = ''; $time_print = ''; if($end_day_print !== '') { // with ending day $date_print = $start_day_print . ' ' . $translator->getMessage('DATES_TILL') . ' ' . $end_day_print; if($parse_day_start['conforms'] && $parse_day_end['conforms']) { // start and end are dates, not string <- ??? $date_print .= ' (' . getDifference($parse_day_start['timestamp'], $parse_day_end['timestamp']) . ' ' . $translator->getMessage('DATES_DAYS') . ')'; } if($start_time_print !== '' && $end_time_print === '' && !$this->isWholeDay()) { // only start time given $time_print = $start_time_print; if($parse_time_start['conforms'] === true) { $time_print .= ' ' . $translator->getMessage('DATES_OCLOCK'); } } elseif($start_time_print === '' && $end_time_print !== '' && !$this->isWholeDay()) { // only end time given $time_print = $translator->getMessage('DATES_TILL') . ' ' . $end_time_print; if($parse_time_end['conforms'] === true) { $time_print .= ' ' . $translator->getMessage('DATES_OCLOCK'); } } elseif($start_time_print !== '' && $end_time_print !== '') { // all times given if (!$this->isWholeDay()) { if ($parse_time_end['conforms'] === true) { $end_time_print .= ' ' . $translator->getMessage('DATES_OCLOCK'); } if ($parse_time_start['conforms'] === true) { $start_time_print .= ' ' . $translator->getMessage('DATES_OCLOCK'); } $date_print = $start_day_print . ', ' . $start_time_print . ' ' . $translator->getMessage('DATES_TILL') . ' ' . $end_day_print . ', ' . $end_time_print; } else { $date_print = $start_day_print . ' ' . $translator->getMessage('DATES_TILL') . ' ' . $end_day_print; } if($parse_day_start['conforms'] && $parse_day_end['conforms']) { $date_print .= ' (' . getDifference($parse_day_start['timestamp'], $parse_day_end['timestamp']) . ' ' . $translator->getMessage('DATES_DAYS') . ')'; } } } else { // without ending day $date_print = $start_day_print; if($start_time_print !== '' && $end_time_print == '' && !$this->isWholeDay()) { // starting time given $time_print = $start_time_print; if($parse_time_start['conforms'] === true) { $time_print .= ' ' . $translator->getMessage('DATES_OCLOCK'); } } elseif($start_time_print === '' && $end_time_print !== '' && !$this->isWholeDay()) { // end time given $time_print = $translator->getMessage('DATES_TILL') . ' ' . $end_time_print; if($parse_time_end['conforms'] === true) { $time_print .= ' ' . $translator->getMessage('DATES_OCLOCK'); } } elseif($start_time_print !== '' && $end_time_print !== '' && !$this->isWholeDay()) { // all times given if($parse_time_end['conforms'] === true) { $end_time_print .= ' ' . $translator->getMessage('DATES_OCLOCK'); } if($parse_time_start['conforms'] === true) { $start_time_print .= ' ' . $translator->getMessage('DATES_OCLOCK'); } if ($start_time_print === $end_time_print) { $time_print = $translator->getMessage('DATES_AT_TIME') . ' ' . $start_time_print; } else { $time_print = $translator->getMessage('DATES_FROM_TIME_LOWER') . ' ' . $start_time_print . ' ' . $translator->getMessage('DATES_TILL') . ' ' . $end_time_print; } } } if($parse_day_start['timestamp'] === $parse_day_end['timestamp'] && $parse_day_start['conforms'] && $parse_day_end['conforms']) { $date_print = $translator->getMessage('DATES_ON_DAY_UPPER') . ' ' . $start_day_print; if (!$this->isWholeDay()) { if ($start_time_print !== '' && $end_time_print === '') { // starting time given $time_print = $start_time_print; } elseif ($start_time_print === '' && $end_time_print !== '') { // endtime given $time_print = $translator->getMessage('DATES_TILL') . ' ' . $end_time_print; } elseif ($start_time_print !== '' && $end_time_print !== '') { // all times given if ($start_time_print === $end_time_print) { $time_print = $translator->getMessage('DATES_AT_TIME') . ' ' . $start_time_print; } else { $time_print = $translator->getMessage('DATES_FROM_TIME_LOWER') . ' ' . $start_time_print . ' ' . $translator->getMessage('DATES_TILL') . ' ' . $end_time_print; } } } } // date and time $datetime = $date_print; if($time_print !== '') { $datetime .= ' ' . $time_print; } return trim($datetime); } /** asks if item is a date in an external calendar * * @param value * * @author CommSy Development Group */ function isExternal() { if ($this->_getValue('external')== 1) { return true; } else { return false; } } /** sets if item is a date in an external calendar * * @param value * * @author CommSy Development Group */ function setExternal ($value) { $this->_setValue('external', $value); } function getUid() { return $this->_getValue('uid'); } function setUid ($value) { $this->_setValue('uid', $value); } /** asks if item is a date is a whole day date. * * @param value * * @author CommSy Development Group */ function isWholeDay() { if ($this->_getValue('whole_day')== 1) { return true; } else { return false; } } /** sets if item is a whole day date * * @param value * * @author CommSy Development Group */ function setWholeDay ($value) { $this->_setValue('whole_day', $value); } function getDateTime_recurrence() { return $this->_getValue('datetime_recurrence'); } function setDateTime_recurrence ($value) { $this->_setValue('datetime_recurrence', $value); } } ?>
commsy/commsy
legacy/classes/cs_dates_item.php
PHP
gpl-2.0
33,248
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html lang="en"> <head> <meta name="generator" content="AWStats 7.0 (build 1.971) from config file awstats.manager.crimea.edu.conf (http://awstats.sourceforge.net)"> <meta name="robots" content="noindex,nofollow"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="description" content="Awstats - Advanced Web Statistics for manager.crimea.edu (2012-08) - alldomains"> <title>Statistics for manager.crimea.edu (2012-08) - alldomains</title> <style type="text/css"> <!-- body { font: 11px verdana, arial, helvetica, sans-serif; background-color: #FFFFFF; margin-top: 0; margin-bottom: 0; } .aws_bodyl { } .aws_border { border-collapse: collapse; background-color: #CCCCDD; padding: 1px 1px 1px 1px; margin-top: 0px; margin-bottom: 0px; } .aws_title { font: 13px verdana, arial, helvetica, sans-serif; font-weight: bold; background-color: #CCCCDD; text-align: center; margin-top: 0; margin-bottom: 0; padding: 1px 1px 1px 1px; color: #000000; } .aws_blank { font: 13px verdana, arial, helvetica, sans-serif; background-color: #FFFFFF; text-align: center; margin-bottom: 0; padding: 1px 1px 1px 1px; } .aws_data { background-color: #FFFFFF; border-top-width: 1px; border-left-width: 0px; border-right-width: 0px; border-bottom-width: 0px; } .aws_formfield { font: 13px verdana, arial, helvetica; } .aws_button { font-family: arial,verdana,helvetica, sans-serif; font-size: 12px; border: 1px solid #ccd7e0; background-image : url(/awstatsicons/other/button.gif); } th { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; padding: 1px 2px 1px 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:center; color: #000000; } th.aws { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; padding: 1px 2px 1px 1px; font-size: 13px; font-weight: bold; } td { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:center; color: #000000; } td.aws { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:left; color: #000000; padding: 0px;} td.awsm { border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; font: 11px verdana, arial, helvetica, sans-serif; text-align:left; color: #000000; padding: 0px; } b { font-weight: bold; } a { font: 11px verdana, arial, helvetica, sans-serif; } a:link { color: #0011BB; text-decoration: none; } a:visited { color: #0011BB; text-decoration: none; } a:hover { color: #605040; text-decoration: underline; } .currentday { font-weight: bold; } //--> </style> </head> <body style="margin-top: 0px"> <a name="top"></a> <a name="menu">&nbsp;</a> <form name="FormDateFilter" action="/cgi-bin/awstats.pl?config=manager.crimea.edu&amp;output=alldomains" style="padding: 0px 0px 0px 0px; margin-top: 0"> <table class="aws_border" border="0" cellpadding="2" cellspacing="0" width="100%"> <tr><td> <table class="aws_data sortable" border="0" cellpadding="1" cellspacing="0" width="100%"> <tr><td class="aws" valign="middle"><b>Statistics for:</b>&nbsp;</td><td class="aws" valign="middle"><span style="font-size: 14px;">manager.crimea.edu</span></td><td align="right" rowspan="3"><a href="http://awstats.sourceforge.net" target="awstatshome"><img src="/awstatsicons/other/awstats_logo6.png" border="0" alt='Awstats Web Site' title='Awstats Web Site' /></a></td></tr> <tr valign="middle"><td class="aws" valign="middle" width="150"><b>Last Update:</b>&nbsp;</td><td class="aws" valign="middle"><span style="font-size: 12px;">29 Sep 2012 - 00:02</span></td></tr> <tr><td class="aws" valign="middle"><b>Reported period:</b></td><td class="aws" valign="middle"><span style="font-size: 14px;">Month Aug 2012</span></td></tr> </table> </td></tr></table> </form> <table> <tr><td class="aws"><a href="javascript:parent.window.close();">Close window</a></td></tr> </table> <a name="domains">&nbsp;</a><br /> <table class="aws_border sortable" border="0" cellpadding="2" cellspacing="0" width="100%"> <tr><td class="aws_title" width="70%">Visitors domains/countries </td><td class="aws_blank">&nbsp;</td></tr> <tr><td colspan="2"> <table class="aws_data" border="1" cellpadding="2" cellspacing="0" width="100%"> <tr bgcolor="#ECECEC"><th width="32">&nbsp;</th><th colspan="2">Domains/Countries</th><th bgcolor="#4477DD" width="80">Pages</th><th bgcolor="#66DDEE" width="80">Hits</th><th class="datasize" bgcolor="#2EA495" width="80">Bandwidth</th><th>&nbsp;</th></tr> </table></td></tr></table><br /> <br /><br /> <span dir="ltr" style="font: 11px verdana, arial, helvetica; color: #000000;"><b>Advanced Web Statistics 7.0 (build 1.971)</b> - <a href="http://awstats.sourceforge.net" target="awstatshome">Created by awstats</a></span><br /> <br /> </body> </html>
mng-crimea/mng-crimea
webstat/awstats.manager.crimea.edu.alldomains.082012.html
HTML
gpl-2.0
5,150
using System; using System.Collections.Generic; using ServiceStack.OrmLite; using ServiceStack.DataAnnotations; namespace PhotoBookmart.DataLayer.Models.Sites { [Alias("TopicLanguage")] [Schema("CMS")] public partial class SiteTopicLanguage : ModelBase { public SiteTopicLanguage() { IsDeleted = false; } [PrimaryKey] [AutoIncrement] public long Id { get; set; } //[Default(0)] //public int SiteId { get; set; } [Default(0)] [ForeignKey(typeof(SiteTopic), OnDelete = "CASCADE", OnUpdate = "CASCADE")] public long TopicId { get; set; } [Default(0)] public long LanguageId { get; set; } [Default(typeof(string), "")] public string LanguageCode { get; set; } public bool IsDefault { get; set; } [Default(typeof(string), "")] public string Title { get; set; } [Default(typeof(string), "")] public string Body { get; set; } [Default(typeof(string), "")] public string MetaKeywords { get; set; } [Default(typeof(string), "")] public string MetaDescription { get; set; } [Default(typeof(string), "")] public string MetaTitle { get; set; } [Default(0)] public int LayoutType { get; set; } [Default(typeof(string), "")] public string MoreLink { get; set; } /// <summary> /// Use this field only in Edit form to let the controller know you want to delete this translation /// </summary> [Ignore] public bool IsDeleted { get; set; } } }
dvchinh/HTQLNHCS
DataModel/Models/Sites/TopicLanguage.cs
C#
gpl-2.0
1,660
/*************************************************************************** qgsgpxfeatureiterator.cpp --------------------- begin : Dezember 2012 copyright : (C) 2012 by Martin Dobias email : wonder dot sk at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgsgpxfeatureiterator.h" #include "qgsgpxprovider.h" #include "qgsapplication.h" #include "qgsgeometry.h" #include "qgslogger.h" #include "qgsmessagelog.h" #include <limits> #include <cstring> QgsGPXFeatureIterator::QgsGPXFeatureIterator( QgsGPXFeatureSource *source, bool ownSource, const QgsFeatureRequest &request ) : QgsAbstractFeatureIteratorFromSource<QgsGPXFeatureSource>( source, ownSource, request ) { rewind(); } QgsGPXFeatureIterator::~QgsGPXFeatureIterator() { close(); } bool QgsGPXFeatureIterator::rewind() { if ( mClosed ) return false; if ( mRequest.filterType() == QgsFeatureRequest::FilterFid ) { mFetchedFid = false; } else { if ( mSource->mFeatureType == QgsGPXProvider::WaypointType ) mWptIter = mSource->data->waypointsBegin(); else if ( mSource->mFeatureType == QgsGPXProvider::RouteType ) mRteIter = mSource->data->routesBegin(); else if ( mSource->mFeatureType == QgsGPXProvider::TrackType ) mTrkIter = mSource->data->tracksBegin(); } return true; } bool QgsGPXFeatureIterator::close() { if ( mClosed ) return false; iteratorClosed(); mClosed = true; return true; } bool QgsGPXFeatureIterator::fetchFeature( QgsFeature &feature ) { feature.setValid( false ); if ( mClosed ) return false; if ( mRequest.filterType() == QgsFeatureRequest::FilterFid ) { bool res = readFid( feature ); close(); return res; } if ( mSource->mFeatureType == QgsGPXProvider::WaypointType ) { // go through the list of waypoints and return the first one that is in // the bounds rectangle for ( ; mWptIter != mSource->data->waypointsEnd(); ++mWptIter ) { if ( readWaypoint( *mWptIter, feature ) ) { ++mWptIter; return true; } } } else if ( mSource->mFeatureType == QgsGPXProvider::RouteType ) { // go through the routes and return the first one that is in the bounds // rectangle for ( ; mRteIter != mSource->data->routesEnd(); ++mRteIter ) { if ( readRoute( *mRteIter, feature ) ) { ++mRteIter; return true; } } } else if ( mSource->mFeatureType == QgsGPXProvider::TrackType ) { // go through the tracks and return the first one that is in the bounds // rectangle for ( ; mTrkIter != mSource->data->tracksEnd(); ++mTrkIter ) { if ( readTrack( *mTrkIter, feature ) ) { ++mTrkIter; return true; } } } close(); return false; } bool QgsGPXFeatureIterator::readFid( QgsFeature &feature ) { if ( mFetchedFid ) return false; mFetchedFid = true; QgsFeatureId fid = mRequest.filterFid(); if ( mSource->mFeatureType == QgsGPXProvider::WaypointType ) { for ( QgsGPSData::WaypointIterator it = mSource->data->waypointsBegin() ; it != mSource->data->waypointsEnd(); ++it ) { if ( it->id == fid ) { readWaypoint( *it, feature ); return true; } } } else if ( mSource->mFeatureType == QgsGPXProvider::RouteType ) { for ( QgsGPSData::RouteIterator it = mSource->data->routesBegin() ; it != mSource->data->routesEnd(); ++it ) { if ( it->id == fid ) { readRoute( *it, feature ); return true; } } } else if ( mSource->mFeatureType == QgsGPXProvider::TrackType ) { for ( QgsGPSData::TrackIterator it = mSource->data->tracksBegin() ; it != mSource->data->tracksEnd(); ++it ) { if ( it->id == fid ) { readTrack( *it, feature ); return true; } } } return false; } bool QgsGPXFeatureIterator::readWaypoint( const QgsWaypoint &wpt, QgsFeature &feature ) { if ( !mRequest.filterRect().isNull() ) { const QgsRectangle &rect = mRequest.filterRect(); if ( ! rect.contains( QgsPoint( wpt.lon, wpt.lat ) ) ) return false; } // some wkb voodoo if ( !( mRequest.flags() & QgsFeatureRequest::NoGeometry ) ) { QgsGeometry *g = readWaypointGeometry( wpt ); feature.setGeometry( *g ); delete g; } feature.setId( wpt.id ); feature.setValid( true ); feature.setFields( mSource->mFields ); // allow name-based attribute lookups feature.initAttributes( mSource->mFields.count() ); readAttributes( feature, wpt ); return true; } bool QgsGPXFeatureIterator::readRoute( const QgsRoute &rte, QgsFeature &feature ) { if ( rte.points.isEmpty() ) return false; QgsGeometry *geometry = readRouteGeometry( rte ); if ( !mRequest.filterRect().isNull() ) { const QgsRectangle &rect = mRequest.filterRect(); if ( ( rte.xMax < rect.xMinimum() ) || ( rte.xMin > rect.xMaximum() ) || ( rte.yMax < rect.yMinimum() ) || ( rte.yMin > rect.yMaximum() ) ) { delete geometry; return false; } if ( !geometry->intersects( rect ) ) //use geos for precise intersection test { delete geometry; return false; } } if ( !( mRequest.flags() & QgsFeatureRequest::NoGeometry ) ) { feature.setGeometry( *geometry ); delete geometry; } else { delete geometry; } feature.setId( rte.id ); feature.setValid( true ); feature.setFields( mSource->mFields ); // allow name-based attribute lookups feature.initAttributes( mSource->mFields.count() ); readAttributes( feature, rte ); return true; } bool QgsGPXFeatureIterator::readTrack( const QgsTrack &trk, QgsFeature &feature ) { //QgsDebugMsg( QString( "GPX feature track segments: %1" ).arg( trk.segments.size() ) ); QgsGeometry *geometry = readTrackGeometry( trk ); if ( !mRequest.filterRect().isNull() ) { const QgsRectangle &rect = mRequest.filterRect(); if ( ( trk.xMax < rect.xMinimum() ) || ( trk.xMin > rect.xMaximum() ) || ( trk.yMax < rect.yMinimum() ) || ( trk.yMin > rect.yMaximum() ) ) { delete geometry; return false; } if ( !geometry->intersects( rect ) ) //use geos for precise intersection test { delete geometry; return false; } } if ( !( mRequest.flags() & QgsFeatureRequest::NoGeometry ) ) { feature.setGeometry( *geometry ); delete geometry; } else { delete geometry; } feature.setId( trk.id ); feature.setValid( true ); feature.setFields( mSource->mFields ); // allow name-based attribute lookups feature.initAttributes( mSource->mFields.count() ); readAttributes( feature, trk ); return true; } void QgsGPXFeatureIterator::readAttributes( QgsFeature &feature, const QgsWaypoint &wpt ) { // add attributes if they are wanted for ( int i = 0; i < mSource->mFields.count(); ++i ) { switch ( mSource->indexToAttr.at( i ) ) { case QgsGPXProvider::NameAttr: feature.setAttribute( i, QVariant( wpt.name ) ); break; case QgsGPXProvider::EleAttr: if ( wpt.ele != -std::numeric_limits<double>::max() ) feature.setAttribute( i, QVariant( wpt.ele ) ); break; case QgsGPXProvider::SymAttr: feature.setAttribute( i, QVariant( wpt.sym ) ); break; case QgsGPXProvider::CmtAttr: feature.setAttribute( i, QVariant( wpt.cmt ) ); break; case QgsGPXProvider::DscAttr: feature.setAttribute( i, QVariant( wpt.desc ) ); break; case QgsGPXProvider::SrcAttr: feature.setAttribute( i, QVariant( wpt.src ) ); break; case QgsGPXProvider::URLAttr: feature.setAttribute( i, QVariant( wpt.url ) ); break; case QgsGPXProvider::URLNameAttr: feature.setAttribute( i, QVariant( wpt.urlname ) ); break; } } } void QgsGPXFeatureIterator::readAttributes( QgsFeature &feature, const QgsRoute &rte ) { // add attributes if they are wanted for ( int i = 0; i < mSource->mFields.count(); ++i ) { switch ( mSource->indexToAttr.at( i ) ) { case QgsGPXProvider::NameAttr: feature.setAttribute( i, QVariant( rte.name ) ); break; case QgsGPXProvider::NumAttr: if ( rte.number != std::numeric_limits<int>::max() ) feature.setAttribute( i, QVariant( rte.number ) ); break; case QgsGPXProvider::CmtAttr: feature.setAttribute( i, QVariant( rte.cmt ) ); break; case QgsGPXProvider::DscAttr: feature.setAttribute( i, QVariant( rte.desc ) ); break; case QgsGPXProvider::SrcAttr: feature.setAttribute( i, QVariant( rte.src ) ); break; case QgsGPXProvider::URLAttr: feature.setAttribute( i, QVariant( rte.url ) ); break; case QgsGPXProvider::URLNameAttr: feature.setAttribute( i, QVariant( rte.urlname ) ); break; } } } void QgsGPXFeatureIterator::readAttributes( QgsFeature &feature, const QgsTrack &trk ) { // add attributes if they are wanted for ( int i = 0; i < mSource->mFields.count(); ++i ) { switch ( mSource->indexToAttr.at( i ) ) { case QgsGPXProvider::NameAttr: feature.setAttribute( i, QVariant( trk.name ) ); break; case QgsGPXProvider::NumAttr: if ( trk.number != std::numeric_limits<int>::max() ) feature.setAttribute( i, QVariant( trk.number ) ); break; case QgsGPXProvider::CmtAttr: feature.setAttribute( i, QVariant( trk.cmt ) ); break; case QgsGPXProvider::DscAttr: feature.setAttribute( i, QVariant( trk.desc ) ); break; case QgsGPXProvider::SrcAttr: feature.setAttribute( i, QVariant( trk.src ) ); break; case QgsGPXProvider::URLAttr: feature.setAttribute( i, QVariant( trk.url ) ); break; case QgsGPXProvider::URLNameAttr: feature.setAttribute( i, QVariant( trk.urlname ) ); break; } } } QgsGeometry *QgsGPXFeatureIterator::readWaypointGeometry( const QgsWaypoint &wpt ) { int size = 1 + sizeof( int ) + 2 * sizeof( double ); unsigned char *geo = new unsigned char[size]; QgsWkbPtr wkbPtr( geo, size ); wkbPtr << ( char ) QgsApplication::endian() << QgsWkbTypes::Point << wpt.lon << wpt.lat; QgsGeometry *g = new QgsGeometry(); g->fromWkb( geo, size ); return g; } QgsGeometry *QgsGPXFeatureIterator::readRouteGeometry( const QgsRoute &rte ) { // some wkb voodoo int size = 1 + 2 * sizeof( int ) + 2 * sizeof( double ) * rte.points.size(); unsigned char *geo = new unsigned char[size]; QgsWkbPtr wkbPtr( geo, size ); wkbPtr << ( char ) QgsApplication::endian() << QgsWkbTypes::LineString << rte.points.size(); for ( int i = 0; i < rte.points.size(); ++i ) { wkbPtr << rte.points[i].lon << rte.points[i].lat; } //create QgsGeometry and use it for intersection test //if geometry is to be fetched, it is attached to the feature, otherwise we delete it QgsGeometry *g = new QgsGeometry(); g->fromWkb( geo, size ); return g; } QgsGeometry *QgsGPXFeatureIterator::readTrackGeometry( const QgsTrack &trk ) { // TODO: support multi line string for segments if ( trk.segments.isEmpty() ) return nullptr; // A track consists of several segments. Add all those segments into one. int totalPoints = 0; for ( int i = 0; i < trk.segments.size(); i ++ ) { totalPoints += trk.segments[i].points.size(); } if ( totalPoints == 0 ) return nullptr; //QgsDebugMsg( "GPX feature track total points: " + QString::number( totalPoints ) ); // some wkb voodoo int size = 1 + 2 * sizeof( int ) + 2 * sizeof( double ) * totalPoints; unsigned char *geo = new unsigned char[size]; if ( !geo ) { QgsDebugMsg( "Track too large!" ); return nullptr; } QgsWkbPtr wkbPtr( geo, size ); wkbPtr << ( char ) QgsApplication::endian() << QgsWkbTypes::LineString << totalPoints; for ( int k = 0; k < trk.segments.size(); k++ ) { int nPoints = trk.segments[k].points.size(); for ( int i = 0; i < nPoints; ++i ) { wkbPtr << trk.segments[k].points[i].lon << trk.segments[k].points[i].lat; } } //create QgsGeometry and use it for intersection test //if geometry is to be fetched, it is attached to the feature, otherwise we delete it QgsGeometry *g = new QgsGeometry(); g->fromWkb( geo, size ); return g; } // ------------ QgsGPXFeatureSource::QgsGPXFeatureSource( const QgsGPXProvider *p ) : mFileName( p->mFileName ) , mFeatureType( p->mFeatureType ) , indexToAttr( p->indexToAttr ) , mFields( p->attributeFields ) { data = QgsGPSData::getData( mFileName ); } QgsGPXFeatureSource::~QgsGPXFeatureSource() { QgsGPSData::releaseData( mFileName ); } QgsFeatureIterator QgsGPXFeatureSource::getFeatures( const QgsFeatureRequest &request ) { return QgsFeatureIterator( new QgsGPXFeatureIterator( this, false, request ) ); }
gioman/QGIS
src/providers/gpx/qgsgpxfeatureiterator.cpp
C++
gpl-2.0
13,657
<?php /* * This file is part of the LightCMSBundle package. * * (c) Fulgurio <http://fulgurio.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Fulgurio\LightCMSBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; /** * Controller displaying dashboard */ class AdminDashboardController extends Controller { /** * Dashboard */ public function indexAction() { return $this->render('FulgurioLightCMSBundle::adminBase.html.twig'); } }
fulgurio/LightCMSBundle
Controller/AdminDashboardController.php
PHP
gpl-2.0
595
¾g@U<?php exit; ?>a:1:{s:7:"content";a:12:{s:10:"_edit_last";a:1:{i:0;s:1:"1";}s:17:"_wp_page_template";a:1:{i:0;s:25:"template-subscription.php";}s:14:"slide_template";a:1:{i:0;s:7:"default";}s:17:"pp_sidebar_layout";a:1:{i:0;s:10:"full-width";}s:17:"pp_filters_switch";a:1:{i:0;s:3:"yes";}s:17:"pp_title_bar_hide";a:1:{i:0;s:2:"on";}s:13:"pp_page_layer";a:1:{i:0;s:11:"home_slider";}s:10:"_edit_lock";a:1:{i:0;s:12:"1422820310:1";}s:14:"pp_parallax_bg";a:1:{i:0;s:75:"http://localhost/Cerveza-Postal/wp-content/uploads/2014/11/plans-banner.jpg";}s:17:"pp_parallax_color";a:1:{i:0;s:7:"#000000";}s:19:"pp_parallax_opacity";a:1:{i:0;s:3:"0.5";}s:11:"pp_subtitle";a:1:{i:0;s:44:"Selecciona un paquete y consiente tu paladar";}}}
betoarpi/Cerveza-Postal
wp-content/cache/object/000000/91d/400/91d400cddb20d5663aaf5790dcedde69.php
PHP
gpl-2.0
727
// Copyright 2008 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include <cinttypes> #include <cstring> #include "Common/CPUDetect.h" #include "Common/CommonTypes.h" #include "Common/Logging/Log.h" #include "Common/x64Emitter.h" #include "Common/x64Reg.h" namespace Gen { struct NormalOpDef { u8 toRm8, toRm32, fromRm8, fromRm32, imm8, imm32, simm8, eaximm8, eaximm32, ext; }; // 0xCC is code for invalid combination of immediates static const NormalOpDef normalops[11] = { {0x00, 0x01, 0x02, 0x03, 0x80, 0x81, 0x83, 0x04, 0x05, 0}, // ADD {0x10, 0x11, 0x12, 0x13, 0x80, 0x81, 0x83, 0x14, 0x15, 2}, // ADC {0x28, 0x29, 0x2A, 0x2B, 0x80, 0x81, 0x83, 0x2C, 0x2D, 5}, // SUB {0x18, 0x19, 0x1A, 0x1B, 0x80, 0x81, 0x83, 0x1C, 0x1D, 3}, // SBB {0x20, 0x21, 0x22, 0x23, 0x80, 0x81, 0x83, 0x24, 0x25, 4}, // AND {0x08, 0x09, 0x0A, 0x0B, 0x80, 0x81, 0x83, 0x0C, 0x0D, 1}, // OR {0x30, 0x31, 0x32, 0x33, 0x80, 0x81, 0x83, 0x34, 0x35, 6}, // XOR {0x88, 0x89, 0x8A, 0x8B, 0xC6, 0xC7, 0xCC, 0xCC, 0xCC, 0}, // MOV {0x84, 0x85, 0x84, 0x85, 0xF6, 0xF7, 0xCC, 0xA8, 0xA9, 0}, // TEST (to == from) {0x38, 0x39, 0x3A, 0x3B, 0x80, 0x81, 0x83, 0x3C, 0x3D, 7}, // CMP {0x86, 0x87, 0x86, 0x87, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 7}, // XCHG }; enum NormalSSEOps { sseCMP = 0xC2, sseADD = 0x58, // ADD sseSUB = 0x5C, // SUB sseAND = 0x54, // AND sseANDN = 0x55, // ANDN sseOR = 0x56, sseXOR = 0x57, sseMUL = 0x59, // MUL sseDIV = 0x5E, // DIV sseMIN = 0x5D, // MIN sseMAX = 0x5F, // MAX sseCOMIS = 0x2F, // COMIS sseUCOMIS = 0x2E, // UCOMIS sseSQRT = 0x51, // SQRT sseRCP = 0x53, // RCP sseRSQRT = 0x52, // RSQRT (NO DOUBLE PRECISION!!!) sseMOVAPfromRM = 0x28, // MOVAP from RM sseMOVAPtoRM = 0x29, // MOVAP to RM sseMOVUPfromRM = 0x10, // MOVUP from RM sseMOVUPtoRM = 0x11, // MOVUP to RM sseMOVLPfromRM = 0x12, sseMOVLPtoRM = 0x13, sseMOVHPfromRM = 0x16, sseMOVHPtoRM = 0x17, sseMOVHLPS = 0x12, sseMOVLHPS = 0x16, sseMOVDQfromRM = 0x6F, sseMOVDQtoRM = 0x7F, sseMASKMOVDQU = 0xF7, sseLDDQU = 0xF0, sseSHUF = 0xC6, sseMOVNTDQ = 0xE7, sseMOVNTP = 0x2B, }; enum class NormalOp { ADD, ADC, SUB, SBB, AND, OR, XOR, MOV, TEST, CMP, XCHG, }; enum class FloatOp { LD = 0, ST = 2, STP = 3, LD80 = 5, STP80 = 7, Invalid = -1, }; void XEmitter::SetCodePtr(u8* ptr, u8* end, bool write_failed) { code = ptr; m_code_end = end; m_write_failed = write_failed; } const u8* XEmitter::GetCodePtr() const { return code; } u8* XEmitter::GetWritableCodePtr() { return code; } const u8* XEmitter::GetCodeEnd() const { return m_code_end; } u8* XEmitter::GetWritableCodeEnd() { return m_code_end; } void XEmitter::Write8(u8 value) { if (code >= m_code_end) { code = m_code_end; m_write_failed = true; return; } *code++ = value; } void XEmitter::Write16(u16 value) { if (code + sizeof(u16) > m_code_end) { code = m_code_end; m_write_failed = true; return; } std::memcpy(code, &value, sizeof(u16)); code += sizeof(u16); } void XEmitter::Write32(u32 value) { if (code + sizeof(u32) > m_code_end) { code = m_code_end; m_write_failed = true; return; } std::memcpy(code, &value, sizeof(u32)); code += sizeof(u32); } void XEmitter::Write64(u64 value) { if (code + sizeof(u64) > m_code_end) { code = m_code_end; m_write_failed = true; return; } std::memcpy(code, &value, sizeof(u64)); code += sizeof(u64); } void XEmitter::ReserveCodeSpace(int bytes) { if (code + bytes > m_code_end) { code = m_code_end; m_write_failed = true; return; } for (int i = 0; i < bytes; i++) *code++ = 0xCC; } u8* XEmitter::AlignCodeTo(size_t alignment) { ASSERT_MSG(DYNA_REC, alignment != 0 && (alignment & (alignment - 1)) == 0, "Alignment must be power of two"); u64 c = reinterpret_cast<u64>(code) & (alignment - 1); if (c) ReserveCodeSpace(static_cast<int>(alignment - c)); return code; } u8* XEmitter::AlignCode4() { return AlignCodeTo(4); } u8* XEmitter::AlignCode16() { return AlignCodeTo(16); } u8* XEmitter::AlignCodePage() { return AlignCodeTo(4096); } // This operation modifies flags; check to see the flags are locked. // If the flags are locked, we should immediately and loudly fail before // causing a subtle JIT bug. void XEmitter::CheckFlags() { ASSERT_MSG(DYNA_REC, !flags_locked, "Attempt to modify flags while flags locked!"); } void XEmitter::WriteModRM(int mod, int reg, int rm) { Write8((u8)((mod << 6) | ((reg & 7) << 3) | (rm & 7))); } void XEmitter::WriteSIB(int scale, int index, int base) { Write8((u8)((scale << 6) | ((index & 7) << 3) | (base & 7))); } void OpArg::WriteREX(XEmitter* emit, int opBits, int bits, int customOp) const { if (customOp == -1) customOp = operandReg; u8 op = 0x40; // REX.W (whether operation is a 64-bit operation) if (opBits == 64) op |= 8; // REX.R (whether ModR/M reg field refers to R8-R15. if (customOp & 8) op |= 4; // REX.X (whether ModR/M SIB index field refers to R8-R15) if (indexReg & 8) op |= 2; // REX.B (whether ModR/M rm or SIB base or opcode reg field refers to R8-R15) if (offsetOrBaseReg & 8) op |= 1; // Write REX if wr have REX bits to write, or if the operation accesses // SIL, DIL, BPL, or SPL. if (op != 0x40 || (scale == SCALE_NONE && bits == 8 && (offsetOrBaseReg & 0x10c) == 4) || (opBits == 8 && (customOp & 0x10c) == 4)) { emit->Write8(op); // Check the operation doesn't access AH, BH, CH, or DH. DEBUG_ASSERT((offsetOrBaseReg & 0x100) == 0); DEBUG_ASSERT((customOp & 0x100) == 0); } } void OpArg::WriteVEX(XEmitter* emit, X64Reg regOp1, X64Reg regOp2, int L, int pp, int mmmmm, int W) const { int R = !(regOp1 & 8); int X = !(indexReg & 8); int B = !(offsetOrBaseReg & 8); int vvvv = (regOp2 == X64Reg::INVALID_REG) ? 0xf : (regOp2 ^ 0xf); // do we need any VEX fields that only appear in the three-byte form? if (X == 1 && B == 1 && W == 0 && mmmmm == 1) { u8 RvvvvLpp = (R << 7) | (vvvv << 3) | (L << 2) | pp; emit->Write8(0xC5); emit->Write8(RvvvvLpp); } else { u8 RXBmmmmm = (R << 7) | (X << 6) | (B << 5) | mmmmm; u8 WvvvvLpp = (W << 7) | (vvvv << 3) | (L << 2) | pp; emit->Write8(0xC4); emit->Write8(RXBmmmmm); emit->Write8(WvvvvLpp); } } void OpArg::WriteRest(XEmitter* emit, int extraBytes, X64Reg _operandReg, bool warn_64bit_offset) const { if (_operandReg == INVALID_REG) _operandReg = (X64Reg)this->operandReg; int mod = 0; int ireg = indexReg; bool SIB = false; int _offsetOrBaseReg = this->offsetOrBaseReg; if (scale == SCALE_RIP) // Also, on 32-bit, just an immediate address { // Oh, RIP addressing. _offsetOrBaseReg = 5; emit->WriteModRM(0, _operandReg, _offsetOrBaseReg); // TODO : add some checks u64 ripAddr = (u64)emit->GetCodePtr() + 4 + extraBytes; s64 distance = (s64)offset - (s64)ripAddr; ASSERT_MSG(DYNA_REC, (distance < 0x80000000LL && distance >= -0x80000000LL) || !warn_64bit_offset, "WriteRest: op out of range (0x%" PRIx64 " uses 0x%" PRIx64 ")", ripAddr, offset); s32 offs = (s32)distance; emit->Write32((u32)offs); return; } if (scale == SCALE_NONE) { // Oh, no memory, Just a reg. mod = 3; // 11 } else if (scale >= SCALE_NOBASE_2 && scale <= SCALE_NOBASE_8) { SIB = true; mod = 0; _offsetOrBaseReg = 5; // Always has 32-bit displacement } else { if (scale != SCALE_ATREG) { SIB = true; } else if ((_offsetOrBaseReg & 7) == 4) { // Special case for which SCALE_ATREG needs SIB SIB = true; ireg = _offsetOrBaseReg; } // Okay, we're fine. Just disp encoding. // We need displacement. Which size? int ioff = (int)(s64)offset; if (ioff == 0 && (_offsetOrBaseReg & 7) != 5) { mod = 0; // No displacement } else if (ioff >= -128 && ioff <= 127) { mod = 1; // 8-bit displacement } else { mod = 2; // 32-bit displacement } } // Okay. Time to do the actual writing // ModRM byte: int oreg = _offsetOrBaseReg; if (SIB) oreg = 4; emit->WriteModRM(mod, _operandReg & 7, oreg & 7); if (SIB) { // SIB byte int ss; switch (scale) { case SCALE_NONE: _offsetOrBaseReg = 4; ss = 0; break; // RSP case SCALE_1: ss = 0; break; case SCALE_2: ss = 1; break; case SCALE_4: ss = 2; break; case SCALE_8: ss = 3; break; case SCALE_NOBASE_2: ss = 1; break; case SCALE_NOBASE_4: ss = 2; break; case SCALE_NOBASE_8: ss = 3; break; case SCALE_ATREG: ss = 0; break; default: ASSERT_MSG(DYNA_REC, 0, "Invalid scale for SIB byte"); ss = 0; break; } emit->Write8((u8)((ss << 6) | ((ireg & 7) << 3) | (_offsetOrBaseReg & 7))); } if (mod == 1) // 8-bit disp { emit->Write8((u8)(s8)(s32)offset); } else if (mod == 2 || (scale >= SCALE_NOBASE_2 && scale <= SCALE_NOBASE_8)) // 32-bit disp { emit->Write32((u32)offset); } } // W = operand extended width (1 if 64-bit) // R = register# upper bit // X = scale amnt upper bit // B = base register# upper bit void XEmitter::Rex(int w, int r, int x, int b) { w = w ? 1 : 0; r = r ? 1 : 0; x = x ? 1 : 0; b = b ? 1 : 0; u8 rx = (u8)(0x40 | (w << 3) | (r << 2) | (x << 1) | (b)); if (rx != 0x40) Write8(rx); } void XEmitter::JMP(const u8* addr, bool force5Bytes) { u64 fn = (u64)addr; if (!force5Bytes) { s64 distance = (s64)(fn - ((u64)code + 2)); ASSERT_MSG(DYNA_REC, distance >= -0x80 && distance < 0x80, "Jump target too far away, needs force5Bytes = true"); // 8 bits will do Write8(0xEB); Write8((u8)(s8)distance); } else { s64 distance = (s64)(fn - ((u64)code + 5)); ASSERT_MSG(DYNA_REC, distance >= -0x80000000LL && distance < 0x80000000LL, "Jump target too far away, needs indirect register"); Write8(0xE9); Write32((u32)(s32)distance); } } void XEmitter::JMPptr(const OpArg& arg2) { OpArg arg = arg2; if (arg.IsImm()) ASSERT_MSG(DYNA_REC, 0, "JMPptr - Imm argument"); arg.operandReg = 4; arg.WriteREX(this, 0, 0); Write8(0xFF); arg.WriteRest(this); } // Can be used to trap other processors, before overwriting their code // not used in Dolphin void XEmitter::JMPself() { Write8(0xEB); Write8(0xFE); } void XEmitter::CALLptr(OpArg arg) { if (arg.IsImm()) ASSERT_MSG(DYNA_REC, 0, "CALLptr - Imm argument"); arg.operandReg = 2; arg.WriteREX(this, 0, 0); Write8(0xFF); arg.WriteRest(this); } void XEmitter::CALL(const void* fnptr) { u64 distance = u64(fnptr) - (u64(code) + 5); ASSERT_MSG(DYNA_REC, distance < 0x0000000080000000ULL || distance >= 0xFFFFFFFF80000000ULL, "CALL out of range (%p calls %p)", code, fnptr); Write8(0xE8); Write32(u32(distance)); } FixupBranch XEmitter::CALL() { FixupBranch branch; branch.type = FixupBranch::Type::Branch32Bit; branch.ptr = code + 5; Write8(0xE8); Write32(0); // If we couldn't write the full call instruction, indicate that in the returned FixupBranch by // setting the branch's address to null. This will prevent a later SetJumpTarget() from writing to // invalid memory. if (HasWriteFailed()) branch.ptr = nullptr; return branch; } FixupBranch XEmitter::J(bool force5bytes) { FixupBranch branch; branch.type = force5bytes ? FixupBranch::Type::Branch32Bit : FixupBranch::Type::Branch8Bit; branch.ptr = code + (force5bytes ? 5 : 2); if (!force5bytes) { // 8 bits will do Write8(0xEB); Write8(0); } else { Write8(0xE9); Write32(0); } // If we couldn't write the full jump instruction, indicate that in the returned FixupBranch by // setting the branch's address to null. This will prevent a later SetJumpTarget() from writing to // invalid memory. if (HasWriteFailed()) branch.ptr = nullptr; return branch; } FixupBranch XEmitter::J_CC(CCFlags conditionCode, bool force5bytes) { FixupBranch branch; branch.type = force5bytes ? FixupBranch::Type::Branch32Bit : FixupBranch::Type::Branch8Bit; branch.ptr = code + (force5bytes ? 6 : 2); if (!force5bytes) { // 8 bits will do Write8(0x70 + conditionCode); Write8(0); } else { Write8(0x0F); Write8(0x80 + conditionCode); Write32(0); } // If we couldn't write the full jump instruction, indicate that in the returned FixupBranch by // setting the branch's address to null. This will prevent a later SetJumpTarget() from writing to // invalid memory. if (HasWriteFailed()) branch.ptr = nullptr; return branch; } void XEmitter::J_CC(CCFlags conditionCode, const u8* addr) { u64 fn = (u64)addr; s64 distance = (s64)(fn - ((u64)code + 2)); if (distance < -0x80 || distance >= 0x80) { distance = (s64)(fn - ((u64)code + 6)); ASSERT_MSG(DYNA_REC, distance >= -0x80000000LL && distance < 0x80000000LL, "Jump target too far away, needs indirect register"); Write8(0x0F); Write8(0x80 + conditionCode); Write32((u32)(s32)distance); } else { Write8(0x70 + conditionCode); Write8((u8)(s8)distance); } } void XEmitter::SetJumpTarget(const FixupBranch& branch, const u8* addr) { if (!branch.ptr) return; if (branch.type == FixupBranch::Type::Branch8Bit) { s64 distance = (s64)(addr - branch.ptr); ASSERT_MSG(DYNA_REC, distance >= -0x80 && distance < 0x80, "Jump target too far away, needs force5Bytes = true"); branch.ptr[-1] = (u8)(s8)distance; } else if (branch.type == FixupBranch::Type::Branch32Bit) { s64 distance = (s64)(addr - branch.ptr); ASSERT_MSG(DYNA_REC, distance >= -0x80000000LL && distance < 0x80000000LL, "Jump target too far away, needs indirect register"); s32 valid_distance = static_cast<s32>(distance); std::memcpy(&branch.ptr[-4], &valid_distance, sizeof(s32)); } } void XEmitter::SetJumpTarget(const FixupBranch& branch) { SetJumpTarget(branch, code); } // Single byte opcodes // There is no PUSHAD/POPAD in 64-bit mode. void XEmitter::INT3() { Write8(0xCC); } void XEmitter::RET() { Write8(0xC3); } void XEmitter::RET_FAST() { Write8(0xF3); Write8(0xC3); } // two-byte return (rep ret) - recommended by AMD optimization manual for the case of jumping to // a ret // The first sign of decadence: optimized NOPs. void XEmitter::NOP(size_t size) { DEBUG_ASSERT((int)size > 0); while (true) { switch (size) { case 0: return; case 1: Write8(0x90); return; case 2: Write8(0x66); Write8(0x90); return; case 3: Write8(0x0F); Write8(0x1F); Write8(0x00); return; case 4: Write8(0x0F); Write8(0x1F); Write8(0x40); Write8(0x00); return; case 5: Write8(0x0F); Write8(0x1F); Write8(0x44); Write8(0x00); Write8(0x00); return; case 6: Write8(0x66); Write8(0x0F); Write8(0x1F); Write8(0x44); Write8(0x00); Write8(0x00); return; case 7: Write8(0x0F); Write8(0x1F); Write8(0x80); Write8(0x00); Write8(0x00); Write8(0x00); Write8(0x00); return; case 8: Write8(0x0F); Write8(0x1F); Write8(0x84); Write8(0x00); Write8(0x00); Write8(0x00); Write8(0x00); Write8(0x00); return; case 9: Write8(0x66); Write8(0x0F); Write8(0x1F); Write8(0x84); Write8(0x00); Write8(0x00); Write8(0x00); Write8(0x00); Write8(0x00); return; case 10: Write8(0x66); Write8(0x66); Write8(0x0F); Write8(0x1F); Write8(0x84); Write8(0x00); Write8(0x00); Write8(0x00); Write8(0x00); Write8(0x00); return; default: // Even though x86 instructions are allowed to be up to 15 bytes long, // AMD advises against using NOPs longer than 11 bytes because they // carry a performance penalty on CPUs older than AMD family 16h. Write8(0x66); Write8(0x66); Write8(0x66); Write8(0x0F); Write8(0x1F); Write8(0x84); Write8(0x00); Write8(0x00); Write8(0x00); Write8(0x00); Write8(0x00); size -= 11; continue; } } } void XEmitter::PAUSE() { Write8(0xF3); NOP(); } // use in tight spinloops for energy saving on some CPU void XEmitter::CLC() { CheckFlags(); Write8(0xF8); } // clear carry void XEmitter::CMC() { CheckFlags(); Write8(0xF5); } // flip carry void XEmitter::STC() { CheckFlags(); Write8(0xF9); } // set carry // TODO: xchg ah, al ??? void XEmitter::XCHG_AHAL() { Write8(0x86); Write8(0xe0); // alt. 86 c4 } // These two can not be executed on early Intel 64-bit CPU:s, only on AMD! void XEmitter::LAHF() { Write8(0x9F); } void XEmitter::SAHF() { CheckFlags(); Write8(0x9E); } void XEmitter::PUSHF() { Write8(0x9C); } void XEmitter::POPF() { CheckFlags(); Write8(0x9D); } void XEmitter::LFENCE() { Write8(0x0F); Write8(0xAE); Write8(0xE8); } void XEmitter::MFENCE() { Write8(0x0F); Write8(0xAE); Write8(0xF0); } void XEmitter::SFENCE() { Write8(0x0F); Write8(0xAE); Write8(0xF8); } void XEmitter::WriteSimple1Byte(int bits, u8 byte, X64Reg reg) { if (bits == 16) Write8(0x66); Rex(bits == 64, 0, 0, (int)reg >> 3); Write8(byte + ((int)reg & 7)); } void XEmitter::WriteSimple2Byte(int bits, u8 byte1, u8 byte2, X64Reg reg) { if (bits == 16) Write8(0x66); Rex(bits == 64, 0, 0, (int)reg >> 3); Write8(byte1); Write8(byte2 + ((int)reg & 7)); } void XEmitter::CWD(int bits) { if (bits == 16) Write8(0x66); Rex(bits == 64, 0, 0, 0); Write8(0x99); } void XEmitter::CBW(int bits) { if (bits == 8) Write8(0x66); Rex(bits == 32, 0, 0, 0); Write8(0x98); } // Simple opcodes // push/pop do not need wide to be 64-bit void XEmitter::PUSH(X64Reg reg) { WriteSimple1Byte(32, 0x50, reg); } void XEmitter::POP(X64Reg reg) { WriteSimple1Byte(32, 0x58, reg); } void XEmitter::PUSH(int bits, const OpArg& reg) { if (reg.IsSimpleReg()) PUSH(reg.GetSimpleReg()); else if (reg.IsImm()) { switch (reg.GetImmBits()) { case 8: Write8(0x6A); Write8((u8)(s8)reg.offset); break; case 16: Write8(0x66); Write8(0x68); Write16((u16)(s16)(s32)reg.offset); break; case 32: Write8(0x68); Write32((u32)reg.offset); break; default: ASSERT_MSG(DYNA_REC, 0, "PUSH - Bad imm bits"); break; } } else { if (bits == 16) Write8(0x66); reg.WriteREX(this, bits, bits); Write8(0xFF); reg.WriteRest(this, 0, (X64Reg)6); } } void XEmitter::POP(int /*bits*/, const OpArg& reg) { if (reg.IsSimpleReg()) POP(reg.GetSimpleReg()); else ASSERT_MSG(DYNA_REC, 0, "POP - Unsupported encoding"); } void XEmitter::BSWAP(int bits, X64Reg reg) { if (bits >= 32) { WriteSimple2Byte(bits, 0x0F, 0xC8, reg); } else if (bits == 16) { ROL(16, R(reg), Imm8(8)); } else if (bits == 8) { // Do nothing - can't bswap a single byte... } else { ASSERT_MSG(DYNA_REC, 0, "BSWAP - Wrong number of bits"); } } // Undefined opcode - reserved // If we ever need a way to always cause a non-breakpoint hard exception... void XEmitter::UD2() { Write8(0x0F); Write8(0x0B); } void XEmitter::PREFETCH(PrefetchLevel level, OpArg arg) { ASSERT_MSG(DYNA_REC, !arg.IsImm(), "PREFETCH - Imm argument"); arg.operandReg = (u8)level; arg.WriteREX(this, 0, 0); Write8(0x0F); Write8(0x18); arg.WriteRest(this); } void XEmitter::SETcc(CCFlags flag, OpArg dest) { ASSERT_MSG(DYNA_REC, !dest.IsImm(), "SETcc - Imm argument"); dest.operandReg = 0; dest.WriteREX(this, 0, 8); Write8(0x0F); Write8(0x90 + (u8)flag); dest.WriteRest(this); } void XEmitter::CMOVcc(int bits, X64Reg dest, OpArg src, CCFlags flag) { ASSERT_MSG(DYNA_REC, !src.IsImm(), "CMOVcc - Imm argument"); ASSERT_MSG(DYNA_REC, bits != 8, "CMOVcc - 8 bits unsupported"); if (bits == 16) Write8(0x66); src.operandReg = dest; src.WriteREX(this, bits, bits); Write8(0x0F); Write8(0x40 + (u8)flag); src.WriteRest(this); } void XEmitter::WriteMulDivType(int bits, OpArg src, int ext) { ASSERT_MSG(DYNA_REC, !src.IsImm(), "WriteMulDivType - Imm argument"); CheckFlags(); src.operandReg = ext; if (bits == 16) Write8(0x66); src.WriteREX(this, bits, bits, 0); if (bits == 8) { Write8(0xF6); } else { Write8(0xF7); } src.WriteRest(this); } void XEmitter::MUL(int bits, const OpArg& src) { WriteMulDivType(bits, src, 4); } void XEmitter::DIV(int bits, const OpArg& src) { WriteMulDivType(bits, src, 6); } void XEmitter::IMUL(int bits, const OpArg& src) { WriteMulDivType(bits, src, 5); } void XEmitter::IDIV(int bits, const OpArg& src) { WriteMulDivType(bits, src, 7); } void XEmitter::NEG(int bits, const OpArg& src) { WriteMulDivType(bits, src, 3); } void XEmitter::NOT(int bits, const OpArg& src) { WriteMulDivType(bits, src, 2); } void XEmitter::WriteBitSearchType(int bits, X64Reg dest, OpArg src, u8 byte2, bool rep) { ASSERT_MSG(DYNA_REC, !src.IsImm(), "WriteBitSearchType - Imm argument"); CheckFlags(); src.operandReg = (u8)dest; if (bits == 16) Write8(0x66); if (rep) Write8(0xF3); src.WriteREX(this, bits, bits); Write8(0x0F); Write8(byte2); src.WriteRest(this); } void XEmitter::MOVNTI(int bits, const OpArg& dest, X64Reg src) { if (bits <= 16) ASSERT_MSG(DYNA_REC, 0, "MOVNTI - bits<=16"); WriteBitSearchType(bits, src, dest, 0xC3); } void XEmitter::BSF(int bits, X64Reg dest, const OpArg& src) { WriteBitSearchType(bits, dest, src, 0xBC); } // Bottom bit to top bit void XEmitter::BSR(int bits, X64Reg dest, const OpArg& src) { WriteBitSearchType(bits, dest, src, 0xBD); } // Top bit to bottom bit void XEmitter::TZCNT(int bits, X64Reg dest, const OpArg& src) { CheckFlags(); if (!cpu_info.bBMI1) PanicAlertFmt("Trying to use BMI1 on a system that doesn't support it. Bad programmer."); WriteBitSearchType(bits, dest, src, 0xBC, true); } void XEmitter::LZCNT(int bits, X64Reg dest, const OpArg& src) { CheckFlags(); if (!cpu_info.bLZCNT) PanicAlertFmt("Trying to use LZCNT on a system that doesn't support it. Bad programmer."); WriteBitSearchType(bits, dest, src, 0xBD, true); } void XEmitter::MOVSX(int dbits, int sbits, X64Reg dest, OpArg src) { ASSERT_MSG(DYNA_REC, !src.IsImm(), "MOVSX - Imm argument"); if (dbits == sbits) { MOV(dbits, R(dest), src); return; } src.operandReg = (u8)dest; if (dbits == 16) Write8(0x66); src.WriteREX(this, dbits, sbits); if (sbits == 8) { Write8(0x0F); Write8(0xBE); } else if (sbits == 16) { Write8(0x0F); Write8(0xBF); } else if (sbits == 32 && dbits == 64) { Write8(0x63); } else { Crash(); } src.WriteRest(this); } void XEmitter::MOVZX(int dbits, int sbits, X64Reg dest, OpArg src) { ASSERT_MSG(DYNA_REC, !src.IsImm(), "MOVZX - Imm argument"); if (dbits == sbits) { MOV(dbits, R(dest), src); return; } src.operandReg = (u8)dest; if (dbits == 16) Write8(0x66); // the 32bit result is automatically zero extended to 64bit src.WriteREX(this, dbits == 64 ? 32 : dbits, sbits); if (sbits == 8) { Write8(0x0F); Write8(0xB6); } else if (sbits == 16) { Write8(0x0F); Write8(0xB7); } else if (sbits == 32 && dbits == 64) { Write8(0x8B); } else { ASSERT_MSG(DYNA_REC, 0, "MOVZX - Invalid size"); } src.WriteRest(this); } void XEmitter::WriteMOVBE(int bits, u8 op, X64Reg reg, const OpArg& arg) { ASSERT_MSG(DYNA_REC, cpu_info.bMOVBE, "Generating MOVBE on a system that does not support it."); if (bits == 8) { MOV(8, op & 1 ? arg : R(reg), op & 1 ? R(reg) : arg); return; } if (bits == 16) Write8(0x66); ASSERT_MSG(DYNA_REC, !arg.IsSimpleReg() && !arg.IsImm(), "MOVBE: need r<-m or m<-r!"); arg.WriteREX(this, bits, bits, reg); Write8(0x0F); Write8(0x38); Write8(op); arg.WriteRest(this, 0, reg); } void XEmitter::MOVBE(int bits, X64Reg dest, const OpArg& src) { WriteMOVBE(bits, 0xF0, dest, src); } void XEmitter::MOVBE(int bits, const OpArg& dest, X64Reg src) { WriteMOVBE(bits, 0xF1, src, dest); } void XEmitter::LoadAndSwap(int size, X64Reg dst, const OpArg& src, bool sign_extend, MovInfo* info) { if (info) { info->address = GetWritableCodePtr(); info->nonAtomicSwapStore = false; } switch (size) { case 8: if (sign_extend) MOVSX(32, 8, dst, src); else MOVZX(32, 8, dst, src); break; case 16: MOVZX(32, 16, dst, src); if (sign_extend) { BSWAP(32, dst); SAR(32, R(dst), Imm8(16)); } else { ROL(16, R(dst), Imm8(8)); } break; case 32: case 64: if (cpu_info.bMOVBE) { MOVBE(size, dst, src); } else { MOV(size, R(dst), src); BSWAP(size, dst); } break; } } void XEmitter::SwapAndStore(int size, const OpArg& dst, X64Reg src, MovInfo* info) { if (cpu_info.bMOVBE) { if (info) { info->address = GetWritableCodePtr(); info->nonAtomicSwapStore = false; } MOVBE(size, dst, src); } else { BSWAP(size, src); if (info) { info->address = GetWritableCodePtr(); info->nonAtomicSwapStore = true; info->nonAtomicSwapStoreSrc = src; } MOV(size, dst, R(src)); } } void XEmitter::LEA(int bits, X64Reg dest, OpArg src) { ASSERT_MSG(DYNA_REC, !src.IsImm(), "LEA - Imm argument"); src.operandReg = (u8)dest; if (bits == 16) Write8(0x66); // TODO: performance warning src.WriteREX(this, bits, bits); Write8(0x8D); src.WriteRest(this, 0, INVALID_REG, bits == 64); } // shift can be either imm8 or cl void XEmitter::WriteShift(int bits, OpArg dest, const OpArg& shift, int ext) { CheckFlags(); bool writeImm = false; if (dest.IsImm()) { ASSERT_MSG(DYNA_REC, 0, "WriteShift - can't shift imms"); } if ((shift.IsSimpleReg() && shift.GetSimpleReg() != ECX) || (shift.IsImm() && shift.GetImmBits() != 8)) { ASSERT_MSG(DYNA_REC, 0, "WriteShift - illegal argument"); } dest.operandReg = ext; if (bits == 16) Write8(0x66); dest.WriteREX(this, bits, bits, 0); if (shift.GetImmBits() == 8) { // ok an imm u8 imm = (u8)shift.offset; if (imm == 1) { Write8(bits == 8 ? 0xD0 : 0xD1); } else { writeImm = true; Write8(bits == 8 ? 0xC0 : 0xC1); } } else { Write8(bits == 8 ? 0xD2 : 0xD3); } dest.WriteRest(this, writeImm ? 1 : 0); if (writeImm) Write8((u8)shift.offset); } // large rotates and shift are slower on Intel than AMD // Intel likes to rotate by 1, and the op is smaller too void XEmitter::ROL(int bits, const OpArg& dest, const OpArg& shift) { WriteShift(bits, dest, shift, 0); } void XEmitter::ROR(int bits, const OpArg& dest, const OpArg& shift) { WriteShift(bits, dest, shift, 1); } void XEmitter::RCL(int bits, const OpArg& dest, const OpArg& shift) { WriteShift(bits, dest, shift, 2); } void XEmitter::RCR(int bits, const OpArg& dest, const OpArg& shift) { WriteShift(bits, dest, shift, 3); } void XEmitter::SHL(int bits, const OpArg& dest, const OpArg& shift) { WriteShift(bits, dest, shift, 4); } void XEmitter::SHR(int bits, const OpArg& dest, const OpArg& shift) { WriteShift(bits, dest, shift, 5); } void XEmitter::SAR(int bits, const OpArg& dest, const OpArg& shift) { WriteShift(bits, dest, shift, 7); } // index can be either imm8 or register, don't use memory destination because it's slow void XEmitter::WriteBitTest(int bits, const OpArg& dest, const OpArg& index, int ext) { CheckFlags(); if (dest.IsImm()) { ASSERT_MSG(DYNA_REC, 0, "WriteBitTest - can't test imms"); } if ((index.IsImm() && index.GetImmBits() != 8)) { ASSERT_MSG(DYNA_REC, 0, "WriteBitTest - illegal argument"); } if (bits == 16) Write8(0x66); if (index.IsImm()) { dest.WriteREX(this, bits, bits); Write8(0x0F); Write8(0xBA); dest.WriteRest(this, 1, (X64Reg)ext); Write8((u8)index.offset); } else { X64Reg operand = index.GetSimpleReg(); dest.WriteREX(this, bits, bits, operand); Write8(0x0F); Write8(0x83 + 8 * ext); dest.WriteRest(this, 1, operand); } } void XEmitter::BT(int bits, const OpArg& dest, const OpArg& index) { WriteBitTest(bits, dest, index, 4); } void XEmitter::BTS(int bits, const OpArg& dest, const OpArg& index) { WriteBitTest(bits, dest, index, 5); } void XEmitter::BTR(int bits, const OpArg& dest, const OpArg& index) { WriteBitTest(bits, dest, index, 6); } void XEmitter::BTC(int bits, const OpArg& dest, const OpArg& index) { WriteBitTest(bits, dest, index, 7); } // shift can be either imm8 or cl void XEmitter::SHRD(int bits, const OpArg& dest, const OpArg& src, const OpArg& shift) { CheckFlags(); if (dest.IsImm()) { ASSERT_MSG(DYNA_REC, 0, "SHRD - can't use imms as destination"); } if (!src.IsSimpleReg()) { ASSERT_MSG(DYNA_REC, 0, "SHRD - must use simple register as source"); } if ((shift.IsSimpleReg() && shift.GetSimpleReg() != ECX) || (shift.IsImm() && shift.GetImmBits() != 8)) { ASSERT_MSG(DYNA_REC, 0, "SHRD - illegal shift"); } if (bits == 16) Write8(0x66); X64Reg operand = src.GetSimpleReg(); dest.WriteREX(this, bits, bits, operand); if (shift.GetImmBits() == 8) { Write8(0x0F); Write8(0xAC); dest.WriteRest(this, 1, operand); Write8((u8)shift.offset); } else { Write8(0x0F); Write8(0xAD); dest.WriteRest(this, 0, operand); } } void XEmitter::SHLD(int bits, const OpArg& dest, const OpArg& src, const OpArg& shift) { CheckFlags(); if (dest.IsImm()) { ASSERT_MSG(DYNA_REC, 0, "SHLD - can't use imms as destination"); } if (!src.IsSimpleReg()) { ASSERT_MSG(DYNA_REC, 0, "SHLD - must use simple register as source"); } if ((shift.IsSimpleReg() && shift.GetSimpleReg() != ECX) || (shift.IsImm() && shift.GetImmBits() != 8)) { ASSERT_MSG(DYNA_REC, 0, "SHLD - illegal shift"); } if (bits == 16) Write8(0x66); X64Reg operand = src.GetSimpleReg(); dest.WriteREX(this, bits, bits, operand); if (shift.GetImmBits() == 8) { Write8(0x0F); Write8(0xA4); dest.WriteRest(this, 1, operand); Write8((u8)shift.offset); } else { Write8(0x0F); Write8(0xA5); dest.WriteRest(this, 0, operand); } } void OpArg::WriteSingleByteOp(XEmitter* emit, u8 op, X64Reg _operandReg, int bits) { if (bits == 16) emit->Write8(0x66); this->operandReg = (u8)_operandReg; WriteREX(emit, bits, bits); emit->Write8(op); WriteRest(emit); } // operand can either be immediate or register void OpArg::WriteNormalOp(XEmitter* emit, bool toRM, NormalOp op, const OpArg& operand, int bits) const { X64Reg _operandReg; if (IsImm()) { ASSERT_MSG(DYNA_REC, 0, "WriteNormalOp - Imm argument, wrong order"); } if (bits == 16) emit->Write8(0x66); int immToWrite = 0; const NormalOpDef& op_def = normalops[static_cast<int>(op)]; if (operand.IsImm()) { WriteREX(emit, bits, bits); if (!toRM) { ASSERT_MSG(DYNA_REC, 0, "WriteNormalOp - Writing to Imm (!toRM)"); } if (operand.scale == SCALE_IMM8 && bits == 8) { // op al, imm8 if (!scale && offsetOrBaseReg == AL && op_def.eaximm8 != 0xCC) { emit->Write8(op_def.eaximm8); emit->Write8((u8)operand.offset); return; } // mov reg, imm8 if (!scale && op == NormalOp::MOV) { emit->Write8(0xB0 + (offsetOrBaseReg & 7)); emit->Write8((u8)operand.offset); return; } // op r/m8, imm8 emit->Write8(op_def.imm8); immToWrite = 8; } else if ((operand.scale == SCALE_IMM16 && bits == 16) || (operand.scale == SCALE_IMM32 && bits == 32) || (operand.scale == SCALE_IMM32 && bits == 64)) { // Try to save immediate size if we can, but first check to see // if the instruction supports simm8. // op r/m, imm8 if (op_def.simm8 != 0xCC && ((operand.scale == SCALE_IMM16 && (s16)operand.offset == (s8)operand.offset) || (operand.scale == SCALE_IMM32 && (s32)operand.offset == (s8)operand.offset))) { emit->Write8(op_def.simm8); immToWrite = 8; } else { // mov reg, imm if (!scale && op == NormalOp::MOV && bits != 64) { emit->Write8(0xB8 + (offsetOrBaseReg & 7)); if (bits == 16) emit->Write16((u16)operand.offset); else emit->Write32((u32)operand.offset); return; } // op eax, imm if (!scale && offsetOrBaseReg == EAX && op_def.eaximm32 != 0xCC) { emit->Write8(op_def.eaximm32); if (bits == 16) emit->Write16((u16)operand.offset); else emit->Write32((u32)operand.offset); return; } // op r/m, imm emit->Write8(op_def.imm32); immToWrite = bits == 16 ? 16 : 32; } } else if ((operand.scale == SCALE_IMM8 && bits == 16) || (operand.scale == SCALE_IMM8 && bits == 32) || (operand.scale == SCALE_IMM8 && bits == 64)) { // op r/m, imm8 emit->Write8(op_def.simm8); immToWrite = 8; } else if (operand.scale == SCALE_IMM64 && bits == 64) { if (scale) { ASSERT_MSG(DYNA_REC, 0, "WriteNormalOp - MOV with 64-bit imm requires register destination"); } // mov reg64, imm64 else if (op == NormalOp::MOV) { // movabs reg64, imm64 (10 bytes) if (static_cast<s64>(operand.offset) != static_cast<s32>(operand.offset)) { emit->Write8(0xB8 + (offsetOrBaseReg & 7)); emit->Write64(operand.offset); return; } // mov reg64, simm32 (7 bytes) emit->Write8(op_def.imm32); immToWrite = 32; } else { ASSERT_MSG(DYNA_REC, 0, "WriteNormalOp - Only MOV can take 64-bit imm"); } } else { ASSERT_MSG(DYNA_REC, 0, "WriteNormalOp - Unhandled case %d %d", operand.scale, bits); } // pass extension in REG of ModRM _operandReg = static_cast<X64Reg>(op_def.ext); } else { _operandReg = (X64Reg)operand.offsetOrBaseReg; WriteREX(emit, bits, bits, _operandReg); // op r/m, reg if (toRM) { emit->Write8(bits == 8 ? op_def.toRm8 : op_def.toRm32); } // op reg, r/m else { emit->Write8(bits == 8 ? op_def.fromRm8 : op_def.fromRm32); } } WriteRest(emit, immToWrite >> 3, _operandReg); switch (immToWrite) { case 0: break; case 8: emit->Write8((u8)operand.offset); break; case 16: emit->Write16((u16)operand.offset); break; case 32: emit->Write32((u32)operand.offset); break; default: ASSERT_MSG(DYNA_REC, 0, "WriteNormalOp - Unhandled case"); } } void XEmitter::WriteNormalOp(int bits, NormalOp op, const OpArg& a1, const OpArg& a2) { if (a1.IsImm()) { // Booh! Can't write to an imm ASSERT_MSG(DYNA_REC, 0, "WriteNormalOp - a1 cannot be imm"); return; } if (a2.IsImm()) { a1.WriteNormalOp(this, true, op, a2, bits); } else { if (a1.IsSimpleReg()) { a2.WriteNormalOp(this, false, op, a1, bits); } else { ASSERT_MSG(DYNA_REC, a2.IsSimpleReg() || a2.IsImm(), "WriteNormalOp - a1 and a2 cannot both be memory"); a1.WriteNormalOp(this, true, op, a2, bits); } } } void XEmitter::ADD(int bits, const OpArg& a1, const OpArg& a2) { CheckFlags(); WriteNormalOp(bits, NormalOp::ADD, a1, a2); } void XEmitter::ADC(int bits, const OpArg& a1, const OpArg& a2) { CheckFlags(); WriteNormalOp(bits, NormalOp::ADC, a1, a2); } void XEmitter::SUB(int bits, const OpArg& a1, const OpArg& a2) { CheckFlags(); WriteNormalOp(bits, NormalOp::SUB, a1, a2); } void XEmitter::SBB(int bits, const OpArg& a1, const OpArg& a2) { CheckFlags(); WriteNormalOp(bits, NormalOp::SBB, a1, a2); } void XEmitter::AND(int bits, const OpArg& a1, const OpArg& a2) { CheckFlags(); WriteNormalOp(bits, NormalOp::AND, a1, a2); } void XEmitter::OR(int bits, const OpArg& a1, const OpArg& a2) { CheckFlags(); WriteNormalOp(bits, NormalOp::OR, a1, a2); } void XEmitter::XOR(int bits, const OpArg& a1, const OpArg& a2) { CheckFlags(); WriteNormalOp(bits, NormalOp::XOR, a1, a2); } void XEmitter::MOV(int bits, const OpArg& a1, const OpArg& a2) { if (bits == 64 && a1.IsSimpleReg() && ((a2.scale == SCALE_IMM64 && a2.offset == static_cast<u32>(a2.offset)) || (a2.scale == SCALE_IMM32 && static_cast<s32>(a2.offset) >= 0))) { WriteNormalOp(32, NormalOp::MOV, a1, a2.AsImm32()); return; } if (a1.IsSimpleReg() && a2.IsSimpleReg() && a1.GetSimpleReg() == a2.GetSimpleReg()) ERROR_LOG_FMT(DYNA_REC, "Redundant MOV @ {} - bug in JIT?", fmt::ptr(code)); WriteNormalOp(bits, NormalOp::MOV, a1, a2); } void XEmitter::TEST(int bits, const OpArg& a1, const OpArg& a2) { CheckFlags(); WriteNormalOp(bits, NormalOp::TEST, a1, a2); } void XEmitter::CMP(int bits, const OpArg& a1, const OpArg& a2) { CheckFlags(); WriteNormalOp(bits, NormalOp::CMP, a1, a2); } void XEmitter::XCHG(int bits, const OpArg& a1, const OpArg& a2) { WriteNormalOp(bits, NormalOp::XCHG, a1, a2); } void XEmitter::CMP_or_TEST(int bits, const OpArg& a1, const OpArg& a2) { CheckFlags(); if (a1.IsSimpleReg() && a2.IsZero()) // turn 'CMP reg, 0' into shorter 'TEST reg, reg' { WriteNormalOp(bits, NormalOp::TEST, a1, a1); } else { WriteNormalOp(bits, NormalOp::CMP, a1, a2); } } void XEmitter::MOV_sum(int bits, X64Reg dest, const OpArg& a1, const OpArg& a2) { // This stomps on flags, so ensure they aren't locked DEBUG_ASSERT(!flags_locked); // Zero shortcuts (note that this can generate no code in the case where a1 == dest && a2 == zero // or a2 == dest && a1 == zero) if (a1.IsZero()) { if (!a2.IsSimpleReg() || a2.GetSimpleReg() != dest) { MOV(bits, R(dest), a2); } return; } if (a2.IsZero()) { if (!a1.IsSimpleReg() || a1.GetSimpleReg() != dest) { MOV(bits, R(dest), a1); } return; } // If dest == a1 or dest == a2 we can simplify this if (a1.IsSimpleReg() && a1.GetSimpleReg() == dest) { ADD(bits, R(dest), a2); return; } if (a2.IsSimpleReg() && a2.GetSimpleReg() == dest) { ADD(bits, R(dest), a1); return; } // TODO: 32-bit optimizations may apply to other bit sizes (confirm) if (bits == 32) { if (a1.IsImm() && a2.IsImm()) { MOV(32, R(dest), Imm32(a1.Imm32() + a2.Imm32())); return; } if (a1.IsSimpleReg() && a2.IsSimpleReg()) { LEA(32, dest, MRegSum(a1.GetSimpleReg(), a2.GetSimpleReg())); return; } if (a1.IsSimpleReg() && a2.IsImm()) { LEA(32, dest, MDisp(a1.GetSimpleReg(), a2.Imm32())); return; } if (a1.IsImm() && a2.IsSimpleReg()) { LEA(32, dest, MDisp(a2.GetSimpleReg(), a1.Imm32())); return; } } // Fallback MOV(bits, R(dest), a1); ADD(bits, R(dest), a2); } void XEmitter::IMUL(int bits, X64Reg regOp, const OpArg& a1, const OpArg& a2) { CheckFlags(); if (bits == 8) { ASSERT_MSG(DYNA_REC, 0, "IMUL - illegal bit size!"); return; } if (a1.IsImm()) { ASSERT_MSG(DYNA_REC, 0, "IMUL - second arg cannot be imm!"); return; } if (!a2.IsImm()) { ASSERT_MSG(DYNA_REC, 0, "IMUL - third arg must be imm!"); return; } if (bits == 16) Write8(0x66); a1.WriteREX(this, bits, bits, regOp); if (a2.GetImmBits() == 8 || (a2.GetImmBits() == 16 && (s8)a2.offset == (s16)a2.offset) || (a2.GetImmBits() == 32 && (s8)a2.offset == (s32)a2.offset)) { Write8(0x6B); a1.WriteRest(this, 1, regOp); Write8((u8)a2.offset); } else { Write8(0x69); if (a2.GetImmBits() == 16 && bits == 16) { a1.WriteRest(this, 2, regOp); Write16((u16)a2.offset); } else if (a2.GetImmBits() == 32 && (bits == 32 || bits == 64)) { a1.WriteRest(this, 4, regOp); Write32((u32)a2.offset); } else { ASSERT_MSG(DYNA_REC, 0, "IMUL - unhandled case!"); } } } void XEmitter::IMUL(int bits, X64Reg regOp, const OpArg& a) { CheckFlags(); if (bits == 8) { ASSERT_MSG(DYNA_REC, 0, "IMUL - illegal bit size!"); return; } if (a.IsImm()) { IMUL(bits, regOp, R(regOp), a); return; } if (bits == 16) Write8(0x66); a.WriteREX(this, bits, bits, regOp); Write8(0x0F); Write8(0xAF); a.WriteRest(this, 0, regOp); } void XEmitter::WriteSSEOp(u8 opPrefix, u16 op, X64Reg regOp, OpArg arg, int extrabytes) { if (opPrefix) Write8(opPrefix); arg.operandReg = regOp; arg.WriteREX(this, 0, 0); Write8(0x0F); if (op > 0xFF) Write8((op >> 8) & 0xFF); Write8(op & 0xFF); arg.WriteRest(this, extrabytes); } static int GetVEXmmmmm(u16 op) { // Currently, only 0x38 and 0x3A are used as secondary escape byte. if ((op >> 8) == 0x3A) return 3; else if ((op >> 8) == 0x38) return 2; else return 1; } static int GetVEXpp(u8 opPrefix) { if (opPrefix == 0x66) return 1; else if (opPrefix == 0xF3) return 2; else if (opPrefix == 0xF2) return 3; else return 0; } void XEmitter::WriteVEXOp(u8 opPrefix, u16 op, X64Reg regOp1, X64Reg regOp2, const OpArg& arg, int W, int extrabytes) { int mmmmm = GetVEXmmmmm(op); int pp = GetVEXpp(opPrefix); // FIXME: we currently don't support 256-bit instructions, and "size" is not the vector size here arg.WriteVEX(this, regOp1, regOp2, 0, pp, mmmmm, W); Write8(op & 0xFF); arg.WriteRest(this, extrabytes, regOp1); } void XEmitter::WriteVEXOp4(u8 opPrefix, u16 op, X64Reg regOp1, X64Reg regOp2, const OpArg& arg, X64Reg regOp3, int W) { WriteVEXOp(opPrefix, op, regOp1, regOp2, arg, W, 1); Write8((u8)regOp3 << 4); } void XEmitter::WriteAVXOp(u8 opPrefix, u16 op, X64Reg regOp1, X64Reg regOp2, const OpArg& arg, int W, int extrabytes) { if (!cpu_info.bAVX) PanicAlertFmt("Trying to use AVX on a system that doesn't support it. Bad programmer."); WriteVEXOp(opPrefix, op, regOp1, regOp2, arg, W, extrabytes); } void XEmitter::WriteAVXOp4(u8 opPrefix, u16 op, X64Reg regOp1, X64Reg regOp2, const OpArg& arg, X64Reg regOp3, int W) { if (!cpu_info.bAVX) PanicAlertFmt("Trying to use AVX on a system that doesn't support it. Bad programmer."); WriteVEXOp4(opPrefix, op, regOp1, regOp2, arg, regOp3, W); } void XEmitter::WriteFMA3Op(u8 op, X64Reg regOp1, X64Reg regOp2, const OpArg& arg, int W) { if (!cpu_info.bFMA) { PanicAlertFmt( "Trying to use FMA3 on a system that doesn't support it. Computer is v. f'n madd."); } WriteVEXOp(0x66, 0x3800 | op, regOp1, regOp2, arg, W); } void XEmitter::WriteFMA4Op(u8 op, X64Reg dest, X64Reg regOp1, X64Reg regOp2, const OpArg& arg, int W) { if (!cpu_info.bFMA4) { PanicAlertFmt( "Trying to use FMA4 on a system that doesn't support it. Computer is v. f'n madd."); } WriteVEXOp4(0x66, 0x3A00 | op, dest, regOp1, arg, regOp2, W); } void XEmitter::WriteBMIOp(int size, u8 opPrefix, u16 op, X64Reg regOp1, X64Reg regOp2, const OpArg& arg, int extrabytes) { if (arg.IsImm()) PanicAlertFmt("BMI1/2 instructions don't support immediate operands."); if (size != 32 && size != 64) PanicAlertFmt("BMI1/2 instructions only support 32-bit and 64-bit modes!"); const int W = size == 64; WriteVEXOp(opPrefix, op, regOp1, regOp2, arg, W, extrabytes); } void XEmitter::WriteBMI1Op(int size, u8 opPrefix, u16 op, X64Reg regOp1, X64Reg regOp2, const OpArg& arg, int extrabytes) { CheckFlags(); if (!cpu_info.bBMI1) PanicAlertFmt("Trying to use BMI1 on a system that doesn't support it. Bad programmer."); WriteBMIOp(size, opPrefix, op, regOp1, regOp2, arg, extrabytes); } void XEmitter::WriteBMI2Op(int size, u8 opPrefix, u16 op, X64Reg regOp1, X64Reg regOp2, const OpArg& arg, int extrabytes) { if (!cpu_info.bBMI2) PanicAlertFmt("Trying to use BMI2 on a system that doesn't support it. Bad programmer."); WriteBMIOp(size, opPrefix, op, regOp1, regOp2, arg, extrabytes); } void XEmitter::MOVD_xmm(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0x6E, dest, arg, 0); } void XEmitter::MOVD_xmm(const OpArg& arg, X64Reg src) { WriteSSEOp(0x66, 0x7E, src, arg, 0); } void XEmitter::MOVQ_xmm(X64Reg dest, OpArg arg) { // Alternate encoding // This does not display correctly in MSVC's debugger, it thinks it's a MOVD arg.operandReg = dest; Write8(0x66); arg.WriteREX(this, 64, 0); Write8(0x0f); Write8(0x6E); arg.WriteRest(this, 0); } void XEmitter::MOVQ_xmm(OpArg arg, X64Reg src) { if (src > 7 || arg.IsSimpleReg()) { // Alternate encoding // This does not display correctly in MSVC's debugger, it thinks it's a MOVD arg.operandReg = src; Write8(0x66); arg.WriteREX(this, 64, 0); Write8(0x0f); Write8(0x7E); arg.WriteRest(this, 0); } else { arg.operandReg = src; arg.WriteREX(this, 0, 0); Write8(0x66); Write8(0x0f); Write8(0xD6); arg.WriteRest(this, 0); } } void XEmitter::WriteMXCSR(OpArg arg, int ext) { if (arg.IsImm() || arg.IsSimpleReg()) ASSERT_MSG(DYNA_REC, 0, "MXCSR - invalid operand"); arg.operandReg = ext; arg.WriteREX(this, 0, 0); Write8(0x0F); Write8(0xAE); arg.WriteRest(this); } void XEmitter::STMXCSR(const OpArg& memloc) { WriteMXCSR(memloc, 3); } void XEmitter::LDMXCSR(const OpArg& memloc) { WriteMXCSR(memloc, 2); } void XEmitter::MOVNTDQ(const OpArg& arg, X64Reg regOp) { WriteSSEOp(0x66, sseMOVNTDQ, regOp, arg); } void XEmitter::MOVNTPS(const OpArg& arg, X64Reg regOp) { WriteSSEOp(0x00, sseMOVNTP, regOp, arg); } void XEmitter::MOVNTPD(const OpArg& arg, X64Reg regOp) { WriteSSEOp(0x66, sseMOVNTP, regOp, arg); } void XEmitter::ADDSS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF3, sseADD, regOp, arg); } void XEmitter::ADDSD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF2, sseADD, regOp, arg); } void XEmitter::SUBSS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF3, sseSUB, regOp, arg); } void XEmitter::SUBSD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF2, sseSUB, regOp, arg); } void XEmitter::CMPSS(X64Reg regOp, const OpArg& arg, u8 compare) { WriteSSEOp(0xF3, sseCMP, regOp, arg, 1); Write8(compare); } void XEmitter::CMPSD(X64Reg regOp, const OpArg& arg, u8 compare) { WriteSSEOp(0xF2, sseCMP, regOp, arg, 1); Write8(compare); } void XEmitter::MULSS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF3, sseMUL, regOp, arg); } void XEmitter::MULSD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF2, sseMUL, regOp, arg); } void XEmitter::DIVSS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF3, sseDIV, regOp, arg); } void XEmitter::DIVSD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF2, sseDIV, regOp, arg); } void XEmitter::MINSS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF3, sseMIN, regOp, arg); } void XEmitter::MINSD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF2, sseMIN, regOp, arg); } void XEmitter::MAXSS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF3, sseMAX, regOp, arg); } void XEmitter::MAXSD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF2, sseMAX, regOp, arg); } void XEmitter::SQRTSS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF3, sseSQRT, regOp, arg); } void XEmitter::SQRTSD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF2, sseSQRT, regOp, arg); } void XEmitter::RCPSS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF3, sseRCP, regOp, arg); } void XEmitter::RSQRTSS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF3, sseRSQRT, regOp, arg); } void XEmitter::ADDPS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseADD, regOp, arg); } void XEmitter::ADDPD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, sseADD, regOp, arg); } void XEmitter::SUBPS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseSUB, regOp, arg); } void XEmitter::SUBPD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, sseSUB, regOp, arg); } void XEmitter::CMPPS(X64Reg regOp, const OpArg& arg, u8 compare) { WriteSSEOp(0x00, sseCMP, regOp, arg, 1); Write8(compare); } void XEmitter::CMPPD(X64Reg regOp, const OpArg& arg, u8 compare) { WriteSSEOp(0x66, sseCMP, regOp, arg, 1); Write8(compare); } void XEmitter::ANDPS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseAND, regOp, arg); } void XEmitter::ANDPD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, sseAND, regOp, arg); } void XEmitter::ANDNPS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseANDN, regOp, arg); } void XEmitter::ANDNPD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, sseANDN, regOp, arg); } void XEmitter::ORPS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseOR, regOp, arg); } void XEmitter::ORPD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, sseOR, regOp, arg); } void XEmitter::XORPS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseXOR, regOp, arg); } void XEmitter::XORPD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, sseXOR, regOp, arg); } void XEmitter::MULPS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseMUL, regOp, arg); } void XEmitter::MULPD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, sseMUL, regOp, arg); } void XEmitter::DIVPS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseDIV, regOp, arg); } void XEmitter::DIVPD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, sseDIV, regOp, arg); } void XEmitter::MINPS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseMIN, regOp, arg); } void XEmitter::MINPD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, sseMIN, regOp, arg); } void XEmitter::MAXPS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseMAX, regOp, arg); } void XEmitter::MAXPD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, sseMAX, regOp, arg); } void XEmitter::SQRTPS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseSQRT, regOp, arg); } void XEmitter::SQRTPD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, sseSQRT, regOp, arg); } void XEmitter::RCPPS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseRCP, regOp, arg); } void XEmitter::RSQRTPS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseRSQRT, regOp, arg); } void XEmitter::SHUFPS(X64Reg regOp, const OpArg& arg, u8 shuffle) { WriteSSEOp(0x00, sseSHUF, regOp, arg, 1); Write8(shuffle); } void XEmitter::SHUFPD(X64Reg regOp, const OpArg& arg, u8 shuffle) { WriteSSEOp(0x66, sseSHUF, regOp, arg, 1); Write8(shuffle); } void XEmitter::COMISS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseCOMIS, regOp, arg); } // weird that these should be packed void XEmitter::COMISD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, sseCOMIS, regOp, arg); } // ordered void XEmitter::UCOMISS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseUCOMIS, regOp, arg); } // unordered void XEmitter::UCOMISD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, sseUCOMIS, regOp, arg); } void XEmitter::MOVAPS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseMOVAPfromRM, regOp, arg); } void XEmitter::MOVAPD(X64Reg regOp, const OpArg& arg) { // Prefer MOVAPS to MOVAPD as there is no reason to use MOVAPD over MOVAPS: // - They have equivalent functionality. // - There has never been a microarchitecture with separate single and double domains. // - MOVAPD is one byte longer than MOVAPS. MOVAPS(regOp, arg); } void XEmitter::MOVAPS(const OpArg& arg, X64Reg regOp) { WriteSSEOp(0x00, sseMOVAPtoRM, regOp, arg); } void XEmitter::MOVAPD(const OpArg& arg, X64Reg regOp) { MOVAPS(arg, regOp); } void XEmitter::MOVUPS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseMOVUPfromRM, regOp, arg); } void XEmitter::MOVUPD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, sseMOVUPfromRM, regOp, arg); } void XEmitter::MOVUPS(const OpArg& arg, X64Reg regOp) { WriteSSEOp(0x00, sseMOVUPtoRM, regOp, arg); } void XEmitter::MOVUPD(const OpArg& arg, X64Reg regOp) { WriteSSEOp(0x66, sseMOVUPtoRM, regOp, arg); } void XEmitter::MOVDQA(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, sseMOVDQfromRM, regOp, arg); } void XEmitter::MOVDQA(const OpArg& arg, X64Reg regOp) { WriteSSEOp(0x66, sseMOVDQtoRM, regOp, arg); } void XEmitter::MOVDQU(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF3, sseMOVDQfromRM, regOp, arg); } void XEmitter::MOVDQU(const OpArg& arg, X64Reg regOp) { WriteSSEOp(0xF3, sseMOVDQtoRM, regOp, arg); } void XEmitter::MOVSS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF3, sseMOVUPfromRM, regOp, arg); } void XEmitter::MOVSD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF2, sseMOVUPfromRM, regOp, arg); } void XEmitter::MOVSS(const OpArg& arg, X64Reg regOp) { WriteSSEOp(0xF3, sseMOVUPtoRM, regOp, arg); } void XEmitter::MOVSD(const OpArg& arg, X64Reg regOp) { WriteSSEOp(0xF2, sseMOVUPtoRM, regOp, arg); } void XEmitter::MOVLPS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseMOVLPfromRM, regOp, arg); } void XEmitter::MOVLPD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, sseMOVLPfromRM, regOp, arg); } void XEmitter::MOVLPS(const OpArg& arg, X64Reg regOp) { WriteSSEOp(0x00, sseMOVLPtoRM, regOp, arg); } void XEmitter::MOVLPD(const OpArg& arg, X64Reg regOp) { WriteSSEOp(0x66, sseMOVLPtoRM, regOp, arg); } void XEmitter::MOVHPS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, sseMOVHPfromRM, regOp, arg); } void XEmitter::MOVHPD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, sseMOVHPfromRM, regOp, arg); } void XEmitter::MOVHPS(const OpArg& arg, X64Reg regOp) { WriteSSEOp(0x00, sseMOVHPtoRM, regOp, arg); } void XEmitter::MOVHPD(const OpArg& arg, X64Reg regOp) { WriteSSEOp(0x66, sseMOVHPtoRM, regOp, arg); } void XEmitter::MOVHLPS(X64Reg regOp1, X64Reg regOp2) { WriteSSEOp(0x00, sseMOVHLPS, regOp1, R(regOp2)); } void XEmitter::MOVLHPS(X64Reg regOp1, X64Reg regOp2) { WriteSSEOp(0x00, sseMOVLHPS, regOp1, R(regOp2)); } void XEmitter::CVTPS2PD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, 0x5A, regOp, arg); } void XEmitter::CVTPD2PS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, 0x5A, regOp, arg); } void XEmitter::CVTSD2SS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF2, 0x5A, regOp, arg); } void XEmitter::CVTSS2SD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF3, 0x5A, regOp, arg); } void XEmitter::CVTSD2SI(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF2, 0x2D, regOp, arg); } void XEmitter::CVTSS2SI(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF3, 0x2D, regOp, arg); } void XEmitter::CVTSI2SD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF2, 0x2A, regOp, arg); } void XEmitter::CVTSI2SS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF3, 0x2A, regOp, arg); } void XEmitter::CVTDQ2PD(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF3, 0xE6, regOp, arg); } void XEmitter::CVTDQ2PS(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x00, 0x5B, regOp, arg); } void XEmitter::CVTPD2DQ(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF2, 0xE6, regOp, arg); } void XEmitter::CVTPS2DQ(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, 0x5B, regOp, arg); } void XEmitter::CVTTSD2SI(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF2, 0x2C, regOp, arg); } void XEmitter::CVTTSS2SI(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF3, 0x2C, regOp, arg); } void XEmitter::CVTTPS2DQ(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0xF3, 0x5B, regOp, arg); } void XEmitter::CVTTPD2DQ(X64Reg regOp, const OpArg& arg) { WriteSSEOp(0x66, 0xE6, regOp, arg); } void XEmitter::MASKMOVDQU(X64Reg dest, X64Reg src) { WriteSSEOp(0x66, sseMASKMOVDQU, dest, R(src)); } void XEmitter::MOVMSKPS(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x00, 0x50, dest, arg); } void XEmitter::MOVMSKPD(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0x50, dest, arg); } void XEmitter::LDDQU(X64Reg dest, const OpArg& arg) { WriteSSEOp(0xF2, sseLDDQU, dest, arg); } // For integer data only void XEmitter::UNPCKLPS(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x00, 0x14, dest, arg); } void XEmitter::UNPCKHPS(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x00, 0x15, dest, arg); } void XEmitter::UNPCKLPD(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0x14, dest, arg); } void XEmitter::UNPCKHPD(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0x15, dest, arg); } // Pretty much every x86 CPU nowadays supports SSE3, // but the SSE2 fallbacks are easy. void XEmitter::MOVSLDUP(X64Reg regOp, const OpArg& arg) { if (cpu_info.bSSE3) { WriteSSEOp(0xF3, 0x12, regOp, arg); } else { if (!arg.IsSimpleReg(regOp)) MOVAPD(regOp, arg); UNPCKLPS(regOp, R(regOp)); } } void XEmitter::MOVSHDUP(X64Reg regOp, const OpArg& arg) { if (cpu_info.bSSE3) { WriteSSEOp(0xF3, 0x16, regOp, arg); } else { if (!arg.IsSimpleReg(regOp)) MOVAPD(regOp, arg); UNPCKHPS(regOp, R(regOp)); } } void XEmitter::MOVDDUP(X64Reg regOp, const OpArg& arg) { if (cpu_info.bSSE3) { WriteSSEOp(0xF2, 0x12, regOp, arg); } else { if (!arg.IsSimpleReg()) { MOVSD(regOp, arg); } else if (regOp != arg.GetSimpleReg()) { MOVAPD(regOp, arg); } UNPCKLPD(regOp, R(regOp)); } } // There are a few more left // Also some integer instructions are missing void XEmitter::PACKSSDW(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0x6B, dest, arg); } void XEmitter::PACKSSWB(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0x63, dest, arg); } void XEmitter::PACKUSWB(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0x67, dest, arg); } void XEmitter::PUNPCKLBW(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0x60, dest, arg); } void XEmitter::PUNPCKLWD(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0x61, dest, arg); } void XEmitter::PUNPCKLDQ(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0x62, dest, arg); } void XEmitter::PUNPCKLQDQ(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0x6C, dest, arg); } void XEmitter::PSRLW(X64Reg reg, int shift) { WriteSSEOp(0x66, 0x71, (X64Reg)2, R(reg)); Write8(shift); } void XEmitter::PSRLD(X64Reg reg, int shift) { WriteSSEOp(0x66, 0x72, (X64Reg)2, R(reg)); Write8(shift); } void XEmitter::PSRLQ(X64Reg reg, int shift) { WriteSSEOp(0x66, 0x73, (X64Reg)2, R(reg)); Write8(shift); } void XEmitter::PSRLQ(X64Reg reg, const OpArg& arg) { WriteSSEOp(0x66, 0xd3, reg, arg); } void XEmitter::PSRLDQ(X64Reg reg, int shift) { WriteSSEOp(0x66, 0x73, (X64Reg)3, R(reg)); Write8(shift); } void XEmitter::PSLLW(X64Reg reg, int shift) { WriteSSEOp(0x66, 0x71, (X64Reg)6, R(reg)); Write8(shift); } void XEmitter::PSLLD(X64Reg reg, int shift) { WriteSSEOp(0x66, 0x72, (X64Reg)6, R(reg)); Write8(shift); } void XEmitter::PSLLQ(X64Reg reg, int shift) { WriteSSEOp(0x66, 0x73, (X64Reg)6, R(reg)); Write8(shift); } void XEmitter::PSLLDQ(X64Reg reg, int shift) { WriteSSEOp(0x66, 0x73, (X64Reg)7, R(reg)); Write8(shift); } // WARNING not REX compatible void XEmitter::PSRAW(X64Reg reg, int shift) { if (reg > 7) PanicAlertFmt("The PSRAW-emitter does not support regs above 7"); Write8(0x66); Write8(0x0f); Write8(0x71); Write8(0xE0 | reg); Write8(shift); } // WARNING not REX compatible void XEmitter::PSRAD(X64Reg reg, int shift) { if (reg > 7) PanicAlertFmt("The PSRAD-emitter does not support regs above 7"); Write8(0x66); Write8(0x0f); Write8(0x72); Write8(0xE0 | reg); Write8(shift); } void XEmitter::WriteSSSE3Op(u8 opPrefix, u16 op, X64Reg regOp, const OpArg& arg, int extrabytes) { if (!cpu_info.bSSSE3) PanicAlertFmt("Trying to use SSSE3 on a system that doesn't support it. Bad programmer."); WriteSSEOp(opPrefix, op, regOp, arg, extrabytes); } void XEmitter::WriteSSE41Op(u8 opPrefix, u16 op, X64Reg regOp, const OpArg& arg, int extrabytes) { if (!cpu_info.bSSE4_1) PanicAlertFmt("Trying to use SSE4.1 on a system that doesn't support it. Bad programmer."); WriteSSEOp(opPrefix, op, regOp, arg, extrabytes); } void XEmitter::PSHUFB(X64Reg dest, const OpArg& arg) { WriteSSSE3Op(0x66, 0x3800, dest, arg); } void XEmitter::PTEST(X64Reg dest, const OpArg& arg) { WriteSSE41Op(0x66, 0x3817, dest, arg); } void XEmitter::PACKUSDW(X64Reg dest, const OpArg& arg) { WriteSSE41Op(0x66, 0x382b, dest, arg); } void XEmitter::PMOVSXBW(X64Reg dest, const OpArg& arg) { WriteSSE41Op(0x66, 0x3820, dest, arg); } void XEmitter::PMOVSXBD(X64Reg dest, const OpArg& arg) { WriteSSE41Op(0x66, 0x3821, dest, arg); } void XEmitter::PMOVSXBQ(X64Reg dest, const OpArg& arg) { WriteSSE41Op(0x66, 0x3822, dest, arg); } void XEmitter::PMOVSXWD(X64Reg dest, const OpArg& arg) { WriteSSE41Op(0x66, 0x3823, dest, arg); } void XEmitter::PMOVSXWQ(X64Reg dest, const OpArg& arg) { WriteSSE41Op(0x66, 0x3824, dest, arg); } void XEmitter::PMOVSXDQ(X64Reg dest, const OpArg& arg) { WriteSSE41Op(0x66, 0x3825, dest, arg); } void XEmitter::PMOVZXBW(X64Reg dest, const OpArg& arg) { WriteSSE41Op(0x66, 0x3830, dest, arg); } void XEmitter::PMOVZXBD(X64Reg dest, const OpArg& arg) { WriteSSE41Op(0x66, 0x3831, dest, arg); } void XEmitter::PMOVZXBQ(X64Reg dest, const OpArg& arg) { WriteSSE41Op(0x66, 0x3832, dest, arg); } void XEmitter::PMOVZXWD(X64Reg dest, const OpArg& arg) { WriteSSE41Op(0x66, 0x3833, dest, arg); } void XEmitter::PMOVZXWQ(X64Reg dest, const OpArg& arg) { WriteSSE41Op(0x66, 0x3834, dest, arg); } void XEmitter::PMOVZXDQ(X64Reg dest, const OpArg& arg) { WriteSSE41Op(0x66, 0x3835, dest, arg); } void XEmitter::PBLENDVB(X64Reg dest, const OpArg& arg) { WriteSSE41Op(0x66, 0x3810, dest, arg); } void XEmitter::BLENDVPS(X64Reg dest, const OpArg& arg) { WriteSSE41Op(0x66, 0x3814, dest, arg); } void XEmitter::BLENDVPD(X64Reg dest, const OpArg& arg) { WriteSSE41Op(0x66, 0x3815, dest, arg); } void XEmitter::BLENDPS(X64Reg dest, const OpArg& arg, u8 blend) { WriteSSE41Op(0x66, 0x3A0C, dest, arg, 1); Write8(blend); } void XEmitter::BLENDPD(X64Reg dest, const OpArg& arg, u8 blend) { WriteSSE41Op(0x66, 0x3A0D, dest, arg, 1); Write8(blend); } void XEmitter::PAND(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xDB, dest, arg); } void XEmitter::PANDN(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xDF, dest, arg); } void XEmitter::PXOR(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xEF, dest, arg); } void XEmitter::POR(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xEB, dest, arg); } void XEmitter::PADDB(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xFC, dest, arg); } void XEmitter::PADDW(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xFD, dest, arg); } void XEmitter::PADDD(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xFE, dest, arg); } void XEmitter::PADDQ(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xD4, dest, arg); } void XEmitter::PADDSB(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xEC, dest, arg); } void XEmitter::PADDSW(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xED, dest, arg); } void XEmitter::PADDUSB(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xDC, dest, arg); } void XEmitter::PADDUSW(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xDD, dest, arg); } void XEmitter::PSUBB(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xF8, dest, arg); } void XEmitter::PSUBW(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xF9, dest, arg); } void XEmitter::PSUBD(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xFA, dest, arg); } void XEmitter::PSUBQ(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xFB, dest, arg); } void XEmitter::PSUBSB(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xE8, dest, arg); } void XEmitter::PSUBSW(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xE9, dest, arg); } void XEmitter::PSUBUSB(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xD8, dest, arg); } void XEmitter::PSUBUSW(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xD9, dest, arg); } void XEmitter::PAVGB(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xE0, dest, arg); } void XEmitter::PAVGW(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xE3, dest, arg); } void XEmitter::PCMPEQB(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0x74, dest, arg); } void XEmitter::PCMPEQW(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0x75, dest, arg); } void XEmitter::PCMPEQD(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0x76, dest, arg); } void XEmitter::PCMPGTB(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0x64, dest, arg); } void XEmitter::PCMPGTW(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0x65, dest, arg); } void XEmitter::PCMPGTD(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0x66, dest, arg); } void XEmitter::PEXTRW(X64Reg dest, const OpArg& arg, u8 subreg) { WriteSSEOp(0x66, 0xC5, dest, arg); Write8(subreg); } void XEmitter::PINSRW(X64Reg dest, const OpArg& arg, u8 subreg) { WriteSSEOp(0x66, 0xC4, dest, arg); Write8(subreg); } void XEmitter::PINSRD(X64Reg dest, const OpArg& arg, u8 subreg) { WriteSSE41Op(0x66, 0x3A22, dest, arg); Write8(subreg); } void XEmitter::PMADDWD(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xF5, dest, arg); } void XEmitter::PSADBW(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xF6, dest, arg); } void XEmitter::PMAXSW(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xEE, dest, arg); } void XEmitter::PMAXUB(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xDE, dest, arg); } void XEmitter::PMINSW(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xEA, dest, arg); } void XEmitter::PMINUB(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xDA, dest, arg); } void XEmitter::PMOVMSKB(X64Reg dest, const OpArg& arg) { WriteSSEOp(0x66, 0xD7, dest, arg); } void XEmitter::PSHUFD(X64Reg regOp, const OpArg& arg, u8 shuffle) { WriteSSEOp(0x66, 0x70, regOp, arg, 1); Write8(shuffle); } void XEmitter::PSHUFLW(X64Reg regOp, const OpArg& arg, u8 shuffle) { WriteSSEOp(0xF2, 0x70, regOp, arg, 1); Write8(shuffle); } void XEmitter::PSHUFHW(X64Reg regOp, const OpArg& arg, u8 shuffle) { WriteSSEOp(0xF3, 0x70, regOp, arg, 1); Write8(shuffle); } // VEX void XEmitter::VADDSS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0xF3, sseADD, regOp1, regOp2, arg); } void XEmitter::VSUBSS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0xF3, sseSUB, regOp1, regOp2, arg); } void XEmitter::VMULSS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0xF3, sseMUL, regOp1, regOp2, arg); } void XEmitter::VDIVSS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0xF3, sseDIV, regOp1, regOp2, arg); } void XEmitter::VADDPS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x00, sseADD, regOp1, regOp2, arg); } void XEmitter::VSUBPS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x00, sseSUB, regOp1, regOp2, arg); } void XEmitter::VMULPS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x00, sseMUL, regOp1, regOp2, arg); } void XEmitter::VDIVPS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x00, sseDIV, regOp1, regOp2, arg); } void XEmitter::VADDSD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0xF2, sseADD, regOp1, regOp2, arg); } void XEmitter::VSUBSD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0xF2, sseSUB, regOp1, regOp2, arg); } void XEmitter::VMULSD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0xF2, sseMUL, regOp1, regOp2, arg); } void XEmitter::VDIVSD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0xF2, sseDIV, regOp1, regOp2, arg); } void XEmitter::VADDPD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x66, sseADD, regOp1, regOp2, arg); } void XEmitter::VSUBPD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x66, sseSUB, regOp1, regOp2, arg); } void XEmitter::VMULPD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x66, sseMUL, regOp1, regOp2, arg); } void XEmitter::VDIVPD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x66, sseDIV, regOp1, regOp2, arg); } void XEmitter::VSQRTSD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0xF2, sseSQRT, regOp1, regOp2, arg); } void XEmitter::VCMPPD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg, u8 compare) { WriteAVXOp(0x66, sseCMP, regOp1, regOp2, arg, 0, 1); Write8(compare); } void XEmitter::VSHUFPS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg, u8 shuffle) { WriteAVXOp(0x00, sseSHUF, regOp1, regOp2, arg, 0, 1); Write8(shuffle); } void XEmitter::VSHUFPD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg, u8 shuffle) { WriteAVXOp(0x66, sseSHUF, regOp1, regOp2, arg, 0, 1); Write8(shuffle); } void XEmitter::VUNPCKLPS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x00, 0x14, regOp1, regOp2, arg); } void XEmitter::VUNPCKLPD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x66, 0x14, regOp1, regOp2, arg); } void XEmitter::VUNPCKHPD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x66, 0x15, regOp1, regOp2, arg); } void XEmitter::VBLENDVPD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg, X64Reg regOp3) { WriteAVXOp4(0x66, 0x3A4B, regOp1, regOp2, arg, regOp3); } void XEmitter::VBLENDPS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg, u8 blend) { WriteAVXOp(0x66, 0x3A0C, regOp1, regOp2, arg, 0, 1); Write8(blend); } void XEmitter::VBLENDPD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg, u8 blend) { WriteAVXOp(0x66, 0x3A0D, regOp1, regOp2, arg, 0, 1); Write8(blend); } void XEmitter::VANDPS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x00, sseAND, regOp1, regOp2, arg); } void XEmitter::VANDPD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x66, sseAND, regOp1, regOp2, arg); } void XEmitter::VANDNPS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x00, sseANDN, regOp1, regOp2, arg); } void XEmitter::VANDNPD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x66, sseANDN, regOp1, regOp2, arg); } void XEmitter::VORPS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x00, sseOR, regOp1, regOp2, arg); } void XEmitter::VORPD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x66, sseOR, regOp1, regOp2, arg); } void XEmitter::VXORPS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x00, sseXOR, regOp1, regOp2, arg); } void XEmitter::VXORPD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x66, sseXOR, regOp1, regOp2, arg); } void XEmitter::VPAND(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x66, 0xDB, regOp1, regOp2, arg); } void XEmitter::VPANDN(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x66, 0xDF, regOp1, regOp2, arg); } void XEmitter::VPOR(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x66, 0xEB, regOp1, regOp2, arg); } void XEmitter::VPXOR(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteAVXOp(0x66, 0xEF, regOp1, regOp2, arg); } void XEmitter::VFMADD132PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x98, regOp1, regOp2, arg); } void XEmitter::VFMADD213PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xA8, regOp1, regOp2, arg); } void XEmitter::VFMADD231PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xB8, regOp1, regOp2, arg); } void XEmitter::VFMADD132PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x98, regOp1, regOp2, arg, 1); } void XEmitter::VFMADD213PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xA8, regOp1, regOp2, arg, 1); } void XEmitter::VFMADD231PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xB8, regOp1, regOp2, arg, 1); } void XEmitter::VFMADD132SS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x99, regOp1, regOp2, arg); } void XEmitter::VFMADD213SS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xA9, regOp1, regOp2, arg); } void XEmitter::VFMADD231SS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xB9, regOp1, regOp2, arg); } void XEmitter::VFMADD132SD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x99, regOp1, regOp2, arg, 1); } void XEmitter::VFMADD213SD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xA9, regOp1, regOp2, arg, 1); } void XEmitter::VFMADD231SD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xB9, regOp1, regOp2, arg, 1); } void XEmitter::VFMSUB132PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x9A, regOp1, regOp2, arg); } void XEmitter::VFMSUB213PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xAA, regOp1, regOp2, arg); } void XEmitter::VFMSUB231PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xBA, regOp1, regOp2, arg); } void XEmitter::VFMSUB132PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x9A, regOp1, regOp2, arg, 1); } void XEmitter::VFMSUB213PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xAA, regOp1, regOp2, arg, 1); } void XEmitter::VFMSUB231PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xBA, regOp1, regOp2, arg, 1); } void XEmitter::VFMSUB132SS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x9B, regOp1, regOp2, arg); } void XEmitter::VFMSUB213SS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xAB, regOp1, regOp2, arg); } void XEmitter::VFMSUB231SS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xBB, regOp1, regOp2, arg); } void XEmitter::VFMSUB132SD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x9B, regOp1, regOp2, arg, 1); } void XEmitter::VFMSUB213SD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xAB, regOp1, regOp2, arg, 1); } void XEmitter::VFMSUB231SD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xBB, regOp1, regOp2, arg, 1); } void XEmitter::VFNMADD132PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x9C, regOp1, regOp2, arg); } void XEmitter::VFNMADD213PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xAC, regOp1, regOp2, arg); } void XEmitter::VFNMADD231PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xBC, regOp1, regOp2, arg); } void XEmitter::VFNMADD132PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x9C, regOp1, regOp2, arg, 1); } void XEmitter::VFNMADD213PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xAC, regOp1, regOp2, arg, 1); } void XEmitter::VFNMADD231PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xBC, regOp1, regOp2, arg, 1); } void XEmitter::VFNMADD132SS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x9D, regOp1, regOp2, arg); } void XEmitter::VFNMADD213SS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xAD, regOp1, regOp2, arg); } void XEmitter::VFNMADD231SS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xBD, regOp1, regOp2, arg); } void XEmitter::VFNMADD132SD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x9D, regOp1, regOp2, arg, 1); } void XEmitter::VFNMADD213SD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xAD, regOp1, regOp2, arg, 1); } void XEmitter::VFNMADD231SD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xBD, regOp1, regOp2, arg, 1); } void XEmitter::VFNMSUB132PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x9E, regOp1, regOp2, arg); } void XEmitter::VFNMSUB213PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xAE, regOp1, regOp2, arg); } void XEmitter::VFNMSUB231PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xBE, regOp1, regOp2, arg); } void XEmitter::VFNMSUB132PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x9E, regOp1, regOp2, arg, 1); } void XEmitter::VFNMSUB213PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xAE, regOp1, regOp2, arg, 1); } void XEmitter::VFNMSUB231PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xBE, regOp1, regOp2, arg, 1); } void XEmitter::VFNMSUB132SS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x9F, regOp1, regOp2, arg); } void XEmitter::VFNMSUB213SS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xAF, regOp1, regOp2, arg); } void XEmitter::VFNMSUB231SS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xBF, regOp1, regOp2, arg); } void XEmitter::VFNMSUB132SD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x9F, regOp1, regOp2, arg, 1); } void XEmitter::VFNMSUB213SD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xAF, regOp1, regOp2, arg, 1); } void XEmitter::VFNMSUB231SD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xBF, regOp1, regOp2, arg, 1); } void XEmitter::VFMADDSUB132PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x96, regOp1, regOp2, arg); } void XEmitter::VFMADDSUB213PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xA6, regOp1, regOp2, arg); } void XEmitter::VFMADDSUB231PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xB6, regOp1, regOp2, arg); } void XEmitter::VFMADDSUB132PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x96, regOp1, regOp2, arg, 1); } void XEmitter::VFMADDSUB213PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xA6, regOp1, regOp2, arg, 1); } void XEmitter::VFMADDSUB231PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xB6, regOp1, regOp2, arg, 1); } void XEmitter::VFMSUBADD132PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x97, regOp1, regOp2, arg); } void XEmitter::VFMSUBADD213PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xA7, regOp1, regOp2, arg); } void XEmitter::VFMSUBADD231PS(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xB7, regOp1, regOp2, arg); } void XEmitter::VFMSUBADD132PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0x97, regOp1, regOp2, arg, 1); } void XEmitter::VFMSUBADD213PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xA7, regOp1, regOp2, arg, 1); } void XEmitter::VFMSUBADD231PD(X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteFMA3Op(0xB7, regOp1, regOp2, arg, 1); } #define FMA4(name, op) \ void XEmitter::name(X64Reg dest, X64Reg regOp1, X64Reg regOp2, const OpArg& arg) \ { \ WriteFMA4Op(op, dest, regOp1, regOp2, arg, 1); \ } \ void XEmitter::name(X64Reg dest, X64Reg regOp1, const OpArg& arg, X64Reg regOp2) \ { \ WriteFMA4Op(op, dest, regOp1, regOp2, arg, 0); \ } FMA4(VFMADDSUBPS, 0x5C) FMA4(VFMADDSUBPD, 0x5D) FMA4(VFMSUBADDPS, 0x5E) FMA4(VFMSUBADDPD, 0x5F) FMA4(VFMADDPS, 0x68) FMA4(VFMADDPD, 0x69) FMA4(VFMADDSS, 0x6A) FMA4(VFMADDSD, 0x6B) FMA4(VFMSUBPS, 0x6C) FMA4(VFMSUBPD, 0x6D) FMA4(VFMSUBSS, 0x6E) FMA4(VFMSUBSD, 0x6F) FMA4(VFNMADDPS, 0x78) FMA4(VFNMADDPD, 0x79) FMA4(VFNMADDSS, 0x7A) FMA4(VFNMADDSD, 0x7B) FMA4(VFNMSUBPS, 0x7C) FMA4(VFNMSUBPD, 0x7D) FMA4(VFNMSUBSS, 0x7E) FMA4(VFNMSUBSD, 0x7F) #undef FMA4 void XEmitter::SARX(int bits, X64Reg regOp1, const OpArg& arg, X64Reg regOp2) { WriteBMI2Op(bits, 0xF3, 0x38F7, regOp1, regOp2, arg); } void XEmitter::SHLX(int bits, X64Reg regOp1, const OpArg& arg, X64Reg regOp2) { WriteBMI2Op(bits, 0x66, 0x38F7, regOp1, regOp2, arg); } void XEmitter::SHRX(int bits, X64Reg regOp1, const OpArg& arg, X64Reg regOp2) { WriteBMI2Op(bits, 0xF2, 0x38F7, regOp1, regOp2, arg); } void XEmitter::RORX(int bits, X64Reg regOp, const OpArg& arg, u8 rotate) { WriteBMI2Op(bits, 0xF2, 0x3AF0, regOp, INVALID_REG, arg, 1); Write8(rotate); } void XEmitter::PEXT(int bits, X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteBMI2Op(bits, 0xF3, 0x38F5, regOp1, regOp2, arg); } void XEmitter::PDEP(int bits, X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteBMI2Op(bits, 0xF2, 0x38F5, regOp1, regOp2, arg); } void XEmitter::MULX(int bits, X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteBMI2Op(bits, 0xF2, 0x38F6, regOp2, regOp1, arg); } void XEmitter::BZHI(int bits, X64Reg regOp1, const OpArg& arg, X64Reg regOp2) { CheckFlags(); WriteBMI2Op(bits, 0x00, 0x38F5, regOp1, regOp2, arg); } void XEmitter::BLSR(int bits, X64Reg regOp, const OpArg& arg) { WriteBMI1Op(bits, 0x00, 0x38F3, (X64Reg)0x1, regOp, arg); } void XEmitter::BLSMSK(int bits, X64Reg regOp, const OpArg& arg) { WriteBMI1Op(bits, 0x00, 0x38F3, (X64Reg)0x2, regOp, arg); } void XEmitter::BLSI(int bits, X64Reg regOp, const OpArg& arg) { WriteBMI1Op(bits, 0x00, 0x38F3, (X64Reg)0x3, regOp, arg); } void XEmitter::BEXTR(int bits, X64Reg regOp1, const OpArg& arg, X64Reg regOp2) { WriteBMI1Op(bits, 0x00, 0x38F7, regOp1, regOp2, arg); } void XEmitter::ANDN(int bits, X64Reg regOp1, X64Reg regOp2, const OpArg& arg) { WriteBMI1Op(bits, 0x00, 0x38F2, regOp1, regOp2, arg); } // Prefixes void XEmitter::LOCK() { Write8(0xF0); } void XEmitter::REP() { Write8(0xF3); } void XEmitter::REPNE() { Write8(0xF2); } void XEmitter::FSOverride() { Write8(0x64); } void XEmitter::GSOverride() { Write8(0x65); } void XEmitter::FWAIT() { Write8(0x9B); } // TODO: make this more generic void XEmitter::WriteFloatLoadStore(int bits, FloatOp op, FloatOp op_80b, const OpArg& arg) { int mf = 0; ASSERT_MSG(DYNA_REC, !(bits == 80 && op_80b == FloatOp::Invalid), "WriteFloatLoadStore: 80 bits not supported for this instruction"); switch (bits) { case 32: mf = 0; break; case 64: mf = 4; break; case 80: mf = 2; break; default: ASSERT_MSG(DYNA_REC, 0, "WriteFloatLoadStore: invalid bits (should be 32/64/80)"); } Write8(0xd9 | mf); // x87 instructions use the reg field of the ModR/M byte as opcode: if (bits == 80) op = op_80b; arg.WriteRest(this, 0, static_cast<X64Reg>(op)); } void XEmitter::FLD(int bits, const OpArg& src) { WriteFloatLoadStore(bits, FloatOp::LD, FloatOp::LD80, src); } void XEmitter::FST(int bits, const OpArg& dest) { WriteFloatLoadStore(bits, FloatOp::ST, FloatOp::Invalid, dest); } void XEmitter::FSTP(int bits, const OpArg& dest) { WriteFloatLoadStore(bits, FloatOp::STP, FloatOp::STP80, dest); } void XEmitter::FNSTSW_AX() { Write8(0xDF); Write8(0xE0); } void XEmitter::RDTSC() { Write8(0x0F); Write8(0x31); } } // namespace Gen
pierrewillenbrock/dolphin
Source/Core/Common/x64Emitter.cpp
C++
gpl-2.0
84,130
package com.ezest.javafx.vijaysimha; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.scene.shape.ArcBuilder; import javafx.scene.shape.ArcToBuilder; import javafx.scene.shape.ArcType; import javafx.scene.shape.CircleBuilder; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.scene.shape.PathBuilder; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.TextBuilder; import javafx.stage.Stage; /** * http://www.hameister.org/JavaFX_Dartboard.html * @author hameister */ public class JavaFX_DartBoard extends Application { // Base for the board size is 400px // The FACTOR_SIZE can be used to change the size of the board private final static double FACTOR_SIZE = 1.0d; private final static double BORDER_SIZE = 50; private final static double WIDTH = (400 + BORDER_SIZE) * FACTOR_SIZE; private final static double HEIGHT = (400 + BORDER_SIZE) * FACTOR_SIZE; private static double OUTER_DOUBLE_RING = 170.0d * FACTOR_SIZE; private static double INNER_DOUBLE_RING = 162.0d * FACTOR_SIZE; private static double OUTER_TRIPLE_RING = 107.0d * FACTOR_SIZE; private static double INNER_TRIPLE_RING = 99.0d * FACTOR_SIZE; private static double BULL = (31.8d / 2) * FACTOR_SIZE; private static double BULLS_EYE = (12.7d / 2) * FACTOR_SIZE; private static double CENTER_X = WIDTH / 2; private static double CENTER_Y = HEIGHT / 2; private static double POSITION_NUMBERS = 200 * FACTOR_SIZE; private final static int ROTATE_ANGLE_DEGREES = 18; // 18 Degrees per field private static int ROTATE_ANGLE_DEGREES_OFFSET = ROTATE_ANGLE_DEGREES / 2; // 9 Degrees per field private static final String[] DARTBOARD_NUMBERS = { "20", "1", "18", "4", "13", "6", "10", "15", "2", "17", "3", "19", "7", "16", "8", "11", "14", "9", "12", "5" }; private static final int FONT_SIZE = 20; @Override public void start(Stage primaryStage) { Pane root = new Pane(); String doubleTripleStyle; String fieldStyle; for (int i = 0; i < DARTBOARD_NUMBERS.length; i++) { if (i % 2 == 0) { doubleTripleStyle = "double-triple-style-green"; fieldStyle = "field-style-light"; } else { doubleTripleStyle = "double-triple-style-red"; fieldStyle = "field-style-dark"; } // Create double rings root.getChildren().add( createDartboardField( i * ROTATE_ANGLE_DEGREES + ROTATE_ANGLE_DEGREES_OFFSET, (i + 1) * ROTATE_ANGLE_DEGREES + ROTATE_ANGLE_DEGREES_OFFSET, INNER_DOUBLE_RING, OUTER_DOUBLE_RING, doubleTripleStyle)); // Create triple rings root.getChildren().add( createDartboardField( i * ROTATE_ANGLE_DEGREES + ROTATE_ANGLE_DEGREES_OFFSET, (i + 1) * ROTATE_ANGLE_DEGREES + ROTATE_ANGLE_DEGREES_OFFSET, INNER_TRIPLE_RING, OUTER_TRIPLE_RING, doubleTripleStyle)); // Create outer fields root.getChildren().add( createDartboardField( i * ROTATE_ANGLE_DEGREES + ROTATE_ANGLE_DEGREES_OFFSET, (i + 1) * ROTATE_ANGLE_DEGREES + ROTATE_ANGLE_DEGREES_OFFSET, OUTER_TRIPLE_RING, INNER_DOUBLE_RING, fieldStyle)); // Create inner fields root.getChildren().add( createDartboardField( i * ROTATE_ANGLE_DEGREES + ROTATE_ANGLE_DEGREES_OFFSET, (i + 1) * ROTATE_ANGLE_DEGREES + ROTATE_ANGLE_DEGREES_OFFSET, BULL, INNER_TRIPLE_RING, fieldStyle)); } // Create Bull root.getChildren().add(ArcBuilder.create() .centerX(CENTER_X) .centerY(CENTER_Y) .type(ArcType.OPEN) .radiusX(BULL) .radiusY(BULL) .strokeWidth(BULL - BULLS_EYE) .styleClass("bull-style") .length(360) .build()); // Create Bulls Eye root.getChildren().add(ArcBuilder .create() .centerX(CENTER_X) .centerY(CENTER_Y) .type(ArcType.OPEN) .radiusX(BULLS_EYE) .radiusY(BULLS_EYE) .strokeWidth(BULLS_EYE) .styleClass("bulls-eye-style") .length(360) .build()); //Yellow circles around Bull root.getChildren().add(CircleBuilder .create() .centerX(CENTER_X) .centerY(CENTER_Y) .radius(BULL) .styleClass("border-line") .build()); //Yellow circles around Bulls eye root.getChildren().add(CircleBuilder .create() .centerX(CENTER_X) .centerY(CENTER_Y) .radius(BULLS_EYE) .styleClass("border-line") .build()); paintNumbers(root); Scene scene = new Scene(root, WIDTH, HEIGHT); primaryStage.setTitle("Dartboard"); primaryStage.setScene(scene); scene.getStylesheets().add("styles/dartboard/theme2.css"); primaryStage.show(); } /** * Find the center on the X-Axis of the text. Is used to position the text * at the correct x position on the board. */ private double calculateTextOffsetX(String text, double fontSize) { return (text.length() / 2) + fontSize * 0.5; } /** * Find the center on the Y-Axis of the text. Is used to position the text * at the correct y position on the board. */ private double calculateTextOffsetY(double fontSize) { return (fontSize / 2) - fontSize * 0.4; } private void paintNumbers(Pane root) { TextBuilder textBuilder = TextBuilder.create() .font(Font.font("Verdana", FontWeight.BOLD, FONT_SIZE * FACTOR_SIZE)) .styleClass("text-surround"); for (int i = 0; i < DARTBOARD_NUMBERS.length; i++) { double degreeStart = i * ROTATE_ANGLE_DEGREES; double angleAlpha = degreeStart * (Math.PI / 180); double pointX1 = CENTER_X + POSITION_NUMBERS * Math.sin(angleAlpha) - calculateTextOffsetX(DARTBOARD_NUMBERS[i], FONT_SIZE); double pointY1 = CENTER_Y - POSITION_NUMBERS * Math.cos(angleAlpha) + calculateTextOffsetY(FONT_SIZE); root.getChildren().add( textBuilder .x(pointX1) .y(pointY1) .text(DARTBOARD_NUMBERS[i]) .build() ); } } private Path createDartboardField(double degreeStart, double degreeEnd, double innerRadius, double outerRadius, String style) { double angleAlpha = degreeStart * (Math.PI / 180); double angleAlphaNext = degreeEnd * (Math.PI / 180); //Point 1 double pointX1 = CENTER_X + innerRadius * Math.sin(angleAlpha); double pointY1 = CENTER_Y - innerRadius * Math.cos(angleAlpha); //Point 2 double pointX2 = CENTER_X + outerRadius * Math.sin(angleAlpha); double pointY2 = CENTER_Y - outerRadius * Math.cos(angleAlpha); //Point 3 double pointX3 = CENTER_X + outerRadius * Math.sin(angleAlphaNext); double pointY3 = CENTER_Y - outerRadius * Math.cos(angleAlphaNext); //Point 4 double pointX4 = CENTER_X + innerRadius * Math.sin(angleAlphaNext); double pointY4 = CENTER_Y - innerRadius * Math.cos(angleAlphaNext); Path path = PathBuilder.create() .styleClass(style) .elements( new MoveTo(pointX1, pointY1), new LineTo(pointX2, pointY2), ArcToBuilder .create() .radiusX(outerRadius) .radiusY(outerRadius) .x(pointX3) .y(pointY3) .sweepFlag(true) .build(), new LineTo(pointX4, pointY4), ArcToBuilder .create() .radiusX(innerRadius) .radiusY(innerRadius) .x(pointX1) .y(pointY1) .sweepFlag(false) .build()) .build(); return path; } public static void main(String[] args) { launch(args); } }
SaiPradeepDandem/javafx-demos
src/main/java/com/ezest/javafx/vijaysimha/JavaFX_DartBoard.java
Java
gpl-2.0
9,388
<?php /* core/modules/system/templates/field-multiple-value-form.html.twig */ class __TwigTemplate_b12b1c5d9d9971d9b4b2bae595e0b002dd20d229bfbb3037426b14b4cbe8a301 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 22 if ((isset($context["multiple"]) ? $context["multiple"] : null)) { // line 23 echo " <div class=\"form-item\"> "; // line 24 echo twig_drupal_escape_filter($this->env, (isset($context["table"]) ? $context["table"] : null), "html", null, true); echo " "; // line 25 if ((isset($context["description"]) ? $context["description"] : null)) { // line 26 echo " <div class=\"description\">"; echo twig_drupal_escape_filter($this->env, (isset($context["description"]) ? $context["description"] : null), "html", null, true); echo "</div> "; } // line 28 echo " "; if ((isset($context["button"]) ? $context["button"] : null)) { // line 29 echo " <div class=\"clearfix\">"; echo twig_drupal_escape_filter($this->env, (isset($context["button"]) ? $context["button"] : null), "html", null, true); echo "</div> "; } // line 31 echo " </div> "; } else { // line 33 echo " "; $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable((isset($context["elements"]) ? $context["elements"] : null)); foreach ($context['_seq'] as $context["_key"] => $context["element"]) { // line 34 echo " "; echo twig_drupal_escape_filter($this->env, (isset($context["element"]) ? $context["element"] : null), "html", null, true); echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['element'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; } } public function getTemplateName() { return "core/modules/system/templates/field-multiple-value-form.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 54 => 34, 30 => 26, 52 => 35, 50 => 34, 45 => 31, 42 => 31, 37 => 29, 31 => 28, 47 => 25, 43 => 24, 36 => 28, 59 => 36, 48 => 38, 44 => 37, 39 => 29, 26 => 27, 24 => 24, 23 => 16, 109 => 106, 106 => 105, 100 => 102, 97 => 101, 95 => 100, 89 => 97, 83 => 96, 79 => 94, 73 => 91, 70 => 90, 68 => 89, 64 => 38, 60 => 27, 57 => 86, 55 => 85, 49 => 33, 41 => 80, 34 => 79, 32 => 78, 28 => 25, 29 => 24, 21 => 23, 19 => 22,); } }
rujiali/cooking4
sites/default/files/php/twig/1#b1#2b#1c5d9d9971d9b4b2bae595e0b002dd20d229bfbb3037426b14b4cbe8a301/c1a8964f766259bc17d15542bb592bad06be875f8a19520329e296b6be3013f7.php
PHP
gpl-2.0
3,196
<html> <head> <title>Templating System Tag Reference: Switch</title> </head> <body bgcolor="#ffffff"> <h2>Switch</h2> <a href="..">Templating System</a> : <a href="../designer-guide.html">Designer Guide</a> : <a href="index.html">Tag Reference</a> : Switch <hr> <h3>Summary</h3> <p>The <kbd>switch</kbd> tag is used to output one of n-sections when the switch variable matches one of the n-case statements. A default section can also be output if none of the n-case statements matches the switch variable.</p> <h3>Usage Examples</h3> <pre> &lt;switch @x@&gt; &lt;case value="Fred"&gt; Hello Fred. &lt;/case&gt; &lt;case value="Greta"&gt; Hello Greta. &lt;/case&gt; &lt;case value="Sam"&gt; Hello Sam &lt;/case&gt; &lt;default&gt; I don't recognize your name. &lt;/default&gt; &lt;/switch&gt; </pre> <p>Tcl-equivalent flags have the same meaning as in the tcl-switch statement. Supported flags include exact, glob, and regexp.</p> <pre> &lt;switch flag=glob @x@&gt; &lt;case value="F*"&gt; Hello Fred. &lt;/case&gt; &lt;case value="G*"&gt; Hello Greta. &lt;/case&gt; &lt;case value="H*"&gt; Hello Sam &lt;/case&gt; &lt;default&gt; You are in the section for people whose names start with F, G, or H. &lt;/default&gt; &lt;/switch&gt; </pre> <p> Case tags also have an alternative form for matching a list of items.</p> <p> <pre> &lt;switch @x@&gt; &lt;case in "Fred" "Greta" "Sam"&gt; Your must be Fred Greta or Sam, but I'm not sure which one. &lt;/case&gt; &lt;default&gt; I don't recognize your name. &lt;/default&gt; &lt;/switch&gt; </pre> <p> <h3>Notes</h3> <ul> <li><p>Any legal variables that may be referenced in the template may also be used in <kbd>switch</kbd> statements. <li><p>Phrases with spaces in them must be enclosed in double quotes and curly braces to be matched correctly. Failure to quote words with spaces correctly results in an error. <pre> &lt;case "{blue sky}"> &lt;td bgcolor="#0000ff"> &lt;/case></pre> </ul> <hr> <!-- <a href="mailto:templating@arsdigita.com">templating@arsdigita.com</a> -->
openacs/openacs-core
packages/acs-templating/www/doc/tagref/switch.html
HTML
gpl-2.0
2,251
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DevExpress.Data.Filtering; using DevExpress.ExpressApp; using DevExpress.ExpressApp.Actions; using DevExpress.ExpressApp.Editors; using DevExpress.ExpressApp.Layout; using DevExpress.ExpressApp.Model.NodeGenerators; using DevExpress.ExpressApp.SystemModule; using DevExpress.ExpressApp.Templates; using DevExpress.ExpressApp.Utils; using DevExpress.Persistent.Base; using DevExpress.Persistent.Validation; using Vinabits_OM_2017.Module.BusinessObjects; using DevExpress.ExpressApp.Web.Editors.ASPx; using DevExpress.Web; using DevExpress.Data; namespace Vinabits_OM_2017.Module.Web.Controllers { // For more typical usage scenarios, be sure to check out https://documentation.devexpress.com/eXpressAppFramework/clsDevExpressExpressAppViewControllertopic.aspx. public partial class DocumentListviewViewController : ViewController { public DocumentListviewViewController() { InitializeComponent(); TargetObjectType = typeof(Document); TargetViewType = ViewType.ListView; TargetViewNesting = Nesting.Root; } protected override void OnActivated() { base.OnActivated(); View.SelectionChanged += View_SelectionChanged; this.actReadMark.Execute += ActReadMark_Execute; this.actUnreadMark.Execute += ActUnreadMark_Execute; this.actFeatureUnmark.Execute += ActFeatureUnmark_Execute; this.actFeatureMarked.Execute += ActFeatureMarked_Execute; refreshActionState(); } private void ActUnreadMark_Execute(object sender, SimpleActionExecuteEventArgs e) { ReadUnread(false, e); } private void ActReadMark_Execute(object sender, SimpleActionExecuteEventArgs e) { ReadUnread(true, e); } private void ActFeatureUnmark_Execute(object sender, SimpleActionExecuteEventArgs e) { FeatureMarked(false, e); } private void View_SelectionChanged(object sender, EventArgs e) { refreshActionState(); } private void refreshActionState() { if (View != null && View.SelectedObjects != null && View.SelectedObjects.Count > 0) { this.actFeatureMarked.Enabled.SetItemValue("buttonStateFeature", true); this.actFeatureUnmark.Enabled.SetItemValue("buttonStateFeatureUnMark", true); this.actReadMark.Enabled.SetItemValue("buttonStateRead", true); this.actUnreadMark.Enabled.SetItemValue("buttonStateUnread", true); } else { this.actFeatureMarked.Enabled.SetItemValue("buttonStateFeature", false); this.actFeatureUnmark.Enabled.SetItemValue("buttonStateFeatureUnMark", false); this.actReadMark.Enabled.SetItemValue("buttonStateRead", false); this.actUnreadMark.Enabled.SetItemValue("buttonStateUnread", false); } } private void ActFeatureMarked_Execute(object sender, SimpleActionExecuteEventArgs e) { FeatureMarked(true, e); } private void FeatureMarked(bool isFeature, SimpleActionExecuteEventArgs e) { Employee curEmp = SecuritySystem.CurrentUser as Employee; foreach (Document selectDoc in e.SelectedObjects) { CriteriaOperator crit = CriteriaOperator.And(new BinaryOperator("LinkEmployee.Oid", curEmp.Oid), new BinaryOperator("LinkDocument.Oid", selectDoc.Oid)); DocumentEmployees docEmp = View.ObjectSpace.FindObject<DocumentEmployees>(crit); if (docEmp != null) { //The Action's state is updated when objects in Views change their values. This work is done by the ActionsCriteriaViewController docEmp.IsFollow = isFeature; docEmp.Save(); docEmp.Session.CommitTransaction(); ASPxGridListEditor listEditor = ((ListView)View).Editor as ASPxGridListEditor; if (listEditor != null) listEditor.UnselectAll(); //View.SelectedObjects.Clear(); //View.Refresh(); } } } private void ReadUnread(bool isRead, SimpleActionExecuteEventArgs e) { Employee curEmp = SecuritySystem.CurrentUser as Employee; foreach (Document selectDoc in e.SelectedObjects) { CriteriaOperator crit = CriteriaOperator.And(new BinaryOperator("LinkEmployee.Oid", curEmp.Oid), new BinaryOperator("LinkDocument.Oid", selectDoc.Oid)); DocumentEmployees docEmp = View.ObjectSpace.FindObject<DocumentEmployees>(crit); if (docEmp != null) { //The Action's state is updated when objects in Views change their values. This work is done by the ActionsCriteriaViewController docEmp.DateRead = isRead ? (docEmp.DateRead > DateTime.MinValue ? docEmp.DateRead : DateTime.Now): DateTime.MinValue; docEmp.Save(); docEmp.Session.CommitTransaction(); ASPxGridListEditor listEditor = ((ListView)View).Editor as ASPxGridListEditor; if (listEditor != null) listEditor.UnselectAll(); //View.SelectedObjects.Clear(); //View.Refresh(); } } } protected override void OnViewControlsCreated() { base.OnViewControlsCreated(); // Access and customize the target View control. // Thêm số thứ tự ListView dv = (ListView)View; ASPxGridListEditor gridListEditor = dv.Editor as ASPxGridListEditor; if (gridListEditor != null) { ASPxGridView gridView = gridListEditor.Grid; // reset the VisibleIndxe start from 1, 0 will be use for ItemNo for (int j = gridView.VisibleColumns.Count - 1; j >= 0; j--) { if (gridView.VisibleColumns[j].VisibleIndex > 0) { gridView.VisibleColumns[j].VisibleIndex = gridView.VisibleColumns[j].VisibleIndex + 1; } } // to add the ItemNo for each row if (gridView.Columns["itemNo"] == null) { GridViewDataTextColumn itemNo = new GridViewDataTextColumn(); itemNo.Caption = "STT"; itemNo.ReadOnly = true; itemNo.UnboundType = UnboundColumnType.String; itemNo.Width = 32; gridView.Columns.Add(itemNo); itemNo.VisibleIndex = 1; } gridView.CustomColumnDisplayText += GridView_CustomColumnDisplayText; ; } } private void GridView_CustomColumnDisplayText(object sender, ASPxGridViewColumnDisplayTextEventArgs e) { if (e.Column.Caption == "STT") { ASPxGridView gridView = (ASPxGridView)sender; e.DisplayText = (e.VisibleIndex + 1).ToString(); } } protected override void OnDeactivated() { this.actReadMark.Execute -= ActReadMark_Execute; this.actUnreadMark.Execute -= ActUnreadMark_Execute; this.actFeatureMarked.Execute -= ActFeatureMarked_Execute; this.actFeatureUnmark.Execute -= ActFeatureUnmark_Execute; // Unsubscribe from previously subscribed events and release other references and resources. base.OnDeactivated(); } } }
daltonnyx/Vinabits_OM
Vinabits_OM_2017.Module.Web/Controllers/Vanban/DocumentListviewViewController.cs
C#
gpl-2.0
8,054
/* * Copyright (c) 2000-2005 Silicon Graphics, Inc. * 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. * * This program is distributed in the hope that it would 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 the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "xfs.h" #include "xfs_fs.h" #include "xfs_shared.h" #include "xfs_format.h" #include "xfs_log_format.h" #include "xfs_trans_resv.h" #include "xfs_mount.h" #include "xfs_error.h" #include "xfs_trans.h" #include "xfs_trans_priv.h" #include "xfs_log.h" #include "xfs_log_priv.h" #include "xfs_log_recover.h" #include "xfs_inode.h" #include "xfs_trace.h" #include "xfs_fsops.h" #include "xfs_cksum.h" #include "xfs_sysfs.h" #include "xfs_sb.h" kmem_zone_t *xfs_log_ticket_zone; /* Local miscellaneous function prototypes */ STATIC int xlog_commit_record( struct xlog *log, struct xlog_ticket *ticket, struct xlog_in_core **iclog, xfs_lsn_t *commitlsnp); STATIC struct xlog * xlog_alloc_log( struct xfs_mount *mp, struct xfs_buftarg *log_target, xfs_daddr_t blk_offset, int num_bblks); STATIC int xlog_space_left( struct xlog *log, atomic64_t *head); STATIC int xlog_sync( struct xlog *log, struct xlog_in_core *iclog); STATIC void xlog_dealloc_log( struct xlog *log); /* local state machine functions */ STATIC void xlog_state_done_syncing(xlog_in_core_t *iclog, int); STATIC void xlog_state_do_callback( struct xlog *log, int aborted, struct xlog_in_core *iclog); STATIC int xlog_state_get_iclog_space( struct xlog *log, int len, struct xlog_in_core **iclog, struct xlog_ticket *ticket, int *continued_write, int *logoffsetp); STATIC int xlog_state_release_iclog( struct xlog *log, struct xlog_in_core *iclog); STATIC void xlog_state_switch_iclogs( struct xlog *log, struct xlog_in_core *iclog, int eventual_size); STATIC void xlog_state_want_sync( struct xlog *log, struct xlog_in_core *iclog); STATIC void xlog_grant_push_ail( struct xlog *log, int need_bytes); STATIC void xlog_regrant_reserve_log_space( struct xlog *log, struct xlog_ticket *ticket); STATIC void xlog_ungrant_log_space( struct xlog *log, struct xlog_ticket *ticket); #if defined(DEBUG) STATIC void xlog_verify_dest_ptr( struct xlog *log, void *ptr); STATIC void xlog_verify_grant_tail( struct xlog *log); STATIC void xlog_verify_iclog( struct xlog *log, struct xlog_in_core *iclog, int count, bool syncing); STATIC void xlog_verify_tail_lsn( struct xlog *log, struct xlog_in_core *iclog, xfs_lsn_t tail_lsn); #else #define xlog_verify_dest_ptr(a,b) #define xlog_verify_grant_tail(a) #define xlog_verify_iclog(a,b,c,d) #define xlog_verify_tail_lsn(a,b,c) #endif STATIC int xlog_iclogs_empty( struct xlog *log); static void xlog_grant_sub_space( struct xlog *log, atomic64_t *head, int bytes) { int64_t head_val = atomic64_read(head); int64_t new, old; do { int cycle, space; xlog_crack_grant_head_val(head_val, &cycle, &space); space -= bytes; if (space < 0) { space += log->l_logsize; cycle--; } old = head_val; new = xlog_assign_grant_head_val(cycle, space); head_val = atomic64_cmpxchg(head, old, new); } while (head_val != old); } static void xlog_grant_add_space( struct xlog *log, atomic64_t *head, int bytes) { int64_t head_val = atomic64_read(head); int64_t new, old; do { int tmp; int cycle, space; xlog_crack_grant_head_val(head_val, &cycle, &space); tmp = log->l_logsize - space; if (tmp > bytes) space += bytes; else { space = bytes - tmp; cycle++; } old = head_val; new = xlog_assign_grant_head_val(cycle, space); head_val = atomic64_cmpxchg(head, old, new); } while (head_val != old); } STATIC void xlog_grant_head_init( struct xlog_grant_head *head) { xlog_assign_grant_head(&head->grant, 1, 0); INIT_LIST_HEAD(&head->waiters); spin_lock_init(&head->lock); } STATIC void xlog_grant_head_wake_all( struct xlog_grant_head *head) { struct xlog_ticket *tic; spin_lock(&head->lock); list_for_each_entry(tic, &head->waiters, t_queue) wake_up_process(tic->t_task); spin_unlock(&head->lock); } static inline int xlog_ticket_reservation( struct xlog *log, struct xlog_grant_head *head, struct xlog_ticket *tic) { if (head == &log->l_write_head) { ASSERT(tic->t_flags & XLOG_TIC_PERM_RESERV); return tic->t_unit_res; } else { if (tic->t_flags & XLOG_TIC_PERM_RESERV) return tic->t_unit_res * tic->t_cnt; else return tic->t_unit_res; } } STATIC bool xlog_grant_head_wake( struct xlog *log, struct xlog_grant_head *head, int *free_bytes) { struct xlog_ticket *tic; int need_bytes; list_for_each_entry(tic, &head->waiters, t_queue) { need_bytes = xlog_ticket_reservation(log, head, tic); if (*free_bytes < need_bytes) return false; *free_bytes -= need_bytes; trace_xfs_log_grant_wake_up(log, tic); wake_up_process(tic->t_task); } return true; } STATIC int xlog_grant_head_wait( struct xlog *log, struct xlog_grant_head *head, struct xlog_ticket *tic, int need_bytes) __releases(&head->lock) __acquires(&head->lock) { list_add_tail(&tic->t_queue, &head->waiters); do { if (XLOG_FORCED_SHUTDOWN(log)) goto shutdown; xlog_grant_push_ail(log, need_bytes); __set_current_state(TASK_UNINTERRUPTIBLE); spin_unlock(&head->lock); XFS_STATS_INC(log->l_mp, xs_sleep_logspace); trace_xfs_log_grant_sleep(log, tic); schedule(); trace_xfs_log_grant_wake(log, tic); spin_lock(&head->lock); if (XLOG_FORCED_SHUTDOWN(log)) goto shutdown; } while (xlog_space_left(log, &head->grant) < need_bytes); list_del_init(&tic->t_queue); return 0; shutdown: list_del_init(&tic->t_queue); return -EIO; } /* * Atomically get the log space required for a log ticket. * * Once a ticket gets put onto head->waiters, it will only return after the * needed reservation is satisfied. * * This function is structured so that it has a lock free fast path. This is * necessary because every new transaction reservation will come through this * path. Hence any lock will be globally hot if we take it unconditionally on * every pass. * * As tickets are only ever moved on and off head->waiters under head->lock, we * only need to take that lock if we are going to add the ticket to the queue * and sleep. We can avoid taking the lock if the ticket was never added to * head->waiters because the t_queue list head will be empty and we hold the * only reference to it so it can safely be checked unlocked. */ STATIC int xlog_grant_head_check( struct xlog *log, struct xlog_grant_head *head, struct xlog_ticket *tic, int *need_bytes) { int free_bytes; int error = 0; ASSERT(!(log->l_flags & XLOG_ACTIVE_RECOVERY)); /* * If there are other waiters on the queue then give them a chance at * logspace before us. Wake up the first waiters, if we do not wake * up all the waiters then go to sleep waiting for more free space, * otherwise try to get some space for this transaction. */ *need_bytes = xlog_ticket_reservation(log, head, tic); free_bytes = xlog_space_left(log, &head->grant); if (!list_empty_careful(&head->waiters)) { spin_lock(&head->lock); if (!xlog_grant_head_wake(log, head, &free_bytes) || free_bytes < *need_bytes) { error = xlog_grant_head_wait(log, head, tic, *need_bytes); } spin_unlock(&head->lock); } else if (free_bytes < *need_bytes) { spin_lock(&head->lock); error = xlog_grant_head_wait(log, head, tic, *need_bytes); spin_unlock(&head->lock); } return error; } static void xlog_tic_reset_res(xlog_ticket_t *tic) { tic->t_res_num = 0; tic->t_res_arr_sum = 0; tic->t_res_num_ophdrs = 0; } static void xlog_tic_add_region(xlog_ticket_t *tic, uint len, uint type) { if (tic->t_res_num == XLOG_TIC_LEN_MAX) { /* add to overflow and start again */ tic->t_res_o_flow += tic->t_res_arr_sum; tic->t_res_num = 0; tic->t_res_arr_sum = 0; } tic->t_res_arr[tic->t_res_num].r_len = len; tic->t_res_arr[tic->t_res_num].r_type = type; tic->t_res_arr_sum += len; tic->t_res_num++; } /* * Replenish the byte reservation required by moving the grant write head. */ int xfs_log_regrant( struct xfs_mount *mp, struct xlog_ticket *tic) { struct xlog *log = mp->m_log; int need_bytes; int error = 0; if (XLOG_FORCED_SHUTDOWN(log)) return -EIO; XFS_STATS_INC(mp, xs_try_logspace); /* * This is a new transaction on the ticket, so we need to change the * transaction ID so that the next transaction has a different TID in * the log. Just add one to the existing tid so that we can see chains * of rolling transactions in the log easily. */ tic->t_tid++; xlog_grant_push_ail(log, tic->t_unit_res); tic->t_curr_res = tic->t_unit_res; xlog_tic_reset_res(tic); if (tic->t_cnt > 0) return 0; trace_xfs_log_regrant(log, tic); error = xlog_grant_head_check(log, &log->l_write_head, tic, &need_bytes); if (error) goto out_error; xlog_grant_add_space(log, &log->l_write_head.grant, need_bytes); trace_xfs_log_regrant_exit(log, tic); xlog_verify_grant_tail(log); return 0; out_error: /* * If we are failing, make sure the ticket doesn't have any current * reservations. We don't want to add this back when the ticket/ * transaction gets cancelled. */ tic->t_curr_res = 0; tic->t_cnt = 0; /* ungrant will give back unit_res * t_cnt. */ return error; } /* * Reserve log space and return a ticket corresponding the reservation. * * Each reservation is going to reserve extra space for a log record header. * When writes happen to the on-disk log, we don't subtract the length of the * log record header from any reservation. By wasting space in each * reservation, we prevent over allocation problems. */ int xfs_log_reserve( struct xfs_mount *mp, int unit_bytes, int cnt, struct xlog_ticket **ticp, uint8_t client, bool permanent) { struct xlog *log = mp->m_log; struct xlog_ticket *tic; int need_bytes; int error = 0; ASSERT(client == XFS_TRANSACTION || client == XFS_LOG); if (XLOG_FORCED_SHUTDOWN(log)) return -EIO; XFS_STATS_INC(mp, xs_try_logspace); ASSERT(*ticp == NULL); tic = xlog_ticket_alloc(log, unit_bytes, cnt, client, permanent, KM_SLEEP | KM_MAYFAIL); if (!tic) return -ENOMEM; *ticp = tic; xlog_grant_push_ail(log, tic->t_cnt ? tic->t_unit_res * tic->t_cnt : tic->t_unit_res); trace_xfs_log_reserve(log, tic); error = xlog_grant_head_check(log, &log->l_reserve_head, tic, &need_bytes); if (error) goto out_error; xlog_grant_add_space(log, &log->l_reserve_head.grant, need_bytes); xlog_grant_add_space(log, &log->l_write_head.grant, need_bytes); trace_xfs_log_reserve_exit(log, tic); xlog_verify_grant_tail(log); return 0; out_error: /* * If we are failing, make sure the ticket doesn't have any current * reservations. We don't want to add this back when the ticket/ * transaction gets cancelled. */ tic->t_curr_res = 0; tic->t_cnt = 0; /* ungrant will give back unit_res * t_cnt. */ return error; } /* * NOTES: * * 1. currblock field gets updated at startup and after in-core logs * marked as with WANT_SYNC. */ /* * This routine is called when a user of a log manager ticket is done with * the reservation. If the ticket was ever used, then a commit record for * the associated transaction is written out as a log operation header with * no data. The flag XLOG_TIC_INITED is set when the first write occurs with * a given ticket. If the ticket was one with a permanent reservation, then * a few operations are done differently. Permanent reservation tickets by * default don't release the reservation. They just commit the current * transaction with the belief that the reservation is still needed. A flag * must be passed in before permanent reservations are actually released. * When these type of tickets are not released, they need to be set into * the inited state again. By doing this, a start record will be written * out when the next write occurs. */ xfs_lsn_t xfs_log_done( struct xfs_mount *mp, struct xlog_ticket *ticket, struct xlog_in_core **iclog, bool regrant) { struct xlog *log = mp->m_log; xfs_lsn_t lsn = 0; if (XLOG_FORCED_SHUTDOWN(log) || /* * If nothing was ever written, don't write out commit record. * If we get an error, just continue and give back the log ticket. */ (((ticket->t_flags & XLOG_TIC_INITED) == 0) && (xlog_commit_record(log, ticket, iclog, &lsn)))) { lsn = (xfs_lsn_t) -1; regrant = false; } if (!regrant) { trace_xfs_log_done_nonperm(log, ticket); /* * Release ticket if not permanent reservation or a specific * request has been made to release a permanent reservation. */ xlog_ungrant_log_space(log, ticket); } else { trace_xfs_log_done_perm(log, ticket); xlog_regrant_reserve_log_space(log, ticket); /* If this ticket was a permanent reservation and we aren't * trying to release it, reset the inited flags; so next time * we write, a start record will be written out. */ ticket->t_flags |= XLOG_TIC_INITED; } xfs_log_ticket_put(ticket); return lsn; } /* * Attaches a new iclog I/O completion callback routine during * transaction commit. If the log is in error state, a non-zero * return code is handed back and the caller is responsible for * executing the callback at an appropriate time. */ int xfs_log_notify( struct xfs_mount *mp, struct xlog_in_core *iclog, xfs_log_callback_t *cb) { int abortflg; spin_lock(&iclog->ic_callback_lock); abortflg = (iclog->ic_state & XLOG_STATE_IOERROR); if (!abortflg) { ASSERT_ALWAYS((iclog->ic_state == XLOG_STATE_ACTIVE) || (iclog->ic_state == XLOG_STATE_WANT_SYNC)); cb->cb_next = NULL; *(iclog->ic_callback_tail) = cb; iclog->ic_callback_tail = &(cb->cb_next); } spin_unlock(&iclog->ic_callback_lock); return abortflg; } int xfs_log_release_iclog( struct xfs_mount *mp, struct xlog_in_core *iclog) { if (xlog_state_release_iclog(mp->m_log, iclog)) { xfs_force_shutdown(mp, SHUTDOWN_LOG_IO_ERROR); return -EIO; } return 0; } /* * Mount a log filesystem * * mp - ubiquitous xfs mount point structure * log_target - buftarg of on-disk log device * blk_offset - Start block # where block size is 512 bytes (BBSIZE) * num_bblocks - Number of BBSIZE blocks in on-disk log * * Return error or zero. */ int xfs_log_mount( xfs_mount_t *mp, xfs_buftarg_t *log_target, xfs_daddr_t blk_offset, int num_bblks) { int error = 0; int min_logfsbs; if (!(mp->m_flags & XFS_MOUNT_NORECOVERY)) { xfs_notice(mp, "Mounting V%d Filesystem", XFS_SB_VERSION_NUM(&mp->m_sb)); } else { xfs_notice(mp, "Mounting V%d filesystem in no-recovery mode. Filesystem will be inconsistent.", XFS_SB_VERSION_NUM(&mp->m_sb)); ASSERT(mp->m_flags & XFS_MOUNT_RDONLY); } mp->m_log = xlog_alloc_log(mp, log_target, blk_offset, num_bblks); if (IS_ERR(mp->m_log)) { error = PTR_ERR(mp->m_log); goto out; } /* * Validate the given log space and drop a critical message via syslog * if the log size is too small that would lead to some unexpected * situations in transaction log space reservation stage. * * Note: we can't just reject the mount if the validation fails. This * would mean that people would have to downgrade their kernel just to * remedy the situation as there is no way to grow the log (short of * black magic surgery with xfs_db). * * We can, however, reject mounts for CRC format filesystems, as the * mkfs binary being used to make the filesystem should never create a * filesystem with a log that is too small. */ min_logfsbs = xfs_log_calc_minimum_size(mp); if (mp->m_sb.sb_logblocks < min_logfsbs) { xfs_warn(mp, "Log size %d blocks too small, minimum size is %d blocks", mp->m_sb.sb_logblocks, min_logfsbs); error = -EINVAL; } else if (mp->m_sb.sb_logblocks > XFS_MAX_LOG_BLOCKS) { xfs_warn(mp, "Log size %d blocks too large, maximum size is %lld blocks", mp->m_sb.sb_logblocks, XFS_MAX_LOG_BLOCKS); error = -EINVAL; } else if (XFS_FSB_TO_B(mp, mp->m_sb.sb_logblocks) > XFS_MAX_LOG_BYTES) { xfs_warn(mp, "log size %lld bytes too large, maximum size is %lld bytes", XFS_FSB_TO_B(mp, mp->m_sb.sb_logblocks), XFS_MAX_LOG_BYTES); error = -EINVAL; } if (error) { if (xfs_sb_version_hascrc(&mp->m_sb)) { xfs_crit(mp, "AAIEEE! Log failed size checks. Abort!"); ASSERT(0); goto out_free_log; } xfs_crit(mp, "Log size out of supported range."); xfs_crit(mp, "Continuing onwards, but if log hangs are experienced then please report this message in the bug report."); } /* * Initialize the AIL now we have a log. */ error = xfs_trans_ail_init(mp); if (error) { xfs_warn(mp, "AIL initialisation failed: error %d", error); goto out_free_log; } mp->m_log->l_ailp = mp->m_ail; /* * skip log recovery on a norecovery mount. pretend it all * just worked. */ if (!(mp->m_flags & XFS_MOUNT_NORECOVERY)) { int readonly = (mp->m_flags & XFS_MOUNT_RDONLY); if (readonly) mp->m_flags &= ~XFS_MOUNT_RDONLY; error = xlog_recover(mp->m_log); if (readonly) mp->m_flags |= XFS_MOUNT_RDONLY; if (error) { xfs_warn(mp, "log mount/recovery failed: error %d", error); xlog_recover_cancel(mp->m_log); goto out_destroy_ail; } } error = xfs_sysfs_init(&mp->m_log->l_kobj, &xfs_log_ktype, &mp->m_kobj, "log"); if (error) goto out_destroy_ail; /* Normal transactions can now occur */ mp->m_log->l_flags &= ~XLOG_ACTIVE_RECOVERY; /* * Now the log has been fully initialised and we know were our * space grant counters are, we can initialise the permanent ticket * needed for delayed logging to work. */ xlog_cil_init_post_recovery(mp->m_log); return 0; out_destroy_ail: xfs_trans_ail_destroy(mp); out_free_log: xlog_dealloc_log(mp->m_log); out: return error; } /* * Finish the recovery of the file system. This is separate from the * xfs_log_mount() call, because it depends on the code in xfs_mountfs() to read * in the root and real-time bitmap inodes between calling xfs_log_mount() and * here. * * If we finish recovery successfully, start the background log work. If we are * not doing recovery, then we have a RO filesystem and we don't need to start * it. */ int xfs_log_mount_finish( struct xfs_mount *mp) { int error = 0; bool readonly = (mp->m_flags & XFS_MOUNT_RDONLY); if (mp->m_flags & XFS_MOUNT_NORECOVERY) { ASSERT(mp->m_flags & XFS_MOUNT_RDONLY); return 0; } else if (readonly) { /* Allow unlinked processing to proceed */ mp->m_flags &= ~XFS_MOUNT_RDONLY; } /* * During the second phase of log recovery, we need iget and * iput to behave like they do for an active filesystem. * xfs_fs_drop_inode needs to be able to prevent the deletion * of inodes before we're done replaying log items on those * inodes. Turn it off immediately after recovery finishes * so that we don't leak the quota inodes if subsequent mount * activities fail. * * We let all inodes involved in redo item processing end up on * the LRU instead of being evicted immediately so that if we do * something to an unlinked inode, the irele won't cause * premature truncation and freeing of the inode, which results * in log recovery failure. We have to evict the unreferenced * lru inodes after clearing SB_ACTIVE because we don't * otherwise clean up the lru if there's a subsequent failure in * xfs_mountfs, which leads to us leaking the inodes if nothing * else (e.g. quotacheck) references the inodes before the * mount failure occurs. */ mp->m_super->s_flags |= SB_ACTIVE; error = xlog_recover_finish(mp->m_log); if (!error) xfs_log_work_queue(mp); mp->m_super->s_flags &= ~SB_ACTIVE; evict_inodes(mp->m_super); if (readonly) mp->m_flags |= XFS_MOUNT_RDONLY; return error; } /* * The mount has failed. Cancel the recovery if it hasn't completed and destroy * the log. */ int xfs_log_mount_cancel( struct xfs_mount *mp) { int error; error = xlog_recover_cancel(mp->m_log); xfs_log_unmount(mp); return error; } /* * Final log writes as part of unmount. * * Mark the filesystem clean as unmount happens. Note that during relocation * this routine needs to be executed as part of source-bag while the * deallocation must not be done until source-end. */ /* * Unmount record used to have a string "Unmount filesystem--" in the * data section where the "Un" was really a magic number (XLOG_UNMOUNT_TYPE). * We just write the magic number now since that particular field isn't * currently architecture converted and "Unmount" is a bit foo. * As far as I know, there weren't any dependencies on the old behaviour. */ static int xfs_log_unmount_write(xfs_mount_t *mp) { struct xlog *log = mp->m_log; xlog_in_core_t *iclog; #ifdef DEBUG xlog_in_core_t *first_iclog; #endif xlog_ticket_t *tic = NULL; xfs_lsn_t lsn; int error; /* * Don't write out unmount record on norecovery mounts or ro devices. * Or, if we are doing a forced umount (typically because of IO errors). */ if (mp->m_flags & XFS_MOUNT_NORECOVERY || xfs_readonly_buftarg(log->l_mp->m_logdev_targp)) { ASSERT(mp->m_flags & XFS_MOUNT_RDONLY); return 0; } error = _xfs_log_force(mp, XFS_LOG_SYNC, NULL); ASSERT(error || !(XLOG_FORCED_SHUTDOWN(log))); #ifdef DEBUG first_iclog = iclog = log->l_iclog; do { if (!(iclog->ic_state & XLOG_STATE_IOERROR)) { ASSERT(iclog->ic_state & XLOG_STATE_ACTIVE); ASSERT(iclog->ic_offset == 0); } iclog = iclog->ic_next; } while (iclog != first_iclog); #endif if (! (XLOG_FORCED_SHUTDOWN(log))) { error = xfs_log_reserve(mp, 600, 1, &tic, XFS_LOG, 0); if (!error) { /* the data section must be 32 bit size aligned */ struct { uint16_t magic; uint16_t pad1; uint32_t pad2; /* may as well make it 64 bits */ } magic = { .magic = XLOG_UNMOUNT_TYPE, }; struct xfs_log_iovec reg = { .i_addr = &magic, .i_len = sizeof(magic), .i_type = XLOG_REG_TYPE_UNMOUNT, }; struct xfs_log_vec vec = { .lv_niovecs = 1, .lv_iovecp = &reg, }; /* remove inited flag, and account for space used */ tic->t_flags = 0; tic->t_curr_res -= sizeof(magic); error = xlog_write(log, &vec, tic, &lsn, NULL, XLOG_UNMOUNT_TRANS); /* * At this point, we're umounting anyway, * so there's no point in transitioning log state * to IOERROR. Just continue... */ } if (error) xfs_alert(mp, "%s: unmount record failed", __func__); spin_lock(&log->l_icloglock); iclog = log->l_iclog; atomic_inc(&iclog->ic_refcnt); xlog_state_want_sync(log, iclog); spin_unlock(&log->l_icloglock); error = xlog_state_release_iclog(log, iclog); spin_lock(&log->l_icloglock); if (!(iclog->ic_state == XLOG_STATE_ACTIVE || iclog->ic_state == XLOG_STATE_DIRTY)) { if (!XLOG_FORCED_SHUTDOWN(log)) { xlog_wait(&iclog->ic_force_wait, &log->l_icloglock); } else { spin_unlock(&log->l_icloglock); } } else { spin_unlock(&log->l_icloglock); } if (tic) { trace_xfs_log_umount_write(log, tic); xlog_ungrant_log_space(log, tic); xfs_log_ticket_put(tic); } } else { /* * We're already in forced_shutdown mode, couldn't * even attempt to write out the unmount transaction. * * Go through the motions of sync'ing and releasing * the iclog, even though no I/O will actually happen, * we need to wait for other log I/Os that may already * be in progress. Do this as a separate section of * code so we'll know if we ever get stuck here that * we're in this odd situation of trying to unmount * a file system that went into forced_shutdown as * the result of an unmount.. */ spin_lock(&log->l_icloglock); iclog = log->l_iclog; atomic_inc(&iclog->ic_refcnt); xlog_state_want_sync(log, iclog); spin_unlock(&log->l_icloglock); error = xlog_state_release_iclog(log, iclog); spin_lock(&log->l_icloglock); if ( ! ( iclog->ic_state == XLOG_STATE_ACTIVE || iclog->ic_state == XLOG_STATE_DIRTY || iclog->ic_state == XLOG_STATE_IOERROR) ) { xlog_wait(&iclog->ic_force_wait, &log->l_icloglock); } else { spin_unlock(&log->l_icloglock); } } return error; } /* xfs_log_unmount_write */ /* * Empty the log for unmount/freeze. * * To do this, we first need to shut down the background log work so it is not * trying to cover the log as we clean up. We then need to unpin all objects in * the log so we can then flush them out. Once they have completed their IO and * run the callbacks removing themselves from the AIL, we can write the unmount * record. */ void xfs_log_quiesce( struct xfs_mount *mp) { cancel_delayed_work_sync(&mp->m_log->l_work); xfs_log_force(mp, XFS_LOG_SYNC); /* * The superblock buffer is uncached and while xfs_ail_push_all_sync() * will push it, xfs_wait_buftarg() will not wait for it. Further, * xfs_buf_iowait() cannot be used because it was pushed with the * XBF_ASYNC flag set, so we need to use a lock/unlock pair to wait for * the IO to complete. */ xfs_ail_push_all_sync(mp->m_ail); xfs_wait_buftarg(mp->m_ddev_targp); xfs_buf_lock(mp->m_sb_bp); xfs_buf_unlock(mp->m_sb_bp); xfs_log_unmount_write(mp); } /* * Shut down and release the AIL and Log. * * During unmount, we need to ensure we flush all the dirty metadata objects * from the AIL so that the log is empty before we write the unmount record to * the log. Once this is done, we can tear down the AIL and the log. */ void xfs_log_unmount( struct xfs_mount *mp) { xfs_log_quiesce(mp); xfs_trans_ail_destroy(mp); xfs_sysfs_del(&mp->m_log->l_kobj); xlog_dealloc_log(mp->m_log); } void xfs_log_item_init( struct xfs_mount *mp, struct xfs_log_item *item, int type, const struct xfs_item_ops *ops) { item->li_mountp = mp; item->li_ailp = mp->m_ail; item->li_type = type; item->li_ops = ops; item->li_lv = NULL; INIT_LIST_HEAD(&item->li_ail); INIT_LIST_HEAD(&item->li_cil); } /* * Wake up processes waiting for log space after we have moved the log tail. */ void xfs_log_space_wake( struct xfs_mount *mp) { struct xlog *log = mp->m_log; int free_bytes; if (XLOG_FORCED_SHUTDOWN(log)) return; if (!list_empty_careful(&log->l_write_head.waiters)) { ASSERT(!(log->l_flags & XLOG_ACTIVE_RECOVERY)); spin_lock(&log->l_write_head.lock); free_bytes = xlog_space_left(log, &log->l_write_head.grant); xlog_grant_head_wake(log, &log->l_write_head, &free_bytes); spin_unlock(&log->l_write_head.lock); } if (!list_empty_careful(&log->l_reserve_head.waiters)) { ASSERT(!(log->l_flags & XLOG_ACTIVE_RECOVERY)); spin_lock(&log->l_reserve_head.lock); free_bytes = xlog_space_left(log, &log->l_reserve_head.grant); xlog_grant_head_wake(log, &log->l_reserve_head, &free_bytes); spin_unlock(&log->l_reserve_head.lock); } } /* * Determine if we have a transaction that has gone to disk that needs to be * covered. To begin the transition to the idle state firstly the log needs to * be idle. That means the CIL, the AIL and the iclogs needs to be empty before * we start attempting to cover the log. * * Only if we are then in a state where covering is needed, the caller is * informed that dummy transactions are required to move the log into the idle * state. * * If there are any items in the AIl or CIL, then we do not want to attempt to * cover the log as we may be in a situation where there isn't log space * available to run a dummy transaction and this can lead to deadlocks when the * tail of the log is pinned by an item that is modified in the CIL. Hence * there's no point in running a dummy transaction at this point because we * can't start trying to idle the log until both the CIL and AIL are empty. */ static int xfs_log_need_covered(xfs_mount_t *mp) { struct xlog *log = mp->m_log; int needed = 0; if (!xfs_fs_writable(mp, SB_FREEZE_WRITE)) return 0; if (!xlog_cil_empty(log)) return 0; spin_lock(&log->l_icloglock); switch (log->l_covered_state) { case XLOG_STATE_COVER_DONE: case XLOG_STATE_COVER_DONE2: case XLOG_STATE_COVER_IDLE: break; case XLOG_STATE_COVER_NEED: case XLOG_STATE_COVER_NEED2: if (xfs_ail_min_lsn(log->l_ailp)) break; if (!xlog_iclogs_empty(log)) break; needed = 1; if (log->l_covered_state == XLOG_STATE_COVER_NEED) log->l_covered_state = XLOG_STATE_COVER_DONE; else log->l_covered_state = XLOG_STATE_COVER_DONE2; break; default: needed = 1; break; } spin_unlock(&log->l_icloglock); return needed; } /* * We may be holding the log iclog lock upon entering this routine. */ xfs_lsn_t xlog_assign_tail_lsn_locked( struct xfs_mount *mp) { struct xlog *log = mp->m_log; struct xfs_log_item *lip; xfs_lsn_t tail_lsn; assert_spin_locked(&mp->m_ail->xa_lock); /* * To make sure we always have a valid LSN for the log tail we keep * track of the last LSN which was committed in log->l_last_sync_lsn, * and use that when the AIL was empty. */ lip = xfs_ail_min(mp->m_ail); if (lip) tail_lsn = lip->li_lsn; else tail_lsn = atomic64_read(&log->l_last_sync_lsn); trace_xfs_log_assign_tail_lsn(log, tail_lsn); atomic64_set(&log->l_tail_lsn, tail_lsn); return tail_lsn; } xfs_lsn_t xlog_assign_tail_lsn( struct xfs_mount *mp) { xfs_lsn_t tail_lsn; spin_lock(&mp->m_ail->xa_lock); tail_lsn = xlog_assign_tail_lsn_locked(mp); spin_unlock(&mp->m_ail->xa_lock); return tail_lsn; } /* * Return the space in the log between the tail and the head. The head * is passed in the cycle/bytes formal parms. In the special case where * the reserve head has wrapped passed the tail, this calculation is no * longer valid. In this case, just return 0 which means there is no space * in the log. This works for all places where this function is called * with the reserve head. Of course, if the write head were to ever * wrap the tail, we should blow up. Rather than catch this case here, * we depend on other ASSERTions in other parts of the code. XXXmiken * * This code also handles the case where the reservation head is behind * the tail. The details of this case are described below, but the end * result is that we return the size of the log as the amount of space left. */ STATIC int xlog_space_left( struct xlog *log, atomic64_t *head) { int free_bytes; int tail_bytes; int tail_cycle; int head_cycle; int head_bytes; xlog_crack_grant_head(head, &head_cycle, &head_bytes); xlog_crack_atomic_lsn(&log->l_tail_lsn, &tail_cycle, &tail_bytes); tail_bytes = BBTOB(tail_bytes); if (tail_cycle == head_cycle && head_bytes >= tail_bytes) free_bytes = log->l_logsize - (head_bytes - tail_bytes); else if (tail_cycle + 1 < head_cycle) return 0; else if (tail_cycle < head_cycle) { ASSERT(tail_cycle == (head_cycle - 1)); free_bytes = tail_bytes - head_bytes; } else { /* * The reservation head is behind the tail. * In this case we just want to return the size of the * log as the amount of space left. */ xfs_alert(log->l_mp, "xlog_space_left: head behind tail"); xfs_alert(log->l_mp, " tail_cycle = %d, tail_bytes = %d", tail_cycle, tail_bytes); xfs_alert(log->l_mp, " GH cycle = %d, GH bytes = %d", head_cycle, head_bytes); ASSERT(0); free_bytes = log->l_logsize; } return free_bytes; } /* * Log function which is called when an io completes. * * The log manager needs its own routine, in order to control what * happens with the buffer after the write completes. */ static void xlog_iodone(xfs_buf_t *bp) { struct xlog_in_core *iclog = bp->b_fspriv; struct xlog *l = iclog->ic_log; int aborted = 0; /* * Race to shutdown the filesystem if we see an error or the iclog is in * IOABORT state. The IOABORT state is only set in DEBUG mode to inject * CRC errors into log recovery. */ if (XFS_TEST_ERROR(bp->b_error, l->l_mp, XFS_ERRTAG_IODONE_IOERR) || iclog->ic_state & XLOG_STATE_IOABORT) { if (iclog->ic_state & XLOG_STATE_IOABORT) iclog->ic_state &= ~XLOG_STATE_IOABORT; xfs_buf_ioerror_alert(bp, __func__); xfs_buf_stale(bp); xfs_force_shutdown(l->l_mp, SHUTDOWN_LOG_IO_ERROR); /* * This flag will be propagated to the trans-committed * callback routines to let them know that the log-commit * didn't succeed. */ aborted = XFS_LI_ABORTED; } else if (iclog->ic_state & XLOG_STATE_IOERROR) { aborted = XFS_LI_ABORTED; } /* log I/O is always issued ASYNC */ ASSERT(bp->b_flags & XBF_ASYNC); xlog_state_done_syncing(iclog, aborted); /* * drop the buffer lock now that we are done. Nothing references * the buffer after this, so an unmount waiting on this lock can now * tear it down safely. As such, it is unsafe to reference the buffer * (bp) after the unlock as we could race with it being freed. */ xfs_buf_unlock(bp); } /* * Return size of each in-core log record buffer. * * All machines get 8 x 32kB buffers by default, unless tuned otherwise. * * If the filesystem blocksize is too large, we may need to choose a * larger size since the directory code currently logs entire blocks. */ STATIC void xlog_get_iclog_buffer_size( struct xfs_mount *mp, struct xlog *log) { int size; int xhdrs; if (mp->m_logbufs <= 0) log->l_iclog_bufs = XLOG_MAX_ICLOGS; else log->l_iclog_bufs = mp->m_logbufs; /* * Buffer size passed in from mount system call. */ if (mp->m_logbsize > 0) { size = log->l_iclog_size = mp->m_logbsize; log->l_iclog_size_log = 0; while (size != 1) { log->l_iclog_size_log++; size >>= 1; } if (xfs_sb_version_haslogv2(&mp->m_sb)) { /* # headers = size / 32k * one header holds cycles from 32k of data */ xhdrs = mp->m_logbsize / XLOG_HEADER_CYCLE_SIZE; if (mp->m_logbsize % XLOG_HEADER_CYCLE_SIZE) xhdrs++; log->l_iclog_hsize = xhdrs << BBSHIFT; log->l_iclog_heads = xhdrs; } else { ASSERT(mp->m_logbsize <= XLOG_BIG_RECORD_BSIZE); log->l_iclog_hsize = BBSIZE; log->l_iclog_heads = 1; } goto done; } /* All machines use 32kB buffers by default. */ log->l_iclog_size = XLOG_BIG_RECORD_BSIZE; log->l_iclog_size_log = XLOG_BIG_RECORD_BSHIFT; /* the default log size is 16k or 32k which is one header sector */ log->l_iclog_hsize = BBSIZE; log->l_iclog_heads = 1; done: /* are we being asked to make the sizes selected above visible? */ if (mp->m_logbufs == 0) mp->m_logbufs = log->l_iclog_bufs; if (mp->m_logbsize == 0) mp->m_logbsize = log->l_iclog_size; } /* xlog_get_iclog_buffer_size */ void xfs_log_work_queue( struct xfs_mount *mp) { queue_delayed_work(mp->m_sync_workqueue, &mp->m_log->l_work, msecs_to_jiffies(xfs_syncd_centisecs * 10)); } /* * Every sync period we need to unpin all items in the AIL and push them to * disk. If there is nothing dirty, then we might need to cover the log to * indicate that the filesystem is idle. */ static void xfs_log_worker( struct work_struct *work) { struct xlog *log = container_of(to_delayed_work(work), struct xlog, l_work); struct xfs_mount *mp = log->l_mp; /* dgc: errors ignored - not fatal and nowhere to report them */ if (xfs_log_need_covered(mp)) { /* * Dump a transaction into the log that contains no real change. * This is needed to stamp the current tail LSN into the log * during the covering operation. * * We cannot use an inode here for this - that will push dirty * state back up into the VFS and then periodic inode flushing * will prevent log covering from making progress. Hence we * synchronously log the superblock instead to ensure the * superblock is immediately unpinned and can be written back. */ xfs_sync_sb(mp, true); } else xfs_log_force(mp, 0); /* start pushing all the metadata that is currently dirty */ xfs_ail_push_all(mp->m_ail); /* queue us up again */ xfs_log_work_queue(mp); } /* * This routine initializes some of the log structure for a given mount point. * Its primary purpose is to fill in enough, so recovery can occur. However, * some other stuff may be filled in too. */ STATIC struct xlog * xlog_alloc_log( struct xfs_mount *mp, struct xfs_buftarg *log_target, xfs_daddr_t blk_offset, int num_bblks) { struct xlog *log; xlog_rec_header_t *head; xlog_in_core_t **iclogp; xlog_in_core_t *iclog, *prev_iclog=NULL; xfs_buf_t *bp; int i; int error = -ENOMEM; uint log2_size = 0; log = kmem_zalloc(sizeof(struct xlog), KM_MAYFAIL); if (!log) { xfs_warn(mp, "Log allocation failed: No memory!"); goto out; } log->l_mp = mp; log->l_targ = log_target; log->l_logsize = BBTOB(num_bblks); log->l_logBBstart = blk_offset; log->l_logBBsize = num_bblks; log->l_covered_state = XLOG_STATE_COVER_IDLE; log->l_flags |= XLOG_ACTIVE_RECOVERY; INIT_DELAYED_WORK(&log->l_work, xfs_log_worker); log->l_prev_block = -1; /* log->l_tail_lsn = 0x100000000LL; cycle = 1; current block = 0 */ xlog_assign_atomic_lsn(&log->l_tail_lsn, 1, 0); xlog_assign_atomic_lsn(&log->l_last_sync_lsn, 1, 0); log->l_curr_cycle = 1; /* 0 is bad since this is initial value */ xlog_grant_head_init(&log->l_reserve_head); xlog_grant_head_init(&log->l_write_head); error = -EFSCORRUPTED; if (xfs_sb_version_hassector(&mp->m_sb)) { log2_size = mp->m_sb.sb_logsectlog; if (log2_size < BBSHIFT) { xfs_warn(mp, "Log sector size too small (0x%x < 0x%x)", log2_size, BBSHIFT); goto out_free_log; } log2_size -= BBSHIFT; if (log2_size > mp->m_sectbb_log) { xfs_warn(mp, "Log sector size too large (0x%x > 0x%x)", log2_size, mp->m_sectbb_log); goto out_free_log; } /* for larger sector sizes, must have v2 or external log */ if (log2_size && log->l_logBBstart > 0 && !xfs_sb_version_haslogv2(&mp->m_sb)) { xfs_warn(mp, "log sector size (0x%x) invalid for configuration.", log2_size); goto out_free_log; } } log->l_sectBBsize = 1 << log2_size; xlog_get_iclog_buffer_size(mp, log); /* * Use a NULL block for the extra log buffer used during splits so that * it will trigger errors if we ever try to do IO on it without first * having set it up properly. */ error = -ENOMEM; bp = xfs_buf_alloc(mp->m_logdev_targp, XFS_BUF_DADDR_NULL, BTOBB(log->l_iclog_size), XBF_NO_IOACCT); if (!bp) goto out_free_log; /* * The iclogbuf buffer locks are held over IO but we are not going to do * IO yet. Hence unlock the buffer so that the log IO path can grab it * when appropriately. */ ASSERT(xfs_buf_islocked(bp)); xfs_buf_unlock(bp); /* use high priority wq for log I/O completion */ bp->b_ioend_wq = mp->m_log_workqueue; bp->b_iodone = xlog_iodone; log->l_xbuf = bp; spin_lock_init(&log->l_icloglock); init_waitqueue_head(&log->l_flush_wait); iclogp = &log->l_iclog; /* * The amount of memory to allocate for the iclog structure is * rather funky due to the way the structure is defined. It is * done this way so that we can use different sizes for machines * with different amounts of memory. See the definition of * xlog_in_core_t in xfs_log_priv.h for details. */ ASSERT(log->l_iclog_size >= 4096); for (i=0; i < log->l_iclog_bufs; i++) { *iclogp = kmem_zalloc(sizeof(xlog_in_core_t), KM_MAYFAIL); if (!*iclogp) goto out_free_iclog; iclog = *iclogp; iclog->ic_prev = prev_iclog; prev_iclog = iclog; bp = xfs_buf_get_uncached(mp->m_logdev_targp, BTOBB(log->l_iclog_size), XBF_NO_IOACCT); if (!bp) goto out_free_iclog; ASSERT(xfs_buf_islocked(bp)); xfs_buf_unlock(bp); /* use high priority wq for log I/O completion */ bp->b_ioend_wq = mp->m_log_workqueue; bp->b_iodone = xlog_iodone; iclog->ic_bp = bp; iclog->ic_data = bp->b_addr; #ifdef DEBUG log->l_iclog_bak[i] = &iclog->ic_header; #endif head = &iclog->ic_header; memset(head, 0, sizeof(xlog_rec_header_t)); head->h_magicno = cpu_to_be32(XLOG_HEADER_MAGIC_NUM); head->h_version = cpu_to_be32( xfs_sb_version_haslogv2(&log->l_mp->m_sb) ? 2 : 1); head->h_size = cpu_to_be32(log->l_iclog_size); /* new fields */ head->h_fmt = cpu_to_be32(XLOG_FMT); memcpy(&head->h_fs_uuid, &mp->m_sb.sb_uuid, sizeof(uuid_t)); iclog->ic_size = BBTOB(bp->b_length) - log->l_iclog_hsize; iclog->ic_state = XLOG_STATE_ACTIVE; iclog->ic_log = log; atomic_set(&iclog->ic_refcnt, 0); spin_lock_init(&iclog->ic_callback_lock); iclog->ic_callback_tail = &(iclog->ic_callback); iclog->ic_datap = (char *)iclog->ic_data + log->l_iclog_hsize; init_waitqueue_head(&iclog->ic_force_wait); init_waitqueue_head(&iclog->ic_write_wait); iclogp = &iclog->ic_next; } *iclogp = log->l_iclog; /* complete ring */ log->l_iclog->ic_prev = prev_iclog; /* re-write 1st prev ptr */ error = xlog_cil_init(log); if (error) goto out_free_iclog; return log; out_free_iclog: for (iclog = log->l_iclog; iclog; iclog = prev_iclog) { prev_iclog = iclog->ic_next; if (iclog->ic_bp) xfs_buf_free(iclog->ic_bp); kmem_free(iclog); } spinlock_destroy(&log->l_icloglock); xfs_buf_free(log->l_xbuf); out_free_log: kmem_free(log); out: return ERR_PTR(error); } /* xlog_alloc_log */ /* * Write out the commit record of a transaction associated with the given * ticket. Return the lsn of the commit record. */ STATIC int xlog_commit_record( struct xlog *log, struct xlog_ticket *ticket, struct xlog_in_core **iclog, xfs_lsn_t *commitlsnp) { struct xfs_mount *mp = log->l_mp; int error; struct xfs_log_iovec reg = { .i_addr = NULL, .i_len = 0, .i_type = XLOG_REG_TYPE_COMMIT, }; struct xfs_log_vec vec = { .lv_niovecs = 1, .lv_iovecp = &reg, }; ASSERT_ALWAYS(iclog); error = xlog_write(log, &vec, ticket, commitlsnp, iclog, XLOG_COMMIT_TRANS); if (error) xfs_force_shutdown(mp, SHUTDOWN_LOG_IO_ERROR); return error; } /* * Push on the buffer cache code if we ever use more than 75% of the on-disk * log space. This code pushes on the lsn which would supposedly free up * the 25% which we want to leave free. We may need to adopt a policy which * pushes on an lsn which is further along in the log once we reach the high * water mark. In this manner, we would be creating a low water mark. */ STATIC void xlog_grant_push_ail( struct xlog *log, int need_bytes) { xfs_lsn_t threshold_lsn = 0; xfs_lsn_t last_sync_lsn; int free_blocks; int free_bytes; int threshold_block; int threshold_cycle; int free_threshold; ASSERT(BTOBB(need_bytes) < log->l_logBBsize); free_bytes = xlog_space_left(log, &log->l_reserve_head.grant); free_blocks = BTOBBT(free_bytes); /* * Set the threshold for the minimum number of free blocks in the * log to the maximum of what the caller needs, one quarter of the * log, and 256 blocks. */ free_threshold = BTOBB(need_bytes); free_threshold = MAX(free_threshold, (log->l_logBBsize >> 2)); free_threshold = MAX(free_threshold, 256); if (free_blocks >= free_threshold) return; xlog_crack_atomic_lsn(&log->l_tail_lsn, &threshold_cycle, &threshold_block); threshold_block += free_threshold; if (threshold_block >= log->l_logBBsize) { threshold_block -= log->l_logBBsize; threshold_cycle += 1; } threshold_lsn = xlog_assign_lsn(threshold_cycle, threshold_block); /* * Don't pass in an lsn greater than the lsn of the last * log record known to be on disk. Use a snapshot of the last sync lsn * so that it doesn't change between the compare and the set. */ last_sync_lsn = atomic64_read(&log->l_last_sync_lsn); if (XFS_LSN_CMP(threshold_lsn, last_sync_lsn) > 0) threshold_lsn = last_sync_lsn; /* * Get the transaction layer to kick the dirty buffers out to * disk asynchronously. No point in trying to do this if * the filesystem is shutting down. */ if (!XLOG_FORCED_SHUTDOWN(log)) xfs_ail_push(log->l_ailp, threshold_lsn); } /* * Stamp cycle number in every block */ STATIC void xlog_pack_data( struct xlog *log, struct xlog_in_core *iclog, int roundoff) { int i, j, k; int size = iclog->ic_offset + roundoff; __be32 cycle_lsn; char *dp; cycle_lsn = CYCLE_LSN_DISK(iclog->ic_header.h_lsn); dp = iclog->ic_datap; for (i = 0; i < BTOBB(size); i++) { if (i >= (XLOG_HEADER_CYCLE_SIZE / BBSIZE)) break; iclog->ic_header.h_cycle_data[i] = *(__be32 *)dp; *(__be32 *)dp = cycle_lsn; dp += BBSIZE; } if (xfs_sb_version_haslogv2(&log->l_mp->m_sb)) { xlog_in_core_2_t *xhdr = iclog->ic_data; for ( ; i < BTOBB(size); i++) { j = i / (XLOG_HEADER_CYCLE_SIZE / BBSIZE); k = i % (XLOG_HEADER_CYCLE_SIZE / BBSIZE); xhdr[j].hic_xheader.xh_cycle_data[k] = *(__be32 *)dp; *(__be32 *)dp = cycle_lsn; dp += BBSIZE; } for (i = 1; i < log->l_iclog_heads; i++) xhdr[i].hic_xheader.xh_cycle = cycle_lsn; } } /* * Calculate the checksum for a log buffer. * * This is a little more complicated than it should be because the various * headers and the actual data are non-contiguous. */ __le32 xlog_cksum( struct xlog *log, struct xlog_rec_header *rhead, char *dp, int size) { uint32_t crc; /* first generate the crc for the record header ... */ crc = xfs_start_cksum_update((char *)rhead, sizeof(struct xlog_rec_header), offsetof(struct xlog_rec_header, h_crc)); /* ... then for additional cycle data for v2 logs ... */ if (xfs_sb_version_haslogv2(&log->l_mp->m_sb)) { union xlog_in_core2 *xhdr = (union xlog_in_core2 *)rhead; int i; int xheads; xheads = size / XLOG_HEADER_CYCLE_SIZE; if (size % XLOG_HEADER_CYCLE_SIZE) xheads++; for (i = 1; i < xheads; i++) { crc = crc32c(crc, &xhdr[i].hic_xheader, sizeof(struct xlog_rec_ext_header)); } } /* ... and finally for the payload */ crc = crc32c(crc, dp, size); return xfs_end_cksum(crc); } /* * The bdstrat callback function for log bufs. This gives us a central * place to trap bufs in case we get hit by a log I/O error and need to * shutdown. Actually, in practice, even when we didn't get a log error, * we transition the iclogs to IOERROR state *after* flushing all existing * iclogs to disk. This is because we don't want anymore new transactions to be * started or completed afterwards. * * We lock the iclogbufs here so that we can serialise against IO completion * during unmount. We might be processing a shutdown triggered during unmount, * and that can occur asynchronously to the unmount thread, and hence we need to * ensure that completes before tearing down the iclogbufs. Hence we need to * hold the buffer lock across the log IO to acheive that. */ STATIC int xlog_bdstrat( struct xfs_buf *bp) { struct xlog_in_core *iclog = bp->b_fspriv; xfs_buf_lock(bp); if (iclog->ic_state & XLOG_STATE_IOERROR) { xfs_buf_ioerror(bp, -EIO); xfs_buf_stale(bp); xfs_buf_ioend(bp); /* * It would seem logical to return EIO here, but we rely on * the log state machine to propagate I/O errors instead of * doing it here. Similarly, IO completion will unlock the * buffer, so we don't do it here. */ return 0; } xfs_buf_submit(bp); return 0; } /* * Flush out the in-core log (iclog) to the on-disk log in an asynchronous * fashion. Previously, we should have moved the current iclog * ptr in the log to point to the next available iclog. This allows further * write to continue while this code syncs out an iclog ready to go. * Before an in-core log can be written out, the data section must be scanned * to save away the 1st word of each BBSIZE block into the header. We replace * it with the current cycle count. Each BBSIZE block is tagged with the * cycle count because there in an implicit assumption that drives will * guarantee that entire 512 byte blocks get written at once. In other words, * we can't have part of a 512 byte block written and part not written. By * tagging each block, we will know which blocks are valid when recovering * after an unclean shutdown. * * This routine is single threaded on the iclog. No other thread can be in * this routine with the same iclog. Changing contents of iclog can there- * fore be done without grabbing the state machine lock. Updating the global * log will require grabbing the lock though. * * The entire log manager uses a logical block numbering scheme. Only * log_sync (and then only bwrite()) know about the fact that the log may * not start with block zero on a given device. The log block start offset * is added immediately before calling bwrite(). */ STATIC int xlog_sync( struct xlog *log, struct xlog_in_core *iclog) { xfs_buf_t *bp; int i; uint count; /* byte count of bwrite */ uint count_init; /* initial count before roundup */ int roundoff; /* roundoff to BB or stripe */ int split = 0; /* split write into two regions */ int error; int v2 = xfs_sb_version_haslogv2(&log->l_mp->m_sb); int size; XFS_STATS_INC(log->l_mp, xs_log_writes); ASSERT(atomic_read(&iclog->ic_refcnt) == 0); /* Add for LR header */ count_init = log->l_iclog_hsize + iclog->ic_offset; /* Round out the log write size */ if (v2 && log->l_mp->m_sb.sb_logsunit > 1) { /* we have a v2 stripe unit to use */ count = XLOG_LSUNITTOB(log, XLOG_BTOLSUNIT(log, count_init)); } else { count = BBTOB(BTOBB(count_init)); } roundoff = count - count_init; ASSERT(roundoff >= 0); ASSERT((v2 && log->l_mp->m_sb.sb_logsunit > 1 && roundoff < log->l_mp->m_sb.sb_logsunit) || (log->l_mp->m_sb.sb_logsunit <= 1 && roundoff < BBTOB(1))); /* move grant heads by roundoff in sync */ xlog_grant_add_space(log, &log->l_reserve_head.grant, roundoff); xlog_grant_add_space(log, &log->l_write_head.grant, roundoff); /* put cycle number in every block */ xlog_pack_data(log, iclog, roundoff); /* real byte length */ size = iclog->ic_offset; if (v2) size += roundoff; iclog->ic_header.h_len = cpu_to_be32(size); bp = iclog->ic_bp; XFS_BUF_SET_ADDR(bp, BLOCK_LSN(be64_to_cpu(iclog->ic_header.h_lsn))); XFS_STATS_ADD(log->l_mp, xs_log_blocks, BTOBB(count)); /* Do we need to split this write into 2 parts? */ if (XFS_BUF_ADDR(bp) + BTOBB(count) > log->l_logBBsize) { char *dptr; split = count - (BBTOB(log->l_logBBsize - XFS_BUF_ADDR(bp))); count = BBTOB(log->l_logBBsize - XFS_BUF_ADDR(bp)); iclog->ic_bwritecnt = 2; /* * Bump the cycle numbers at the start of each block in the * part of the iclog that ends up in the buffer that gets * written to the start of the log. * * Watch out for the header magic number case, though. */ dptr = (char *)&iclog->ic_header + count; for (i = 0; i < split; i += BBSIZE) { uint32_t cycle = be32_to_cpu(*(__be32 *)dptr); if (++cycle == XLOG_HEADER_MAGIC_NUM) cycle++; *(__be32 *)dptr = cpu_to_be32(cycle); dptr += BBSIZE; } } else { iclog->ic_bwritecnt = 1; } /* calculcate the checksum */ iclog->ic_header.h_crc = xlog_cksum(log, &iclog->ic_header, iclog->ic_datap, size); /* * Intentionally corrupt the log record CRC based on the error injection * frequency, if defined. This facilitates testing log recovery in the * event of torn writes. Hence, set the IOABORT state to abort the log * write on I/O completion and shutdown the fs. The subsequent mount * detects the bad CRC and attempts to recover. */ if (XFS_TEST_ERROR(false, log->l_mp, XFS_ERRTAG_LOG_BAD_CRC)) { iclog->ic_header.h_crc &= cpu_to_le32(0xAAAAAAAA); iclog->ic_state |= XLOG_STATE_IOABORT; xfs_warn(log->l_mp, "Intentionally corrupted log record at LSN 0x%llx. Shutdown imminent.", be64_to_cpu(iclog->ic_header.h_lsn)); } bp->b_io_length = BTOBB(count); bp->b_fspriv = iclog; bp->b_flags &= ~XBF_FLUSH; bp->b_flags |= (XBF_ASYNC | XBF_SYNCIO | XBF_WRITE | XBF_FUA); /* * Flush the data device before flushing the log to make sure all meta * data written back from the AIL actually made it to disk before * stamping the new log tail LSN into the log buffer. For an external * log we need to issue the flush explicitly, and unfortunately * synchronously here; for an internal log we can simply use the block * layer state machine for preflushes. */ if (log->l_mp->m_logdev_targp != log->l_mp->m_ddev_targp) xfs_blkdev_issue_flush(log->l_mp->m_ddev_targp); else bp->b_flags |= XBF_FLUSH; ASSERT(XFS_BUF_ADDR(bp) <= log->l_logBBsize-1); ASSERT(XFS_BUF_ADDR(bp) + BTOBB(count) <= log->l_logBBsize); xlog_verify_iclog(log, iclog, count, true); /* account for log which doesn't start at block #0 */ XFS_BUF_SET_ADDR(bp, XFS_BUF_ADDR(bp) + log->l_logBBstart); /* * Don't call xfs_bwrite here. We do log-syncs even when the filesystem * is shutting down. */ error = xlog_bdstrat(bp); if (error) { xfs_buf_ioerror_alert(bp, "xlog_sync"); return error; } if (split) { bp = iclog->ic_log->l_xbuf; XFS_BUF_SET_ADDR(bp, 0); /* logical 0 */ xfs_buf_associate_memory(bp, (char *)&iclog->ic_header + count, split); bp->b_fspriv = iclog; bp->b_flags &= ~XBF_FLUSH; bp->b_flags |= (XBF_ASYNC | XBF_SYNCIO | XBF_WRITE | XBF_FUA); ASSERT(XFS_BUF_ADDR(bp) <= log->l_logBBsize-1); ASSERT(XFS_BUF_ADDR(bp) + BTOBB(count) <= log->l_logBBsize); /* account for internal log which doesn't start at block #0 */ XFS_BUF_SET_ADDR(bp, XFS_BUF_ADDR(bp) + log->l_logBBstart); error = xlog_bdstrat(bp); if (error) { xfs_buf_ioerror_alert(bp, "xlog_sync (split)"); return error; } } return 0; } /* xlog_sync */ /* * Deallocate a log structure */ STATIC void xlog_dealloc_log( struct xlog *log) { xlog_in_core_t *iclog, *next_iclog; int i; xlog_cil_destroy(log); /* * Cycle all the iclogbuf locks to make sure all log IO completion * is done before we tear down these buffers. */ iclog = log->l_iclog; for (i = 0; i < log->l_iclog_bufs; i++) { xfs_buf_lock(iclog->ic_bp); xfs_buf_unlock(iclog->ic_bp); iclog = iclog->ic_next; } /* * Always need to ensure that the extra buffer does not point to memory * owned by another log buffer before we free it. Also, cycle the lock * first to ensure we've completed IO on it. */ xfs_buf_lock(log->l_xbuf); xfs_buf_unlock(log->l_xbuf); xfs_buf_set_empty(log->l_xbuf, BTOBB(log->l_iclog_size)); xfs_buf_free(log->l_xbuf); iclog = log->l_iclog; for (i = 0; i < log->l_iclog_bufs; i++) { xfs_buf_free(iclog->ic_bp); next_iclog = iclog->ic_next; kmem_free(iclog); iclog = next_iclog; } spinlock_destroy(&log->l_icloglock); log->l_mp->m_log = NULL; kmem_free(log); } /* xlog_dealloc_log */ /* * Update counters atomically now that memcpy is done. */ /* ARGSUSED */ static inline void xlog_state_finish_copy( struct xlog *log, struct xlog_in_core *iclog, int record_cnt, int copy_bytes) { spin_lock(&log->l_icloglock); be32_add_cpu(&iclog->ic_header.h_num_logops, record_cnt); iclog->ic_offset += copy_bytes; spin_unlock(&log->l_icloglock); } /* xlog_state_finish_copy */ /* * print out info relating to regions written which consume * the reservation */ void xlog_print_tic_res( struct xfs_mount *mp, struct xlog_ticket *ticket) { uint i; uint ophdr_spc = ticket->t_res_num_ophdrs * (uint)sizeof(xlog_op_header_t); /* match with XLOG_REG_TYPE_* in xfs_log.h */ #define REG_TYPE_STR(type, str) [XLOG_REG_TYPE_##type] = str static char *res_type_str[XLOG_REG_TYPE_MAX + 1] = { REG_TYPE_STR(BFORMAT, "bformat"), REG_TYPE_STR(BCHUNK, "bchunk"), REG_TYPE_STR(EFI_FORMAT, "efi_format"), REG_TYPE_STR(EFD_FORMAT, "efd_format"), REG_TYPE_STR(IFORMAT, "iformat"), REG_TYPE_STR(ICORE, "icore"), REG_TYPE_STR(IEXT, "iext"), REG_TYPE_STR(IBROOT, "ibroot"), REG_TYPE_STR(ILOCAL, "ilocal"), REG_TYPE_STR(IATTR_EXT, "iattr_ext"), REG_TYPE_STR(IATTR_BROOT, "iattr_broot"), REG_TYPE_STR(IATTR_LOCAL, "iattr_local"), REG_TYPE_STR(QFORMAT, "qformat"), REG_TYPE_STR(DQUOT, "dquot"), REG_TYPE_STR(QUOTAOFF, "quotaoff"), REG_TYPE_STR(LRHEADER, "LR header"), REG_TYPE_STR(UNMOUNT, "unmount"), REG_TYPE_STR(COMMIT, "commit"), REG_TYPE_STR(TRANSHDR, "trans header"), REG_TYPE_STR(ICREATE, "inode create") }; #undef REG_TYPE_STR xfs_warn(mp, "ticket reservation summary:"); xfs_warn(mp, " unit res = %d bytes", ticket->t_unit_res); xfs_warn(mp, " current res = %d bytes", ticket->t_curr_res); xfs_warn(mp, " total reg = %u bytes (o/flow = %u bytes)", ticket->t_res_arr_sum, ticket->t_res_o_flow); xfs_warn(mp, " ophdrs = %u (ophdr space = %u bytes)", ticket->t_res_num_ophdrs, ophdr_spc); xfs_warn(mp, " ophdr + reg = %u bytes", ticket->t_res_arr_sum + ticket->t_res_o_flow + ophdr_spc); xfs_warn(mp, " num regions = %u", ticket->t_res_num); for (i = 0; i < ticket->t_res_num; i++) { uint r_type = ticket->t_res_arr[i].r_type; xfs_warn(mp, "region[%u]: %s - %u bytes", i, ((r_type <= 0 || r_type > XLOG_REG_TYPE_MAX) ? "bad-rtype" : res_type_str[r_type]), ticket->t_res_arr[i].r_len); } } /* * Print a summary of the transaction. */ void xlog_print_trans( struct xfs_trans *tp) { struct xfs_mount *mp = tp->t_mountp; struct xfs_log_item_desc *lidp; /* dump core transaction and ticket info */ xfs_warn(mp, "transaction summary:"); xfs_warn(mp, " flags = 0x%x", tp->t_flags); xlog_print_tic_res(mp, tp->t_ticket); /* dump each log item */ list_for_each_entry(lidp, &tp->t_items, lid_trans) { struct xfs_log_item *lip = lidp->lid_item; struct xfs_log_vec *lv = lip->li_lv; struct xfs_log_iovec *vec; int i; xfs_warn(mp, "log item: "); xfs_warn(mp, " type = 0x%x", lip->li_type); xfs_warn(mp, " flags = 0x%x", lip->li_flags); if (!lv) continue; xfs_warn(mp, " niovecs = %d", lv->lv_niovecs); xfs_warn(mp, " size = %d", lv->lv_size); xfs_warn(mp, " bytes = %d", lv->lv_bytes); xfs_warn(mp, " buf len = %d", lv->lv_buf_len); /* dump each iovec for the log item */ vec = lv->lv_iovecp; for (i = 0; i < lv->lv_niovecs; i++) { int dumplen = min(vec->i_len, 32); xfs_warn(mp, " iovec[%d]", i); xfs_warn(mp, " type = 0x%x", vec->i_type); xfs_warn(mp, " len = %d", vec->i_len); xfs_warn(mp, " first %d bytes of iovec[%d]:", dumplen, i); xfs_hex_dump(vec->i_addr, dumplen); vec++; } } } /* * Calculate the potential space needed by the log vector. Each region gets * its own xlog_op_header_t and may need to be double word aligned. */ static int xlog_write_calc_vec_length( struct xlog_ticket *ticket, struct xfs_log_vec *log_vector) { struct xfs_log_vec *lv; int headers = 0; int len = 0; int i; /* acct for start rec of xact */ if (ticket->t_flags & XLOG_TIC_INITED) headers++; for (lv = log_vector; lv; lv = lv->lv_next) { /* we don't write ordered log vectors */ if (lv->lv_buf_len == XFS_LOG_VEC_ORDERED) continue; headers += lv->lv_niovecs; for (i = 0; i < lv->lv_niovecs; i++) { struct xfs_log_iovec *vecp = &lv->lv_iovecp[i]; len += vecp->i_len; xlog_tic_add_region(ticket, vecp->i_len, vecp->i_type); } } ticket->t_res_num_ophdrs += headers; len += headers * sizeof(struct xlog_op_header); return len; } /* * If first write for transaction, insert start record We can't be trying to * commit if we are inited. We can't have any "partial_copy" if we are inited. */ static int xlog_write_start_rec( struct xlog_op_header *ophdr, struct xlog_ticket *ticket) { if (!(ticket->t_flags & XLOG_TIC_INITED)) return 0; ophdr->oh_tid = cpu_to_be32(ticket->t_tid); ophdr->oh_clientid = ticket->t_clientid; ophdr->oh_len = 0; ophdr->oh_flags = XLOG_START_TRANS; ophdr->oh_res2 = 0; ticket->t_flags &= ~XLOG_TIC_INITED; return sizeof(struct xlog_op_header); } static xlog_op_header_t * xlog_write_setup_ophdr( struct xlog *log, struct xlog_op_header *ophdr, struct xlog_ticket *ticket, uint flags) { ophdr->oh_tid = cpu_to_be32(ticket->t_tid); ophdr->oh_clientid = ticket->t_clientid; ophdr->oh_res2 = 0; /* are we copying a commit or unmount record? */ ophdr->oh_flags = flags; /* * We've seen logs corrupted with bad transaction client ids. This * makes sure that XFS doesn't generate them on. Turn this into an EIO * and shut down the filesystem. */ switch (ophdr->oh_clientid) { case XFS_TRANSACTION: case XFS_VOLUME: case XFS_LOG: break; default: xfs_warn(log->l_mp, "Bad XFS transaction clientid 0x%x in ticket 0x%p", ophdr->oh_clientid, ticket); return NULL; } return ophdr; } /* * Set up the parameters of the region copy into the log. This has * to handle region write split across multiple log buffers - this * state is kept external to this function so that this code can * be written in an obvious, self documenting manner. */ static int xlog_write_setup_copy( struct xlog_ticket *ticket, struct xlog_op_header *ophdr, int space_available, int space_required, int *copy_off, int *copy_len, int *last_was_partial_copy, int *bytes_consumed) { int still_to_copy; still_to_copy = space_required - *bytes_consumed; *copy_off = *bytes_consumed; if (still_to_copy <= space_available) { /* write of region completes here */ *copy_len = still_to_copy; ophdr->oh_len = cpu_to_be32(*copy_len); if (*last_was_partial_copy) ophdr->oh_flags |= (XLOG_END_TRANS|XLOG_WAS_CONT_TRANS); *last_was_partial_copy = 0; *bytes_consumed = 0; return 0; } /* partial write of region, needs extra log op header reservation */ *copy_len = space_available; ophdr->oh_len = cpu_to_be32(*copy_len); ophdr->oh_flags |= XLOG_CONTINUE_TRANS; if (*last_was_partial_copy) ophdr->oh_flags |= XLOG_WAS_CONT_TRANS; *bytes_consumed += *copy_len; (*last_was_partial_copy)++; /* account for new log op header */ ticket->t_curr_res -= sizeof(struct xlog_op_header); ticket->t_res_num_ophdrs++; return sizeof(struct xlog_op_header); } static int xlog_write_copy_finish( struct xlog *log, struct xlog_in_core *iclog, uint flags, int *record_cnt, int *data_cnt, int *partial_copy, int *partial_copy_len, int log_offset, struct xlog_in_core **commit_iclog) { if (*partial_copy) { /* * This iclog has already been marked WANT_SYNC by * xlog_state_get_iclog_space. */ xlog_state_finish_copy(log, iclog, *record_cnt, *data_cnt); *record_cnt = 0; *data_cnt = 0; return xlog_state_release_iclog(log, iclog); } *partial_copy = 0; *partial_copy_len = 0; if (iclog->ic_size - log_offset <= sizeof(xlog_op_header_t)) { /* no more space in this iclog - push it. */ xlog_state_finish_copy(log, iclog, *record_cnt, *data_cnt); *record_cnt = 0; *data_cnt = 0; spin_lock(&log->l_icloglock); xlog_state_want_sync(log, iclog); spin_unlock(&log->l_icloglock); if (!commit_iclog) return xlog_state_release_iclog(log, iclog); ASSERT(flags & XLOG_COMMIT_TRANS); *commit_iclog = iclog; } return 0; } /* * Write some region out to in-core log * * This will be called when writing externally provided regions or when * writing out a commit record for a given transaction. * * General algorithm: * 1. Find total length of this write. This may include adding to the * lengths passed in. * 2. Check whether we violate the tickets reservation. * 3. While writing to this iclog * A. Reserve as much space in this iclog as can get * B. If this is first write, save away start lsn * C. While writing this region: * 1. If first write of transaction, write start record * 2. Write log operation header (header per region) * 3. Find out if we can fit entire region into this iclog * 4. Potentially, verify destination memcpy ptr * 5. Memcpy (partial) region * 6. If partial copy, release iclog; otherwise, continue * copying more regions into current iclog * 4. Mark want sync bit (in simulation mode) * 5. Release iclog for potential flush to on-disk log. * * ERRORS: * 1. Panic if reservation is overrun. This should never happen since * reservation amounts are generated internal to the filesystem. * NOTES: * 1. Tickets are single threaded data structures. * 2. The XLOG_END_TRANS & XLOG_CONTINUE_TRANS flags are passed down to the * syncing routine. When a single log_write region needs to span * multiple in-core logs, the XLOG_CONTINUE_TRANS bit should be set * on all log operation writes which don't contain the end of the * region. The XLOG_END_TRANS bit is used for the in-core log * operation which contains the end of the continued log_write region. * 3. When xlog_state_get_iclog_space() grabs the rest of the current iclog, * we don't really know exactly how much space will be used. As a result, * we don't update ic_offset until the end when we know exactly how many * bytes have been written out. */ int xlog_write( struct xlog *log, struct xfs_log_vec *log_vector, struct xlog_ticket *ticket, xfs_lsn_t *start_lsn, struct xlog_in_core **commit_iclog, uint flags) { struct xlog_in_core *iclog = NULL; struct xfs_log_iovec *vecp; struct xfs_log_vec *lv; int len; int index; int partial_copy = 0; int partial_copy_len = 0; int contwr = 0; int record_cnt = 0; int data_cnt = 0; int error; *start_lsn = 0; len = xlog_write_calc_vec_length(ticket, log_vector); /* * Region headers and bytes are already accounted for. * We only need to take into account start records and * split regions in this function. */ if (ticket->t_flags & XLOG_TIC_INITED) ticket->t_curr_res -= sizeof(xlog_op_header_t); /* * Commit record headers need to be accounted for. These * come in as separate writes so are easy to detect. */ if (flags & (XLOG_COMMIT_TRANS | XLOG_UNMOUNT_TRANS)) ticket->t_curr_res -= sizeof(xlog_op_header_t); if (ticket->t_curr_res < 0) { xfs_alert_tag(log->l_mp, XFS_PTAG_LOGRES, "ctx ticket reservation ran out. Need to up reservation"); xlog_print_tic_res(log->l_mp, ticket); xfs_force_shutdown(log->l_mp, SHUTDOWN_LOG_IO_ERROR); } index = 0; lv = log_vector; vecp = lv->lv_iovecp; while (lv && (!lv->lv_niovecs || index < lv->lv_niovecs)) { void *ptr; int log_offset; error = xlog_state_get_iclog_space(log, len, &iclog, ticket, &contwr, &log_offset); if (error) return error; ASSERT(log_offset <= iclog->ic_size - 1); ptr = iclog->ic_datap + log_offset; /* start_lsn is the first lsn written to. That's all we need. */ if (!*start_lsn) *start_lsn = be64_to_cpu(iclog->ic_header.h_lsn); /* * This loop writes out as many regions as can fit in the amount * of space which was allocated by xlog_state_get_iclog_space(). */ while (lv && (!lv->lv_niovecs || index < lv->lv_niovecs)) { struct xfs_log_iovec *reg; struct xlog_op_header *ophdr; int start_rec_copy; int copy_len; int copy_off; bool ordered = false; /* ordered log vectors have no regions to write */ if (lv->lv_buf_len == XFS_LOG_VEC_ORDERED) { ASSERT(lv->lv_niovecs == 0); ordered = true; goto next_lv; } reg = &vecp[index]; ASSERT(reg->i_len % sizeof(int32_t) == 0); ASSERT((unsigned long)ptr % sizeof(int32_t) == 0); start_rec_copy = xlog_write_start_rec(ptr, ticket); if (start_rec_copy) { record_cnt++; xlog_write_adv_cnt(&ptr, &len, &log_offset, start_rec_copy); } ophdr = xlog_write_setup_ophdr(log, ptr, ticket, flags); if (!ophdr) return -EIO; xlog_write_adv_cnt(&ptr, &len, &log_offset, sizeof(struct xlog_op_header)); len += xlog_write_setup_copy(ticket, ophdr, iclog->ic_size-log_offset, reg->i_len, &copy_off, &copy_len, &partial_copy, &partial_copy_len); xlog_verify_dest_ptr(log, ptr); /* * Copy region. * * Unmount records just log an opheader, so can have * empty payloads with no data region to copy. Hence we * only copy the payload if the vector says it has data * to copy. */ ASSERT(copy_len >= 0); if (copy_len > 0) { memcpy(ptr, reg->i_addr + copy_off, copy_len); xlog_write_adv_cnt(&ptr, &len, &log_offset, copy_len); } copy_len += start_rec_copy + sizeof(xlog_op_header_t); record_cnt++; data_cnt += contwr ? copy_len : 0; error = xlog_write_copy_finish(log, iclog, flags, &record_cnt, &data_cnt, &partial_copy, &partial_copy_len, log_offset, commit_iclog); if (error) return error; /* * if we had a partial copy, we need to get more iclog * space but we don't want to increment the region * index because there is still more is this region to * write. * * If we completed writing this region, and we flushed * the iclog (indicated by resetting of the record * count), then we also need to get more log space. If * this was the last record, though, we are done and * can just return. */ if (partial_copy) break; if (++index == lv->lv_niovecs) { next_lv: lv = lv->lv_next; index = 0; if (lv) vecp = lv->lv_iovecp; } if (record_cnt == 0 && ordered == false) { if (!lv) return 0; break; } } } ASSERT(len == 0); xlog_state_finish_copy(log, iclog, record_cnt, data_cnt); if (!commit_iclog) return xlog_state_release_iclog(log, iclog); ASSERT(flags & XLOG_COMMIT_TRANS); *commit_iclog = iclog; return 0; } /***************************************************************************** * * State Machine functions * ***************************************************************************** */ /* Clean iclogs starting from the head. This ordering must be * maintained, so an iclog doesn't become ACTIVE beyond one that * is SYNCING. This is also required to maintain the notion that we use * a ordered wait queue to hold off would be writers to the log when every * iclog is trying to sync to disk. * * State Change: DIRTY -> ACTIVE */ STATIC void xlog_state_clean_log( struct xlog *log) { xlog_in_core_t *iclog; int changed = 0; iclog = log->l_iclog; do { if (iclog->ic_state == XLOG_STATE_DIRTY) { iclog->ic_state = XLOG_STATE_ACTIVE; iclog->ic_offset = 0; ASSERT(iclog->ic_callback == NULL); /* * If the number of ops in this iclog indicate it just * contains the dummy transaction, we can * change state into IDLE (the second time around). * Otherwise we should change the state into * NEED a dummy. * We don't need to cover the dummy. */ if (!changed && (be32_to_cpu(iclog->ic_header.h_num_logops) == XLOG_COVER_OPS)) { changed = 1; } else { /* * We have two dirty iclogs so start over * This could also be num of ops indicates * this is not the dummy going out. */ changed = 2; } iclog->ic_header.h_num_logops = 0; memset(iclog->ic_header.h_cycle_data, 0, sizeof(iclog->ic_header.h_cycle_data)); iclog->ic_header.h_lsn = 0; } else if (iclog->ic_state == XLOG_STATE_ACTIVE) /* do nothing */; else break; /* stop cleaning */ iclog = iclog->ic_next; } while (iclog != log->l_iclog); /* log is locked when we are called */ /* * Change state for the dummy log recording. * We usually go to NEED. But we go to NEED2 if the changed indicates * we are done writing the dummy record. * If we are done with the second dummy recored (DONE2), then * we go to IDLE. */ if (changed) { switch (log->l_covered_state) { case XLOG_STATE_COVER_IDLE: case XLOG_STATE_COVER_NEED: case XLOG_STATE_COVER_NEED2: log->l_covered_state = XLOG_STATE_COVER_NEED; break; case XLOG_STATE_COVER_DONE: if (changed == 1) log->l_covered_state = XLOG_STATE_COVER_NEED2; else log->l_covered_state = XLOG_STATE_COVER_NEED; break; case XLOG_STATE_COVER_DONE2: if (changed == 1) log->l_covered_state = XLOG_STATE_COVER_IDLE; else log->l_covered_state = XLOG_STATE_COVER_NEED; break; default: ASSERT(0); } } } /* xlog_state_clean_log */ STATIC xfs_lsn_t xlog_get_lowest_lsn( struct xlog *log) { xlog_in_core_t *lsn_log; xfs_lsn_t lowest_lsn, lsn; lsn_log = log->l_iclog; lowest_lsn = 0; do { if (!(lsn_log->ic_state & (XLOG_STATE_ACTIVE|XLOG_STATE_DIRTY))) { lsn = be64_to_cpu(lsn_log->ic_header.h_lsn); if ((lsn && !lowest_lsn) || (XFS_LSN_CMP(lsn, lowest_lsn) < 0)) { lowest_lsn = lsn; } } lsn_log = lsn_log->ic_next; } while (lsn_log != log->l_iclog); return lowest_lsn; } STATIC void xlog_state_do_callback( struct xlog *log, int aborted, struct xlog_in_core *ciclog) { xlog_in_core_t *iclog; xlog_in_core_t *first_iclog; /* used to know when we've * processed all iclogs once */ xfs_log_callback_t *cb, *cb_next; int flushcnt = 0; xfs_lsn_t lowest_lsn; int ioerrors; /* counter: iclogs with errors */ int loopdidcallbacks; /* flag: inner loop did callbacks*/ int funcdidcallbacks; /* flag: function did callbacks */ int repeats; /* for issuing console warnings if * looping too many times */ int wake = 0; spin_lock(&log->l_icloglock); first_iclog = iclog = log->l_iclog; ioerrors = 0; funcdidcallbacks = 0; repeats = 0; do { /* * Scan all iclogs starting with the one pointed to by the * log. Reset this starting point each time the log is * unlocked (during callbacks). * * Keep looping through iclogs until one full pass is made * without running any callbacks. */ first_iclog = log->l_iclog; iclog = log->l_iclog; loopdidcallbacks = 0; repeats++; do { /* skip all iclogs in the ACTIVE & DIRTY states */ if (iclog->ic_state & (XLOG_STATE_ACTIVE|XLOG_STATE_DIRTY)) { iclog = iclog->ic_next; continue; } /* * Between marking a filesystem SHUTDOWN and stopping * the log, we do flush all iclogs to disk (if there * wasn't a log I/O error). So, we do want things to * go smoothly in case of just a SHUTDOWN w/o a * LOG_IO_ERROR. */ if (!(iclog->ic_state & XLOG_STATE_IOERROR)) { /* * Can only perform callbacks in order. Since * this iclog is not in the DONE_SYNC/ * DO_CALLBACK state, we skip the rest and * just try to clean up. If we set our iclog * to DO_CALLBACK, we will not process it when * we retry since a previous iclog is in the * CALLBACK and the state cannot change since * we are holding the l_icloglock. */ if (!(iclog->ic_state & (XLOG_STATE_DONE_SYNC | XLOG_STATE_DO_CALLBACK))) { if (ciclog && (ciclog->ic_state == XLOG_STATE_DONE_SYNC)) { ciclog->ic_state = XLOG_STATE_DO_CALLBACK; } break; } /* * We now have an iclog that is in either the * DO_CALLBACK or DONE_SYNC states. The other * states (WANT_SYNC, SYNCING, or CALLBACK were * caught by the above if and are going to * clean (i.e. we aren't doing their callbacks) * see the above if. */ /* * We will do one more check here to see if we * have chased our tail around. */ lowest_lsn = xlog_get_lowest_lsn(log); if (lowest_lsn && XFS_LSN_CMP(lowest_lsn, be64_to_cpu(iclog->ic_header.h_lsn)) < 0) { iclog = iclog->ic_next; continue; /* Leave this iclog for * another thread */ } iclog->ic_state = XLOG_STATE_CALLBACK; /* * Completion of a iclog IO does not imply that * a transaction has completed, as transactions * can be large enough to span many iclogs. We * cannot change the tail of the log half way * through a transaction as this may be the only * transaction in the log and moving th etail to * point to the middle of it will prevent * recovery from finding the start of the * transaction. Hence we should only update the * last_sync_lsn if this iclog contains * transaction completion callbacks on it. * * We have to do this before we drop the * icloglock to ensure we are the only one that * can update it. */ ASSERT(XFS_LSN_CMP(atomic64_read(&log->l_last_sync_lsn), be64_to_cpu(iclog->ic_header.h_lsn)) <= 0); if (iclog->ic_callback) atomic64_set(&log->l_last_sync_lsn, be64_to_cpu(iclog->ic_header.h_lsn)); } else ioerrors++; spin_unlock(&log->l_icloglock); /* * Keep processing entries in the callback list until * we come around and it is empty. We need to * atomically see that the list is empty and change the * state to DIRTY so that we don't miss any more * callbacks being added. */ spin_lock(&iclog->ic_callback_lock); cb = iclog->ic_callback; while (cb) { iclog->ic_callback_tail = &(iclog->ic_callback); iclog->ic_callback = NULL; spin_unlock(&iclog->ic_callback_lock); /* perform callbacks in the order given */ for (; cb; cb = cb_next) { cb_next = cb->cb_next; cb->cb_func(cb->cb_arg, aborted); } spin_lock(&iclog->ic_callback_lock); cb = iclog->ic_callback; } loopdidcallbacks++; funcdidcallbacks++; spin_lock(&log->l_icloglock); ASSERT(iclog->ic_callback == NULL); spin_unlock(&iclog->ic_callback_lock); if (!(iclog->ic_state & XLOG_STATE_IOERROR)) iclog->ic_state = XLOG_STATE_DIRTY; /* * Transition from DIRTY to ACTIVE if applicable. * NOP if STATE_IOERROR. */ xlog_state_clean_log(log); /* wake up threads waiting in xfs_log_force() */ wake_up_all(&iclog->ic_force_wait); iclog = iclog->ic_next; } while (first_iclog != iclog); if (repeats > 5000) { flushcnt += repeats; repeats = 0; xfs_warn(log->l_mp, "%s: possible infinite loop (%d iterations)", __func__, flushcnt); } } while (!ioerrors && loopdidcallbacks); #ifdef DEBUG /* * Make one last gasp attempt to see if iclogs are being left in limbo. * If the above loop finds an iclog earlier than the current iclog and * in one of the syncing states, the current iclog is put into * DO_CALLBACK and the callbacks are deferred to the completion of the * earlier iclog. Walk the iclogs in order and make sure that no iclog * is in DO_CALLBACK unless an earlier iclog is in one of the syncing * states. * * Note that SYNCING|IOABORT is a valid state so we cannot just check * for ic_state == SYNCING. */ if (funcdidcallbacks) { first_iclog = iclog = log->l_iclog; do { ASSERT(iclog->ic_state != XLOG_STATE_DO_CALLBACK); /* * Terminate the loop if iclogs are found in states * which will cause other threads to clean up iclogs. * * SYNCING - i/o completion will go through logs * DONE_SYNC - interrupt thread should be waiting for * l_icloglock * IOERROR - give up hope all ye who enter here */ if (iclog->ic_state == XLOG_STATE_WANT_SYNC || iclog->ic_state & XLOG_STATE_SYNCING || iclog->ic_state == XLOG_STATE_DONE_SYNC || iclog->ic_state == XLOG_STATE_IOERROR ) break; iclog = iclog->ic_next; } while (first_iclog != iclog); } #endif if (log->l_iclog->ic_state & (XLOG_STATE_ACTIVE|XLOG_STATE_IOERROR)) wake = 1; spin_unlock(&log->l_icloglock); if (wake) wake_up_all(&log->l_flush_wait); } /* * Finish transitioning this iclog to the dirty state. * * Make sure that we completely execute this routine only when this is * the last call to the iclog. There is a good chance that iclog flushes, * when we reach the end of the physical log, get turned into 2 separate * calls to bwrite. Hence, one iclog flush could generate two calls to this * routine. By using the reference count bwritecnt, we guarantee that only * the second completion goes through. * * Callbacks could take time, so they are done outside the scope of the * global state machine log lock. */ STATIC void xlog_state_done_syncing( xlog_in_core_t *iclog, int aborted) { struct xlog *log = iclog->ic_log; spin_lock(&log->l_icloglock); ASSERT(iclog->ic_state == XLOG_STATE_SYNCING || iclog->ic_state == XLOG_STATE_IOERROR); ASSERT(atomic_read(&iclog->ic_refcnt) == 0); ASSERT(iclog->ic_bwritecnt == 1 || iclog->ic_bwritecnt == 2); /* * If we got an error, either on the first buffer, or in the case of * split log writes, on the second, we mark ALL iclogs STATE_IOERROR, * and none should ever be attempted to be written to disk * again. */ if (iclog->ic_state != XLOG_STATE_IOERROR) { if (--iclog->ic_bwritecnt == 1) { spin_unlock(&log->l_icloglock); return; } iclog->ic_state = XLOG_STATE_DONE_SYNC; } /* * Someone could be sleeping prior to writing out the next * iclog buffer, we wake them all, one will get to do the * I/O, the others get to wait for the result. */ wake_up_all(&iclog->ic_write_wait); spin_unlock(&log->l_icloglock); xlog_state_do_callback(log, aborted, iclog); /* also cleans log */ } /* xlog_state_done_syncing */ /* * If the head of the in-core log ring is not (ACTIVE or DIRTY), then we must * sleep. We wait on the flush queue on the head iclog as that should be * the first iclog to complete flushing. Hence if all iclogs are syncing, * we will wait here and all new writes will sleep until a sync completes. * * The in-core logs are used in a circular fashion. They are not used * out-of-order even when an iclog past the head is free. * * return: * * log_offset where xlog_write() can start writing into the in-core * log's data space. * * in-core log pointer to which xlog_write() should write. * * boolean indicating this is a continued write to an in-core log. * If this is the last write, then the in-core log's offset field * needs to be incremented, depending on the amount of data which * is copied. */ STATIC int xlog_state_get_iclog_space( struct xlog *log, int len, struct xlog_in_core **iclogp, struct xlog_ticket *ticket, int *continued_write, int *logoffsetp) { int log_offset; xlog_rec_header_t *head; xlog_in_core_t *iclog; int error; restart: spin_lock(&log->l_icloglock); if (XLOG_FORCED_SHUTDOWN(log)) { spin_unlock(&log->l_icloglock); return -EIO; } iclog = log->l_iclog; if (iclog->ic_state != XLOG_STATE_ACTIVE) { XFS_STATS_INC(log->l_mp, xs_log_noiclogs); /* Wait for log writes to have flushed */ xlog_wait(&log->l_flush_wait, &log->l_icloglock); goto restart; } head = &iclog->ic_header; atomic_inc(&iclog->ic_refcnt); /* prevents sync */ log_offset = iclog->ic_offset; /* On the 1st write to an iclog, figure out lsn. This works * if iclogs marked XLOG_STATE_WANT_SYNC always write out what they are * committing to. If the offset is set, that's how many blocks * must be written. */ if (log_offset == 0) { ticket->t_curr_res -= log->l_iclog_hsize; xlog_tic_add_region(ticket, log->l_iclog_hsize, XLOG_REG_TYPE_LRHEADER); head->h_cycle = cpu_to_be32(log->l_curr_cycle); head->h_lsn = cpu_to_be64( xlog_assign_lsn(log->l_curr_cycle, log->l_curr_block)); ASSERT(log->l_curr_block >= 0); } /* If there is enough room to write everything, then do it. Otherwise, * claim the rest of the region and make sure the XLOG_STATE_WANT_SYNC * bit is on, so this will get flushed out. Don't update ic_offset * until you know exactly how many bytes get copied. Therefore, wait * until later to update ic_offset. * * xlog_write() algorithm assumes that at least 2 xlog_op_header_t's * can fit into remaining data section. */ if (iclog->ic_size - iclog->ic_offset < 2*sizeof(xlog_op_header_t)) { xlog_state_switch_iclogs(log, iclog, iclog->ic_size); /* * If I'm the only one writing to this iclog, sync it to disk. * We need to do an atomic compare and decrement here to avoid * racing with concurrent atomic_dec_and_lock() calls in * xlog_state_release_iclog() when there is more than one * reference to the iclog. */ if (!atomic_add_unless(&iclog->ic_refcnt, -1, 1)) { /* we are the only one */ spin_unlock(&log->l_icloglock); error = xlog_state_release_iclog(log, iclog); if (error) return error; } else { spin_unlock(&log->l_icloglock); } goto restart; } /* Do we have enough room to write the full amount in the remainder * of this iclog? Or must we continue a write on the next iclog and * mark this iclog as completely taken? In the case where we switch * iclogs (to mark it taken), this particular iclog will release/sync * to disk in xlog_write(). */ if (len <= iclog->ic_size - iclog->ic_offset) { *continued_write = 0; iclog->ic_offset += len; } else { *continued_write = 1; xlog_state_switch_iclogs(log, iclog, iclog->ic_size); } *iclogp = iclog; ASSERT(iclog->ic_offset <= iclog->ic_size); spin_unlock(&log->l_icloglock); *logoffsetp = log_offset; return 0; } /* xlog_state_get_iclog_space */ /* The first cnt-1 times through here we don't need to * move the grant write head because the permanent * reservation has reserved cnt times the unit amount. * Release part of current permanent unit reservation and * reset current reservation to be one units worth. Also * move grant reservation head forward. */ STATIC void xlog_regrant_reserve_log_space( struct xlog *log, struct xlog_ticket *ticket) { trace_xfs_log_regrant_reserve_enter(log, ticket); if (ticket->t_cnt > 0) ticket->t_cnt--; xlog_grant_sub_space(log, &log->l_reserve_head.grant, ticket->t_curr_res); xlog_grant_sub_space(log, &log->l_write_head.grant, ticket->t_curr_res); ticket->t_curr_res = ticket->t_unit_res; xlog_tic_reset_res(ticket); trace_xfs_log_regrant_reserve_sub(log, ticket); /* just return if we still have some of the pre-reserved space */ if (ticket->t_cnt > 0) return; xlog_grant_add_space(log, &log->l_reserve_head.grant, ticket->t_unit_res); trace_xfs_log_regrant_reserve_exit(log, ticket); ticket->t_curr_res = ticket->t_unit_res; xlog_tic_reset_res(ticket); } /* xlog_regrant_reserve_log_space */ /* * Give back the space left from a reservation. * * All the information we need to make a correct determination of space left * is present. For non-permanent reservations, things are quite easy. The * count should have been decremented to zero. We only need to deal with the * space remaining in the current reservation part of the ticket. If the * ticket contains a permanent reservation, there may be left over space which * needs to be released. A count of N means that N-1 refills of the current * reservation can be done before we need to ask for more space. The first * one goes to fill up the first current reservation. Once we run out of * space, the count will stay at zero and the only space remaining will be * in the current reservation field. */ STATIC void xlog_ungrant_log_space( struct xlog *log, struct xlog_ticket *ticket) { int bytes; if (ticket->t_cnt > 0) ticket->t_cnt--; trace_xfs_log_ungrant_enter(log, ticket); trace_xfs_log_ungrant_sub(log, ticket); /* * If this is a permanent reservation ticket, we may be able to free * up more space based on the remaining count. */ bytes = ticket->t_curr_res; if (ticket->t_cnt > 0) { ASSERT(ticket->t_flags & XLOG_TIC_PERM_RESERV); bytes += ticket->t_unit_res*ticket->t_cnt; } xlog_grant_sub_space(log, &log->l_reserve_head.grant, bytes); xlog_grant_sub_space(log, &log->l_write_head.grant, bytes); trace_xfs_log_ungrant_exit(log, ticket); xfs_log_space_wake(log->l_mp); } /* * Flush iclog to disk if this is the last reference to the given iclog and * the WANT_SYNC bit is set. * * When this function is entered, the iclog is not necessarily in the * WANT_SYNC state. It may be sitting around waiting to get filled. * * */ STATIC int xlog_state_release_iclog( struct xlog *log, struct xlog_in_core *iclog) { int sync = 0; /* do we sync? */ if (iclog->ic_state & XLOG_STATE_IOERROR) return -EIO; ASSERT(atomic_read(&iclog->ic_refcnt) > 0); if (!atomic_dec_and_lock(&iclog->ic_refcnt, &log->l_icloglock)) return 0; if (iclog->ic_state & XLOG_STATE_IOERROR) { spin_unlock(&log->l_icloglock); return -EIO; } ASSERT(iclog->ic_state == XLOG_STATE_ACTIVE || iclog->ic_state == XLOG_STATE_WANT_SYNC); if (iclog->ic_state == XLOG_STATE_WANT_SYNC) { /* update tail before writing to iclog */ xfs_lsn_t tail_lsn = xlog_assign_tail_lsn(log->l_mp); sync++; iclog->ic_state = XLOG_STATE_SYNCING; iclog->ic_header.h_tail_lsn = cpu_to_be64(tail_lsn); xlog_verify_tail_lsn(log, iclog, tail_lsn); /* cycle incremented when incrementing curr_block */ } spin_unlock(&log->l_icloglock); /* * We let the log lock go, so it's possible that we hit a log I/O * error or some other SHUTDOWN condition that marks the iclog * as XLOG_STATE_IOERROR before the bwrite. However, we know that * this iclog has consistent data, so we ignore IOERROR * flags after this point. */ if (sync) return xlog_sync(log, iclog); return 0; } /* xlog_state_release_iclog */ /* * This routine will mark the current iclog in the ring as WANT_SYNC * and move the current iclog pointer to the next iclog in the ring. * When this routine is called from xlog_state_get_iclog_space(), the * exact size of the iclog has not yet been determined. All we know is * that every data block. We have run out of space in this log record. */ STATIC void xlog_state_switch_iclogs( struct xlog *log, struct xlog_in_core *iclog, int eventual_size) { ASSERT(iclog->ic_state == XLOG_STATE_ACTIVE); if (!eventual_size) eventual_size = iclog->ic_offset; iclog->ic_state = XLOG_STATE_WANT_SYNC; iclog->ic_header.h_prev_block = cpu_to_be32(log->l_prev_block); log->l_prev_block = log->l_curr_block; log->l_prev_cycle = log->l_curr_cycle; /* roll log?: ic_offset changed later */ log->l_curr_block += BTOBB(eventual_size)+BTOBB(log->l_iclog_hsize); /* Round up to next log-sunit */ if (xfs_sb_version_haslogv2(&log->l_mp->m_sb) && log->l_mp->m_sb.sb_logsunit > 1) { uint32_t sunit_bb = BTOBB(log->l_mp->m_sb.sb_logsunit); log->l_curr_block = roundup(log->l_curr_block, sunit_bb); } if (log->l_curr_block >= log->l_logBBsize) { /* * Rewind the current block before the cycle is bumped to make * sure that the combined LSN never transiently moves forward * when the log wraps to the next cycle. This is to support the * unlocked sample of these fields from xlog_valid_lsn(). Most * other cases should acquire l_icloglock. */ log->l_curr_block -= log->l_logBBsize; ASSERT(log->l_curr_block >= 0); smp_wmb(); log->l_curr_cycle++; if (log->l_curr_cycle == XLOG_HEADER_MAGIC_NUM) log->l_curr_cycle++; } ASSERT(iclog == log->l_iclog); log->l_iclog = iclog->ic_next; } /* xlog_state_switch_iclogs */ /* * Write out all data in the in-core log as of this exact moment in time. * * Data may be written to the in-core log during this call. However, * we don't guarantee this data will be written out. A change from past * implementation means this routine will *not* write out zero length LRs. * * Basically, we try and perform an intelligent scan of the in-core logs. * If we determine there is no flushable data, we just return. There is no * flushable data if: * * 1. the current iclog is active and has no data; the previous iclog * is in the active or dirty state. * 2. the current iclog is drity, and the previous iclog is in the * active or dirty state. * * We may sleep if: * * 1. the current iclog is not in the active nor dirty state. * 2. the current iclog dirty, and the previous iclog is not in the * active nor dirty state. * 3. the current iclog is active, and there is another thread writing * to this particular iclog. * 4. a) the current iclog is active and has no other writers * b) when we return from flushing out this iclog, it is still * not in the active nor dirty state. */ int _xfs_log_force( struct xfs_mount *mp, uint flags, int *log_flushed) { struct xlog *log = mp->m_log; struct xlog_in_core *iclog; xfs_lsn_t lsn; XFS_STATS_INC(mp, xs_log_force); xlog_cil_force(log); spin_lock(&log->l_icloglock); iclog = log->l_iclog; if (iclog->ic_state & XLOG_STATE_IOERROR) { spin_unlock(&log->l_icloglock); return -EIO; } /* If the head iclog is not active nor dirty, we just attach * ourselves to the head and go to sleep. */ if (iclog->ic_state == XLOG_STATE_ACTIVE || iclog->ic_state == XLOG_STATE_DIRTY) { /* * If the head is dirty or (active and empty), then * we need to look at the previous iclog. If the previous * iclog is active or dirty we are done. There is nothing * to sync out. Otherwise, we attach ourselves to the * previous iclog and go to sleep. */ if (iclog->ic_state == XLOG_STATE_DIRTY || (atomic_read(&iclog->ic_refcnt) == 0 && iclog->ic_offset == 0)) { iclog = iclog->ic_prev; if (iclog->ic_state == XLOG_STATE_ACTIVE || iclog->ic_state == XLOG_STATE_DIRTY) goto no_sleep; else goto maybe_sleep; } else { if (atomic_read(&iclog->ic_refcnt) == 0) { /* We are the only one with access to this * iclog. Flush it out now. There should * be a roundoff of zero to show that someone * has already taken care of the roundoff from * the previous sync. */ atomic_inc(&iclog->ic_refcnt); lsn = be64_to_cpu(iclog->ic_header.h_lsn); xlog_state_switch_iclogs(log, iclog, 0); spin_unlock(&log->l_icloglock); if (xlog_state_release_iclog(log, iclog)) return -EIO; if (log_flushed) *log_flushed = 1; spin_lock(&log->l_icloglock); if (be64_to_cpu(iclog->ic_header.h_lsn) == lsn && iclog->ic_state != XLOG_STATE_DIRTY) goto maybe_sleep; else goto no_sleep; } else { /* Someone else is writing to this iclog. * Use its call to flush out the data. However, * the other thread may not force out this LR, * so we mark it WANT_SYNC. */ xlog_state_switch_iclogs(log, iclog, 0); goto maybe_sleep; } } } /* By the time we come around again, the iclog could've been filled * which would give it another lsn. If we have a new lsn, just * return because the relevant data has been flushed. */ maybe_sleep: if (flags & XFS_LOG_SYNC) { /* * We must check if we're shutting down here, before * we wait, while we're holding the l_icloglock. * Then we check again after waking up, in case our * sleep was disturbed by a bad news. */ if (iclog->ic_state & XLOG_STATE_IOERROR) { spin_unlock(&log->l_icloglock); return -EIO; } XFS_STATS_INC(mp, xs_log_force_sleep); xlog_wait(&iclog->ic_force_wait, &log->l_icloglock); /* * No need to grab the log lock here since we're * only deciding whether or not to return EIO * and the memory read should be atomic. */ if (iclog->ic_state & XLOG_STATE_IOERROR) return -EIO; } else { no_sleep: spin_unlock(&log->l_icloglock); } return 0; } /* * Wrapper for _xfs_log_force(), to be used when caller doesn't care * about errors or whether the log was flushed or not. This is the normal * interface to use when trying to unpin items or move the log forward. */ void xfs_log_force( xfs_mount_t *mp, uint flags) { trace_xfs_log_force(mp, 0, _RET_IP_); _xfs_log_force(mp, flags, NULL); } /* * Force the in-core log to disk for a specific LSN. * * Find in-core log with lsn. * If it is in the DIRTY state, just return. * If it is in the ACTIVE state, move the in-core log into the WANT_SYNC * state and go to sleep or return. * If it is in any other state, go to sleep or return. * * Synchronous forces are implemented with a signal variable. All callers * to force a given lsn to disk will wait on a the sv attached to the * specific in-core log. When given in-core log finally completes its * write to disk, that thread will wake up all threads waiting on the * sv. */ int _xfs_log_force_lsn( struct xfs_mount *mp, xfs_lsn_t lsn, uint flags, int *log_flushed) { struct xlog *log = mp->m_log; struct xlog_in_core *iclog; int already_slept = 0; ASSERT(lsn != 0); XFS_STATS_INC(mp, xs_log_force); lsn = xlog_cil_force_lsn(log, lsn); if (lsn == NULLCOMMITLSN) return 0; try_again: spin_lock(&log->l_icloglock); iclog = log->l_iclog; if (iclog->ic_state & XLOG_STATE_IOERROR) { spin_unlock(&log->l_icloglock); return -EIO; } do { if (be64_to_cpu(iclog->ic_header.h_lsn) != lsn) { iclog = iclog->ic_next; continue; } if (iclog->ic_state == XLOG_STATE_DIRTY) { spin_unlock(&log->l_icloglock); return 0; } if (iclog->ic_state == XLOG_STATE_ACTIVE) { /* * We sleep here if we haven't already slept (e.g. * this is the first time we've looked at the correct * iclog buf) and the buffer before us is going to * be sync'ed. The reason for this is that if we * are doing sync transactions here, by waiting for * the previous I/O to complete, we can allow a few * more transactions into this iclog before we close * it down. * * Otherwise, we mark the buffer WANT_SYNC, and bump * up the refcnt so we can release the log (which * drops the ref count). The state switch keeps new * transaction commits from using this buffer. When * the current commits finish writing into the buffer, * the refcount will drop to zero and the buffer will * go out then. */ if (!already_slept && (iclog->ic_prev->ic_state & (XLOG_STATE_WANT_SYNC | XLOG_STATE_SYNCING))) { ASSERT(!(iclog->ic_state & XLOG_STATE_IOERROR)); XFS_STATS_INC(mp, xs_log_force_sleep); xlog_wait(&iclog->ic_prev->ic_write_wait, &log->l_icloglock); already_slept = 1; goto try_again; } atomic_inc(&iclog->ic_refcnt); xlog_state_switch_iclogs(log, iclog, 0); spin_unlock(&log->l_icloglock); if (xlog_state_release_iclog(log, iclog)) return -EIO; if (log_flushed) *log_flushed = 1; spin_lock(&log->l_icloglock); } if ((flags & XFS_LOG_SYNC) && /* sleep */ !(iclog->ic_state & (XLOG_STATE_ACTIVE | XLOG_STATE_DIRTY))) { /* * Don't wait on completion if we know that we've * gotten a log write error. */ if (iclog->ic_state & XLOG_STATE_IOERROR) { spin_unlock(&log->l_icloglock); return -EIO; } XFS_STATS_INC(mp, xs_log_force_sleep); xlog_wait(&iclog->ic_force_wait, &log->l_icloglock); /* * No need to grab the log lock here since we're * only deciding whether or not to return EIO * and the memory read should be atomic. */ if (iclog->ic_state & XLOG_STATE_IOERROR) return -EIO; } else { /* just return */ spin_unlock(&log->l_icloglock); } return 0; } while (iclog != log->l_iclog); spin_unlock(&log->l_icloglock); return 0; } /* * Wrapper for _xfs_log_force_lsn(), to be used when caller doesn't care * about errors or whether the log was flushed or not. This is the normal * interface to use when trying to unpin items or move the log forward. */ void xfs_log_force_lsn( xfs_mount_t *mp, xfs_lsn_t lsn, uint flags) { trace_xfs_log_force(mp, lsn, _RET_IP_); _xfs_log_force_lsn(mp, lsn, flags, NULL); } /* * Called when we want to mark the current iclog as being ready to sync to * disk. */ STATIC void xlog_state_want_sync( struct xlog *log, struct xlog_in_core *iclog) { assert_spin_locked(&log->l_icloglock); if (iclog->ic_state == XLOG_STATE_ACTIVE) { xlog_state_switch_iclogs(log, iclog, 0); } else { ASSERT(iclog->ic_state & (XLOG_STATE_WANT_SYNC|XLOG_STATE_IOERROR)); } } /***************************************************************************** * * TICKET functions * ***************************************************************************** */ /* * Free a used ticket when its refcount falls to zero. */ void xfs_log_ticket_put( xlog_ticket_t *ticket) { ASSERT(atomic_read(&ticket->t_ref) > 0); if (atomic_dec_and_test(&ticket->t_ref)) kmem_zone_free(xfs_log_ticket_zone, ticket); } xlog_ticket_t * xfs_log_ticket_get( xlog_ticket_t *ticket) { ASSERT(atomic_read(&ticket->t_ref) > 0); atomic_inc(&ticket->t_ref); return ticket; } /* * Figure out the total log space unit (in bytes) that would be * required for a log ticket. */ int xfs_log_calc_unit_res( struct xfs_mount *mp, int unit_bytes) { struct xlog *log = mp->m_log; int iclog_space; uint num_headers; /* * Permanent reservations have up to 'cnt'-1 active log operations * in the log. A unit in this case is the amount of space for one * of these log operations. Normal reservations have a cnt of 1 * and their unit amount is the total amount of space required. * * The following lines of code account for non-transaction data * which occupy space in the on-disk log. * * Normal form of a transaction is: * <oph><trans-hdr><start-oph><reg1-oph><reg1><reg2-oph>...<commit-oph> * and then there are LR hdrs, split-recs and roundoff at end of syncs. * * We need to account for all the leadup data and trailer data * around the transaction data. * And then we need to account for the worst case in terms of using * more space. * The worst case will happen if: * - the placement of the transaction happens to be such that the * roundoff is at its maximum * - the transaction data is synced before the commit record is synced * i.e. <transaction-data><roundoff> | <commit-rec><roundoff> * Therefore the commit record is in its own Log Record. * This can happen as the commit record is called with its * own region to xlog_write(). * This then means that in the worst case, roundoff can happen for * the commit-rec as well. * The commit-rec is smaller than padding in this scenario and so it is * not added separately. */ /* for trans header */ unit_bytes += sizeof(xlog_op_header_t); unit_bytes += sizeof(xfs_trans_header_t); /* for start-rec */ unit_bytes += sizeof(xlog_op_header_t); /* * for LR headers - the space for data in an iclog is the size minus * the space used for the headers. If we use the iclog size, then we * undercalculate the number of headers required. * * Furthermore - the addition of op headers for split-recs might * increase the space required enough to require more log and op * headers, so take that into account too. * * IMPORTANT: This reservation makes the assumption that if this * transaction is the first in an iclog and hence has the LR headers * accounted to it, then the remaining space in the iclog is * exclusively for this transaction. i.e. if the transaction is larger * than the iclog, it will be the only thing in that iclog. * Fundamentally, this means we must pass the entire log vector to * xlog_write to guarantee this. */ iclog_space = log->l_iclog_size - log->l_iclog_hsize; num_headers = howmany(unit_bytes, iclog_space); /* for split-recs - ophdrs added when data split over LRs */ unit_bytes += sizeof(xlog_op_header_t) * num_headers; /* add extra header reservations if we overrun */ while (!num_headers || howmany(unit_bytes, iclog_space) > num_headers) { unit_bytes += sizeof(xlog_op_header_t); num_headers++; } unit_bytes += log->l_iclog_hsize * num_headers; /* for commit-rec LR header - note: padding will subsume the ophdr */ unit_bytes += log->l_iclog_hsize; /* for roundoff padding for transaction data and one for commit record */ if (xfs_sb_version_haslogv2(&mp->m_sb) && mp->m_sb.sb_logsunit > 1) { /* log su roundoff */ unit_bytes += 2 * mp->m_sb.sb_logsunit; } else { /* BB roundoff */ unit_bytes += 2 * BBSIZE; } return unit_bytes; } /* * Allocate and initialise a new log ticket. */ struct xlog_ticket * xlog_ticket_alloc( struct xlog *log, int unit_bytes, int cnt, char client, bool permanent, xfs_km_flags_t alloc_flags) { struct xlog_ticket *tic; int unit_res; tic = kmem_zone_zalloc(xfs_log_ticket_zone, alloc_flags); if (!tic) return NULL; unit_res = xfs_log_calc_unit_res(log->l_mp, unit_bytes); atomic_set(&tic->t_ref, 1); tic->t_task = current; INIT_LIST_HEAD(&tic->t_queue); tic->t_unit_res = unit_res; tic->t_curr_res = unit_res; tic->t_cnt = cnt; tic->t_ocnt = cnt; tic->t_tid = prandom_u32(); tic->t_clientid = client; tic->t_flags = XLOG_TIC_INITED; if (permanent) tic->t_flags |= XLOG_TIC_PERM_RESERV; xlog_tic_reset_res(tic); return tic; } /****************************************************************************** * * Log debug routines * ****************************************************************************** */ #if defined(DEBUG) /* * Make sure that the destination ptr is within the valid data region of * one of the iclogs. This uses backup pointers stored in a different * part of the log in case we trash the log structure. */ void xlog_verify_dest_ptr( struct xlog *log, void *ptr) { int i; int good_ptr = 0; for (i = 0; i < log->l_iclog_bufs; i++) { if (ptr >= log->l_iclog_bak[i] && ptr <= log->l_iclog_bak[i] + log->l_iclog_size) good_ptr++; } if (!good_ptr) xfs_emerg(log->l_mp, "%s: invalid ptr", __func__); } /* * Check to make sure the grant write head didn't just over lap the tail. If * the cycles are the same, we can't be overlapping. Otherwise, make sure that * the cycles differ by exactly one and check the byte count. * * This check is run unlocked, so can give false positives. Rather than assert * on failures, use a warn-once flag and a panic tag to allow the admin to * determine if they want to panic the machine when such an error occurs. For * debug kernels this will have the same effect as using an assert but, unlinke * an assert, it can be turned off at runtime. */ STATIC void xlog_verify_grant_tail( struct xlog *log) { int tail_cycle, tail_blocks; int cycle, space; xlog_crack_grant_head(&log->l_write_head.grant, &cycle, &space); xlog_crack_atomic_lsn(&log->l_tail_lsn, &tail_cycle, &tail_blocks); if (tail_cycle != cycle) { if (cycle - 1 != tail_cycle && !(log->l_flags & XLOG_TAIL_WARN)) { xfs_alert_tag(log->l_mp, XFS_PTAG_LOGRES, "%s: cycle - 1 != tail_cycle", __func__); log->l_flags |= XLOG_TAIL_WARN; } if (space > BBTOB(tail_blocks) && !(log->l_flags & XLOG_TAIL_WARN)) { xfs_alert_tag(log->l_mp, XFS_PTAG_LOGRES, "%s: space > BBTOB(tail_blocks)", __func__); log->l_flags |= XLOG_TAIL_WARN; } } } /* check if it will fit */ STATIC void xlog_verify_tail_lsn( struct xlog *log, struct xlog_in_core *iclog, xfs_lsn_t tail_lsn) { int blocks; if (CYCLE_LSN(tail_lsn) == log->l_prev_cycle) { blocks = log->l_logBBsize - (log->l_prev_block - BLOCK_LSN(tail_lsn)); if (blocks < BTOBB(iclog->ic_offset)+BTOBB(log->l_iclog_hsize)) xfs_emerg(log->l_mp, "%s: ran out of log space", __func__); } else { ASSERT(CYCLE_LSN(tail_lsn)+1 == log->l_prev_cycle); if (BLOCK_LSN(tail_lsn) == log->l_prev_block) xfs_emerg(log->l_mp, "%s: tail wrapped", __func__); blocks = BLOCK_LSN(tail_lsn) - log->l_prev_block; if (blocks < BTOBB(iclog->ic_offset) + 1) xfs_emerg(log->l_mp, "%s: ran out of log space", __func__); } } /* xlog_verify_tail_lsn */ /* * Perform a number of checks on the iclog before writing to disk. * * 1. Make sure the iclogs are still circular * 2. Make sure we have a good magic number * 3. Make sure we don't have magic numbers in the data * 4. Check fields of each log operation header for: * A. Valid client identifier * B. tid ptr value falls in valid ptr space (user space code) * C. Length in log record header is correct according to the * individual operation headers within record. * 5. When a bwrite will occur within 5 blocks of the front of the physical * log, check the preceding blocks of the physical log to make sure all * the cycle numbers agree with the current cycle number. */ STATIC void xlog_verify_iclog( struct xlog *log, struct xlog_in_core *iclog, int count, bool syncing) { xlog_op_header_t *ophead; xlog_in_core_t *icptr; xlog_in_core_2_t *xhdr; void *base_ptr, *ptr, *p; ptrdiff_t field_offset; uint8_t clientid; int len, i, j, k, op_len; int idx; /* check validity of iclog pointers */ spin_lock(&log->l_icloglock); icptr = log->l_iclog; for (i = 0; i < log->l_iclog_bufs; i++, icptr = icptr->ic_next) ASSERT(icptr); if (icptr != log->l_iclog) xfs_emerg(log->l_mp, "%s: corrupt iclog ring", __func__); spin_unlock(&log->l_icloglock); /* check log magic numbers */ if (iclog->ic_header.h_magicno != cpu_to_be32(XLOG_HEADER_MAGIC_NUM)) xfs_emerg(log->l_mp, "%s: invalid magic num", __func__); base_ptr = ptr = &iclog->ic_header; p = &iclog->ic_header; for (ptr += BBSIZE; ptr < base_ptr + count; ptr += BBSIZE) { if (*(__be32 *)ptr == cpu_to_be32(XLOG_HEADER_MAGIC_NUM)) xfs_emerg(log->l_mp, "%s: unexpected magic num", __func__); } /* check fields */ len = be32_to_cpu(iclog->ic_header.h_num_logops); base_ptr = ptr = iclog->ic_datap; ophead = ptr; xhdr = iclog->ic_data; for (i = 0; i < len; i++) { ophead = ptr; /* clientid is only 1 byte */ p = &ophead->oh_clientid; field_offset = p - base_ptr; if (!syncing || (field_offset & 0x1ff)) { clientid = ophead->oh_clientid; } else { idx = BTOBBT((char *)&ophead->oh_clientid - iclog->ic_datap); if (idx >= (XLOG_HEADER_CYCLE_SIZE / BBSIZE)) { j = idx / (XLOG_HEADER_CYCLE_SIZE / BBSIZE); k = idx % (XLOG_HEADER_CYCLE_SIZE / BBSIZE); clientid = xlog_get_client_id( xhdr[j].hic_xheader.xh_cycle_data[k]); } else { clientid = xlog_get_client_id( iclog->ic_header.h_cycle_data[idx]); } } if (clientid != XFS_TRANSACTION && clientid != XFS_LOG) xfs_warn(log->l_mp, "%s: invalid clientid %d op 0x%p offset 0x%lx", __func__, clientid, ophead, (unsigned long)field_offset); /* check length */ p = &ophead->oh_len; field_offset = p - base_ptr; if (!syncing || (field_offset & 0x1ff)) { op_len = be32_to_cpu(ophead->oh_len); } else { idx = BTOBBT((uintptr_t)&ophead->oh_len - (uintptr_t)iclog->ic_datap); if (idx >= (XLOG_HEADER_CYCLE_SIZE / BBSIZE)) { j = idx / (XLOG_HEADER_CYCLE_SIZE / BBSIZE); k = idx % (XLOG_HEADER_CYCLE_SIZE / BBSIZE); op_len = be32_to_cpu(xhdr[j].hic_xheader.xh_cycle_data[k]); } else { op_len = be32_to_cpu(iclog->ic_header.h_cycle_data[idx]); } } ptr += sizeof(xlog_op_header_t) + op_len; } } /* xlog_verify_iclog */ #endif /* * Mark all iclogs IOERROR. l_icloglock is held by the caller. */ STATIC int xlog_state_ioerror( struct xlog *log) { xlog_in_core_t *iclog, *ic; iclog = log->l_iclog; if (! (iclog->ic_state & XLOG_STATE_IOERROR)) { /* * Mark all the incore logs IOERROR. * From now on, no log flushes will result. */ ic = iclog; do { ic->ic_state = XLOG_STATE_IOERROR; ic = ic->ic_next; } while (ic != iclog); return 0; } /* * Return non-zero, if state transition has already happened. */ return 1; } /* * This is called from xfs_force_shutdown, when we're forcibly * shutting down the filesystem, typically because of an IO error. * Our main objectives here are to make sure that: * a. if !logerror, flush the logs to disk. Anything modified * after this is ignored. * b. the filesystem gets marked 'SHUTDOWN' for all interested * parties to find out, 'atomically'. * c. those who're sleeping on log reservations, pinned objects and * other resources get woken up, and be told the bad news. * d. nothing new gets queued up after (b) and (c) are done. * * Note: for the !logerror case we need to flush the regions held in memory out * to disk first. This needs to be done before the log is marked as shutdown, * otherwise the iclog writes will fail. */ int xfs_log_force_umount( struct xfs_mount *mp, int logerror) { struct xlog *log; int retval; log = mp->m_log; /* * If this happens during log recovery, don't worry about * locking; the log isn't open for business yet. */ if (!log || log->l_flags & XLOG_ACTIVE_RECOVERY) { mp->m_flags |= XFS_MOUNT_FS_SHUTDOWN; if (mp->m_sb_bp) mp->m_sb_bp->b_flags |= XBF_DONE; return 0; } /* * Somebody could've already done the hard work for us. * No need to get locks for this. */ if (logerror && log->l_iclog->ic_state & XLOG_STATE_IOERROR) { ASSERT(XLOG_FORCED_SHUTDOWN(log)); return 1; } /* * Flush all the completed transactions to disk before marking the log * being shut down. We need to do it in this order to ensure that * completed operations are safely on disk before we shut down, and that * we don't have to issue any buffer IO after the shutdown flags are set * to guarantee this. */ if (!logerror) _xfs_log_force(mp, XFS_LOG_SYNC, NULL); /* * mark the filesystem and the as in a shutdown state and wake * everybody up to tell them the bad news. */ spin_lock(&log->l_icloglock); mp->m_flags |= XFS_MOUNT_FS_SHUTDOWN; if (mp->m_sb_bp) mp->m_sb_bp->b_flags |= XBF_DONE; /* * Mark the log and the iclogs with IO error flags to prevent any * further log IO from being issued or completed. */ log->l_flags |= XLOG_IO_ERROR; retval = xlog_state_ioerror(log); spin_unlock(&log->l_icloglock); /* * We don't want anybody waiting for log reservations after this. That * means we have to wake up everybody queued up on reserveq as well as * writeq. In addition, we make sure in xlog_{re}grant_log_space that * we don't enqueue anything once the SHUTDOWN flag is set, and this * action is protected by the grant locks. */ xlog_grant_head_wake_all(&log->l_reserve_head); xlog_grant_head_wake_all(&log->l_write_head); /* * Wake up everybody waiting on xfs_log_force. Wake the CIL push first * as if the log writes were completed. The abort handling in the log * item committed callback functions will do this again under lock to * avoid races. */ wake_up_all(&log->l_cilp->xc_commit_wait); xlog_state_do_callback(log, XFS_LI_ABORTED, NULL); #ifdef XFSERRORDEBUG { xlog_in_core_t *iclog; spin_lock(&log->l_icloglock); iclog = log->l_iclog; do { ASSERT(iclog->ic_callback == 0); iclog = iclog->ic_next; } while (iclog != log->l_iclog); spin_unlock(&log->l_icloglock); } #endif /* return non-zero if log IOERROR transition had already happened */ return retval; } STATIC int xlog_iclogs_empty( struct xlog *log) { xlog_in_core_t *iclog; iclog = log->l_iclog; do { /* endianness does not matter here, zero is zero in * any language. */ if (iclog->ic_header.h_num_logops) return 0; iclog = iclog->ic_next; } while (iclog != log->l_iclog); return 1; } /* * Verify that an LSN stamped into a piece of metadata is valid. This is * intended for use in read verifiers on v5 superblocks. */ bool xfs_log_check_lsn( struct xfs_mount *mp, xfs_lsn_t lsn) { struct xlog *log = mp->m_log; bool valid; /* * norecovery mode skips mount-time log processing and unconditionally * resets the in-core LSN. We can't validate in this mode, but * modifications are not allowed anyways so just return true. */ if (mp->m_flags & XFS_MOUNT_NORECOVERY) return true; /* * Some metadata LSNs are initialized to NULL (e.g., the agfl). This is * handled by recovery and thus safe to ignore here. */ if (lsn == NULLCOMMITLSN) return true; valid = xlog_valid_lsn(mp->m_log, lsn); /* warn the user about what's gone wrong before verifier failure */ if (!valid) { spin_lock(&log->l_icloglock); xfs_warn(mp, "Corruption warning: Metadata has LSN (%d:%d) ahead of current LSN (%d:%d). " "Please unmount and run xfs_repair (>= v4.3) to resolve.", CYCLE_LSN(lsn), BLOCK_LSN(lsn), log->l_curr_cycle, log->l_curr_block); spin_unlock(&log->l_icloglock); } return valid; }
jmahler/linux-next
fs/xfs/xfs_log.c
C
gpl-2.0
116,711
.rublon-unlocked { top: -5px; } .rublon-locked { top: -4px; }
khanhnd91/khaosan
wp-content/plugins/rublon/assets/css/rublon2factor_admin_safari.css
CSS
gpl-2.0
64
# Working Unit Test Benches for Network Simulator # Last Revised: 14 November 2015 by Sushant Sundaresh & Sith Domrongkitchaiporn ''' IMPORTANT: Please turn off logging (MEASUREMENT_ENABLE = False) in constants.py before running these testbenches. ''' # Unit Testing Framework import unittest # Test Modules import reporter, node, host, link, router import flow, event_simulator, event, events import link, link_buffer, packet import constants from static_flow_test_node import * import visualize class testMeasurementAnalysis (unittest.TestCase): ''' Tests visualize.py time-averaging function ''' def test_time_averaging (self): self.assertTrue(visualize.test_windowed_time_average()) class TestStaticDataSinkFlow (unittest.TestCase): ''' ### Might break for dynamic TCP ### if this is implemented on receiver side as well Create Flow Data Sink Create Static_Data_Sink_Test_Node Tell Flow its number or expected packets Create Event Simulator For now: Ask flow to receive a packet, check that Ack has same packet ID Ask flow to receive the same packet again, should get same result. ''' sim = "" # event simulator f = "" # flow, data source, static n = "" # test node def setUp (self): self.f = flow.Data_Sink("f1sink","h2","h1",\ 3*constants.DATA_PACKET_BITWIDTH, 1.0) self.n = Static_Data_Sink_Test_Node ("h2","f1sink") self.sim = event_simulator.Event_Simulator({"f1sink":self.f,"h2":self.n}) self.f.set_flow_size(2) def test_basic_ack (self): packets = [ packet.Packet("f1source","h1","h2","",0,0), \ packet.Packet("f1source","h1","h2","",1,0)] self.n.receive(packets[0]) self.assertEqual(self.n.head_of_tx_buff(),0) self.n.receive(packets[1]) self.assertEqual(self.n.head_of_tx_buff(),1) # Two packets received, two packets acknowledged with self.assertRaises(ValueError): self.n.head_of_tx_buff() # Repeated packets just get repeated acks self.n.receive(packets[1]) self.assertEqual(self.n.head_of_tx_buff(),1) class TestStaticDataSourceFlow (unittest.TestCase): ''' ### Will break for dynamic TCP ### Assumes Flow (Data Source) Window Size hard-coded to 2 Create Flow Data Source Create Static_Data_Source_Test_Node Create Event Simulator Start Flow -> pokes tcp -> sends two packets to Node Check that these were sent to Node Fake Acks through Node to Flow Check that this updates Node Tx_Buffer (more sends from Flow) Check what Timeout Does ''' sim = "" # event simulator f = "" # flow, data source, static n = "" # test node def setUp (self): self.f = flow.Data_Source("f1","h1","h2",\ 3*constants.DATA_PACKET_BITWIDTH, 1.0) self.n = Static_Data_Source_Test_Node ("h1","f1") self.sim = event_simulator.Event_Simulator({"f1":self.f,"h1":self.n}) def test_static_flow_source (self): # The first static flow source implementation # just has packets/acks have the same id. # There is no chance of 'duplicate acks' to indicate loss self.f.start() # do this manually so don't have to run simulator self.assertEqual(self.n.head_of_tx_buff(),0) packet1 = self.n.tx_buff[0] self.assertEqual(self.n.head_of_tx_buff(),1) with self.assertRaises(ValueError): self.n.head_of_tx_buff() self.n.receive(packet.Packet("","h2","h1",\ constants.DATA_PACKET_ACKNOWLEDGEMENT_TYPE,\ 0,constants.DATA_ACK_BITWIDTH)) self.assertEqual(self.n.head_of_tx_buff(),2) with self.assertRaises(ValueError): self.n.head_of_tx_buff() self.f.time_out(packet1) # check that next packet has id 1 self.assertEqual(self.n.head_of_tx_buff(),1) class TestLinkTransmissionEvents(unittest.TestCase): sim = "" # simulator link = "" # link lNode = "" # left node rNode = "" # right node lPs = [] # left packets rPs = [] # right packets # Create Event Simulator # Create Link & Nodes (not Hosts, so don't need working Flow) on either side # Create three packets from either side, to the other, and send them. def setUp (self): self.lNode = node.Node("h1") self.rNode = node.Node("h2") # don't need flow, as no packet timeouts created to callback to flow # and node receive is a dummy function for i in 1, 2, 3: self.lPs.append(packet.Packet("","h1","h2","data",i,1000)) # 1000kbit self.rPs.append(packet.Packet("","h2","h1","data",i,1000)) self.link = link.Link("l1", "h1", "h2", 1000.0, 10.0, 3000.0) # 1000kbit/ms, 10 ms prop delay, 3000kbit buffers self.sim = event_simulator.Event_Simulator({"l1":self.link, \ "h1":self.lNode, \ "h2":self.rNode}) # Order the packet sends 2L-2R-L-R # Run Sim Forward # Watch for transmission events in EventSimulator, with proper timestamp # Watch for propagation events in EventSimulator, with proper timestamp # Make sure these are sequential, with only one Tx event at a time in # the queue, and two propagations in each direction chained, and one isolated. # Note this tests most events we're trying to deal with. def test_packet_callbacks_and_timing (self): self.link.send(self.rPs.pop(0),"h2") # right going packets # are favored in time tie breaks self.link.send(self.rPs.pop(0),"h2") self.link.send(self.rPs.pop(0),"h2") self.link.send(self.lPs.pop(0),"h1") # all have timestamp 0.0 # so link should switch directions # between each packet # Confirm Handle_Packet_Transmission events show up in EventSim # with proper timestamps self.assertTrue(self.sim.get_current_time() == 0) self.sim.run_next_event() self.assertTrue(self.sim.get_current_time() == 1) # right packet1 load # into channel at # 1ms going h2->h1 self.assertTrue(self.link.transmission_direction == constants.RTL) self.sim.run_next_event() self.assertTrue(self.sim.get_current_time() == 11) # propagation done # direction switched # next packet loaded # LTR self.assertTrue(self.link.transmission_direction == constants.LTR) # next event is a load (12) # then a propagation (22) # then # the next event should be # both remaining h2 packets # loaded, as left buffer # is empty self.sim.run_next_event() self.assertTrue(self.sim.get_current_time() == 12) self.sim.run_next_event() self.assertTrue(self.sim.get_current_time() == 22) self.assertTrue(self.link.transmission_direction == constants.RTL) self.sim.run_next_event() self.sim.run_next_event() # two loads self.assertTrue(self.sim.get_current_time() == 24) self.assertTrue(self.link.transmission_direction == constants.RTL) self.sim.run_next_event() # two propagations self.sim.run_next_event() self.assertTrue(self.link.transmission_direction == constants.RTL) self.assertTrue(self.sim.get_current_time() == 34) class TestLinkBuffer(unittest.TestCase): # test variables l = "" # a link buffer p = "" # a packet exactly half the size of the buffer s = "" # event simulator def setUp (self): c = 100 # buffer capacity in bits self.s = event_simulator.Event_Simulator({}) self.l = link_buffer.LinkBuffer(c) self.l.set_event_simulator(self.s) self.p = packet.Packet("","","","","",c/2) def test_enqueue_dequeue (self): self.assertTrue(self.l.can_enqueue(self.p)) self.l.enqueue(self.p) self.assertTrue(self.l.can_enqueue(self.p)) self.l.enqueue(self.p) self.assertFalse(self.l.can_enqueue(self.p)) self.l.enqueue(self.p) # dropped self.l.enqueue(self.p) # dropped self.assertTrue(self.l.can_dequeue()) self.assertTrue( isinstance(self.l.dequeue(),packet.Packet) ) self.assertTrue(self.l.can_dequeue()) self.assertTrue( isinstance(self.l.dequeue(),packet.Packet) ) self.assertFalse(self.l.can_dequeue()) with self.assertRaises(ValueError): self.l.dequeue() class TestReporter(unittest.TestCase): # Set ID of reporter def test_get_id(self): ID = "H1" r = reporter.Reporter(ID) r.log("Hello World!") self.assertEqual(r.get_id(), ID) class TestNode(unittest.TestCase): # Set ID of node through super initialiation def test_init(self): ID = "H2" n = node.Node(ID) n.log("Hello World!") self.assertEqual(n.get_id(), ID) # Should not break, as receive is a dummy function def test_receive(self): ID = "H2" n = node.Node(ID) n.receive(0) class TestEventSimulator(unittest.TestCase): def test_init_and_basic_simulation (self): e = event_simulator.Event_Simulator({"h1":host.Host("h1",["l1"]),\ "h2":host.Host("h2",["l1"]),\ "f1":flow.Data_Source("f1", "h1", "h2", 20, 1)}) self.assertEqual(e.get_current_time(), 0.0) self.assertFalse(e.are_flows_done()) self.assertEqual(e.get_element("h1").get_id(), "h1") self.assertEqual(e.get_element("h2").get_id(), "h2") self.assertEqual(e.get_element("f1").get_id(), "f1") e.request_event(event.Event().set_completion_time(1.0)) e.request_event(event.Event().set_completion_time(2.0)) e.request_event(event.Event().set_completion_time(0.5)) e.request_event(event.Event().set_completion_time(1.5)) e.request_event(event.Event().set_completion_time(0.2)) ''' Now event heap should be ordered 0.2, 0.5, 1, 1.5, 2 ''' e.run_next_event() self.assertEqual(e.get_current_time(), 0.2) e.run_next_event() self.assertEqual(e.get_current_time(), 0.5) e.run_next_event() self.assertEqual(e.get_current_time(), 1.0) e.run_next_event() self.assertEqual(e.get_current_time(), 1.5) e.run_next_event() self.assertEqual(e.get_current_time(), 2.0) class TestHost(unittest.TestCase): # Set ID of host through super initialiation def test_init(self): ID = "H1" Links = ["L1"] h = host.Host(ID,Links) h.log("Hello World!") self.assertEqual(h.get_id(), ID) with self.assertRaises(ValueError): h2 = host.Host(ID,["L1","L2"]) class TestLink(unittest.TestCase): ID = "" left = "" right = "" rate = "" delay = "" buff = "" l = "" def setUp(self): self.ID = "L1" self.left = "H1" self.right = "H2" self.rate = "10" self.delay = "10" self.buff = "64" self.l = link.Link(self.ID,self.left,self.right,self.rate,self.delay,self.buff) # Set ID of link through super initialiation def test_get_id(self): self.assertEqual(self.l.get_id(), self.ID) def test_get_left(self): self.assertEqual(self.l.get_left(),self.left) def test_get_right(self): self.assertEqual(self.l.get_right(),self.right) def test_get_rate(self): self.assertEqual(self.l.get_rate(),float(self.rate)) def test_get_delay(self): self.assertEqual(self.l.get_delay(),float(self.delay)) def test_get_buff(self): self.assertEqual(self.l.get_buff(),float(self.buff) * 8.0) # bytes to bits class TestRouter(unittest.TestCase): # Set ID of link through super initialiation def test_init(self): ID = "R1" links = ["H1","H2","H3"] r = router.Router(ID,links) self.assertEqual(r.get_id(), ID) self.assertEqual(r.get_link(),links) class TestFlow(unittest.TestCase): # Set ID of link through super initialiation def test_init(self): ID = "F1" source = "H1" dest = "H2" size = "20" start = "1" f = flow.Flow(ID,source,dest,size,start) self.assertEqual(f.get_id(), ID) self.assertEqual(f.get_source(), source) self.assertEqual(f.get_dest(), dest) self.assertEqual(f.get_size(), int(size) * 8.0 * 1000.0) # MByte -> KBit self.assertEqual(f.get_start(), int(start) * 1000) # s to ms # Run Specific Tests if __name__ == "__main__": reporter_suite = unittest.TestLoader().loadTestsFromTestCase(TestReporter) node_suite = unittest.TestLoader().loadTestsFromTestCase(TestNode) host_suite = unittest.TestLoader().loadTestsFromTestCase(TestHost) link_suite = unittest.TestLoader().loadTestsFromTestCase(TestLink) router_suite = unittest.TestLoader().loadTestsFromTestCase(TestRouter) flow_suite = unittest.TestLoader().loadTestsFromTestCase(TestFlow) sim_suite = unittest.TestLoader().loadTestsFromTestCase(TestEventSimulator) linkbuffer_suite = unittest.TestLoader().loadTestsFromTestCase(TestLinkBuffer) link_tx_suite = unittest.TestLoader().loadTestsFromTestCase(TestLinkTransmissionEvents) static_flow_data_source_suite = \ unittest.TestLoader().loadTestsFromTestCase(TestStaticDataSourceFlow) static_flow_data_sink_suite = \ unittest.TestLoader().loadTestsFromTestCase(TestStaticDataSinkFlow) visualize_suite = \ unittest.TestLoader().loadTestsFromTestCase(testMeasurementAnalysis) test_suites = [reporter_suite, node_suite, host_suite, link_suite,\ router_suite, flow_suite, sim_suite, linkbuffer_suite,\ link_tx_suite,static_flow_data_source_suite,\ static_flow_data_sink_suite, visualize_suite] for suite in test_suites: unittest.TextTestRunner(verbosity=2).run(suite) print "\n\n\n"
sssundar/NetworkSimulator
Code/Python/unit_test_benches.py
Python
gpl-2.0
12,927
<?php /* * This file is part of the Sententiaregum project. * * (c) Maximilian Bosch <maximilian@mbosch.me> * (c) Ben Bieler <ben@benbieler.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace AppBundle\Tests\Unit\Model\User; use AppBundle\Model\User\Role; class RoleTest extends \PHPUnit_Framework_TestCase { public function testSerialization(): void { $role = new Role('ROLE_USER'); $serialized = serialize($role); $this->assertNotEmpty($serialized); $newRole = unserialize($serialized); $this->assertSame('ROLE_USER', $newRole->getRole()); } }
Sententiaregum/Sententiaregum
src/AppBundle/Tests/Unit/Model/User/RoleTest.php
PHP
gpl-2.0
737
<?php /** * Template Name: Maintainance page * * @package Organique */ // WP header ?> <div class="container"> <h2>Hi! We are currently working on an exciting new upgrade to our site. In the meantime, to place an order please call 08096879999</h2> </div>
integrait/wp_ds
wp-content/themes/sistina/maintainance.php
PHP
gpl-2.0
262
.mark{width:10px;height:10px;position:absolute;background-size:contain}
lduarte1991/diacritic-annotator
build/diacritic-annotator.min.css
CSS
gpl-2.0
71
/* * max77843-muic.h - MUIC for the Maxim 77843 * * Copyright (C) 2011 Samsung Electrnoics * Seoyoung Jeong <seo0.jeong@samsung.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * This driver is based on max14577-muic.h * */ #ifndef __MAX77843_MUIC_H__ #define __MAX77843_MUIC_H__ #define MUIC_DEV_NAME "muic-max77843" /* muic chip specific internal data structure */ struct max77843_muic_data { struct device *dev; struct i2c_client *i2c; /* i2c addr: 0x4A; MUIC */ struct mutex muic_mutex; /* model dependant mfd platform data */ struct max77843_platform_data *mfd_pdata; int irq_adc1k; int irq_adcerr; int irq_adc; int irq_chgtyp; int irq_vbvolt; int irq_vdnmon; int irq_mrxrdy; int irq_mpnack; int irq_vbadc; /* model dependant muic platform data */ struct muic_platform_data *pdata; /* muic current attached device */ muic_attached_dev_t attached_dev; /* muic support vps list */ bool muic_support_list[ATTACHED_DEV_NUM]; bool is_muic_ready; /* check is otg test for jig uart off + vb */ bool is_otg_test; bool is_factory_start; bool is_afc_muic_ready; bool is_afc_handshaking; bool is_afc_muic_prepare; bool is_charger_ready; bool is_qc_vb_settle; u8 is_boot_dpdnvden; u8 tx_data; bool is_mrxrdy; int afc_count; muic_afc_data_t afc_data; u8 qc_hv; struct delayed_work hv_muic_qc_vb_work; /* muic status value */ u8 status1; u8 status2; u8 status3; /* muic hvcontrol value */ u8 hvcontrol1; u8 hvcontrol2; struct work_struct muic_reset_work; }; /* max77843 muic register read/write related information defines. */ /* MAX77843 REGISTER ENABLE or DISABLE bit */ enum max77843_reg_bit_control { MAX77843_DISABLE_BIT = 0, MAX77843_ENABLE_BIT, }; /* MAX77843 STATUS1 register */ #define STATUS1_ADC_SHIFT 0 #define STATUS1_ADCERR_SHIFT 6 #define STATUS1_ADC1K_SHIFT 7 #define STATUS1_ADC_MASK (0x1f << STATUS1_ADC_SHIFT) #define STATUS1_ADCERR_MASK (0x1 << STATUS1_ADCERR_SHIFT) #define STATUS1_ADC1K_MASK (0x1 << STATUS1_ADC1K_SHIFT) /* MAX77843 STATUS2 register */ #define STATUS2_CHGTYP_SHIFT 0 #define STATUS2_CHGDETRUN_SHIFT 3 #define STATUS2_DCDTMR_SHIFT 4 #define STATUS2_DXOVP_SHIFT 5 #define STATUS2_VBVOLT_SHIFT 6 #define STATUS2_CHGTYP_MASK (0x7 << STATUS2_CHGTYP_SHIFT) #define STATUS2_CHGDETRUN_MASK (0x1 << STATUS2_CHGDETRUN_SHIFT) #define STATUS2_DCDTMR_MASK (0x1 << STATUS2_DCDTMR_SHIFT) #define STATUS2_DXOVP_MASK (0x1 << STATUS2_DXOVP_SHIFT) #define STATUS2_VBVOLT_MASK (0x1 << STATUS2_VBVOLT_SHIFT) /* MAX77843 CDETCTRL1 register */ #define CHGDETEN_SHIFT 0 #define CHGTYPM_SHIFT 1 #define CDDELAY_SHIFT 4 #define CHGDETEN_MASK (0x1 << CHGDETEN_SHIFT) #define CHGTYPM_MASK (0x1 << CHGTYPM_SHIFT) #define CDDELAY_MASK (0x1 << CDDELAY_SHIFT) /* MAX77843 CONTROL1 register */ #define COMN1SW_SHIFT 0 #define COMP2SW_SHIFT 3 #define NOBCCOMP_SHIFT 6 #define IDBEN_SHIFT 7 #define COMN1SW_MASK (0x7 << COMN1SW_SHIFT) #define COMP2SW_MASK (0x7 << COMP2SW_SHIFT) #define NOBCCOMP_MASK (0x1 << NOBCCOMP_SHIFT) #define IDBEN_MASK (0x1 << IDBEN_SHIFT) #define CLEAR_IDBEN_RSVD_MASK (COMN1SW_MASK | COMP2SW_MASK) /* MAX77843 CONTROL2 register */ #define CTRL2_LOWPWR_SHIFT 0 #define CTRL2_CPEN_SHIFT 2 #define CTRL2_ACCDET_SHIFT 5 #define CTRL2_LOWPWR_MASK (0x1 << CTRL2_LOWPWR_SHIFT) #define CTRL2_CPEN_MASK (0x1 << CTRL2_CPEN_SHIFT) #define CTRL2_ACCDET_MASK (0x1 << CTRL2_ACCDET_SHIFT) #define CTRL2_CPEN1_LOWPWD0 ((MAX77843_ENABLE_BIT << CTRL2_CPEN_SHIFT) | \ (MAX77843_DISABLE_BIT << CTRL2_ADCLOWPWR_SHIFT)) #define CTRL2_CPEN0_LOWPWD1 ((MAX77843_DISABLE_BIT << CTRL2_CPEN_SHIFT) | \ (MAX77843_ENABLE_BIT << CTRL2_ADCLOWPWR_SHIFT)) /* MAX77843 CONTROL3 register */ #define CTRL3_JIGSET_SHIFT 0 #define CTRL3_JIGSET_MASK (0x3 << CTRL3_JIGSET_SHIFT) /* MAX77843 CONTROL4 register */ #define CTRL4_ADCDBSET_SHIFT 0 #define CTRL4_ADCMODE_SHIFT 6 #define CTRL4_ADCDBSET_MASK (0x3 << CTRL4_ADCDBSET_SHIFT) #define CTRL4_ADCMODE_MASK (0x3 << CTRL4_ADCMODE_SHIFT) typedef enum { VB_LOW = 0x00, VB_HIGH = (0x1 << STATUS2_VBVOLT_SHIFT), VB_DONTCARE = 0xff, } vbvolt_t; typedef enum { CHGDETRUN_FALSE = 0x00, CHGDETRUN_TRUE = (0x1 << STATUS2_CHGDETRUN_SHIFT), CHGDETRUN_DONTCARE = 0xff, } chgdetrun_t; /* MAX77843 MUIC Output of USB Charger Detection */ typedef enum { /* No Valid voltage at VB (Vvb < Vvbdet) */ CHGTYP_NO_VOLTAGE = 0x00, /* Unknown (D+/D- does not present a valid USB charger signature) */ CHGTYP_USB = 0x01, /* Charging Downstream Port */ CHGTYP_CDP = 0x02, /* Dedicated Charger (D+/D- shorted) */ CHGTYP_DEDICATED_CHARGER = 0x03, /* Special 500mA charger, max current 500mA */ CHGTYP_500MA = 0x04, /* Special 1A charger, max current 1A */ CHGTYP_1A = 0x05, /* Special charger - 3.3V bias on D+/D- */ CHGTYP_SPECIAL_3_3V_CHARGER = 0x06, /* Reserved */ CHGTYP_RFU = 0x07, /* Any charger w/o USB */ CHGTYP_UNOFFICIAL_CHARGER = 0xfc, /* Any charger type */ CHGTYP_ANY = 0xfd, /* Don't care charger type */ CHGTYP_DONTCARE = 0xfe, CHGTYP_MAX, CHGTYP_INIT, CHGTYP_MIN = CHGTYP_NO_VOLTAGE } chgtyp_t; typedef enum { PROCESS_ATTACH = 0, PROCESS_LOGICALLY_DETACH, PROCESS_NONE, } process_t; /* muic register value for COMN1, COMN2 in CTRL1 reg */ /* * MAX77843 CONTROL1 register * ID Bypass [7] / Mic En [6] / D+ [5:3] / D- [2:0] * 0: ID Bypass Open / 1: IDB connect to UID * 0: Mic En Open / 1: Mic connect to VB * 000: Open / 001: USB / 010: Audio / 011: UART */ enum max77843_reg_ctrl1_val { MAX77843_MUIC_CTRL1_ID_OPEN = 0x0, MAX77843_MUIC_CTRL1_ID_BYPASS = 0x1, MAX77843_MUIC_CTRL1_NO_BC_COMP_OFF = 0x0, MAX77843_MUIC_CTRL1_NO_BC_COMP_ON = 0x1, MAX77843_MUIC_CTRL1_COM_OPEN = 0x00, MAX77843_MUIC_CTRL1_COM_USB = 0x01, MAX77843_MUIC_CTRL1_COM_AUDIO = 0x02, MAX77843_MUIC_CTRL1_COM_UART = 0x03, MAX77843_MUIC_CTRL1_COM_USB_CP = 0x04, MAX77843_MUIC_CTRL1_COM_UART_CP = 0x05, }; typedef enum { CTRL1_OPEN = (MAX77843_MUIC_CTRL1_ID_OPEN << IDBEN_SHIFT) | \ (MAX77843_MUIC_CTRL1_NO_BC_COMP_OFF << NOBCCOMP_SHIFT) | \ (MAX77843_MUIC_CTRL1_COM_OPEN << COMP2SW_SHIFT) | \ (MAX77843_MUIC_CTRL1_COM_OPEN << COMN1SW_SHIFT), CTRL1_USB = (MAX77843_MUIC_CTRL1_ID_OPEN << IDBEN_SHIFT) | \ (MAX77843_MUIC_CTRL1_NO_BC_COMP_OFF << NOBCCOMP_SHIFT) | \ (MAX77843_MUIC_CTRL1_COM_USB << COMP2SW_SHIFT) | \ (MAX77843_MUIC_CTRL1_COM_USB << COMN1SW_SHIFT), CTRL1_AUDIO = (MAX77843_MUIC_CTRL1_ID_OPEN << IDBEN_SHIFT) | \ (MAX77843_MUIC_CTRL1_NO_BC_COMP_OFF << NOBCCOMP_SHIFT) | \ (MAX77843_MUIC_CTRL1_COM_AUDIO << COMP2SW_SHIFT) | \ (MAX77843_MUIC_CTRL1_COM_AUDIO << COMN1SW_SHIFT), CTRL1_UART = (MAX77843_MUIC_CTRL1_ID_OPEN << IDBEN_SHIFT) | \ (MAX77843_MUIC_CTRL1_NO_BC_COMP_OFF << NOBCCOMP_SHIFT) | \ (MAX77843_MUIC_CTRL1_COM_UART << COMP2SW_SHIFT) | \ (MAX77843_MUIC_CTRL1_COM_UART << COMN1SW_SHIFT), CTRL1_USB_CP = (MAX77843_MUIC_CTRL1_ID_OPEN << IDBEN_SHIFT) | \ (MAX77843_MUIC_CTRL1_NO_BC_COMP_OFF << NOBCCOMP_SHIFT) | \ (MAX77843_MUIC_CTRL1_COM_USB_CP << COMP2SW_SHIFT) | \ (MAX77843_MUIC_CTRL1_COM_USB_CP << COMN1SW_SHIFT), CTRL1_UART_CP = (MAX77843_MUIC_CTRL1_ID_OPEN << IDBEN_SHIFT) | \ (MAX77843_MUIC_CTRL1_NO_BC_COMP_OFF << NOBCCOMP_SHIFT) | \ (MAX77843_MUIC_CTRL1_COM_UART_CP << COMP2SW_SHIFT) | \ (MAX77843_MUIC_CTRL1_COM_UART_CP << COMN1SW_SHIFT), CTRL1_USB_DOCK = (MAX77843_MUIC_CTRL1_ID_OPEN << IDBEN_SHIFT) | \ (MAX77843_MUIC_CTRL1_NO_BC_COMP_ON << NOBCCOMP_SHIFT) | \ (MAX77843_MUIC_CTRL1_COM_USB << COMP2SW_SHIFT) | \ (MAX77843_MUIC_CTRL1_COM_USB << COMN1SW_SHIFT), } max77843_reg_ctrl1_t; enum { MAX77843_MUIC_CTRL4_ADCMODE_ALWAYS_ON = 0x00, MAX77843_MUIC_CTRL4_ADCMODE_ALWAYS_ON_1M_MON = 0x01, MAX77843_MUIC_CTRL4_ADCMODE_ONE_SHOT = 0x02, MAX77843_MUIC_CTRL4_ADCMODE_2S_PULSE = 0x03 }; extern struct device *switch_device; #endif /* __MAX77843_MUIC_H__ */
goodhanrry/N910U_goodhanrry_kernel
include/linux/muic/max77843-muic.h
C
gpl-2.0
8,655
/* * event tracer * * Copyright (C) 2008 Red Hat Inc, Steven Rostedt <srostedt@redhat.com> * * - Added format output of fields of the trace point. * This was based off of work by Tom Zanussi <tzanussi@gmail.com>. * */ #include <linux/workqueue.h> #include <linux/spinlock.h> #include <linux/kthread.h> #include <linux/debugfs.h> #include <linux/uaccess.h> #include <linux/module.h> #include <linux/ctype.h> #include <linux/delay.h> #include <asm/setup.h> #include "trace_output.h" #undef TRACE_SYSTEM #define TRACE_SYSTEM "TRACE_SYSTEM" DEFINE_MUTEX(event_mutex); LIST_HEAD(ftrace_events); #define COMMON_FIELD_COUNT 5 int trace_define_field(struct ftrace_event_call *call, const char *type, const char *name, int offset, int size, int is_signed, int filter_type) { struct ftrace_event_field *field; field = kzalloc(sizeof(*field), GFP_KERNEL); if (!field) goto err; field->name = kstrdup(name, GFP_KERNEL); if (!field->name) goto err; field->type = kstrdup(type, GFP_KERNEL); if (!field->type) goto err; if (filter_type == FILTER_OTHER) field->filter_type = filter_assign_type(type); else field->filter_type = filter_type; field->offset = offset; field->size = size; field->is_signed = is_signed; list_add(&field->link, &call->fields); return 0; err: if (field) { kfree(field->name); kfree(field->type); } kfree(field); return -ENOMEM; } EXPORT_SYMBOL_GPL(trace_define_field); #define __common_field(type, item) \ ret = trace_define_field(call, #type, "common_" #item, \ offsetof(typeof(ent), item), \ sizeof(ent.item), \ is_signed_type(type), FILTER_OTHER); \ if (ret) \ return ret; int trace_define_common_fields(struct ftrace_event_call *call) { int ret; struct trace_entry ent; __common_field(unsigned short, type); __common_field(unsigned char, flags); __common_field(unsigned char, preempt_count); __common_field(int, pid); __common_field(int, lock_depth); return ret; } EXPORT_SYMBOL_GPL(trace_define_common_fields); void trace_destroy_fields(struct ftrace_event_call *call) { struct ftrace_event_field *field, *next; list_for_each_entry_safe(field, next, &call->fields, link) { list_del(&field->link); kfree(field->type); kfree(field->name); kfree(field); } } void trace_event_enable_cmd_record(bool enable) { struct ftrace_event_call *call; mutex_lock(&event_mutex); list_for_each_entry(call, &ftrace_events, list) { if (!(call->flags & TRACE_EVENT_FL_ENABLED)) continue; if (enable) { tracing_start_cmdline_record(); call->flags |= TRACE_EVENT_FL_RECORDED_CMD; } else { tracing_stop_cmdline_record(); call->flags &= ~TRACE_EVENT_FL_RECORDED_CMD; } } mutex_unlock(&event_mutex); } static int ftrace_event_enable_disable(struct ftrace_event_call *call, int enable) { int ret = 0; switch (enable) { case 0: if (call->flags & TRACE_EVENT_FL_ENABLED) { call->flags &= ~TRACE_EVENT_FL_ENABLED; if (call->flags & TRACE_EVENT_FL_RECORDED_CMD) { tracing_stop_cmdline_record(); call->flags &= ~TRACE_EVENT_FL_RECORDED_CMD; } call->unregfunc(call); } break; case 1: if (!(call->flags & TRACE_EVENT_FL_ENABLED)) { if (trace_flags & TRACE_ITER_RECORD_CMD) { tracing_start_cmdline_record(); call->flags |= TRACE_EVENT_FL_RECORDED_CMD; } ret = call->regfunc(call); if (ret) { tracing_stop_cmdline_record(); pr_info("event trace: Could not enable event " "%s\n", call->name); break; } call->flags |= TRACE_EVENT_FL_ENABLED; } break; } return ret; } static void ftrace_clear_events(void) { struct ftrace_event_call *call; mutex_lock(&event_mutex); list_for_each_entry(call, &ftrace_events, list) { ftrace_event_enable_disable(call, 0); } mutex_unlock(&event_mutex); } /* * __ftrace_set_clr_event(NULL, NULL, NULL, set) will set/unset all events. */ static int __ftrace_set_clr_event(const char *match, const char *sub, const char *event, int set) { struct ftrace_event_call *call; int ret = -EINVAL; mutex_lock(&event_mutex); list_for_each_entry(call, &ftrace_events, list) { if (!call->name || !call->regfunc) continue; if (match && strcmp(match, call->name) != 0 && strcmp(match, call->system) != 0) continue; if (sub && strcmp(sub, call->system) != 0) continue; if (event && strcmp(event, call->name) != 0) continue; ftrace_event_enable_disable(call, set); ret = 0; } mutex_unlock(&event_mutex); return ret; } static int ftrace_set_clr_event(char *buf, int set) { char *event = NULL, *sub = NULL, *match; /* * The buf format can be <subsystem>:<event-name> * *:<event-name> means any event by that name. * :<event-name> is the same. * * <subsystem>:* means all events in that subsystem * <subsystem>: means the same. * * <name> (no ':') means all events in a subsystem with * the name <name> or any event that matches <name> */ match = strsep(&buf, ":"); if (buf) { sub = match; event = buf; match = NULL; if (!strlen(sub) || strcmp(sub, "*") == 0) sub = NULL; if (!strlen(event) || strcmp(event, "*") == 0) event = NULL; } return __ftrace_set_clr_event(match, sub, event, set); } /** * trace_set_clr_event - enable or disable an event * @system: system name to match (NULL for any system) * @event: event name to match (NULL for all events, within system) * @set: 1 to enable, 0 to disable * * This is a way for other parts of the kernel to enable or disable * event recording. * * Returns 0 on success, -EINVAL if the parameters do not match any * registered events. */ int trace_set_clr_event(const char *system, const char *event, int set) { return __ftrace_set_clr_event(NULL, system, event, set); } /* 128 should be much more than enough */ #define EVENT_BUF_SIZE 127 static ssize_t ftrace_event_write(struct file *file, const char __user *ubuf, size_t cnt, loff_t *ppos) { struct trace_parser parser; ssize_t read, ret; if (!cnt) return 0; ret = tracing_update_buffers(); if (ret < 0) return ret; if (trace_parser_get_init(&parser, EVENT_BUF_SIZE + 1)) return -ENOMEM; read = trace_get_user(&parser, ubuf, cnt, ppos); if (read >= 0 && trace_parser_loaded((&parser))) { int set = 1; if (*parser.buffer == '!') set = 0; parser.buffer[parser.idx] = 0; ret = ftrace_set_clr_event(parser.buffer + !set, set); if (ret) goto out_put; } ret = read; out_put: trace_parser_put(&parser); return ret; } static void * t_next(struct seq_file *m, void *v, loff_t *pos) { struct ftrace_event_call *call = v; (*pos)++; list_for_each_entry_continue(call, &ftrace_events, list) { /* * The ftrace subsystem is for showing formats only. * They can not be enabled or disabled via the event files. */ if (call->regfunc) return call; } return NULL; } static void *t_start(struct seq_file *m, loff_t *pos) { struct ftrace_event_call *call; loff_t l; mutex_lock(&event_mutex); call = list_entry(&ftrace_events, struct ftrace_event_call, list); for (l = 0; l <= *pos; ) { call = t_next(m, call, &l); if (!call) break; } return call; } static void * s_next(struct seq_file *m, void *v, loff_t *pos) { struct ftrace_event_call *call = v; (*pos)++; list_for_each_entry_continue(call, &ftrace_events, list) { if (call->flags & TRACE_EVENT_FL_ENABLED) return call; } return NULL; } static void *s_start(struct seq_file *m, loff_t *pos) { struct ftrace_event_call *call; loff_t l; mutex_lock(&event_mutex); call = list_entry(&ftrace_events, struct ftrace_event_call, list); for (l = 0; l <= *pos; ) { call = s_next(m, call, &l); if (!call) break; } return call; } static int t_show(struct seq_file *m, void *v) { struct ftrace_event_call *call = v; if (strcmp(call->system, TRACE_SYSTEM) != 0) seq_printf(m, "%s:", call->system); seq_printf(m, "%s\n", call->name); return 0; } static void t_stop(struct seq_file *m, void *p) { mutex_unlock(&event_mutex); } static int ftrace_event_seq_open(struct inode *inode, struct file *file) { const struct seq_operations *seq_ops; if ((file->f_mode & FMODE_WRITE) && (file->f_flags & O_TRUNC)) ftrace_clear_events(); seq_ops = inode->i_private; return seq_open(file, seq_ops); } static ssize_t event_enable_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { struct ftrace_event_call *call = filp->private_data; char *buf; if (call->flags & TRACE_EVENT_FL_ENABLED) buf = "1\n"; else buf = "0\n"; return simple_read_from_buffer(ubuf, cnt, ppos, buf, 2); } static ssize_t event_enable_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { struct ftrace_event_call *call = filp->private_data; char buf[64]; unsigned long val; int ret; if (cnt >= sizeof(buf)) return -EINVAL; if (copy_from_user(&buf, ubuf, cnt)) return -EFAULT; buf[cnt] = 0; ret = strict_strtoul(buf, 10, &val); if (ret < 0) return ret; ret = tracing_update_buffers(); if (ret < 0) return ret; switch (val) { case 0: case 1: mutex_lock(&event_mutex); ret = ftrace_event_enable_disable(call, val); mutex_unlock(&event_mutex); break; default: return -EINVAL; } *ppos += cnt; return ret ? ret : cnt; } static ssize_t system_enable_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { const char set_to_char[4] = { '?', '0', '1', 'X' }; const char *system = filp->private_data; struct ftrace_event_call *call; char buf[2]; int set = 0; int ret; mutex_lock(&event_mutex); list_for_each_entry(call, &ftrace_events, list) { if (!call->name || !call->regfunc) continue; if (system && strcmp(call->system, system) != 0) continue; /* * We need to find out if all the events are set * or if all events or cleared, or if we have * a mixture. */ set |= (1 << !!(call->flags & TRACE_EVENT_FL_ENABLED)); /* * If we have a mixture, no need to look further. */ if (set == 3) break; } mutex_unlock(&event_mutex); buf[0] = set_to_char[set]; buf[1] = '\n'; ret = simple_read_from_buffer(ubuf, cnt, ppos, buf, 2); return ret; } static ssize_t system_enable_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { const char *system = filp->private_data; unsigned long val; char buf[64]; ssize_t ret; if (cnt >= sizeof(buf)) return -EINVAL; if (copy_from_user(&buf, ubuf, cnt)) return -EFAULT; buf[cnt] = 0; ret = strict_strtoul(buf, 10, &val); if (ret < 0) return ret; ret = tracing_update_buffers(); if (ret < 0) return ret; if (val != 0 && val != 1) return -EINVAL; ret = __ftrace_set_clr_event(NULL, system, NULL, val); if (ret) goto out; ret = cnt; out: *ppos += cnt; return ret; } extern char *__bad_type_size(void); #undef FIELD #define FIELD(type, name) \ sizeof(type) != sizeof(field.name) ? __bad_type_size() : \ #type, "common_" #name, offsetof(typeof(field), name), \ sizeof(field.name), is_signed_type(type) static int trace_write_header(struct trace_seq *s) { struct trace_entry field; /* struct trace_entry */ return trace_seq_printf(s, "\tfield:%s %s;\toffset:%zu;\tsize:%zu;\tsigned:%u;\n" "\tfield:%s %s;\toffset:%zu;\tsize:%zu;\tsigned:%u;\n" "\tfield:%s %s;\toffset:%zu;\tsize:%zu;\tsigned:%u;\n" "\tfield:%s %s;\toffset:%zu;\tsize:%zu;\tsigned:%u;\n" "\tfield:%s %s;\toffset:%zu;\tsize:%zu;\tsigned:%u;\n" "\n", FIELD(unsigned short, type), FIELD(unsigned char, flags), FIELD(unsigned char, preempt_count), FIELD(int, pid), FIELD(int, lock_depth)); } static ssize_t event_format_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { struct ftrace_event_call *call = filp->private_data; struct trace_seq *s; char *buf; int r; if (*ppos) return 0; s = kmalloc(sizeof(*s), GFP_KERNEL); if (!s) return -ENOMEM; trace_seq_init(s); /* If any of the first writes fail, so will the show_format. */ trace_seq_printf(s, "name: %s\n", call->name); trace_seq_printf(s, "ID: %d\n", call->id); trace_seq_printf(s, "format:\n"); trace_write_header(s); r = call->fmt.show_format(call, s); if (!r) { /* * ug! The format output is bigger than a PAGE!! */ buf = "FORMAT TOO BIG\n"; r = simple_read_from_buffer(ubuf, cnt, ppos, buf, strlen(buf)); goto out; } r = simple_read_from_buffer(ubuf, cnt, ppos, s->buffer, s->len); out: kfree(s); return r; } enum { FORMAT_HEADER = 1, FORMAT_PRINTFMT = 2, }; static void *f_next(struct seq_file *m, void *v, loff_t *pos) { struct ftrace_event_call *call = m->private; struct ftrace_event_field *field; struct list_head *head; loff_t index = *pos; (*pos)++; head = &call->fields; switch ((unsigned long)v) { case FORMAT_HEADER: if (unlikely(list_empty(head))) return NULL; field = list_entry(head->prev, struct ftrace_event_field, link); return field; case FORMAT_PRINTFMT: /* all done */ return NULL; } /* * To separate common fields from event fields, the * LSB is set on the first event field. Clear it in case. */ v = (void *)((unsigned long)v & ~1L); field = v; if (field->link.prev == head) return (void *)FORMAT_PRINTFMT; field = list_entry(field->link.prev, struct ftrace_event_field, link); /* Set the LSB to notify f_show to print an extra newline */ if (index == COMMON_FIELD_COUNT) field = (struct ftrace_event_field *) ((unsigned long)field | 1); return field; } static void *f_start(struct seq_file *m, loff_t *pos) { loff_t l = 0; void *p; /* Start by showing the header */ if (!*pos) return (void *)FORMAT_HEADER; p = (void *)FORMAT_HEADER; do { p = f_next(m, p, &l); } while (p && l < *pos); return p; } static int f_show(struct seq_file *m, void *v) { struct ftrace_event_call *call = m->private; struct ftrace_event_field *field; const char *array_descriptor; switch ((unsigned long)v) { case FORMAT_HEADER: seq_printf(m, "name: %s\n", call->name); seq_printf(m, "ID: %d\n", call->id); seq_printf(m, "format:\n"); return 0; case FORMAT_PRINTFMT: seq_printf(m, "\nprint fmt: %s\n", call->fmt.print_fmt); return 0; } /* * To separate common fields from event fields, the * LSB is set on the first event field. Clear it and * print a newline if it is set. */ if ((unsigned long)v & 1) { seq_putc(m, '\n'); v = (void *)((unsigned long)v & ~1L); } field = v; /* * Smartly shows the array type(except dynamic array). * Normal: * field:TYPE VAR * If TYPE := TYPE[LEN], it is shown: * field:TYPE VAR[LEN] */ array_descriptor = strchr(field->type, '['); if (!strncmp(field->type, "__data_loc", 10)) array_descriptor = NULL; if (!array_descriptor) seq_printf(m, "\tfield:%s %s;\toffset:%u;\tsize:%u;\tsigned:%d;\n", field->type, field->name, field->offset, field->size, !!field->is_signed); else seq_printf(m, "\tfield:%.*s %s%s;\toffset:%u;\tsize:%u;\tsigned:%d;\n", (int)(array_descriptor - field->type), field->type, field->name, array_descriptor, field->offset, field->size, !!field->is_signed); return 0; } static void f_stop(struct seq_file *m, void *p) { } static const struct seq_operations trace_format_seq_ops = { .start = f_start, .next = f_next, .stop = f_stop, .show = f_show, }; static int trace_format_open(struct inode *inode, struct file *file) { struct ftrace_event_call *call = inode->i_private; struct seq_file *m; int ret; ret = seq_open(file, &trace_format_seq_ops); if (ret < 0) return ret; m = file->private_data; m->private = call; return 0; } static ssize_t event_id_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { struct ftrace_event_call *call = filp->private_data; struct trace_seq *s; int r; if (*ppos) return 0; s = kmalloc(sizeof(*s), GFP_KERNEL); if (!s) return -ENOMEM; trace_seq_init(s); trace_seq_printf(s, "%d\n", call->id); r = simple_read_from_buffer(ubuf, cnt, ppos, s->buffer, s->len); kfree(s); return r; } static ssize_t event_filter_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { struct ftrace_event_call *call = filp->private_data; struct trace_seq *s; int r; if (*ppos) return 0; s = kmalloc(sizeof(*s), GFP_KERNEL); if (!s) return -ENOMEM; trace_seq_init(s); print_event_filter(call, s); r = simple_read_from_buffer(ubuf, cnt, ppos, s->buffer, s->len); kfree(s); return r; } static ssize_t event_filter_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { struct ftrace_event_call *call = filp->private_data; char *buf; int err; if (cnt >= PAGE_SIZE) return -EINVAL; buf = (char *)__get_free_page(GFP_TEMPORARY); if (!buf) return -ENOMEM; if (copy_from_user(buf, ubuf, cnt)) { free_page((unsigned long) buf); return -EFAULT; } buf[cnt] = '\0'; err = apply_event_filter(call, buf); free_page((unsigned long) buf); if (err < 0) return err; *ppos += cnt; return cnt; } static ssize_t subsystem_filter_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { struct event_subsystem *system = filp->private_data; struct trace_seq *s; int r; if (*ppos) return 0; s = kmalloc(sizeof(*s), GFP_KERNEL); if (!s) return -ENOMEM; trace_seq_init(s); print_subsystem_event_filter(system, s); r = simple_read_from_buffer(ubuf, cnt, ppos, s->buffer, s->len); kfree(s); return r; } static ssize_t subsystem_filter_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { struct event_subsystem *system = filp->private_data; char *buf; int err; if (cnt >= PAGE_SIZE) return -EINVAL; buf = (char *)__get_free_page(GFP_TEMPORARY); if (!buf) return -ENOMEM; if (copy_from_user(buf, ubuf, cnt)) { free_page((unsigned long) buf); return -EFAULT; } buf[cnt] = '\0'; err = apply_subsystem_event_filter(system, buf); free_page((unsigned long) buf); if (err < 0) return err; *ppos += cnt; return cnt; } static ssize_t show_header(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { int (*func)(struct trace_seq *s) = filp->private_data; struct trace_seq *s; int r; if (*ppos) return 0; s = kmalloc(sizeof(*s), GFP_KERNEL); if (!s) return -ENOMEM; trace_seq_init(s); func(s); r = simple_read_from_buffer(ubuf, cnt, ppos, s->buffer, s->len); kfree(s); return r; } static const struct seq_operations show_event_seq_ops = { .start = t_start, .next = t_next, .show = t_show, .stop = t_stop, }; static const struct seq_operations show_set_event_seq_ops = { .start = s_start, .next = s_next, .show = t_show, .stop = t_stop, }; static const struct file_operations ftrace_avail_fops = { .open = ftrace_event_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static const struct file_operations ftrace_set_event_fops = { .open = ftrace_event_seq_open, .read = seq_read, .write = ftrace_event_write, .llseek = seq_lseek, .release = seq_release, }; static const struct file_operations ftrace_enable_fops = { .open = tracing_open_generic, .read = event_enable_read, .write = event_enable_write, }; static const struct file_operations ftrace_event_format_print_fmt_fops = { .open = trace_format_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static const struct file_operations ftrace_event_format_fops = { .open = tracing_open_generic, .read = event_format_read, }; static const struct file_operations ftrace_event_id_fops = { .open = tracing_open_generic, .read = event_id_read, }; static const struct file_operations ftrace_event_filter_fops = { .open = tracing_open_generic, .read = event_filter_read, .write = event_filter_write, }; static const struct file_operations ftrace_subsystem_filter_fops = { .open = tracing_open_generic, .read = subsystem_filter_read, .write = subsystem_filter_write, }; static const struct file_operations ftrace_system_enable_fops = { .open = tracing_open_generic, .read = system_enable_read, .write = system_enable_write, }; static const struct file_operations ftrace_show_header_fops = { .open = tracing_open_generic, .read = show_header, }; static struct dentry *event_trace_events_dir(void) { static struct dentry *d_tracer; static struct dentry *d_events; if (d_events) return d_events; d_tracer = tracing_init_dentry(); if (!d_tracer) return NULL; d_events = debugfs_create_dir("events", d_tracer); if (!d_events) pr_warning("Could not create debugfs " "'events' directory\n"); return d_events; } static LIST_HEAD(event_subsystems); static struct dentry * event_subsystem_dir(const char *name, struct dentry *d_events) { struct event_subsystem *system; struct dentry *entry; /* First see if we did not already create this dir */ list_for_each_entry(system, &event_subsystems, list) { if (strcmp(system->name, name) == 0) { system->nr_events++; return system->entry; } } /* need to create new entry */ system = kmalloc(sizeof(*system), GFP_KERNEL); if (!system) { pr_warning("No memory to create event subsystem %s\n", name); return d_events; } system->entry = debugfs_create_dir(name, d_events); if (!system->entry) { pr_warning("Could not create event subsystem %s\n", name); kfree(system); return d_events; } system->nr_events = 1; system->name = kstrdup(name, GFP_KERNEL); if (!system->name) { debugfs_remove(system->entry); kfree(system); return d_events; } list_add(&system->list, &event_subsystems); system->filter = NULL; system->filter = kzalloc(sizeof(struct event_filter), GFP_KERNEL); if (!system->filter) { pr_warning("Could not allocate filter for subsystem " "'%s'\n", name); return system->entry; } entry = debugfs_create_file("filter", 0644, system->entry, system, &ftrace_subsystem_filter_fops); if (!entry) { kfree(system->filter); system->filter = NULL; pr_warning("Could not create debugfs " "'%s/filter' entry\n", name); } entry = trace_create_file("enable", 0644, system->entry, (void *)system->name, &ftrace_system_enable_fops); return system->entry; } static bool is_print_fmt_event(struct ftrace_event_call *call) { return call->flags & TRACE_EVENT_FL_KABI_PRINT_FMT; } static int event_create_dir(struct ftrace_event_call *call, struct dentry *d_events, const struct file_operations *id, const struct file_operations *enable, const struct file_operations *filter, const struct file_operations *format) { struct dentry *entry; int ret; /* * If the trace point header did not define TRACE_SYSTEM * then the system would be called "TRACE_SYSTEM". */ if (strcmp(call->system, TRACE_SYSTEM) != 0) d_events = event_subsystem_dir(call->system, d_events); call->dir = debugfs_create_dir(call->name, d_events); if (!call->dir) { pr_warning("Could not create debugfs " "'%s' directory\n", call->name); return -1; } if (call->regfunc) entry = trace_create_file("enable", 0644, call->dir, call, enable); if (call->id && call->profile_enable) entry = trace_create_file("id", 0444, call->dir, call, id); if (call->define_fields) { ret = call->define_fields(call); if (ret < 0) { pr_warning("Could not initialize trace point" " events/%s\n", call->name); return ret; } entry = trace_create_file("filter", 0644, call->dir, call, filter); } /* A trace may not want to export its format */ if (!(is_print_fmt_event(call)) && !call->fmt.show_format) return 0; entry = trace_create_file("format", 0444, call->dir, call, format); return 0; } static int __trace_add_event_call(struct ftrace_event_call *call) { struct dentry *d_events; const struct file_operations *format; int ret; if (!call->name) return -EINVAL; if (call->raw_init) { ret = call->raw_init(call); if (ret < 0) { if (ret != -ENOSYS) pr_warning("Could not initialize trace " "events/%s\n", call->name); return ret; } } d_events = event_trace_events_dir(); if (!d_events) return -ENOENT; if (is_print_fmt_event(call)) format = &ftrace_event_format_print_fmt_fops; else format = &ftrace_event_format_fops; list_add(&call->list, &ftrace_events); ret = event_create_dir(call, d_events, &ftrace_event_id_fops, &ftrace_enable_fops, &ftrace_event_filter_fops, format); if (ret < 0) list_del(&call->list); return ret; } /* Add an additional event_call dynamically */ int trace_add_event_call(struct ftrace_event_call *call) { int ret; mutex_lock(&event_mutex); ret = __trace_add_event_call(call); mutex_unlock(&event_mutex); return ret; } static void remove_subsystem_dir(const char *name) { struct event_subsystem *system; if (strcmp(name, TRACE_SYSTEM) == 0) return; list_for_each_entry(system, &event_subsystems, list) { if (strcmp(system->name, name) == 0) { if (!--system->nr_events) { struct event_filter *filter = system->filter; debugfs_remove_recursive(system->entry); list_del(&system->list); if (filter) { kfree(filter->filter_string); kfree(filter); } kfree(system->name); kfree(system); } break; } } } /* * Must be called under locking both of event_mutex and trace_event_mutex. */ static void __trace_remove_event_call(struct ftrace_event_call *call) { ftrace_event_enable_disable(call, 0); if (call->event) __unregister_ftrace_event(call->event); debugfs_remove_recursive(call->dir); list_del(&call->list); trace_destroy_fields(call); destroy_preds(call); remove_subsystem_dir(call->system); } /* Remove an event_call */ void trace_remove_event_call(struct ftrace_event_call *call) { mutex_lock(&event_mutex); down_write(&trace_event_mutex); __trace_remove_event_call(call); up_write(&trace_event_mutex); mutex_unlock(&event_mutex); } #define for_each_event(event, start, end) \ for (event = start; \ (unsigned long)event < (unsigned long)end; \ event++) #ifdef CONFIG_MODULES static LIST_HEAD(ftrace_module_file_list); /* * Modules must own their file_operations to keep up with * reference counting. */ struct ftrace_module_file_ops { struct list_head list; struct module *mod; struct file_operations id; struct file_operations enable; struct file_operations format; struct file_operations filter; }; static struct ftrace_module_file_ops * trace_create_file_ops(struct module *mod, bool print_fmt) { struct ftrace_module_file_ops *file_ops; /* * This is a bit of a PITA. To allow for correct reference * counting, modules must "own" their file_operations. * To do this, we allocate the file operations that will be * used in the event directory. */ file_ops = kmalloc(sizeof(*file_ops), GFP_KERNEL); if (!file_ops) return NULL; file_ops->mod = mod; file_ops->id = ftrace_event_id_fops; file_ops->id.owner = mod; file_ops->enable = ftrace_enable_fops; file_ops->enable.owner = mod; file_ops->filter = ftrace_event_filter_fops; file_ops->filter.owner = mod; if (print_fmt) file_ops->format = ftrace_event_format_print_fmt_fops; else file_ops->format = ftrace_event_format_fops; file_ops->format.owner = mod; list_add(&file_ops->list, &ftrace_module_file_list); return file_ops; } static int __trace_module_add_events(struct module *mod, struct ftrace_event_call *call, struct ftrace_module_file_ops **file_ops, struct dentry *d_events) { int ret; /* The linker may leave blanks */ if (!call->name) return 0; if (call->raw_init) { ret = call->raw_init(call); if (ret < 0) { if (ret != -ENOSYS) pr_warning("Could not initialize trace " "point events/%s\n", call->name); return 0; } } /* * This module has events, create file ops for this module * if not already done. */ if (!*file_ops) { bool print_fmt = is_print_fmt_event(call); *file_ops = trace_create_file_ops(mod, print_fmt); if (!*file_ops) return -ENOMEM; } call->mod = mod; list_add(&call->list, &ftrace_events); event_create_dir(call, d_events, &(*file_ops)->id, &(*file_ops)->enable, &(*file_ops)->filter, &(*file_ops)->format); return 0; } static void trace_module_add_events(struct module *mod) { struct ftrace_module_file_ops *file_ops = NULL; struct ftrace_event_call *call, *start = NULL, *end; struct ftrace_event_call **pcall, **pstart = NULL, **pend; struct dentry *d_events; int ret; if (module_has_ftrace_events_ptrs(mod)) { pstart = module_ftrace_events_ptrs_unmask(mod->trace_events.ptrs); pend = pstart + mod->num_trace_events; } else { start = mod->trace_events.events; end = mod->trace_events.events + mod->num_trace_events; } if (start == NULL && pstart == NULL) return; d_events = event_trace_events_dir(); if (!d_events) return; if (pstart) { for_each_event(pcall, pstart, pend) { call = *pcall; ret = __trace_module_add_events(mod, call, &file_ops, d_events); if (ret < 0) return; } } else { for_each_event(call, start, end) { ret = __trace_module_add_events(mod, call, &file_ops, d_events); if (ret < 0) return; } } } static void trace_module_remove_events(struct module *mod) { struct ftrace_module_file_ops *file_ops; struct ftrace_event_call *call, *p; bool found = false; down_write(&trace_event_mutex); list_for_each_entry_safe(call, p, &ftrace_events, list) { if (call->mod == mod) { found = true; __trace_remove_event_call(call); } } /* Now free the file_operations */ list_for_each_entry(file_ops, &ftrace_module_file_list, list) { if (file_ops->mod == mod) break; } if (&file_ops->list != &ftrace_module_file_list) { list_del(&file_ops->list); kfree(file_ops); } /* * It is safest to reset the ring buffer if the module being unloaded * registered any events. */ if (found) tracing_reset_current_online_cpus(); up_write(&trace_event_mutex); } static int trace_module_notify(struct notifier_block *self, unsigned long val, void *data) { struct module *mod = data; mutex_lock(&event_mutex); switch (val) { case MODULE_STATE_COMING: trace_module_add_events(mod); break; case MODULE_STATE_GOING: trace_module_remove_events(mod); break; } mutex_unlock(&event_mutex); return 0; } #else static int trace_module_notify(struct notifier_block *self, unsigned long val, void *data) { return 0; } #endif /* CONFIG_MODULES */ static struct notifier_block trace_module_nb = { .notifier_call = trace_module_notify, .priority = 0, }; extern struct ftrace_event_call *__start_ftrace_events[]; extern struct ftrace_event_call *__stop_ftrace_events[]; static char bootup_event_buf[COMMAND_LINE_SIZE] __initdata; static __init int setup_trace_event(char *str) { strlcpy(bootup_event_buf, str, COMMAND_LINE_SIZE); ring_buffer_expanded = 1; tracing_selftest_disabled = 1; return 1; } __setup("trace_event=", setup_trace_event); static __init int event_trace_init(void) { struct ftrace_event_call *call, **callp; struct dentry *d_tracer; struct dentry *entry; struct dentry *d_events; int ret; char *buf = bootup_event_buf; char *token; d_tracer = tracing_init_dentry(); if (!d_tracer) return 0; entry = debugfs_create_file("available_events", 0444, d_tracer, (void *)&show_event_seq_ops, &ftrace_avail_fops); if (!entry) pr_warning("Could not create debugfs " "'available_events' entry\n"); entry = debugfs_create_file("set_event", 0644, d_tracer, (void *)&show_set_event_seq_ops, &ftrace_set_event_fops); if (!entry) pr_warning("Could not create debugfs " "'set_event' entry\n"); d_events = event_trace_events_dir(); if (!d_events) return 0; /* ring buffer internal formats */ trace_create_file("header_page", 0444, d_events, ring_buffer_print_page_header, &ftrace_show_header_fops); trace_create_file("header_event", 0444, d_events, ring_buffer_print_entry_header, &ftrace_show_header_fops); trace_create_file("enable", 0644, d_events, NULL, &ftrace_system_enable_fops); for_each_event(callp, __start_ftrace_events, __stop_ftrace_events) { call = *callp; /* The linker may leave blanks */ if (!call->name) continue; if (call->raw_init) { ret = call->raw_init(call); if (ret < 0) { if (ret != -ENOSYS) pr_warning("Could not initialize trace " "point events/%s\n", call->name); continue; } } list_add(&call->list, &ftrace_events); event_create_dir(call, d_events, &ftrace_event_id_fops, &ftrace_enable_fops, &ftrace_event_filter_fops, &ftrace_event_format_print_fmt_fops); } while (true) { token = strsep(&buf, ","); if (!token) break; if (!*token) continue; ret = ftrace_set_clr_event(token, 1); if (ret) pr_warning("Failed to enable trace event: %s\n", token); } ret = register_module_notifier(&trace_module_nb); if (ret) pr_warning("Failed to register trace events module notifier\n"); return 0; } fs_initcall(event_trace_init); #ifdef CONFIG_FTRACE_STARTUP_TEST static DEFINE_SPINLOCK(test_spinlock); static DEFINE_SPINLOCK(test_spinlock_irq); static DEFINE_MUTEX(test_mutex); static __init void test_work(struct work_struct *dummy) { spin_lock(&test_spinlock); spin_lock_irq(&test_spinlock_irq); udelay(1); spin_unlock_irq(&test_spinlock_irq); spin_unlock(&test_spinlock); mutex_lock(&test_mutex); msleep(1); mutex_unlock(&test_mutex); } static __init int event_test_thread(void *unused) { void *test_malloc; test_malloc = kmalloc(1234, GFP_KERNEL); if (!test_malloc) pr_info("failed to kmalloc\n"); schedule_on_each_cpu(test_work); kfree(test_malloc); set_current_state(TASK_INTERRUPTIBLE); while (!kthread_should_stop()) schedule(); return 0; } /* * Do various things that may trigger events. */ static __init void event_test_stuff(void) { struct task_struct *test_thread; test_thread = kthread_run(event_test_thread, NULL, "test-events"); msleep(1); kthread_stop(test_thread); } /* * For every trace event defined, we will test each trace point separately, * and then by groups, and finally all trace points. */ static __init void event_trace_self_tests(void) { struct ftrace_event_call *call; struct event_subsystem *system; int ret; pr_info("Running tests on trace events:\n"); list_for_each_entry(call, &ftrace_events, list) { /* Only test those that have a regfunc */ if (!call->regfunc) continue; /* * Testing syscall events here is pretty useless, but * we still do it if configured. But this is time consuming. * What we really need is a user thread to perform the * syscalls as we test. */ #ifndef CONFIG_EVENT_TRACE_TEST_SYSCALLS if (call->system && strcmp(call->system, "syscalls") == 0) continue; #endif pr_info("Testing event %s: ", call->name); /* * If an event is already enabled, someone is using * it and the self test should not be on. */ if (call->flags & TRACE_EVENT_FL_ENABLED) { pr_warning("Enabled event during self test!\n"); WARN_ON_ONCE(1); continue; } ftrace_event_enable_disable(call, 1); event_test_stuff(); ftrace_event_enable_disable(call, 0); pr_cont("OK\n"); } /* Now test at the sub system level */ pr_info("Running tests on trace event systems:\n"); list_for_each_entry(system, &event_subsystems, list) { /* the ftrace system is special, skip it */ if (strcmp(system->name, "ftrace") == 0) continue; pr_info("Testing event system %s: ", system->name); ret = __ftrace_set_clr_event(NULL, system->name, NULL, 1); if (WARN_ON_ONCE(ret)) { pr_warning("error enabling system %s\n", system->name); continue; } event_test_stuff(); ret = __ftrace_set_clr_event(NULL, system->name, NULL, 0); if (WARN_ON_ONCE(ret)) pr_warning("error disabling system %s\n", system->name); pr_cont("OK\n"); } /* Test with all events enabled */ pr_info("Running tests on all trace events:\n"); pr_info("Testing all events: "); ret = __ftrace_set_clr_event(NULL, NULL, NULL, 1); if (WARN_ON_ONCE(ret)) { pr_warning("error enabling all events\n"); return; } event_test_stuff(); /* reset sysname */ ret = __ftrace_set_clr_event(NULL, NULL, NULL, 0); if (WARN_ON_ONCE(ret)) { pr_warning("error disabling all events\n"); return; } pr_cont("OK\n"); } #ifdef CONFIG_FUNCTION_TRACER static DEFINE_PER_CPU(atomic_t, ftrace_test_event_disable); static void function_test_events_call(unsigned long ip, unsigned long parent_ip) { struct ring_buffer_event *event; struct ring_buffer *buffer; struct ftrace_entry *entry; unsigned long flags; long disabled; int resched; int cpu; int pc; pc = preempt_count(); resched = ftrace_preempt_disable(); cpu = raw_smp_processor_id(); disabled = atomic_inc_return(&per_cpu(ftrace_test_event_disable, cpu)); if (disabled != 1) goto out; local_save_flags(flags); event = trace_current_buffer_lock_reserve(&buffer, TRACE_FN, sizeof(*entry), flags, pc); if (!event) goto out; entry = ring_buffer_event_data(event); entry->ip = ip; entry->parent_ip = parent_ip; trace_nowake_buffer_unlock_commit(buffer, event, flags, pc); out: atomic_dec(&per_cpu(ftrace_test_event_disable, cpu)); ftrace_preempt_enable(resched); } static struct ftrace_ops trace_ops __initdata = { .func = function_test_events_call, }; static __init void event_trace_self_test_with_function(void) { register_ftrace_function(&trace_ops); pr_info("Running tests again, along with the function tracer\n"); event_trace_self_tests(); unregister_ftrace_function(&trace_ops); } #else static __init void event_trace_self_test_with_function(void) { } #endif static __init int event_trace_self_tests_init(void) { if (!tracing_selftest_disabled) { event_trace_self_tests(); event_trace_self_test_with_function(); } return 0; } late_initcall(event_trace_self_tests_init); #endif
kofemann/linux-redpatch
kernel/trace/trace_events.c
C
gpl-2.0
38,122
#ifndef CACHE_H #define CACHE_H #include "git-compat-util.h" #include "strbuf.h" #include "hash.h" #include "advice.h" #include "gettext.h" #include "convert.h" #include SHA1_HEADER #ifndef git_SHA_CTX #define git_SHA_CTX SHA_CTX #define git_SHA1_Init SHA1_Init #define git_SHA1_Update SHA1_Update #define git_SHA1_Final SHA1_Final #endif #include <zlib.h> typedef struct git_zstream { z_stream z; unsigned long avail_in; unsigned long avail_out; unsigned long total_in; unsigned long total_out; unsigned char *next_in; unsigned char *next_out; } git_zstream; void git_inflate_init(git_zstream *); void git_inflate_init_gzip_only(git_zstream *); void git_inflate_end(git_zstream *); int git_inflate(git_zstream *, int flush); void git_deflate_init(git_zstream *, int level); void git_deflate_init_gzip(git_zstream *, int level); void git_deflate_end(git_zstream *); int git_deflate_end_gently(git_zstream *); int git_deflate(git_zstream *, int flush); unsigned long git_deflate_bound(git_zstream *, unsigned long); #if defined(DT_UNKNOWN) && !defined(NO_D_TYPE_IN_DIRENT) #define DTYPE(de) ((de)->d_type) #else #undef DT_UNKNOWN #undef DT_DIR #undef DT_REG #undef DT_LNK #define DT_UNKNOWN 0 #define DT_DIR 1 #define DT_REG 2 #define DT_LNK 3 #define DTYPE(de) DT_UNKNOWN #endif /* unknown mode (impossible combination S_IFIFO|S_IFCHR) */ #define S_IFINVALID 0030000 /* * A "directory link" is a link to another git directory. * * The value 0160000 is not normally a valid mode, and * also just happens to be S_IFDIR + S_IFLNK * * NOTE! We *really* shouldn't depend on the S_IFxxx macros * always having the same values everywhere. We should use * our internal git values for these things, and then we can * translate that to the OS-specific value. It just so * happens that everybody shares the same bit representation * in the UNIX world (and apparently wider too..) */ #define S_IFGITLINK 0160000 #define S_ISGITLINK(m) (((m) & S_IFMT) == S_IFGITLINK) /* * Intensive research over the course of many years has shown that * port 9418 is totally unused by anything else. Or * * Your search - "port 9418" - did not match any documents. * * as www.google.com puts it. * * This port has been properly assigned for git use by IANA: * git (Assigned-9418) [I06-050728-0001]. * * git 9418/tcp git pack transfer service * git 9418/udp git pack transfer service * * with Linus Torvalds <torvalds@osdl.org> as the point of * contact. September 2005. * * See http://www.iana.org/assignments/port-numbers */ #define DEFAULT_GIT_PORT 9418 /* * Basic data structures for the directory cache */ #define CACHE_SIGNATURE 0x44495243 /* "DIRC" */ struct cache_header { unsigned int hdr_signature; unsigned int hdr_version; unsigned int hdr_entries; }; /* * The "cache_time" is just the low 32 bits of the * time. It doesn't matter if it overflows - we only * check it for equality in the 32 bits we save. */ struct cache_time { unsigned int sec; unsigned int nsec; }; /* * dev/ino/uid/gid/size are also just tracked to the low 32 bits * Again - this is just a (very strong in practice) heuristic that * the inode hasn't changed. * * We save the fields in big-endian order to allow using the * index file over NFS transparently. */ struct ondisk_cache_entry { struct cache_time ctime; struct cache_time mtime; unsigned int dev; unsigned int ino; unsigned int mode; unsigned int uid; unsigned int gid; unsigned int size; unsigned char sha1[20]; unsigned short flags; char name[FLEX_ARRAY]; /* more */ }; /* * This struct is used when CE_EXTENDED bit is 1 * The struct must match ondisk_cache_entry exactly from * ctime till flags */ struct ondisk_cache_entry_extended { struct cache_time ctime; struct cache_time mtime; unsigned int dev; unsigned int ino; unsigned int mode; unsigned int uid; unsigned int gid; unsigned int size; unsigned char sha1[20]; unsigned short flags; unsigned short flags2; char name[FLEX_ARRAY]; /* more */ }; struct cache_entry { struct cache_time ce_ctime; struct cache_time ce_mtime; unsigned int ce_dev; unsigned int ce_ino; unsigned int ce_mode; unsigned int ce_uid; unsigned int ce_gid; unsigned int ce_size; unsigned int ce_flags; unsigned char sha1[20]; struct cache_entry *next; char name[FLEX_ARRAY]; /* more */ }; #define CE_NAMEMASK (0x0fff) #define CE_STAGEMASK (0x3000) #define CE_EXTENDED (0x4000) #define CE_VALID (0x8000) #define CE_STAGESHIFT 12 /* * Range 0xFFFF0000 in ce_flags is divided into * two parts: in-memory flags and on-disk ones. * Flags in CE_EXTENDED_FLAGS will get saved on-disk * if you want to save a new flag, add it in * CE_EXTENDED_FLAGS * * In-memory only flags */ #define CE_UPDATE (1 << 16) #define CE_REMOVE (1 << 17) #define CE_UPTODATE (1 << 18) #define CE_ADDED (1 << 19) #define CE_HASHED (1 << 20) #define CE_UNHASHED (1 << 21) #define CE_WT_REMOVE (1 << 22) /* remove in work directory */ #define CE_CONFLICTED (1 << 23) #define CE_UNPACKED (1 << 24) #define CE_NEW_SKIP_WORKTREE (1 << 25) /* * Extended on-disk flags */ #define CE_INTENT_TO_ADD (1 << 29) #define CE_SKIP_WORKTREE (1 << 30) /* CE_EXTENDED2 is for future extension */ #define CE_EXTENDED2 (1 << 31) #define CE_EXTENDED_FLAGS (CE_INTENT_TO_ADD | CE_SKIP_WORKTREE) /* * Safeguard to avoid saving wrong flags: * - CE_EXTENDED2 won't get saved until its semantic is known * - Bits in 0x0000FFFF have been saved in ce_flags already * - Bits in 0x003F0000 are currently in-memory flags */ #if CE_EXTENDED_FLAGS & 0x803FFFFF #error "CE_EXTENDED_FLAGS out of range" #endif /* * Copy the sha1 and stat state of a cache entry from one to * another. But we never change the name, or the hash state! */ #define CE_STATE_MASK (CE_HASHED | CE_UNHASHED) static inline void copy_cache_entry(struct cache_entry *dst, struct cache_entry *src) { unsigned int state = dst->ce_flags & CE_STATE_MASK; /* Don't copy hash chain and name */ memcpy(dst, src, offsetof(struct cache_entry, next)); /* Restore the hash state */ dst->ce_flags = (dst->ce_flags & ~CE_STATE_MASK) | state; } static inline unsigned create_ce_flags(size_t len, unsigned stage) { if (len >= CE_NAMEMASK) len = CE_NAMEMASK; return (len | (stage << CE_STAGESHIFT)); } static inline size_t ce_namelen(const struct cache_entry *ce) { size_t len = ce->ce_flags & CE_NAMEMASK; if (len < CE_NAMEMASK) return len; return strlen(ce->name + CE_NAMEMASK) + CE_NAMEMASK; } #define ce_size(ce) cache_entry_size(ce_namelen(ce)) #define ondisk_ce_size(ce) (((ce)->ce_flags & CE_EXTENDED) ? \ ondisk_cache_entry_extended_size(ce_namelen(ce)) : \ ondisk_cache_entry_size(ce_namelen(ce))) #define ce_stage(ce) ((CE_STAGEMASK & (ce)->ce_flags) >> CE_STAGESHIFT) #define ce_uptodate(ce) ((ce)->ce_flags & CE_UPTODATE) #define ce_skip_worktree(ce) ((ce)->ce_flags & CE_SKIP_WORKTREE) #define ce_mark_uptodate(ce) ((ce)->ce_flags |= CE_UPTODATE) #define ce_permissions(mode) (((mode) & 0100) ? 0755 : 0644) static inline unsigned int create_ce_mode(unsigned int mode) { if (S_ISLNK(mode)) return S_IFLNK; if (S_ISDIR(mode) || S_ISGITLINK(mode)) return S_IFGITLINK; return S_IFREG | ce_permissions(mode); } static inline unsigned int ce_mode_from_stat(struct cache_entry *ce, unsigned int mode) { extern int trust_executable_bit, has_symlinks; if (!has_symlinks && S_ISREG(mode) && ce && S_ISLNK(ce->ce_mode)) return ce->ce_mode; if (!trust_executable_bit && S_ISREG(mode)) { if (ce && S_ISREG(ce->ce_mode)) return ce->ce_mode; return create_ce_mode(0666); } return create_ce_mode(mode); } static inline int ce_to_dtype(const struct cache_entry *ce) { unsigned ce_mode = ntohl(ce->ce_mode); if (S_ISREG(ce_mode)) return DT_REG; else if (S_ISDIR(ce_mode) || S_ISGITLINK(ce_mode)) return DT_DIR; else if (S_ISLNK(ce_mode)) return DT_LNK; else return DT_UNKNOWN; } static inline unsigned int canon_mode(unsigned int mode) { if (S_ISREG(mode)) return S_IFREG | ce_permissions(mode); if (S_ISLNK(mode)) return S_IFLNK; if (S_ISDIR(mode)) return S_IFDIR; return S_IFGITLINK; } #define flexible_size(STRUCT,len) ((offsetof(struct STRUCT,name) + (len) + 8) & ~7) #define cache_entry_size(len) flexible_size(cache_entry,len) #define ondisk_cache_entry_size(len) flexible_size(ondisk_cache_entry,len) #define ondisk_cache_entry_extended_size(len) flexible_size(ondisk_cache_entry_extended,len) struct index_state { struct cache_entry **cache; unsigned int cache_nr, cache_alloc, cache_changed; struct string_list *resolve_undo; struct cache_tree *cache_tree; struct cache_time timestamp; void *alloc; unsigned name_hash_initialized : 1, initialized : 1; struct hash_table name_hash; }; extern struct index_state the_index; /* Name hashing */ extern void add_name_hash(struct index_state *istate, struct cache_entry *ce); /* * We don't actually *remove* it, we can just mark it invalid so that * we won't find it in lookups. * * Not only would we have to search the lists (simple enough), but * we'd also have to rehash other hash buckets in case this makes the * hash bucket empty (common). So it's much better to just mark * it. */ static inline void remove_name_hash(struct cache_entry *ce) { ce->ce_flags |= CE_UNHASHED; } #ifndef NO_THE_INDEX_COMPATIBILITY_MACROS #define active_cache (the_index.cache) #define active_nr (the_index.cache_nr) #define active_alloc (the_index.cache_alloc) #define active_cache_changed (the_index.cache_changed) #define active_cache_tree (the_index.cache_tree) #define read_cache() read_index(&the_index) #define read_cache_from(path) read_index_from(&the_index, (path)) #define read_cache_preload(pathspec) read_index_preload(&the_index, (pathspec)) #define is_cache_unborn() is_index_unborn(&the_index) #define read_cache_unmerged() read_index_unmerged(&the_index) #define write_cache(newfd, cache, entries) write_index(&the_index, (newfd)) #define discard_cache() discard_index(&the_index) #define unmerged_cache() unmerged_index(&the_index) #define cache_name_pos(name, namelen) index_name_pos(&the_index,(name),(namelen)) #define add_cache_entry(ce, option) add_index_entry(&the_index, (ce), (option)) #define rename_cache_entry_at(pos, new_name) rename_index_entry_at(&the_index, (pos), (new_name)) #define remove_cache_entry_at(pos) remove_index_entry_at(&the_index, (pos)) #define remove_file_from_cache(path) remove_file_from_index(&the_index, (path)) #define add_to_cache(path, st, flags) add_to_index(&the_index, (path), (st), (flags)) #define add_file_to_cache(path, flags) add_file_to_index(&the_index, (path), (flags)) #define refresh_cache(flags) refresh_index(&the_index, (flags), NULL, NULL, NULL) #define ce_match_stat(ce, st, options) ie_match_stat(&the_index, (ce), (st), (options)) #define ce_modified(ce, st, options) ie_modified(&the_index, (ce), (st), (options)) #define cache_name_exists(name, namelen, igncase) index_name_exists(&the_index, (name), (namelen), (igncase)) #define cache_name_is_other(name, namelen) index_name_is_other(&the_index, (name), (namelen)) #define resolve_undo_clear() resolve_undo_clear_index(&the_index) #define unmerge_cache_entry_at(at) unmerge_index_entry_at(&the_index, at) #define unmerge_cache(pathspec) unmerge_index(&the_index, pathspec) #endif enum object_type { OBJ_BAD = -1, OBJ_NONE = 0, OBJ_COMMIT = 1, OBJ_TREE = 2, OBJ_BLOB = 3, OBJ_TAG = 4, /* 5 for future expansion */ OBJ_OFS_DELTA = 6, OBJ_REF_DELTA = 7, OBJ_ANY, OBJ_MAX }; static inline enum object_type object_type(unsigned int mode) { return S_ISDIR(mode) ? OBJ_TREE : S_ISGITLINK(mode) ? OBJ_COMMIT : OBJ_BLOB; } #define GIT_DIR_ENVIRONMENT "GIT_DIR" #define GIT_WORK_TREE_ENVIRONMENT "GIT_WORK_TREE" #define DEFAULT_GIT_DIR_ENVIRONMENT ".git" #define DB_ENVIRONMENT "GIT_OBJECT_DIRECTORY" #define INDEX_ENVIRONMENT "GIT_INDEX_FILE" #define GRAFT_ENVIRONMENT "GIT_GRAFT_FILE" #define TEMPLATE_DIR_ENVIRONMENT "GIT_TEMPLATE_DIR" #define CONFIG_ENVIRONMENT "GIT_CONFIG" #define CONFIG_DATA_ENVIRONMENT "GIT_CONFIG_PARAMETERS" #define EXEC_PATH_ENVIRONMENT "GIT_EXEC_PATH" #define CEILING_DIRECTORIES_ENVIRONMENT "GIT_CEILING_DIRECTORIES" #define NO_REPLACE_OBJECTS_ENVIRONMENT "GIT_NO_REPLACE_OBJECTS" #define GITATTRIBUTES_FILE ".gitattributes" #define INFOATTRIBUTES_FILE "info/attributes" #define ATTRIBUTE_MACRO_PREFIX "[attr]" #define GIT_NOTES_REF_ENVIRONMENT "GIT_NOTES_REF" #define GIT_NOTES_DEFAULT_REF "refs/notes/commits" #define GIT_NOTES_DISPLAY_REF_ENVIRONMENT "GIT_NOTES_DISPLAY_REF" #define GIT_NOTES_REWRITE_REF_ENVIRONMENT "GIT_NOTES_REWRITE_REF" #define GIT_NOTES_REWRITE_MODE_ENVIRONMENT "GIT_NOTES_REWRITE_MODE" /* * Repository-local GIT_* environment variables * The array is NULL-terminated to simplify its usage in contexts such * environment creation or simple walk of the list. * The number of non-NULL entries is available as a macro. */ #define LOCAL_REPO_ENV_SIZE 9 extern const char *const local_repo_env[LOCAL_REPO_ENV_SIZE + 1]; extern int is_bare_repository_cfg; extern int is_bare_repository(void); extern int is_inside_git_dir(void); extern char *git_work_tree_cfg; extern int is_inside_work_tree(void); extern int have_git_dir(void); extern const char *get_git_dir(void); extern char *get_object_directory(void); extern char *get_index_file(void); extern char *get_graft_file(void); extern int set_git_dir(const char *path); extern const char *get_git_work_tree(void); extern const char *read_gitfile_gently(const char *path); extern void set_git_work_tree(const char *tree); #define ALTERNATE_DB_ENVIRONMENT "GIT_ALTERNATE_OBJECT_DIRECTORIES" extern const char **get_pathspec(const char *prefix, const char **pathspec); extern void setup_work_tree(void); extern const char *setup_git_directory_gently(int *); extern const char *setup_git_directory(void); extern char *prefix_path(const char *prefix, int len, const char *path); extern const char *prefix_filename(const char *prefix, int len, const char *path); extern int check_filename(const char *prefix, const char *name); extern void verify_filename(const char *prefix, const char *name); extern void verify_non_filename(const char *prefix, const char *name); #define INIT_DB_QUIET 0x0001 extern int set_git_dir_init(const char *git_dir, const char *real_git_dir, int); extern int init_db(const char *template_dir, unsigned int flags); #define alloc_nr(x) (((x)+16)*3/2) /* * Realloc the buffer pointed at by variable 'x' so that it can hold * at least 'nr' entries; the number of entries currently allocated * is 'alloc', using the standard growing factor alloc_nr() macro. * * DO NOT USE any expression with side-effect for 'x', 'nr', or 'alloc'. */ #define ALLOC_GROW(x, nr, alloc) \ do { \ if ((nr) > alloc) { \ if (alloc_nr(alloc) < (nr)) \ alloc = (nr); \ else \ alloc = alloc_nr(alloc); \ x = xrealloc((x), alloc * sizeof(*(x))); \ } \ } while (0) /* Initialize and use the cache information */ extern int read_index(struct index_state *); extern int read_index_preload(struct index_state *, const char **pathspec); extern int read_index_from(struct index_state *, const char *path); extern int is_index_unborn(struct index_state *); extern int read_index_unmerged(struct index_state *); extern int write_index(struct index_state *, int newfd); extern int discard_index(struct index_state *); extern int unmerged_index(const struct index_state *); extern int verify_path(const char *path); extern struct cache_entry *index_name_exists(struct index_state *istate, const char *name, int namelen, int igncase); extern int index_name_pos(const struct index_state *, const char *name, int namelen); #define ADD_CACHE_OK_TO_ADD 1 /* Ok to add */ #define ADD_CACHE_OK_TO_REPLACE 2 /* Ok to replace file/directory */ #define ADD_CACHE_SKIP_DFCHECK 4 /* Ok to skip DF conflict checks */ #define ADD_CACHE_JUST_APPEND 8 /* Append only; tree.c::read_tree() */ #define ADD_CACHE_NEW_ONLY 16 /* Do not replace existing ones */ extern int add_index_entry(struct index_state *, struct cache_entry *ce, int option); extern void rename_index_entry_at(struct index_state *, int pos, const char *new_name); extern int remove_index_entry_at(struct index_state *, int pos); extern void remove_marked_cache_entries(struct index_state *istate); extern int remove_file_from_index(struct index_state *, const char *path); #define ADD_CACHE_VERBOSE 1 #define ADD_CACHE_PRETEND 2 #define ADD_CACHE_IGNORE_ERRORS 4 #define ADD_CACHE_IGNORE_REMOVAL 8 #define ADD_CACHE_INTENT 16 extern int add_to_index(struct index_state *, const char *path, struct stat *, int flags); extern int add_file_to_index(struct index_state *, const char *path, int flags); extern struct cache_entry *make_cache_entry(unsigned int mode, const unsigned char *sha1, const char *path, int stage, int refresh); extern int ce_same_name(struct cache_entry *a, struct cache_entry *b); extern int index_name_is_other(const struct index_state *, const char *, int); /* do stat comparison even if CE_VALID is true */ #define CE_MATCH_IGNORE_VALID 01 /* do not check the contents but report dirty on racily-clean entries */ #define CE_MATCH_RACY_IS_DIRTY 02 /* do stat comparison even if CE_SKIP_WORKTREE is true */ #define CE_MATCH_IGNORE_SKIP_WORKTREE 04 extern int ie_match_stat(const struct index_state *, struct cache_entry *, struct stat *, unsigned int); extern int ie_modified(const struct index_state *, struct cache_entry *, struct stat *, unsigned int); struct pathspec { const char **raw; /* get_pathspec() result, not freed by free_pathspec() */ int nr; unsigned int has_wildcard:1; unsigned int recursive:1; int max_depth; struct pathspec_item { const char *match; int len; unsigned int use_wildcard:1; } *items; }; extern int init_pathspec(struct pathspec *, const char **); extern void free_pathspec(struct pathspec *); extern int ce_path_match(const struct cache_entry *ce, const struct pathspec *pathspec); #define HASH_WRITE_OBJECT 1 #define HASH_FORMAT_CHECK 2 extern int index_fd(unsigned char *sha1, int fd, struct stat *st, enum object_type type, const char *path, unsigned flags); extern int index_path(unsigned char *sha1, const char *path, struct stat *st, unsigned flags); extern void fill_stat_cache_info(struct cache_entry *ce, struct stat *st); #define REFRESH_REALLY 0x0001 /* ignore_valid */ #define REFRESH_UNMERGED 0x0002 /* allow unmerged */ #define REFRESH_QUIET 0x0004 /* be quiet about it */ #define REFRESH_IGNORE_MISSING 0x0008 /* ignore non-existent */ #define REFRESH_IGNORE_SUBMODULES 0x0010 /* ignore submodules */ #define REFRESH_IN_PORCELAIN 0x0020 /* user friendly output, not "needs update" */ extern int refresh_index(struct index_state *, unsigned int flags, const char **pathspec, char *seen, const char *header_msg); struct lock_file { struct lock_file *next; int fd; pid_t owner; char on_list; char filename[PATH_MAX]; }; #define LOCK_DIE_ON_ERROR 1 #define LOCK_NODEREF 2 extern int unable_to_lock_error(const char *path, int err); extern NORETURN void unable_to_lock_index_die(const char *path, int err); extern int hold_lock_file_for_update(struct lock_file *, const char *path, int); extern int hold_lock_file_for_append(struct lock_file *, const char *path, int); extern int commit_lock_file(struct lock_file *); extern void update_index_if_able(struct index_state *, struct lock_file *); extern int hold_locked_index(struct lock_file *, int); extern int commit_locked_index(struct lock_file *); extern void set_alternate_index_output(const char *); extern int close_lock_file(struct lock_file *); extern void rollback_lock_file(struct lock_file *); extern int delete_ref(const char *, const unsigned char *sha1, int delopt); /* Environment bits from configuration mechanism */ extern int trust_executable_bit; extern int trust_ctime; extern int quote_path_fully; extern int has_symlinks; extern int minimum_abbrev, default_abbrev; extern int ignore_case; extern int assume_unchanged; extern int prefer_symlink_refs; extern int log_all_ref_updates; extern int warn_ambiguous_refs; extern int shared_repository; extern const char *apply_default_whitespace; extern const char *apply_default_ignorewhitespace; extern int zlib_compression_level; extern int core_compression_level; extern int core_compression_seen; extern size_t packed_git_window_size; extern size_t packed_git_limit; extern size_t delta_base_cache_limit; extern unsigned long big_file_threshold; extern int read_replace_refs; extern int fsync_object_files; extern int core_preload_index; extern int core_apply_sparse_checkout; enum branch_track { BRANCH_TRACK_UNSPECIFIED = -1, BRANCH_TRACK_NEVER = 0, BRANCH_TRACK_REMOTE, BRANCH_TRACK_ALWAYS, BRANCH_TRACK_EXPLICIT, BRANCH_TRACK_OVERRIDE }; enum rebase_setup_type { AUTOREBASE_NEVER = 0, AUTOREBASE_LOCAL, AUTOREBASE_REMOTE, AUTOREBASE_ALWAYS }; enum push_default_type { PUSH_DEFAULT_NOTHING = 0, PUSH_DEFAULT_MATCHING, PUSH_DEFAULT_UPSTREAM, PUSH_DEFAULT_CURRENT }; extern enum branch_track git_branch_track; extern enum rebase_setup_type autorebase; extern enum push_default_type push_default; enum object_creation_mode { OBJECT_CREATION_USES_HARDLINKS = 0, OBJECT_CREATION_USES_RENAMES = 1 }; extern enum object_creation_mode object_creation_mode; extern char *notes_ref_name; extern int grafts_replace_parents; #define GIT_REPO_VERSION 0 extern int repository_format_version; extern int check_repository_format(void); #define MTIME_CHANGED 0x0001 #define CTIME_CHANGED 0x0002 #define OWNER_CHANGED 0x0004 #define MODE_CHANGED 0x0008 #define INODE_CHANGED 0x0010 #define DATA_CHANGED 0x0020 #define TYPE_CHANGED 0x0040 extern char *mksnpath(char *buf, size_t n, const char *fmt, ...) __attribute__((format (printf, 3, 4))); extern char *git_snpath(char *buf, size_t n, const char *fmt, ...) __attribute__((format (printf, 3, 4))); extern char *git_pathdup(const char *fmt, ...) __attribute__((format (printf, 1, 2))); /* Return a statically allocated filename matching the sha1 signature */ extern char *mkpath(const char *fmt, ...) __attribute__((format (printf, 1, 2))); extern char *git_path(const char *fmt, ...) __attribute__((format (printf, 1, 2))); extern char *git_path_submodule(const char *path, const char *fmt, ...) __attribute__((format (printf, 2, 3))); extern char *sha1_file_name(const unsigned char *sha1); extern char *sha1_pack_name(const unsigned char *sha1); extern char *sha1_pack_index_name(const unsigned char *sha1); extern const char *find_unique_abbrev(const unsigned char *sha1, int); extern const unsigned char null_sha1[20]; static inline int hashcmp(const unsigned char *sha1, const unsigned char *sha2) { int i; for (i = 0; i < 20; i++, sha1++, sha2++) { if (*sha1 != *sha2) return *sha1 - *sha2; } return 0; } static inline int is_null_sha1(const unsigned char *sha1) { return !hashcmp(sha1, null_sha1); } static inline void hashcpy(unsigned char *sha_dst, const unsigned char *sha_src) { memcpy(sha_dst, sha_src, 20); } static inline void hashclr(unsigned char *hash) { memset(hash, 0, 20); } #define EMPTY_TREE_SHA1_HEX \ "4b825dc642cb6eb9a060e54bf8d69288fbee4904" #define EMPTY_TREE_SHA1_BIN_LITERAL \ "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60" \ "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04" #define EMPTY_TREE_SHA1_BIN \ ((const unsigned char *) EMPTY_TREE_SHA1_BIN_LITERAL) int git_mkstemp(char *path, size_t n, const char *template); int git_mkstemps(char *path, size_t n, const char *template, int suffix_len); /* set default permissions by passing mode arguments to open(2) */ int git_mkstemps_mode(char *pattern, int suffix_len, int mode); int git_mkstemp_mode(char *pattern, int mode); /* * NOTE NOTE NOTE!! * * PERM_UMASK, OLD_PERM_GROUP and OLD_PERM_EVERYBODY enumerations must * not be changed. Old repositories have core.sharedrepository written in * numeric format, and therefore these values are preserved for compatibility * reasons. */ enum sharedrepo { PERM_UMASK = 0, OLD_PERM_GROUP = 1, OLD_PERM_EVERYBODY = 2, PERM_GROUP = 0660, PERM_EVERYBODY = 0664 }; int git_config_perm(const char *var, const char *value); int set_shared_perm(const char *path, int mode); #define adjust_shared_perm(path) set_shared_perm((path), 0) int safe_create_leading_directories(char *path); int safe_create_leading_directories_const(const char *path); int mkdir_in_gitdir(const char *path); extern char *expand_user_path(const char *path); char *enter_repo(char *path, int strict); static inline int is_absolute_path(const char *path) { return is_dir_sep(path[0]) || has_dos_drive_prefix(path); } int is_directory(const char *); const char *real_path(const char *path); const char *absolute_path(const char *path); const char *relative_path(const char *abs, const char *base); int normalize_path_copy(char *dst, const char *src); int longest_ancestor_length(const char *path, const char *prefix_list); char *strip_path_suffix(const char *path, const char *suffix); int daemon_avoid_alias(const char *path); int offset_1st_component(const char *path); /* object replacement */ #define READ_SHA1_FILE_REPLACE 1 extern void *read_sha1_file_extended(const unsigned char *sha1, enum object_type *type, unsigned long *size, unsigned flag); static inline void *read_sha1_file(const unsigned char *sha1, enum object_type *type, unsigned long *size) { return read_sha1_file_extended(sha1, type, size, READ_SHA1_FILE_REPLACE); } extern const unsigned char *do_lookup_replace_object(const unsigned char *sha1); static inline const unsigned char *lookup_replace_object(const unsigned char *sha1) { if (!read_replace_refs) return sha1; return do_lookup_replace_object(sha1); } /* Read and unpack a sha1 file into memory, write memory to a sha1 file */ extern int sha1_object_info(const unsigned char *, unsigned long *); extern int hash_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *sha1); extern int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *return_sha1); extern int pretend_sha1_file(void *, unsigned long, enum object_type, unsigned char *); extern int force_object_loose(const unsigned char *sha1, time_t mtime); extern void *map_sha1_file(const unsigned char *sha1, unsigned long *size); extern int unpack_sha1_header(git_zstream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz); extern int parse_sha1_header(const char *hdr, unsigned long *sizep); /* global flag to enable extra checks when accessing packed objects */ extern int do_check_packed_object_crc; extern int check_sha1_signature(const unsigned char *sha1, void *buf, unsigned long size, const char *type); extern int move_temp_to_file(const char *tmpfile, const char *filename); extern int has_sha1_pack(const unsigned char *sha1); extern int has_sha1_file(const unsigned char *sha1); extern int has_loose_object_nonlocal(const unsigned char *sha1); extern int has_pack_index(const unsigned char *sha1); extern void assert_sha1_type(const unsigned char *sha1, enum object_type expect); extern const signed char hexval_table[256]; static inline unsigned int hexval(unsigned char c) { return hexval_table[c]; } /* Convert to/from hex/sha1 representation */ #define MINIMUM_ABBREV minimum_abbrev #define DEFAULT_ABBREV default_abbrev struct object_context { unsigned char tree[20]; char path[PATH_MAX]; unsigned mode; }; extern int get_sha1(const char *str, unsigned char *sha1); extern int get_sha1_with_mode_1(const char *str, unsigned char *sha1, unsigned *mode, int only_to_die, const char *prefix); static inline int get_sha1_with_mode(const char *str, unsigned char *sha1, unsigned *mode) { return get_sha1_with_mode_1(str, sha1, mode, 0, NULL); } extern int get_sha1_with_context_1(const char *name, unsigned char *sha1, struct object_context *orc, int only_to_die, const char *prefix); static inline int get_sha1_with_context(const char *str, unsigned char *sha1, struct object_context *orc) { return get_sha1_with_context_1(str, sha1, orc, 0, NULL); } extern int get_sha1_hex(const char *hex, unsigned char *sha1); extern char *sha1_to_hex(const unsigned char *sha1); /* static buffer result! */ extern int read_ref(const char *filename, unsigned char *sha1); extern const char *resolve_ref(const char *path, unsigned char *sha1, int, int *); extern int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref); extern int dwim_log(const char *str, int len, unsigned char *sha1, char **ref); extern int interpret_branch_name(const char *str, struct strbuf *); extern int get_sha1_mb(const char *str, unsigned char *sha1); extern int refname_match(const char *abbrev_name, const char *full_name, const char **rules); extern const char *ref_rev_parse_rules[]; extern const char *ref_fetch_rules[]; extern int create_symref(const char *ref, const char *refs_heads_master, const char *logmsg); extern int validate_headref(const char *ref); extern int base_name_compare(const char *name1, int len1, int mode1, const char *name2, int len2, int mode2); extern int df_name_compare(const char *name1, int len1, int mode1, const char *name2, int len2, int mode2); extern int cache_name_compare(const char *name1, int len1, const char *name2, int len2); extern void *read_object_with_reference(const unsigned char *sha1, const char *required_type, unsigned long *size, unsigned char *sha1_ret); extern struct object *peel_to_type(const char *name, int namelen, struct object *o, enum object_type); enum date_mode { DATE_NORMAL = 0, DATE_RELATIVE, DATE_SHORT, DATE_LOCAL, DATE_ISO8601, DATE_RFC2822, DATE_RAW }; const char *show_date(unsigned long time, int timezone, enum date_mode mode); const char *show_date_relative(unsigned long time, int tz, const struct timeval *now, char *timebuf, size_t timebuf_size); int parse_date(const char *date, char *buf, int bufsize); int parse_date_basic(const char *date, unsigned long *timestamp, int *offset); void datestamp(char *buf, int bufsize); #define approxidate(s) approxidate_careful((s), NULL) unsigned long approxidate_careful(const char *, int *); unsigned long approxidate_relative(const char *date, const struct timeval *now); enum date_mode parse_date_format(const char *format); #define IDENT_WARN_ON_NO_NAME 1 #define IDENT_ERROR_ON_NO_NAME 2 #define IDENT_NO_DATE 4 extern const char *git_author_info(int); extern const char *git_committer_info(int); extern const char *fmt_ident(const char *name, const char *email, const char *date_str, int); extern const char *fmt_name(const char *name, const char *email); extern const char *git_editor(void); extern const char *git_pager(int stdout_is_tty); struct checkout { const char *base_dir; int base_dir_len; unsigned force:1, quiet:1, not_new:1, refresh_cache:1; }; extern int checkout_entry(struct cache_entry *ce, const struct checkout *state, char *topath); struct cache_def { char path[PATH_MAX + 1]; int len; int flags; int track_flags; int prefix_len_stat_func; }; extern int has_symlink_leading_path(const char *name, int len); extern int threaded_has_symlink_leading_path(struct cache_def *, const char *, int); extern int check_leading_path(const char *name, int len); extern int has_dirs_only_path(const char *name, int len, int prefix_len); extern void schedule_dir_for_removal(const char *name, int len); extern void remove_scheduled_dirs(void); extern struct alternate_object_database { struct alternate_object_database *next; char *name; char base[FLEX_ARRAY]; /* more */ } *alt_odb_list; extern void prepare_alt_odb(void); extern void add_to_alternates_file(const char *reference); typedef int alt_odb_fn(struct alternate_object_database *, void *); extern void foreach_alt_odb(alt_odb_fn, void*); struct pack_window { struct pack_window *next; unsigned char *base; off_t offset; size_t len; unsigned int last_used; unsigned int inuse_cnt; }; extern struct packed_git { struct packed_git *next; struct pack_window *windows; off_t pack_size; const void *index_data; size_t index_size; uint32_t num_objects; uint32_t num_bad_objects; unsigned char *bad_object_sha1; int index_version; time_t mtime; int pack_fd; unsigned pack_local:1, pack_keep:1, do_not_close:1; unsigned char sha1[20]; /* something like ".git/objects/pack/xxxxx.pack" */ char pack_name[FLEX_ARRAY]; /* more */ } *packed_git; struct pack_entry { off_t offset; unsigned char sha1[20]; struct packed_git *p; }; struct ref { struct ref *next; unsigned char old_sha1[20]; unsigned char new_sha1[20]; char *symref; unsigned int force:1, merge:1, nonfastforward:1, deletion:1; enum { REF_STATUS_NONE = 0, REF_STATUS_OK, REF_STATUS_REJECT_NONFASTFORWARD, REF_STATUS_REJECT_NODELETE, REF_STATUS_UPTODATE, REF_STATUS_REMOTE_REJECT, REF_STATUS_EXPECTING_REPORT } status; char *remote_status; struct ref *peer_ref; /* when renaming */ char name[FLEX_ARRAY]; /* more */ }; #define REF_NORMAL (1u << 0) #define REF_HEADS (1u << 1) #define REF_TAGS (1u << 2) extern struct ref *find_ref_by_name(const struct ref *list, const char *name); #define CONNECT_VERBOSE (1u << 0) extern char *git_getpass(const char *prompt); extern struct child_process *git_connect(int fd[2], const char *url, const char *prog, int flags); extern int finish_connect(struct child_process *conn); extern int git_connection_is_socket(struct child_process *conn); extern int path_match(const char *path, int nr, char **match); struct extra_have_objects { int nr, alloc; unsigned char (*array)[20]; }; extern struct ref **get_remote_heads(int in, struct ref **list, int nr_match, char **match, unsigned int flags, struct extra_have_objects *); extern int server_supports(const char *feature); extern struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path); extern void prepare_packed_git(void); extern void reprepare_packed_git(void); extern void install_packed_git(struct packed_git *pack); extern struct packed_git *find_sha1_pack(const unsigned char *sha1, struct packed_git *packs); extern void pack_report(void); extern int open_pack_index(struct packed_git *); extern void close_pack_index(struct packed_git *); extern unsigned char *use_pack(struct packed_git *, struct pack_window **, off_t, unsigned long *); extern void close_pack_windows(struct packed_git *); extern void unuse_pack(struct pack_window **); extern void free_pack_by_name(const char *); extern void clear_delta_base_cache(void); extern struct packed_git *add_packed_git(const char *, int, int); extern const unsigned char *nth_packed_object_sha1(struct packed_git *, uint32_t); extern off_t nth_packed_object_offset(const struct packed_git *, uint32_t); extern off_t find_pack_entry_one(const unsigned char *, struct packed_git *); extern void *unpack_entry(struct packed_git *, off_t, enum object_type *, unsigned long *); extern unsigned long unpack_object_header_buffer(const unsigned char *buf, unsigned long len, enum object_type *type, unsigned long *sizep); extern unsigned long get_size_from_delta(struct packed_git *, struct pack_window **, off_t); extern int unpack_object_header(struct packed_git *, struct pack_window **, off_t *, unsigned long *); struct object_info { /* Request */ unsigned long *sizep; /* Response */ enum { OI_CACHED, OI_LOOSE, OI_PACKED, OI_DBCACHED } whence; union { /* * struct { * ... Nothing to expose in this case * } cached; * struct { * ... Nothing to expose in this case * } loose; */ struct { struct packed_git *pack; off_t offset; unsigned int is_delta; } packed; } u; }; extern int sha1_object_info_extended(const unsigned char *, struct object_info *); /* Dumb servers support */ extern int update_server_info(int); /* git_config_parse_key() returns these negated: */ #define CONFIG_INVALID_KEY 1 #define CONFIG_NO_SECTION_OR_NAME 2 /* git_config_set(), git_config_set_multivar() return the above or these: */ #define CONFIG_NO_LOCK -1 #define CONFIG_INVALID_FILE 3 #define CONFIG_NO_WRITE 4 #define CONFIG_NOTHING_SET 5 #define CONFIG_INVALID_PATTERN 6 typedef int (*config_fn_t)(const char *, const char *, void *); extern int git_default_config(const char *, const char *, void *); extern int git_config_from_file(config_fn_t fn, const char *, void *); extern void git_config_push_parameter(const char *text); extern int git_config_from_parameters(config_fn_t fn, void *data); extern int git_config(config_fn_t fn, void *); extern int git_config_early(config_fn_t fn, void *, const char *repo_config); extern int git_parse_ulong(const char *, unsigned long *); extern int git_config_int(const char *, const char *); extern unsigned long git_config_ulong(const char *, const char *); extern int git_config_bool_or_int(const char *, const char *, int *); extern int git_config_bool(const char *, const char *); extern int git_config_maybe_bool(const char *, const char *); extern int git_config_string(const char **, const char *, const char *); extern int git_config_pathname(const char **, const char *, const char *); extern int git_config_set(const char *, const char *); extern int git_config_parse_key(const char *, char **, int *); extern int git_config_set_multivar(const char *, const char *, const char *, int); extern int git_config_rename_section(const char *, const char *); extern const char *git_etc_gitconfig(void); extern int check_repository_format_version(const char *var, const char *value, void *cb); extern int git_env_bool(const char *, int); extern int git_config_system(void); extern int config_error_nonbool(const char *); extern const char *get_log_output_encoding(void); extern const char *get_commit_output_encoding(void); extern int git_config_parse_parameter(const char *, config_fn_t fn, void *data); extern const char *config_exclusive_filename; #define MAX_GITNAME (1000) extern char git_default_email[MAX_GITNAME]; extern char git_default_name[MAX_GITNAME]; #define IDENT_NAME_GIVEN 01 #define IDENT_MAIL_GIVEN 02 #define IDENT_ALL_GIVEN (IDENT_NAME_GIVEN|IDENT_MAIL_GIVEN) extern int user_ident_explicitly_given; extern int user_ident_sufficiently_given(void); extern const char *git_commit_encoding; extern const char *git_log_output_encoding; extern const char *git_mailmap_file; /* IO helper functions */ extern void maybe_flush_or_die(FILE *, const char *); extern int copy_fd(int ifd, int ofd); extern int copy_file(const char *dst, const char *src, int mode); extern int copy_file_with_time(const char *dst, const char *src, int mode); extern void write_or_die(int fd, const void *buf, size_t count); extern int write_or_whine(int fd, const void *buf, size_t count, const char *msg); extern int write_or_whine_pipe(int fd, const void *buf, size_t count, const char *msg); extern void fsync_or_die(int fd, const char *); extern ssize_t read_in_full(int fd, void *buf, size_t count); extern ssize_t write_in_full(int fd, const void *buf, size_t count); static inline ssize_t write_str_in_full(int fd, const char *str) { return write_in_full(fd, str, strlen(str)); } /* pager.c */ extern void setup_pager(void); extern const char *pager_program; extern int pager_in_use(void); extern int pager_use_color; extern const char *editor_program; extern const char *askpass_program; extern const char *excludes_file; /* base85 */ int decode_85(char *dst, const char *line, int linelen); void encode_85(char *buf, const unsigned char *data, int bytes); /* alloc.c */ extern void *alloc_blob_node(void); extern void *alloc_tree_node(void); extern void *alloc_commit_node(void); extern void *alloc_tag_node(void); extern void *alloc_object_node(void); extern void alloc_report(void); /* trace.c */ __attribute__((format (printf, 1, 2))) extern void trace_printf(const char *format, ...); extern void trace_vprintf(const char *key, const char *format, va_list ap); __attribute__((format (printf, 2, 3))) extern void trace_argv_printf(const char **argv, const char *format, ...); extern void trace_repo_setup(const char *prefix); extern int trace_want(const char *key); extern void trace_strbuf(const char *key, const struct strbuf *buf); void packet_trace_identity(const char *prog); /* add */ /* * return 0 if success, 1 - if addition of a file failed and * ADD_FILES_IGNORE_ERRORS was specified in flags */ int add_files_to_cache(const char *prefix, const char **pathspec, int flags); /* diff.c */ extern int diff_auto_refresh_index; /* match-trees.c */ void shift_tree(const unsigned char *, const unsigned char *, unsigned char *, int); void shift_tree_by(const unsigned char *, const unsigned char *, unsigned char *, const char *); /* * whitespace rules. * used by both diff and apply * last two digits are tab width */ #define WS_BLANK_AT_EOL 0100 #define WS_SPACE_BEFORE_TAB 0200 #define WS_INDENT_WITH_NON_TAB 0400 #define WS_CR_AT_EOL 01000 #define WS_BLANK_AT_EOF 02000 #define WS_TAB_IN_INDENT 04000 #define WS_TRAILING_SPACE (WS_BLANK_AT_EOL|WS_BLANK_AT_EOF) #define WS_DEFAULT_RULE (WS_TRAILING_SPACE|WS_SPACE_BEFORE_TAB|8) #define WS_TAB_WIDTH_MASK 077 extern unsigned whitespace_rule_cfg; extern unsigned whitespace_rule(const char *); extern unsigned parse_whitespace_rule(const char *); extern unsigned ws_check(const char *line, int len, unsigned ws_rule); extern void ws_check_emit(const char *line, int len, unsigned ws_rule, FILE *stream, const char *set, const char *reset, const char *ws); extern char *whitespace_error_string(unsigned ws); extern void ws_fix_copy(struct strbuf *, const char *, int, unsigned, int *); extern int ws_blank_line(const char *line, int len, unsigned ws_rule); #define ws_tab_width(rule) ((rule) & WS_TAB_WIDTH_MASK) /* ls-files */ int report_path_error(const char *ps_matched, const char **pathspec, int prefix_offset); void overlay_tree_on_cache(const char *tree_name, const char *prefix); char *alias_lookup(const char *alias); int split_cmdline(char *cmdline, const char ***argv); /* Takes a negative value returned by split_cmdline */ const char *split_cmdline_strerror(int cmdline_errno); /* git.c */ struct startup_info { int have_repository; const char *prefix; }; extern struct startup_info *startup_info; /* builtin/merge.c */ int checkout_fast_forward(const unsigned char *from, const unsigned char *to); #endif /* CACHE_H */
dragonfax/git_webos
cache.h
C
gpl-2.0
42,649