code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
<?php
defined('_JEXEC') or die('Direct Access to ' . basename(__FILE__) . 'is not allowed.');
/**
*
* @package VirtueMart
* @subpackage vmpayment
* @version $Id: closeauthorizationresponse.php 8703 2015-02-15 17:11:16Z alatak $
* @author Valérie Isaksen
* @link http://www.virtuemart.net
* @copyright Copyright (c) 2004 - March 03 2015 VirtueMart Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*
*/
class amazonHelperCloseAuthorizationResponse extends amazonHelper {
public function __construct (OffAmazonPaymentsService_Model_CloseAuthorizationResponse $closeAuthorizationResponse, $method) {
parent::__construct($closeAuthorizationResponse, $method);
}
public function getStoreInternalData () {
return NULL;
}
function getContents () {
$contents = $this->tableStart("CloseAuthorizationResponse");
$contents .= $this->getRow("Dump: ", var_export($this->amazonData, true));
$contents .= $this->tableEnd();
return $contents;
}
}
|
L16jovenesTIC/portal-web
|
plugins/vmpayment/amazon/helpers/closeauthorizationresponse.php
|
PHP
|
gpl-2.0
| 1,298
|
/*
* i2c-nforce2-s4985.c - i2c-nforce2 extras for the Tyan S4985 motherboard
*
* Copyright (C) 2008 Jean Delvare <khali@linux-fr.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.
*/
/*
* We select the channels by sending commands to the Philips
* PCA9556 chip at I2C address 0x18. The main adapter is used for
* the non-multiplexed part of the bus, and 4 virtual adapters
* are defined for the multiplexed addresses: 0x50-0x53 (memory
* module EEPROM) located on channels 1-4. We define one virtual
* adapter per CPU, which corresponds to one multiplexed channel:
* CPU0: virtual adapter 1, channel 1
* CPU1: virtual adapter 2, channel 2
* CPU2: virtual adapter 3, channel 3
* CPU3: virtual adapter 4, channel 4
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/i2c.h>
#include <linux/mutex.h>
extern struct i2c_adapter *nforce2_smbus;
static struct i2c_adapter *s4985_adapter;
static struct i2c_algorithm *s4985_algo;
/* Wrapper access functions for multiplexed SMBus */
static DEFINE_MUTEX(nforce2_lock);
static s32 nforce2_access_virt0(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size,
union i2c_smbus_data *data)
{
int error;
/* We exclude the multiplexed addresses */
if ((addr & 0xfc) == 0x50 || (addr & 0xfc) == 0x30
|| addr == 0x18)
return -ENXIO;
mutex_lock(&nforce2_lock);
error = nforce2_smbus->algo->smbus_xfer(adap, addr, flags, read_write,
command, size, data);
mutex_unlock(&nforce2_lock);
return error;
}
/* We remember the last used channels combination so as to only switch
channels when it is really needed. This greatly reduces the SMBus
overhead, but also assumes that nobody will be writing to the PCA9556
in our back. */
static u8 last_channels;
static inline s32 nforce2_access_channel(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size,
union i2c_smbus_data *data,
u8 channels)
{
int error;
/* We exclude the non-multiplexed addresses */
if ((addr & 0xfc) != 0x50 && (addr & 0xfc) != 0x30)
return -ENXIO;
mutex_lock(&nforce2_lock);
if (last_channels != channels) {
union i2c_smbus_data mplxdata;
mplxdata.byte = channels;
error = nforce2_smbus->algo->smbus_xfer(adap, 0x18, 0,
I2C_SMBUS_WRITE, 0x01,
I2C_SMBUS_BYTE_DATA,
&mplxdata);
if (error)
goto UNLOCK;
last_channels = channels;
}
error = nforce2_smbus->algo->smbus_xfer(adap, addr, flags, read_write,
command, size, data);
UNLOCK:
mutex_unlock(&nforce2_lock);
return error;
}
static s32 nforce2_access_virt1(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size,
union i2c_smbus_data *data)
{
/* CPU0: channel 1 enabled */
return nforce2_access_channel(adap, addr, flags, read_write, command,
size, data, 0x02);
}
static s32 nforce2_access_virt2(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size,
union i2c_smbus_data *data)
{
/* CPU1: channel 2 enabled */
return nforce2_access_channel(adap, addr, flags, read_write, command,
size, data, 0x04);
}
static s32 nforce2_access_virt3(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size,
union i2c_smbus_data *data)
{
/* CPU2: channel 3 enabled */
return nforce2_access_channel(adap, addr, flags, read_write, command,
size, data, 0x08);
}
static s32 nforce2_access_virt4(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size,
union i2c_smbus_data *data)
{
/* CPU3: channel 4 enabled */
return nforce2_access_channel(adap, addr, flags, read_write, command,
size, data, 0x10);
}
static int __init nforce2_s4985_init(void)
{
int i, error;
union i2c_smbus_data ioconfig;
if (!nforce2_smbus)
return -ENODEV;
/* Configure the PCA9556 multiplexer */
ioconfig.byte = 0x00; /* All I/O to output mode */
error = i2c_smbus_xfer(nforce2_smbus, 0x18, 0, I2C_SMBUS_WRITE, 0x03,
I2C_SMBUS_BYTE_DATA, &ioconfig);
if (error) {
dev_err(&nforce2_smbus->dev, "PCA9556 configuration failed\n");
error = -EIO;
goto ERROR0;
}
/* Unregister physical bus */
i2c_del_adapter(nforce2_smbus);
printk(KERN_INFO "Enabling SMBus multiplexing for Tyan S4985\n");
/* Define the 5 virtual adapters and algorithms structures */
s4985_adapter = kzalloc(5 * sizeof(struct i2c_adapter), GFP_KERNEL);
if (!s4985_adapter) {
error = -ENOMEM;
goto ERROR1;
}
s4985_algo = kzalloc(5 * sizeof(struct i2c_algorithm), GFP_KERNEL);
if (!s4985_algo) {
error = -ENOMEM;
goto ERROR2;
}
/* Fill in the new structures */
s4985_algo[0] = *(nforce2_smbus->algo);
s4985_algo[0].smbus_xfer = nforce2_access_virt0;
s4985_adapter[0] = *nforce2_smbus;
s4985_adapter[0].algo = s4985_algo;
s4985_adapter[0].dev.parent = nforce2_smbus->dev.parent;
for (i = 1; i < 5; i++) {
s4985_algo[i] = *(nforce2_smbus->algo);
s4985_adapter[i] = *nforce2_smbus;
snprintf(s4985_adapter[i].name, sizeof(s4985_adapter[i].name),
"SMBus nForce2 adapter (CPU%d)", i - 1);
s4985_adapter[i].algo = s4985_algo + i;
s4985_adapter[i].dev.parent = nforce2_smbus->dev.parent;
}
s4985_algo[1].smbus_xfer = nforce2_access_virt1;
s4985_algo[2].smbus_xfer = nforce2_access_virt2;
s4985_algo[3].smbus_xfer = nforce2_access_virt3;
s4985_algo[4].smbus_xfer = nforce2_access_virt4;
/* Register virtual adapters */
for (i = 0; i < 5; i++) {
error = i2c_add_adapter(s4985_adapter + i);
if (error) {
printk(KERN_ERR "i2c-nforce2-s4985: "
"Virtual adapter %d registration "
"failed, module not inserted\n", i);
for (i--; i >= 0; i--)
i2c_del_adapter(s4985_adapter + i);
goto ERROR3;
}
}
return 0;
ERROR3:
kfree(s4985_algo);
s4985_algo = NULL;
ERROR2:
kfree(s4985_adapter);
s4985_adapter = NULL;
ERROR1:
/* Restore physical bus */
i2c_add_adapter(nforce2_smbus);
ERROR0:
return error;
}
static void __exit nforce2_s4985_exit(void)
{
if (s4985_adapter) {
int i;
for (i = 0; i < 5; i++)
i2c_del_adapter(s4985_adapter+i);
kfree(s4985_adapter);
s4985_adapter = NULL;
}
kfree(s4985_algo);
s4985_algo = NULL;
/* Restore physical bus */
if (i2c_add_adapter(nforce2_smbus))
printk(KERN_ERR "i2c-nforce2-s4985: "
"Physical bus restoration failed\n");
}
MODULE_AUTHOR("Jean Delvare <khali@linux-fr.org>");
MODULE_DESCRIPTION("S4985 SMBus multiplexing");
MODULE_LICENSE("GPL");
module_init(nforce2_s4985_init);
module_exit(nforce2_s4985_exit);
|
cneira/ebpf-backports
|
linux-3.10.0-514.21.1.el7.x86_64/drivers/i2c/busses/i2c-nforce2-s4985.c
|
C
|
gpl-2.0
| 7,163
|
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest19748")
public class BenchmarkTest19748 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] values = request.getParameterValues("foo");
String param;
if (values.length != 0)
param = request.getParameterValues("foo")[0];
else param = null;
String bar = doSomething(param);
String sql = "UPDATE USERS SET PASSWORD='" + bar + "' WHERE USERNAME='foo'";
try {
java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
int count = statement.executeUpdate( sql, new String[] {"user","password"} );
} catch (java.sql.SQLException e) {
throw new ServletException(e);
}
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
String bar;
// Simple ? condition that assigns param to bar on false condition
int i = 106;
bar = (7*42) - i > 200 ? "This should never happen" : param;
return bar;
}
}
|
iammyr/Benchmark
|
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest19748.java
|
Java
|
gpl-2.0
| 2,359
|
[INFO [!Query!]|I]
[SWITCH [!action!]|=]
[CASE new]
[MODULE Murphy/Enquiry/NavBar?Last=__NOUVELLE_DEMANDE__]
[MODULE Murphy/Enquiry/New]
[/CASE]
[DEFAULT]
[IF [!I::TypeSearch!]=Child]
[MODULE Murphy/Enquiry/NavBar]
[MODULE Murphy/Enquiry/List]
[MODULE Murphy/Enquiry/List?filter=current]
// [MODULE Murphy/Enquiry/List?filter=completed]
[MODULE Murphy/Enquiry/List?filter=closed]
[ELSE]
[MODULE Murphy/Enquiry/NavBar?Last=__DEMANDE_FICHE__]
[MODULE Murphy/Enquiry/Fiche]
[/IF]
[/DEFAULT]
[/SWITCH]
|
MAN-IN-WAN/Kob-Eye
|
Skins/MWCCLIENT/Modules/Murphy/Enquiry/Default.md
|
Markdown
|
gpl-2.0
| 536
|
<?php
/* "Copyright 2012 A3 Revolution Web Design" This software is distributed under the terms of GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 */
// File Security Check
if ( ! defined( 'ABSPATH' ) ) exit;
?>
<?php
/*-----------------------------------------------------------------------------------
A3rev Plugin Fonts Face
TABLE OF CONTENTS
- var default_fonts
- var google_fonts
- __construct()
- get_default_fonts()
- get_google_fonts()
- generate_font_css()
- generate_google_webfonts()
-----------------------------------------------------------------------------------*/
class WC_Email_Inquiry_Fonts_Face extends WC_Email_Inquiry_Admin_UI
{
/**
* Window Default Fonts
*/
public $default_fonts = array(
'Arial, sans-serif' => 'Arial',
'Verdana, Geneva, sans-serif' => 'Verdana',
'Trebuchet MS, Tahoma, sans-serif' => 'Trebuchet',
'Georgia, serif' => 'Georgia',
'Times New Roman, serif' => 'Times New Roman',
'Tahoma, Geneva, Verdana, sans-serif' => 'Tahoma',
'Palatino, Palatino Linotype, serif' => 'Palatino',
'Helvetica Neue, Helvetica, sans-serif' => 'Helvetica*',
'Calibri, Candara, Segoe, Optima, sans-serif' => 'Calibri*',
'Myriad Pro, Myriad, sans-serif' => 'Myriad Pro*',
'Lucida Grande, Lucida Sans Unicode, Lucida Sans, sans-serif' => 'Lucida',
'Arial Black, sans-serif' => 'Arial Black',
'Gill Sans, Gill Sans MT, Calibri, sans-serif' => 'Gill Sans*',
'Geneva, Tahoma, Verdana, sans-serif' => 'Geneva*',
'Impact, Charcoal, sans-serif' => 'Impact',
'Courier, Courier New, monospace' => 'Courier',
'Century Gothic, sans-serif' => 'Century Gothic',
);
/*-----------------------------------------------------------------------------------*/
/* Google Webfonts Array */
/* Documentation:
/*
/* name: The name of the Google Font.
/* variant: The Google Font API variants available for the font.
/*-----------------------------------------------------------------------------------*/
// Available Google webfont names
public $google_fonts = array( array( 'name' => "Cantarell", 'variant' => ':r,b,i,bi'),
array( 'name' => "Cardo", 'variant' => ''),
array( 'name' => "Crimson Text", 'variant' => ''),
array( 'name' => "Droid Sans", 'variant' => ':r,b'),
array( 'name' => "Droid Sans Mono", 'variant' => ''),
array( 'name' => "Droid Serif", 'variant' => ':r,b,i,bi'),
array( 'name' => "IM Fell DW Pica", 'variant' => ':r,i'),
array( 'name' => "Inconsolata", 'variant' => ''),
array( 'name' => "Josefin Sans", 'variant' => ':400,400italic,700,700italic'),
array( 'name' => "Josefin Slab", 'variant' => ':r,b,i,bi'),
array( 'name' => "Lobster", 'variant' => ''),
array( 'name' => "Molengo", 'variant' => ''),
array( 'name' => "Nobile", 'variant' => ':r,b,i,bi'),
array( 'name' => "OFL Sorts Mill Goudy TT", 'variant' => ':r,i'),
array( 'name' => "Old Standard TT", 'variant' => ':r,b,i'),
array( 'name' => "Reenie Beanie", 'variant' => ''),
array( 'name' => "Tangerine", 'variant' => ':r,b'),
array( 'name' => "Vollkorn", 'variant' => ':r,b'),
array( 'name' => "Yanone Kaffeesatz", 'variant' => ':r,b'),
array( 'name' => "Cuprum", 'variant' => ''),
array( 'name' => "Neucha", 'variant' => ''),
array( 'name' => "Neuton", 'variant' => ''),
array( 'name' => "PT Sans", 'variant' => ':r,b,i,bi'),
array( 'name' => "PT Sans Caption", 'variant' => ':r,b'),
array( 'name' => "PT Sans Narrow", 'variant' => ':r,b'),
array( 'name' => "Philosopher", 'variant' => ''),
array( 'name' => "Allerta", 'variant' => ''),
array( 'name' => "Allerta Stencil", 'variant' => ''),
array( 'name' => "Arimo", 'variant' => ':r,b,i,bi'),
array( 'name' => "Arvo", 'variant' => ':r,b,i,bi'),
array( 'name' => "Bentham", 'variant' => ''),
array( 'name' => "Coda", 'variant' => ':800'),
array( 'name' => "Cousine", 'variant' => ''),
array( 'name' => "Covered By Your Grace", 'variant' => ''),
array( 'name' => "Geo", 'variant' => ''),
array( 'name' => "Just Me Again Down Here", 'variant' => ''),
array( 'name' => "Puritan", 'variant' => ':r,b,i,bi'),
array( 'name' => "Raleway", 'variant' => ':100'),
array( 'name' => "Tinos", 'variant' => ':r,b,i,bi'),
array( 'name' => "UnifrakturCook", 'variant' => ':bold'),
array( 'name' => "UnifrakturMaguntia", 'variant' => ''),
array( 'name' => "Mountains of Christmas", 'variant' => ''),
array( 'name' => "Lato", 'variant' => ':400,700,400italic'),
array( 'name' => "Orbitron", 'variant' => ':r,b,i,bi'),
array( 'name' => "Allan", 'variant' => ':bold'),
array( 'name' => "Anonymous Pro", 'variant' => ':r,b,i,bi'),
array( 'name' => "Copse", 'variant' => ''),
array( 'name' => "Kenia", 'variant' => ''),
array( 'name' => "Ubuntu", 'variant' => ':r,b,i,bi'),
array( 'name' => "Vibur", 'variant' => ''),
array( 'name' => "Sniglet", 'variant' => ':800'),
array( 'name' => "Syncopate", 'variant' => ''),
array( 'name' => "Cabin", 'variant' => ':400,400italic,700,700italic,'),
array( 'name' => "Merriweather", 'variant' => ''),
array( 'name' => "Maiden Orange", 'variant' => ''),
array( 'name' => "Just Another Hand", 'variant' => ''),
array( 'name' => "Kristi", 'variant' => ''),
array( 'name' => "Corben", 'variant' => ':b'),
array( 'name' => "Gruppo", 'variant' => ''),
array( 'name' => "Buda", 'variant' => ':light'),
array( 'name' => "Lekton", 'variant' => ''),
array( 'name' => "Luckiest Guy", 'variant' => ''),
array( 'name' => "Crushed", 'variant' => ''),
array( 'name' => "Chewy", 'variant' => ''),
array( 'name' => "Coming Soon", 'variant' => ''),
array( 'name' => "Crafty Girls", 'variant' => ''),
array( 'name' => "Fontdiner Swanky", 'variant' => ''),
array( 'name' => "Permanent Marker", 'variant' => ''),
array( 'name' => "Rock Salt", 'variant' => ''),
array( 'name' => "Sunshiney", 'variant' => ''),
array( 'name' => "Unkempt", 'variant' => ''),
array( 'name' => "Calligraffitti", 'variant' => ''),
array( 'name' => "Cherry Cream Soda", 'variant' => ''),
array( 'name' => "Homemade Apple", 'variant' => ''),
array( 'name' => "Irish Growler", 'variant' => ''),
array( 'name' => "Kranky", 'variant' => ''),
array( 'name' => "Schoolbell", 'variant' => ''),
array( 'name' => "Slackey", 'variant' => ''),
array( 'name' => "Walter Turncoat", 'variant' => ''),
array( 'name' => "Radley", 'variant' => ''),
array( 'name' => "Meddon", 'variant' => ''),
array( 'name' => "Kreon", 'variant' => ':r,b'),
array( 'name' => "Dancing Script", 'variant' => ''),
array( 'name' => "Goudy Bookletter 1911", 'variant' => ''),
array( 'name' => "PT Serif Caption", 'variant' => ':r,i'),
array( 'name' => "PT Serif", 'variant' => ':r,b,i,bi'),
array( 'name' => "Astloch", 'variant' => ':b'),
array( 'name' => "Bevan", 'variant' => ''),
array( 'name' => "Anton", 'variant' => ''),
array( 'name' => "Expletus Sans", 'variant' => ':b'),
array( 'name' => "VT323", 'variant' => ''),
array( 'name' => "Pacifico", 'variant' => ''),
array( 'name' => "Candal", 'variant' => ''),
array( 'name' => "Architects Daughter", 'variant' => ''),
array( 'name' => "Indie Flower", 'variant' => ''),
array( 'name' => "League Script", 'variant' => ''),
array( 'name' => "Quattrocento", 'variant' => ''),
array( 'name' => "Amaranth", 'variant' => ''),
array( 'name' => "Irish Grover", 'variant' => ''),
array( 'name' => "Oswald", 'variant' => ':400,300,700'),
array( 'name' => "EB Garamond", 'variant' => ''),
array( 'name' => "Nova Round", 'variant' => ''),
array( 'name' => "Nova Slim", 'variant' => ''),
array( 'name' => "Nova Script", 'variant' => ''),
array( 'name' => "Nova Cut", 'variant' => ''),
array( 'name' => "Nova Mono", 'variant' => ''),
array( 'name' => "Nova Oval", 'variant' => ''),
array( 'name' => "Nova Flat", 'variant' => ''),
array( 'name' => "Terminal Dosis Light", 'variant' => ''),
array( 'name' => "Michroma", 'variant' => ''),
array( 'name' => "Miltonian", 'variant' => ''),
array( 'name' => "Miltonian Tattoo", 'variant' => ''),
array( 'name' => "Annie Use Your Telescope", 'variant' => ''),
array( 'name' => "Dawning of a New Day", 'variant' => ''),
array( 'name' => "Sue Ellen Francisco", 'variant' => ''),
array( 'name' => "Waiting for the Sunrise", 'variant' => ''),
array( 'name' => "Special Elite", 'variant' => ''),
array( 'name' => "Quattrocento Sans", 'variant' => ''),
array( 'name' => "Smythe", 'variant' => ''),
array( 'name' => "The Girl Next Door", 'variant' => ''),
array( 'name' => "Aclonica", 'variant' => ''),
array( 'name' => "News Cycle", 'variant' => ''),
array( 'name' => "Damion", 'variant' => ''),
array( 'name' => "Wallpoet", 'variant' => ''),
array( 'name' => "Over the Rainbow", 'variant' => ''),
array( 'name' => "MedievalSharp", 'variant' => ''),
array( 'name' => "Six Caps", 'variant' => ''),
array( 'name' => "Swanky and Moo Moo", 'variant' => ''),
array( 'name' => "Bigshot One", 'variant' => ''),
array( 'name' => "Francois One", 'variant' => ''),
array( 'name' => "Sigmar One", 'variant' => ''),
array( 'name' => "Carter One", 'variant' => ''),
array( 'name' => "Holta3revd One SC", 'variant' => ''),
array( 'name' => "Paytone One", 'variant' => ''),
array( 'name' => "Monofett", 'variant' => ''),
array( 'name' => "Rokkitt", 'variant' => ':400,700'),
array( 'name' => "Megrim", 'variant' => ''),
array( 'name' => "Judson", 'variant' => ':r,ri,b'),
array( 'name' => "Didact Gothic", 'variant' => ''),
array( 'name' => "Play", 'variant' => ':r,b'),
array( 'name' => "Ultra", 'variant' => ''),
array( 'name' => "Metrophobic", 'variant' => ''),
array( 'name' => "Mako", 'variant' => ''),
array( 'name' => "Shanti", 'variant' => ''),
array( 'name' => "Caudex", 'variant' => ':r,b,i,bi'),
array( 'name' => "Jura", 'variant' => ''),
array( 'name' => "Ruslan Display", 'variant' => ''),
array( 'name' => "Brawler", 'variant' => ''),
array( 'name' => "Nunito", 'variant' => ''),
array( 'name' => "Wire One", 'variant' => ''),
array( 'name' => "Podkova", 'variant' => ''),
array( 'name' => "Muli", 'variant' => ''),
array( 'name' => "Maven Pro", 'variant' => ':400,500,700'),
array( 'name' => "Tenor Sans", 'variant' => ''),
array( 'name' => "Limelight", 'variant' => ''),
array( 'name' => "Playfair Display", 'variant' => ''),
array( 'name' => "Artifika", 'variant' => ''),
array( 'name' => "Lora", 'variant' => ''),
array( 'name' => "Kameron", 'variant' => ':r,b'),
array( 'name' => "Cedarville Cursive", 'variant' => ''),
array( 'name' => "Zeyada", 'variant' => ''),
array( 'name' => "La Belle Aurore", 'variant' => ''),
array( 'name' => "Shadows Into Light", 'variant' => ''),
array( 'name' => "Lobster Two", 'variant' => ':r,b,i,bi'),
array( 'name' => "Nixie One", 'variant' => ''),
array( 'name' => "Redressed", 'variant' => ''),
array( 'name' => "Bangers", 'variant' => ''),
array( 'name' => "Open Sans Condensed", 'variant' => ':300italic,400italic,700italic,400,300,700'),
array( 'name' => "Open Sans", 'variant' => ':r,i,b,bi'),
array( 'name' => "Varela", 'variant' => ''),
array( 'name' => "Goblin One", 'variant' => ''),
array( 'name' => "Asset", 'variant' => ''),
array( 'name' => "Gravitas One", 'variant' => ''),
array( 'name' => "Hammersmith One", 'variant' => ''),
array( 'name' => "Stardos Stencil", 'variant' => ''),
array( 'name' => "Love Ya Like A Sister", 'variant' => ''),
array( 'name' => "Loved by the King", 'variant' => ''),
array( 'name' => "Bowlby One SC", 'variant' => ''),
array( 'name' => "Forum", 'variant' => ''),
array( 'name' => "Patrick Hand", 'variant' => ''),
array( 'name' => "Varela Round", 'variant' => ''),
array( 'name' => "Yeseva One", 'variant' => ''),
array( 'name' => "Give You Glory", 'variant' => ''),
array( 'name' => "Modern Antiqua", 'variant' => ''),
array( 'name' => "Bowlby One", 'variant' => ''),
array( 'name' => "Tienne", 'variant' => ''),
array( 'name' => "Istok Web", 'variant' => ':r,b,i,bi'),
array( 'name' => "Yellowtail", 'variant' => ''),
array( 'name' => "Pompiere", 'variant' => ''),
array( 'name' => "Unna", 'variant' => ''),
array( 'name' => "Rosario", 'variant' => ''),
array( 'name' => "Leckerli One", 'variant' => ''),
array( 'name' => "Snippet", 'variant' => ''),
array( 'name' => "Ovo", 'variant' => ''),
array( 'name' => "IM Fell English", 'variant' => ':r,i'),
array( 'name' => "IM Fell English SC", 'variant' => ''),
array( 'name' => "Gloria Hallelujah", 'variant' => ''),
array( 'name' => "Kelly Slab", 'variant' => ''),
array( 'name' => "Black Ops One", 'variant' => ''),
array( 'name' => "Carme", 'variant' => ''),
array( 'name' => "Aubrey", 'variant' => ''),
array( 'name' => "Federo", 'variant' => ''),
array( 'name' => "Delius", 'variant' => ''),
array( 'name' => "Rochester", 'variant' => ''),
array( 'name' => "Rationale", 'variant' => ''),
array( 'name' => "Abel", 'variant' => ''),
array( 'name' => "Marvel", 'variant' => ':r,b,i,bi'),
array( 'name' => "Actor", 'variant' => ''),
array( 'name' => "Delius Swash Caps", 'variant' => ''),
array( 'name' => "Smokum", 'variant' => ''),
array( 'name' => "Tulpen One", 'variant' => ''),
array( 'name' => "Coustard", 'variant' => ':r,b'),
array( 'name' => "Andika", 'variant' => ''),
array( 'name' => "Alice", 'variant' => ''),
array( 'name' => "Questrial", 'variant' => ''),
array( 'name' => "Comfortaa", 'variant' => ':r,b'),
array( 'name' => "Geostar", 'variant' => ''),
array( 'name' => "Geostar Fill", 'variant' => ''),
array( 'name' => "Volkhov", 'variant' => ''),
array( 'name' => "Voltaire", 'variant' => ''),
array( 'name' => "Montez", 'variant' => ''),
array( 'name' => "Short Stack", 'variant' => ''),
array( 'name' => "Vidaloka", 'variant' => ''),
array( 'name' => "Aldrich", 'variant' => ''),
array( 'name' => "Numans", 'variant' => ''),
array( 'name' => "Days One", 'variant' => ''),
array( 'name' => "Gentium Book Basic", 'variant' => ''),
array( 'name' => "Monoton", 'variant' => ''),
array( 'name' => "Alike", 'variant' => ''),
array( 'name' => "Delius Unicase", 'variant' => ''),
array( 'name' => "Abril Fatface", 'variant' => ''),
array( 'name' => "Dorsa", 'variant' => ''),
array( 'name' => "Antic", 'variant' => ''),
array( 'name' => "Passero One", 'variant' => ''),
array( 'name' => "Fana3revd Text", 'variant' => ''),
array( 'name' => "Prociono", 'variant' => ''),
array( 'name' => "Merienda One", 'variant' => ''),
array( 'name' => "Changa One", 'variant' => ''),
array( 'name' => "Julee", 'variant' => ''),
array( 'name' => "Prata", 'variant' => ''),
array( 'name' => "Adamina", 'variant' => ''),
array( 'name' => "Sorts Mill Goudy", 'variant' => ''),
array( 'name' => "Terminal Dosis", 'variant' => ''),
array( 'name' => "Sansita One", 'variant' => ''),
array( 'name' => "Chivo", 'variant' => ''),
array( 'name' => "Spinnaker", 'variant' => ''),
array( 'name' => "Poller One", 'variant' => ''),
array( 'name' => "Alike Angular", 'variant' => ''),
array( 'name' => "Gochi Hand", 'variant' => ''),
array( 'name' => "Poly", 'variant' => ''),
array( 'name' => "Andada", 'variant' => ''),
array( 'name' => "Federant", 'variant' => ''),
array( 'name' => "Ubuntu Condensed", 'variant' => ''),
array( 'name' => "Ubuntu Mono", 'variant' => ''),
array( 'name' => "Sancreek", 'variant' => ''),
array( 'name' => "Coda", 'variant' => ''),
array( 'name' => "Rancho", 'variant' => ''),
array( 'name' => "Satisfy", 'variant' => ''),
array( 'name' => "Pinyon Script", 'variant' => ''),
array( 'name' => "Vast Shadow", 'variant' => ''),
array( 'name' => "Marck Script", 'variant' => ''),
array( 'name' => "Salsa", 'variant' => ''),
array( 'name' => "Amatic SC", 'variant' => ''),
array( 'name' => "Quicksand", 'variant' => ''),
array( 'name' => "Linden Hill", 'variant' => ''),
array( 'name' => "Corben", 'variant' => ''),
array( 'name' => "Creepster Caps", 'variant' => ''),
array( 'name' => "Butcherman Caps", 'variant' => ''),
array( 'name' => "Eater Caps", 'variant' => ''),
array( 'name' => "Nosifer Caps", 'variant' => ''),
array( 'name' => "Atomic Age", 'variant' => ''),
array( 'name' => "Contrail One", 'variant' => ''),
array( 'name' => "Jockey One", 'variant' => ''),
array( 'name' => "Cabin Sketch", 'variant' => ':r,b'),
array( 'name' => "Cabin Condensed", 'variant' => ':r,b'),
array( 'name' => "Fjord One", 'variant' => ''),
array( 'name' => "Rametto One", 'variant' => ''),
array( 'name' => "Mate", 'variant' => ':r,i'),
array( 'name' => "Mate SC", 'variant' => ''),
array( 'name' => "Arapey", 'variant' => ':r,i'),
array( 'name' => "Supermercado One", 'variant' => ''),
array( 'name' => "Petrona", 'variant' => ''),
array( 'name' => "Lancelot", 'variant' => ''),
array( 'name' => "Convergence", 'variant' => ''),
array( 'name' => "Cutive", 'variant' => ''),
array( 'name' => "Karla", 'variant' => ':400,400italic,700,700italic'),
array( 'name' => "Bitter", 'variant' => ':r,i,b'),
array( 'name' => "Asap", 'variant' => ':400,700,400italic,700italic'),
array( 'name' => "Bree Serif", 'variant' => '')
);
/*-----------------------------------------------------------------------------------*/
/* Fonts Face Constructor */
/*-----------------------------------------------------------------------------------*/
public function __construct() {
$google_fonts = apply_filters( $this->plugin_name . '_google_fonts', $this->google_fonts );
sort( $google_fonts );
$new_google_fonts = array();
foreach ( $google_fonts as $row ) {
$new_google_fonts[$row['name']] = $row;
}
$this->google_fonts = $new_google_fonts;
}
/*-----------------------------------------------------------------------------------*/
/* Get Window Default Fonts */
/*-----------------------------------------------------------------------------------*/
public function get_default_fonts() {
$default_fonts = apply_filters( $this->plugin_name . '_default_fonts', $this->default_fonts );
asort( $default_fonts );
return $default_fonts;
}
/*-----------------------------------------------------------------------------------*/
/* Get Google Fonts */
/*-----------------------------------------------------------------------------------*/
public function get_google_fonts() {
return $this->google_fonts;
}
/*-----------------------------------------------------------------------------------*/
/* generate_font_css() */
/* Generate font CSS for frontend */
/*-----------------------------------------------------------------------------------*/
public function generate_font_css( $option, $em = '1.2' ) {
$google_fonts = $this->get_google_fonts();
if ( array_key_exists( $option['face'], $google_fonts ) ) {
$option['face'] = "'" . $option['face'] . "', arial, sans-serif";
}
if ( !@$option['style'] && !@$option['size'] && !@$option['color'] )
return 'font-family: '.stripslashes($option["face"]).' !important;';
else
return 'font:'.$option['style'].' '.$option['size'].' '.stripslashes($option['face']).' !important; color:'.$option['color'].' !important;';
}
/*-----------------------------------------------------------------------------------*/
/* Google Webfonts Stylesheet Generator */
/*-----------------------------------------------------------------------------------*/
/*
INSTRUCTIONS: Needs to be loaded for the Google Fonts options to work for font options.
add_action( 'wp_head', array( $this, 'generate_google_webfonts' ) );
*/
public function generate_google_webfonts( $my_google_fonts = array(), $echo = true ) {
$google_fonts = $this->get_google_fonts();
$fonts = '';
$output = '';
// Go through the options
if ( is_array( $my_google_fonts ) ) {
foreach ( $my_google_fonts as $font_face ) {
// Check if the google font name exists in the current "face" option
if ( array_key_exists( $font_face, $google_fonts ) && !strstr( $fonts, $font_face ) ) {
$fonts .= $google_fonts[$font_face]['name'].$google_fonts[$font_face]['variant']."|";
}
} // End Foreach Loop
// Output google font css in header
if ( trim( $fonts ) != '' ) {
$fonts = str_replace( " ","+",$fonts);
$output .= "\n<!-- Google Webfonts -->\n";
$output .= '<link href="http'. ( is_ssl() ? 's' : '' ) .'://fonts.googleapis.com/css?family=' . $fonts .'" rel="stylesheet" type="text/css" />'."\n";
$output = str_replace( '|"','"',$output);
}
}
if ( $echo )
echo $output;
else
return $output;
} // End generate_google_webfonts()
}
global $wc_ei_fonts_face;
$wc_ei_fonts_face = new WC_Email_Inquiry_Fonts_Face();
|
mselango/driz-project
|
wp-content/plugins/woocommerce-email-inquiry-cart-options/admin/includes/fonts_face.php
|
PHP
|
gpl-2.0
| 22,359
|
#ifndef _ASM_X8664_PROTO_H
#define _ASM_X8664_PROTO_H 1
#include <asm/ldt.h>
/* misc architecture specific prototypes */
struct cpuinfo_x86;
struct pt_regs;
extern void get_cpu_vendor(struct cpuinfo_x86*);
extern void start_kernel(void);
extern void pda_init(int);
extern void early_idt_handler(void);
extern void mcheck_init(struct cpuinfo_x86 *c);
#ifdef CONFIG_MTRR
extern void mtrr_ap_init(void);
extern void mtrr_bp_init(void);
#else
#define mtrr_ap_init() do {} while (0)
#define mtrr_bp_init() do {} while (0)
#endif
extern void init_memory_mapping(unsigned long start, unsigned long end);
extern void system_call(void);
extern int kernel_syscall(void);
extern void syscall_init(void);
extern void ia32_syscall(void);
extern void ia32_cstar_target(void);
extern void ia32_sysenter_target(void);
extern void config_acpi_tables(void);
extern void ia32_syscall(void);
extern void iommu_hole_init(void);
extern void time_init_gtod(void);
extern int pmtimer_mark_offset(void);
extern unsigned int do_gettimeoffset_pm(void);
extern u32 pmtmr_ioport;
extern unsigned long long monotonic_base;
extern int sysctl_vsyscall;
extern void do_softirq_thunk(void);
extern int numa_setup(char *opt);
extern int setup_early_printk(char *);
extern void early_printk(const char *fmt, ...) __attribute__((format(printf,1,2)));
extern void early_identify_cpu(struct cpuinfo_x86 *c);
extern int k8_scan_nodes(unsigned long start, unsigned long end);
extern void numa_initmem_init(unsigned long start_pfn, unsigned long end_pfn);
extern unsigned long numa_free_all_bootmem(void);
extern void reserve_bootmem_generic(unsigned long phys, unsigned len);
extern void free_bootmem_generic(unsigned long phys, unsigned len);
extern void load_gs_index(unsigned gs);
extern unsigned long end_pfn_map;
extern cpumask_t cpu_initialized;
extern void show_trace(unsigned long * rsp);
extern void show_registers(struct pt_regs *regs);
extern void exception_table_check(void);
extern void acpi_reserve_bootmem(void);
extern void swap_low_mappings(void);
extern void oops_begin(void);
extern void die(const char *,struct pt_regs *,long);
extern void __die(const char * str, struct pt_regs * regs, long err);
extern void __show_regs(struct pt_regs * regs);
extern void show_regs(struct pt_regs * regs);
extern char *syscall32_page;
extern void syscall32_cpu_init(void);
extern void setup_node_bootmem(int nodeid, unsigned long start, unsigned long end);
extern void check_ioapic(void);
extern void check_efer(void);
extern int unhandled_signal(struct task_struct *tsk, int sig);
extern void select_idle_routine(const struct cpuinfo_x86 *c);
extern void swiotlb_init(void);
extern unsigned long max_mapnr;
extern unsigned long end_pfn;
extern unsigned long table_start, table_end;
extern int exception_trace;
extern int force_iommu, no_iommu;
extern int using_apic_timer;
extern int disable_apic;
extern unsigned cpu_khz;
extern int ioapic_force;
extern int skip_ioapic_setup;
extern int acpi_ht;
extern int acpi_disabled;
extern int fallback_aper_order;
extern int fallback_aper_force;
extern int iommu_aperture;
extern int iommu_aperture_disabled;
extern int iommu_aperture_allowed;
extern int fix_aperture;
extern int force_iommu;
extern int reboot_force;
extern void smp_local_timer_interrupt(struct pt_regs * regs);
long do_arch_prctl(struct task_struct *task, int code, unsigned long addr);
#define round_up(x,y) (((x) + (y) - 1) & ~((y)-1))
#define round_down(x,y) ((x) & ~((y)-1))
#endif
|
waterice/Test-Git
|
include/asm-x86_64/proto.h
|
C
|
gpl-2.0
| 3,509
|
/* linux/drivers/cdrom/optcd.c - Optics Storage 8000 AT CDROM driver
$Id: optcd.c,v 1.1.1.1 2007/06/12 07:27:09 eyryu Exp $
Copyright (C) 1995 Leo Spiekman (spiekman@dutette.et.tudelft.nl)
Based on Aztech CD268 CDROM driver by Werner Zimmermann and preworks
by Eberhard Moenkeberg (emoenke@gwdg.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, 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Revision history
14-5-95 v0.0 Plays sound tracks. No reading of data CDs yet.
Detection of disk change doesn't work.
21-5-95 v0.1 First ALPHA version. CD can be mounted. The
device major nr is borrowed from the Aztech
driver. Speed is around 240 kb/s, as measured
with "time dd if=/dev/cdrom of=/dev/null \
bs=2048 count=4096".
24-6-95 v0.2 Reworked the #defines for the command codes
and the like, as well as the structure of
the hardware communication protocol, to
reflect the "official" documentation, kindly
supplied by C.K. Tan, Optics Storage Pte. Ltd.
Also tidied up the state machine somewhat.
28-6-95 v0.3 Removed the ISP-16 interface code, as this
should go into its own driver. The driver now
has its own major nr.
Disk change detection now seems to work, too.
This version became part of the standard
kernel as of version 1.3.7
24-9-95 v0.4 Re-inserted ISP-16 interface code which I
copied from sjcd.c, with a few changes.
Updated README.optcd. Submitted for
inclusion in 1.3.21
29-9-95 v0.4a Fixed bug that prevented compilation as module
25-10-95 v0.5 Started multisession code. Implementation
copied from Werner Zimmermann, who copied it
from Heiko Schlittermann's mcdx.
17-1-96 v0.6 Multisession works; some cleanup too.
18-4-96 v0.7 Increased some timing constants;
thanks to Luke McFarlane. Also tidied up some
printk behaviour. ISP16 initialization
is now handled by a separate driver.
09-11-99 Make kernel-parameter implementation work with 2.3.x
Removed init_module & cleanup_module in favor of
module_init & module_exit.
Torben Mathiasen <tmm@image.dk>
*/
/* Includes */
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <asm/io.h>
#include <linux/blkdev.h>
#include <linux/cdrom.h>
#include "optcd.h"
#include <asm/uaccess.h>
#define MAJOR_NR OPTICS_CDROM_MAJOR
#define QUEUE (opt_queue)
#define CURRENT elv_next_request(opt_queue)
/* Debug support */
/* Don't forget to add new debug flags here. */
#if DEBUG_DRIVE_IF | DEBUG_VFS | DEBUG_CONV | DEBUG_TOC | \
DEBUG_BUFFERS | DEBUG_REQUEST | DEBUG_STATE | DEBUG_MULTIS
#define DEBUG(x) debug x
static void debug(int debug_this, const char* fmt, ...)
{
char s[1024];
va_list args;
if (!debug_this)
return;
va_start(args, fmt);
vsnprintf(s, sizeof(s), fmt, args);
printk(KERN_DEBUG "optcd: %s\n", s);
va_end(args);
}
#else
#define DEBUG(x)
#endif
/* Drive hardware/firmware characteristics
Identifiers in accordance with Optics Storage documentation */
#define optcd_port optcd /* Needed for the modutils. */
static short optcd_port = OPTCD_PORTBASE; /* I/O base of drive. */
module_param(optcd_port, short, 0);
/* Drive registers, read */
#define DATA_PORT optcd_port /* Read data/status */
#define STATUS_PORT optcd_port+1 /* Indicate data/status availability */
/* Drive registers, write */
#define COMIN_PORT optcd_port /* For passing command/parameter */
#define RESET_PORT optcd_port+1 /* Write anything and wait 0.5 sec */
#define HCON_PORT optcd_port+2 /* Host Xfer Configuration */
/* Command completion/status read from DATA register */
#define ST_DRVERR 0x80
#define ST_DOOR_OPEN 0x40
#define ST_MIXEDMODE_DISK 0x20
#define ST_MODE_BITS 0x1c
#define ST_M_STOP 0x00
#define ST_M_READ 0x04
#define ST_M_AUDIO 0x04
#define ST_M_PAUSE 0x08
#define ST_M_INITIAL 0x0c
#define ST_M_ERROR 0x10
#define ST_M_OTHERS 0x14
#define ST_MODE2TRACK 0x02
#define ST_DSK_CHG 0x01
#define ST_L_LOCK 0x01
#define ST_CMD_OK 0x00
#define ST_OP_OK 0x01
#define ST_PA_OK 0x02
#define ST_OP_ERROR 0x05
#define ST_PA_ERROR 0x06
/* Error codes (appear as command completion code from DATA register) */
/* Player related errors */
#define ERR_ILLCMD 0x11 /* Illegal command to player module */
#define ERR_ILLPARM 0x12 /* Illegal parameter to player module */
#define ERR_SLEDGE 0x13
#define ERR_FOCUS 0x14
#define ERR_MOTOR 0x15
#define ERR_RADIAL 0x16
#define ERR_PLL 0x17 /* PLL lock error */
#define ERR_SUB_TIM 0x18 /* Subcode timeout error */
#define ERR_SUB_NF 0x19 /* Subcode not found error */
#define ERR_TRAY 0x1a
#define ERR_TOC 0x1b /* Table of Contents read error */
#define ERR_JUMP 0x1c
/* Data errors */
#define ERR_MODE 0x21
#define ERR_FORM 0x22
#define ERR_HEADADDR 0x23 /* Header Address not found */
#define ERR_CRC 0x24
#define ERR_ECC 0x25 /* Uncorrectable ECC error */
#define ERR_CRC_UNC 0x26 /* CRC error and uncorrectable error */
#define ERR_ILLBSYNC 0x27 /* Illegal block sync error */
#define ERR_VDST 0x28 /* VDST not found */
/* Timeout errors */
#define ERR_READ_TIM 0x31 /* Read timeout error */
#define ERR_DEC_STP 0x32 /* Decoder stopped */
#define ERR_DEC_TIM 0x33 /* Decoder interrupt timeout error */
/* Function abort codes */
#define ERR_KEY 0x41 /* Key -Detected abort */
#define ERR_READ_FINISH 0x42 /* Read Finish */
/* Second Byte diagnostic codes */
#define ERR_NOBSYNC 0x01 /* No block sync */
#define ERR_SHORTB 0x02 /* Short block */
#define ERR_LONGB 0x03 /* Long block */
#define ERR_SHORTDSP 0x04 /* Short DSP word */
#define ERR_LONGDSP 0x05 /* Long DSP word */
/* Status availability flags read from STATUS register */
#define FL_EJECT 0x20
#define FL_WAIT 0x10 /* active low */
#define FL_EOP 0x08 /* active low */
#define FL_STEN 0x04 /* Status available when low */
#define FL_DTEN 0x02 /* Data available when low */
#define FL_DRQ 0x01 /* active low */
#define FL_RESET 0xde /* These bits are high after a reset */
#define FL_STDT (FL_STEN|FL_DTEN)
/* Transfer mode, written to HCON register */
#define HCON_DTS 0x08
#define HCON_SDRQB 0x04
#define HCON_LOHI 0x02
#define HCON_DMA16 0x01
/* Drive command set, written to COMIN register */
/* Quick response commands */
#define COMDRVST 0x20 /* Drive Status Read */
#define COMERRST 0x21 /* Error Status Read */
#define COMIOCTLISTAT 0x22 /* Status Read; reset disk changed bit */
#define COMINITSINGLE 0x28 /* Initialize Single Speed */
#define COMINITDOUBLE 0x29 /* Initialize Double Speed */
#define COMUNLOCK 0x30 /* Unlock */
#define COMLOCK 0x31 /* Lock */
#define COMLOCKST 0x32 /* Lock/Unlock Status */
#define COMVERSION 0x40 /* Get Firmware Revision */
#define COMVOIDREADMODE 0x50 /* Void Data Read Mode */
/* Read commands */
#define COMFETCH 0x60 /* Prefetch Data */
#define COMREAD 0x61 /* Read */
#define COMREADRAW 0x62 /* Read Raw Data */
#define COMREADALL 0x63 /* Read All 2646 Bytes */
/* Player control commands */
#define COMLEADIN 0x70 /* Seek To Lead-in */
#define COMSEEK 0x71 /* Seek */
#define COMPAUSEON 0x80 /* Pause On */
#define COMPAUSEOFF 0x81 /* Pause Off */
#define COMSTOP 0x82 /* Stop */
#define COMOPEN 0x90 /* Open Tray Door */
#define COMCLOSE 0x91 /* Close Tray Door */
#define COMPLAY 0xa0 /* Audio Play */
#define COMPLAY_TNO 0xa2 /* Audio Play By Track Number */
#define COMSUBQ 0xb0 /* Read Sub-q Code */
#define COMLOCATION 0xb1 /* Read Head Position */
/* Audio control commands */
#define COMCHCTRL 0xc0 /* Audio Channel Control */
/* Miscellaneous (test) commands */
#define COMDRVTEST 0xd0 /* Write Test Bytes */
#define COMTEST 0xd1 /* Diagnostic Test */
/* Low level drive interface. Only here we do actual I/O
Waiting for status / data available */
/* Busy wait until FLAG goes low. Return 0 on timeout. */
static inline int flag_low(int flag, unsigned long timeout)
{
int flag_high;
unsigned long count = 0;
while ((flag_high = (inb(STATUS_PORT) & flag)))
if (++count >= timeout)
break;
DEBUG((DEBUG_DRIVE_IF, "flag_low 0x%x count %ld%s",
flag, count, flag_high ? " timeout" : ""));
return !flag_high;
}
/* Timed waiting for status or data */
static int sleep_timeout; /* max # of ticks to sleep */
static DECLARE_WAIT_QUEUE_HEAD(waitq);
static void sleep_timer(unsigned long data);
static DEFINE_TIMER(delay_timer, sleep_timer, 0, 0);
static DEFINE_SPINLOCK(optcd_lock);
static struct request_queue *opt_queue;
/* Timer routine: wake up when desired flag goes low,
or when timeout expires. */
static void sleep_timer(unsigned long data)
{
int flags = inb(STATUS_PORT) & FL_STDT;
if (flags == FL_STDT && --sleep_timeout > 0) {
mod_timer(&delay_timer, jiffies + HZ/100); /* multi-statement macro */
} else
wake_up(&waitq);
}
/* Sleep until FLAG goes low. Return 0 on timeout or wrong flag low. */
static int sleep_flag_low(int flag, unsigned long timeout)
{
int flag_high;
DEBUG((DEBUG_DRIVE_IF, "sleep_flag_low"));
sleep_timeout = timeout;
flag_high = inb(STATUS_PORT) & flag;
if (flag_high && sleep_timeout > 0) {
mod_timer(&delay_timer, jiffies + HZ/100);
sleep_on(&waitq);
flag_high = inb(STATUS_PORT) & flag;
}
DEBUG((DEBUG_DRIVE_IF, "flag 0x%x count %ld%s",
flag, timeout, flag_high ? " timeout" : ""));
return !flag_high;
}
/* Low level drive interface. Only here we do actual I/O
Sending commands and parameters */
/* Errors in the command protocol */
#define ERR_IF_CMD_TIMEOUT 0x100
#define ERR_IF_ERR_TIMEOUT 0x101
#define ERR_IF_RESP_TIMEOUT 0x102
#define ERR_IF_DATA_TIMEOUT 0x103
#define ERR_IF_NOSTAT 0x104
/* Send command code. Return <0 indicates error */
static int send_cmd(int cmd)
{
unsigned char ack;
DEBUG((DEBUG_DRIVE_IF, "sending command 0x%02x\n", cmd));
outb(HCON_DTS, HCON_PORT); /* Enable Suspend Data Transfer */
outb(cmd, COMIN_PORT); /* Send command code */
if (!flag_low(FL_STEN, BUSY_TIMEOUT)) /* Wait for status */
return -ERR_IF_CMD_TIMEOUT;
ack = inb(DATA_PORT); /* read command acknowledge */
outb(HCON_SDRQB, HCON_PORT); /* Disable Suspend Data Transfer */
return ack==ST_OP_OK ? 0 : -ack;
}
/* Send command parameters. Return <0 indicates error */
static int send_params(struct cdrom_msf *params)
{
unsigned char ack;
DEBUG((DEBUG_DRIVE_IF, "sending parameters"
" %02x:%02x:%02x"
" %02x:%02x:%02x",
params->cdmsf_min0,
params->cdmsf_sec0,
params->cdmsf_frame0,
params->cdmsf_min1,
params->cdmsf_sec1,
params->cdmsf_frame1));
outb(params->cdmsf_min0, COMIN_PORT);
outb(params->cdmsf_sec0, COMIN_PORT);
outb(params->cdmsf_frame0, COMIN_PORT);
outb(params->cdmsf_min1, COMIN_PORT);
outb(params->cdmsf_sec1, COMIN_PORT);
outb(params->cdmsf_frame1, COMIN_PORT);
if (!flag_low(FL_STEN, BUSY_TIMEOUT)) /* Wait for status */
return -ERR_IF_CMD_TIMEOUT;
ack = inb(DATA_PORT); /* read command acknowledge */
return ack==ST_PA_OK ? 0 : -ack;
}
/* Send parameters for SEEK command. Return <0 indicates error */
static int send_seek_params(struct cdrom_msf *params)
{
unsigned char ack;
DEBUG((DEBUG_DRIVE_IF, "sending seek parameters"
" %02x:%02x:%02x",
params->cdmsf_min0,
params->cdmsf_sec0,
params->cdmsf_frame0));
outb(params->cdmsf_min0, COMIN_PORT);
outb(params->cdmsf_sec0, COMIN_PORT);
outb(params->cdmsf_frame0, COMIN_PORT);
if (!flag_low(FL_STEN, BUSY_TIMEOUT)) /* Wait for status */
return -ERR_IF_CMD_TIMEOUT;
ack = inb(DATA_PORT); /* read command acknowledge */
return ack==ST_PA_OK ? 0 : -ack;
}
/* Wait for command execution status. Choice between busy waiting
and sleeping. Return value <0 indicates timeout. */
static inline int get_exec_status(int busy_waiting)
{
unsigned char exec_status;
if (busy_waiting
? !flag_low(FL_STEN, BUSY_TIMEOUT)
: !sleep_flag_low(FL_STEN, SLEEP_TIMEOUT))
return -ERR_IF_CMD_TIMEOUT;
exec_status = inb(DATA_PORT);
DEBUG((DEBUG_DRIVE_IF, "returned exec status 0x%02x", exec_status));
return exec_status;
}
/* Wait busy for extra byte of data that a command returns.
Return value <0 indicates timeout. */
static inline int get_data(int short_timeout)
{
unsigned char data;
if (!flag_low(FL_STEN, short_timeout ? FAST_TIMEOUT : BUSY_TIMEOUT))
return -ERR_IF_DATA_TIMEOUT;
data = inb(DATA_PORT);
DEBUG((DEBUG_DRIVE_IF, "returned data 0x%02x", data));
return data;
}
/* Returns 0 if failed */
static int reset_drive(void)
{
unsigned long count = 0;
int flags;
DEBUG((DEBUG_DRIVE_IF, "reset drive"));
outb(0, RESET_PORT);
while (++count < RESET_WAIT)
inb(DATA_PORT);
count = 0;
while ((flags = (inb(STATUS_PORT) & FL_RESET)) != FL_RESET)
if (++count >= BUSY_TIMEOUT)
break;
DEBUG((DEBUG_DRIVE_IF, "reset %s",
flags == FL_RESET ? "succeeded" : "failed"));
if (flags != FL_RESET)
return 0; /* Reset failed */
outb(HCON_SDRQB, HCON_PORT); /* Disable Suspend Data Transfer */
return 1; /* Reset succeeded */
}
/* Facilities for asynchronous operation */
/* Read status/data availability flags FL_STEN and FL_DTEN */
static inline int stdt_flags(void)
{
return inb(STATUS_PORT) & FL_STDT;
}
/* Fetch status that has previously been waited for. <0 means not available */
static inline int fetch_status(void)
{
unsigned char status;
if (inb(STATUS_PORT) & FL_STEN)
return -ERR_IF_NOSTAT;
status = inb(DATA_PORT);
DEBUG((DEBUG_DRIVE_IF, "fetched exec status 0x%02x", status));
return status;
}
/* Fetch data that has previously been waited for. */
static inline void fetch_data(char *buf, int n)
{
insb(DATA_PORT, buf, n);
DEBUG((DEBUG_DRIVE_IF, "fetched 0x%x bytes", n));
}
/* Flush status and data fifos */
static inline void flush_data(void)
{
while ((inb(STATUS_PORT) & FL_STDT) != FL_STDT)
inb(DATA_PORT);
DEBUG((DEBUG_DRIVE_IF, "flushed fifos"));
}
/* Command protocol */
/* Send a simple command and wait for response. Command codes < COMFETCH
are quick response commands */
static inline int exec_cmd(int cmd)
{
int ack = send_cmd(cmd);
if (ack < 0)
return ack;
return get_exec_status(cmd < COMFETCH);
}
/* Send a command with parameters. Don't wait for the response,
* which consists of data blocks read from the CD. */
static inline int exec_read_cmd(int cmd, struct cdrom_msf *params)
{
int ack = send_cmd(cmd);
if (ack < 0)
return ack;
return send_params(params);
}
/* Send a seek command with parameters and wait for response */
static inline int exec_seek_cmd(int cmd, struct cdrom_msf *params)
{
int ack = send_cmd(cmd);
if (ack < 0)
return ack;
ack = send_seek_params(params);
if (ack < 0)
return ack;
return 0;
}
/* Send a command with parameters and wait for response */
static inline int exec_long_cmd(int cmd, struct cdrom_msf *params)
{
int ack = exec_read_cmd(cmd, params);
if (ack < 0)
return ack;
return get_exec_status(0);
}
/* Address conversion routines */
/* Binary to BCD (2 digits) */
static inline void single_bin2bcd(u_char *p)
{
DEBUG((DEBUG_CONV, "bin2bcd %02d", *p));
*p = (*p % 10) | ((*p / 10) << 4);
}
/* Convert entire msf struct */
static void bin2bcd(struct cdrom_msf *msf)
{
single_bin2bcd(&msf->cdmsf_min0);
single_bin2bcd(&msf->cdmsf_sec0);
single_bin2bcd(&msf->cdmsf_frame0);
single_bin2bcd(&msf->cdmsf_min1);
single_bin2bcd(&msf->cdmsf_sec1);
single_bin2bcd(&msf->cdmsf_frame1);
}
/* Linear block address to minute, second, frame form */
#define CD_FPM (CD_SECS * CD_FRAMES) /* frames per minute */
static void lba2msf(int lba, struct cdrom_msf *msf)
{
DEBUG((DEBUG_CONV, "lba2msf %d", lba));
lba += CD_MSF_OFFSET;
msf->cdmsf_min0 = lba / CD_FPM; lba %= CD_FPM;
msf->cdmsf_sec0 = lba / CD_FRAMES;
msf->cdmsf_frame0 = lba % CD_FRAMES;
msf->cdmsf_min1 = 0;
msf->cdmsf_sec1 = 0;
msf->cdmsf_frame1 = 0;
bin2bcd(msf);
}
/* Two BCD digits to binary */
static inline u_char bcd2bin(u_char bcd)
{
DEBUG((DEBUG_CONV, "bcd2bin %x%02x", bcd));
return (bcd >> 4) * 10 + (bcd & 0x0f);
}
static void msf2lba(union cdrom_addr *addr)
{
addr->lba = addr->msf.minute * CD_FPM
+ addr->msf.second * CD_FRAMES
+ addr->msf.frame - CD_MSF_OFFSET;
}
/* Minute, second, frame address BCD to binary or to linear address,
depending on MODE */
static void msf_bcd2bin(union cdrom_addr *addr)
{
addr->msf.minute = bcd2bin(addr->msf.minute);
addr->msf.second = bcd2bin(addr->msf.second);
addr->msf.frame = bcd2bin(addr->msf.frame);
}
/* High level drive commands */
static int audio_status = CDROM_AUDIO_NO_STATUS;
static char toc_uptodate = 0;
static char disk_changed = 1;
/* Get drive status, flagging completion of audio play and disk changes. */
static int drive_status(void)
{
int status;
status = exec_cmd(COMIOCTLISTAT);
DEBUG((DEBUG_DRIVE_IF, "IOCTLISTAT: %03x", status));
if (status < 0)
return status;
if (status == 0xff) /* No status available */
return -ERR_IF_NOSTAT;
if (((status & ST_MODE_BITS) != ST_M_AUDIO) &&
(audio_status == CDROM_AUDIO_PLAY)) {
audio_status = CDROM_AUDIO_COMPLETED;
}
if (status & ST_DSK_CHG) {
toc_uptodate = 0;
disk_changed = 1;
audio_status = CDROM_AUDIO_NO_STATUS;
}
return status;
}
/* Read the current Q-channel info. Also used for reading the
table of contents. qp->cdsc_format must be set on entry to
indicate the desired address format */
static int get_q_channel(struct cdrom_subchnl *qp)
{
int status, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10;
status = drive_status();
if (status < 0)
return status;
qp->cdsc_audiostatus = audio_status;
status = exec_cmd(COMSUBQ);
if (status < 0)
return status;
d1 = get_data(0);
if (d1 < 0)
return d1;
qp->cdsc_adr = d1;
qp->cdsc_ctrl = d1 >> 4;
d2 = get_data(0);
if (d2 < 0)
return d2;
qp->cdsc_trk = bcd2bin(d2);
d3 = get_data(0);
if (d3 < 0)
return d3;
qp->cdsc_ind = bcd2bin(d3);
d4 = get_data(0);
if (d4 < 0)
return d4;
qp->cdsc_reladdr.msf.minute = d4;
d5 = get_data(0);
if (d5 < 0)
return d5;
qp->cdsc_reladdr.msf.second = d5;
d6 = get_data(0);
if (d6 < 0)
return d6;
qp->cdsc_reladdr.msf.frame = d6;
d7 = get_data(0);
if (d7 < 0)
return d7;
/* byte not used */
d8 = get_data(0);
if (d8 < 0)
return d8;
qp->cdsc_absaddr.msf.minute = d8;
d9 = get_data(0);
if (d9 < 0)
return d9;
qp->cdsc_absaddr.msf.second = d9;
d10 = get_data(0);
if (d10 < 0)
return d10;
qp->cdsc_absaddr.msf.frame = d10;
DEBUG((DEBUG_TOC, "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
d1, d2, d3, d4, d5, d6, d7, d8, d9, d10));
msf_bcd2bin(&qp->cdsc_absaddr);
msf_bcd2bin(&qp->cdsc_reladdr);
if (qp->cdsc_format == CDROM_LBA) {
msf2lba(&qp->cdsc_absaddr);
msf2lba(&qp->cdsc_reladdr);
}
return 0;
}
/* Table of contents handling */
/* Errors in table of contents */
#define ERR_TOC_MISSINGINFO 0x120
#define ERR_TOC_MISSINGENTRY 0x121
struct cdrom_disk_info {
unsigned char first;
unsigned char last;
struct cdrom_msf0 disk_length;
struct cdrom_msf0 first_track;
/* Multisession info: */
unsigned char next;
struct cdrom_msf0 next_session;
struct cdrom_msf0 last_session;
unsigned char multi;
unsigned char xa;
unsigned char audio;
};
static struct cdrom_disk_info disk_info;
#define MAX_TRACKS 111
static struct cdrom_subchnl toc[MAX_TRACKS];
#define QINFO_FIRSTTRACK 100 /* bcd2bin(0xa0) */
#define QINFO_LASTTRACK 101 /* bcd2bin(0xa1) */
#define QINFO_DISKLENGTH 102 /* bcd2bin(0xa2) */
#define QINFO_NEXTSESSION 110 /* bcd2bin(0xb0) */
#define I_FIRSTTRACK 0x01
#define I_LASTTRACK 0x02
#define I_DISKLENGTH 0x04
#define I_NEXTSESSION 0x08
#define I_ALL (I_FIRSTTRACK | I_LASTTRACK | I_DISKLENGTH)
#if DEBUG_TOC
static void toc_debug_info(int i)
{
printk(KERN_DEBUG "#%3d ctl %1x, adr %1x, track %2d index %3d"
" %2d:%02d.%02d %2d:%02d.%02d\n",
i, toc[i].cdsc_ctrl, toc[i].cdsc_adr,
toc[i].cdsc_trk, toc[i].cdsc_ind,
toc[i].cdsc_reladdr.msf.minute,
toc[i].cdsc_reladdr.msf.second,
toc[i].cdsc_reladdr.msf.frame,
toc[i].cdsc_absaddr.msf.minute,
toc[i].cdsc_absaddr.msf.second,
toc[i].cdsc_absaddr.msf.frame);
}
#endif
static int read_toc(void)
{
int status, limit, count;
unsigned char got_info = 0;
struct cdrom_subchnl q_info;
#if DEBUG_TOC
int i;
#endif
DEBUG((DEBUG_TOC, "starting read_toc"));
count = 0;
for (limit = 60; limit > 0; limit--) {
int index;
q_info.cdsc_format = CDROM_MSF;
status = get_q_channel(&q_info);
if (status < 0)
return status;
index = q_info.cdsc_ind;
if (index > 0 && index < MAX_TRACKS
&& q_info.cdsc_trk == 0 && toc[index].cdsc_ind == 0) {
toc[index] = q_info;
DEBUG((DEBUG_TOC, "got %d", index));
if (index < 100)
count++;
switch (q_info.cdsc_ind) {
case QINFO_FIRSTTRACK:
got_info |= I_FIRSTTRACK;
break;
case QINFO_LASTTRACK:
got_info |= I_LASTTRACK;
break;
case QINFO_DISKLENGTH:
got_info |= I_DISKLENGTH;
break;
case QINFO_NEXTSESSION:
got_info |= I_NEXTSESSION;
break;
}
}
if ((got_info & I_ALL) == I_ALL
&& toc[QINFO_FIRSTTRACK].cdsc_absaddr.msf.minute + count
>= toc[QINFO_LASTTRACK].cdsc_absaddr.msf.minute + 1)
break;
}
/* Construct disk_info from TOC */
if (disk_info.first == 0) {
disk_info.first = toc[QINFO_FIRSTTRACK].cdsc_absaddr.msf.minute;
disk_info.first_track.minute =
toc[disk_info.first].cdsc_absaddr.msf.minute;
disk_info.first_track.second =
toc[disk_info.first].cdsc_absaddr.msf.second;
disk_info.first_track.frame =
toc[disk_info.first].cdsc_absaddr.msf.frame;
}
disk_info.last = toc[QINFO_LASTTRACK].cdsc_absaddr.msf.minute;
disk_info.disk_length.minute =
toc[QINFO_DISKLENGTH].cdsc_absaddr.msf.minute;
disk_info.disk_length.second =
toc[QINFO_DISKLENGTH].cdsc_absaddr.msf.second-2;
disk_info.disk_length.frame =
toc[QINFO_DISKLENGTH].cdsc_absaddr.msf.frame;
disk_info.next_session.minute =
toc[QINFO_NEXTSESSION].cdsc_reladdr.msf.minute;
disk_info.next_session.second =
toc[QINFO_NEXTSESSION].cdsc_reladdr.msf.second;
disk_info.next_session.frame =
toc[QINFO_NEXTSESSION].cdsc_reladdr.msf.frame;
disk_info.next = toc[QINFO_FIRSTTRACK].cdsc_absaddr.msf.minute;
disk_info.last_session.minute =
toc[disk_info.next].cdsc_absaddr.msf.minute;
disk_info.last_session.second =
toc[disk_info.next].cdsc_absaddr.msf.second;
disk_info.last_session.frame =
toc[disk_info.next].cdsc_absaddr.msf.frame;
toc[disk_info.last + 1].cdsc_absaddr.msf.minute =
disk_info.disk_length.minute;
toc[disk_info.last + 1].cdsc_absaddr.msf.second =
disk_info.disk_length.second;
toc[disk_info.last + 1].cdsc_absaddr.msf.frame =
disk_info.disk_length.frame;
#if DEBUG_TOC
for (i = 1; i <= disk_info.last + 1; i++)
toc_debug_info(i);
toc_debug_info(QINFO_FIRSTTRACK);
toc_debug_info(QINFO_LASTTRACK);
toc_debug_info(QINFO_DISKLENGTH);
toc_debug_info(QINFO_NEXTSESSION);
#endif
DEBUG((DEBUG_TOC, "exiting read_toc, got_info %x, count %d",
got_info, count));
if ((got_info & I_ALL) != I_ALL
|| toc[QINFO_FIRSTTRACK].cdsc_absaddr.msf.minute + count
< toc[QINFO_LASTTRACK].cdsc_absaddr.msf.minute + 1)
return -ERR_TOC_MISSINGINFO;
return 0;
}
#ifdef MULTISESSION
static int get_multi_disk_info(void)
{
int sessions, status;
struct cdrom_msf multi_index;
for (sessions = 2; sessions < 10 /* %%for now */; sessions++) {
int count;
for (count = 100; count < MAX_TRACKS; count++)
toc[count].cdsc_ind = 0;
multi_index.cdmsf_min0 = disk_info.next_session.minute;
multi_index.cdmsf_sec0 = disk_info.next_session.second;
multi_index.cdmsf_frame0 = disk_info.next_session.frame;
if (multi_index.cdmsf_sec0 >= 20)
multi_index.cdmsf_sec0 -= 20;
else {
multi_index.cdmsf_sec0 += 40;
multi_index.cdmsf_min0--;
}
DEBUG((DEBUG_MULTIS, "Try %d: %2d:%02d.%02d", sessions,
multi_index.cdmsf_min0,
multi_index.cdmsf_sec0,
multi_index.cdmsf_frame0));
bin2bcd(&multi_index);
multi_index.cdmsf_min1 = 0;
multi_index.cdmsf_sec1 = 0;
multi_index.cdmsf_frame1 = 1;
status = exec_read_cmd(COMREAD, &multi_index);
if (status < 0) {
DEBUG((DEBUG_TOC, "exec_read_cmd COMREAD: %02x",
-status));
break;
}
status = sleep_flag_low(FL_DTEN, MULTI_SEEK_TIMEOUT) ?
0 : -ERR_TOC_MISSINGINFO;
flush_data();
if (status < 0) {
DEBUG((DEBUG_TOC, "sleep_flag_low: %02x", -status));
break;
}
status = read_toc();
if (status < 0) {
DEBUG((DEBUG_TOC, "read_toc: %02x", -status));
break;
}
disk_info.multi = 1;
}
exec_cmd(COMSTOP);
if (status < 0)
return -EIO;
return 0;
}
#endif /* MULTISESSION */
static int update_toc(void)
{
int status, count;
if (toc_uptodate)
return 0;
DEBUG((DEBUG_TOC, "starting update_toc"));
disk_info.first = 0;
for (count = 0; count < MAX_TRACKS; count++)
toc[count].cdsc_ind = 0;
status = exec_cmd(COMLEADIN);
if (status < 0)
return -EIO;
status = read_toc();
if (status < 0) {
DEBUG((DEBUG_TOC, "read_toc: %02x", -status));
return -EIO;
}
/* Audio disk detection. Look at first track. */
disk_info.audio =
(toc[disk_info.first].cdsc_ctrl & CDROM_DATA_TRACK) ? 0 : 1;
/* XA detection */
disk_info.xa = drive_status() & ST_MODE2TRACK;
/* Multisession detection: if we want this, define MULTISESSION */
disk_info.multi = 0;
#ifdef MULTISESSION
if (disk_info.xa)
get_multi_disk_info(); /* Here disk_info.multi is set */
#endif /* MULTISESSION */
if (disk_info.multi)
printk(KERN_WARNING "optcd: Multisession support experimental, "
"see Documentation/cdrom/optcd\n");
DEBUG((DEBUG_TOC, "exiting update_toc"));
toc_uptodate = 1;
return 0;
}
/* Request handling */
static int current_valid(void)
{
return CURRENT &&
CURRENT->cmd == READ &&
CURRENT->sector != -1;
}
/* Buffers for block size conversion. */
#define NOBUF -1
static char buf[CD_FRAMESIZE * N_BUFS];
static volatile int buf_bn[N_BUFS], next_bn;
static volatile int buf_in = 0, buf_out = NOBUF;
static inline void opt_invalidate_buffers(void)
{
int i;
DEBUG((DEBUG_BUFFERS, "executing opt_invalidate_buffers"));
for (i = 0; i < N_BUFS; i++)
buf_bn[i] = NOBUF;
buf_out = NOBUF;
}
/* Take care of the different block sizes between cdrom and Linux.
When Linux gets variable block sizes this will probably go away. */
static void transfer(void)
{
#if DEBUG_BUFFERS | DEBUG_REQUEST
printk(KERN_DEBUG "optcd: executing transfer\n");
#endif
if (!current_valid())
return;
while (CURRENT -> nr_sectors) {
int bn = CURRENT -> sector / 4;
int i, offs, nr_sectors;
for (i = 0; i < N_BUFS && buf_bn[i] != bn; ++i);
DEBUG((DEBUG_REQUEST, "found %d", i));
if (i >= N_BUFS) {
buf_out = NOBUF;
break;
}
offs = (i * 4 + (CURRENT -> sector & 3)) * 512;
nr_sectors = 4 - (CURRENT -> sector & 3);
if (buf_out != i) {
buf_out = i;
if (buf_bn[i] != bn) {
buf_out = NOBUF;
continue;
}
}
if (nr_sectors > CURRENT -> nr_sectors)
nr_sectors = CURRENT -> nr_sectors;
memcpy(CURRENT -> buffer, buf + offs, nr_sectors * 512);
CURRENT -> nr_sectors -= nr_sectors;
CURRENT -> sector += nr_sectors;
CURRENT -> buffer += nr_sectors * 512;
}
}
/* State machine for reading disk blocks */
enum state_e {
S_IDLE, /* 0 */
S_START, /* 1 */
S_READ, /* 2 */
S_DATA, /* 3 */
S_STOP, /* 4 */
S_STOPPING /* 5 */
};
static volatile enum state_e state = S_IDLE;
#if DEBUG_STATE
static volatile enum state_e state_old = S_STOP;
static volatile int flags_old = 0;
static volatile long state_n = 0;
#endif
/* Used as mutex to keep do_optcd_request (and other processes calling
ioctl) out while some process is inside a VFS call.
Reverse is accomplished by checking if state = S_IDLE upon entry
of opt_ioctl and opt_media_change. */
static int in_vfs = 0;
static volatile int transfer_is_active = 0;
static volatile int error = 0; /* %% do something with this?? */
static int tries; /* ibid?? */
static int timeout = 0;
static void poll(unsigned long data);
static struct timer_list req_timer = {.function = poll};
static void poll(unsigned long data)
{
static volatile int read_count = 1;
int flags;
int loop_again = 1;
int status = 0;
int skip = 0;
if (error) {
printk(KERN_ERR "optcd: I/O error 0x%02x\n", error);
opt_invalidate_buffers();
if (!tries--) {
printk(KERN_ERR "optcd: read block %d failed;"
" Giving up\n", next_bn);
if (transfer_is_active)
loop_again = 0;
if (current_valid())
end_request(CURRENT, 0);
tries = 5;
}
error = 0;
state = S_STOP;
}
while (loop_again)
{
loop_again = 0; /* each case must flip this back to 1 if we want
to come back up here */
#if DEBUG_STATE
if (state == state_old)
state_n++;
else {
state_old = state;
if (++state_n > 1)
printk(KERN_DEBUG "optcd: %ld times "
"in previous state\n", state_n);
printk(KERN_DEBUG "optcd: state %d\n", state);
state_n = 0;
}
#endif
switch (state) {
case S_IDLE:
return;
case S_START:
if (in_vfs)
break;
if (send_cmd(COMDRVST)) {
state = S_IDLE;
while (current_valid())
end_request(CURRENT, 0);
return;
}
state = S_READ;
timeout = READ_TIMEOUT;
break;
case S_READ: {
struct cdrom_msf msf;
if (!skip) {
status = fetch_status();
if (status < 0)
break;
if (status & ST_DSK_CHG) {
toc_uptodate = 0;
opt_invalidate_buffers();
}
}
skip = 0;
if ((status & ST_DOOR_OPEN) || (status & ST_DRVERR)) {
toc_uptodate = 0;
opt_invalidate_buffers();
printk(KERN_WARNING "optcd: %s\n",
(status & ST_DOOR_OPEN)
? "door open"
: "disk removed");
state = S_IDLE;
while (current_valid())
end_request(CURRENT, 0);
return;
}
if (!current_valid()) {
state = S_STOP;
loop_again = 1;
break;
}
next_bn = CURRENT -> sector / 4;
lba2msf(next_bn, &msf);
read_count = N_BUFS;
msf.cdmsf_frame1 = read_count; /* Not BCD! */
DEBUG((DEBUG_REQUEST, "reading %x:%x.%x %x:%x.%x",
msf.cdmsf_min0,
msf.cdmsf_sec0,
msf.cdmsf_frame0,
msf.cdmsf_min1,
msf.cdmsf_sec1,
msf.cdmsf_frame1));
DEBUG((DEBUG_REQUEST, "next_bn:%d buf_in:%d"
" buf_out:%d buf_bn:%d",
next_bn,
buf_in,
buf_out,
buf_bn[buf_in]));
exec_read_cmd(COMREAD, &msf);
state = S_DATA;
timeout = READ_TIMEOUT;
break;
}
case S_DATA:
flags = stdt_flags() & (FL_STEN|FL_DTEN);
#if DEBUG_STATE
if (flags != flags_old) {
flags_old = flags;
printk(KERN_DEBUG "optcd: flags:%x\n", flags);
}
if (flags == FL_STEN)
printk(KERN_DEBUG "timeout cnt: %d\n", timeout);
#endif
switch (flags) {
case FL_DTEN: /* only STEN low */
if (!tries--) {
printk(KERN_ERR
"optcd: read block %d failed; "
"Giving up\n", next_bn);
if (transfer_is_active) {
tries = 0;
break;
}
if (current_valid())
end_request(CURRENT, 0);
tries = 5;
}
state = S_START;
timeout = READ_TIMEOUT;
loop_again = 1;
case (FL_STEN|FL_DTEN): /* both high */
break;
default: /* DTEN low */
tries = 5;
if (!current_valid() && buf_in == buf_out) {
state = S_STOP;
loop_again = 1;
break;
}
if (read_count<=0)
printk(KERN_WARNING
"optcd: warning - try to read"
" 0 frames\n");
while (read_count) {
buf_bn[buf_in] = NOBUF;
if (!flag_low(FL_DTEN, BUSY_TIMEOUT)) {
/* should be no waiting here!?? */
printk(KERN_ERR
"read_count:%d "
"CURRENT->nr_sectors:%ld "
"buf_in:%d\n",
read_count,
CURRENT->nr_sectors,
buf_in);
printk(KERN_ERR
"transfer active: %x\n",
transfer_is_active);
read_count = 0;
state = S_STOP;
loop_again = 1;
end_request(CURRENT, 0);
break;
}
fetch_data(buf+
CD_FRAMESIZE*buf_in,
CD_FRAMESIZE);
read_count--;
DEBUG((DEBUG_REQUEST,
"S_DATA; ---I've read data- "
"read_count: %d",
read_count));
DEBUG((DEBUG_REQUEST,
"next_bn:%d buf_in:%d "
"buf_out:%d buf_bn:%d",
next_bn,
buf_in,
buf_out,
buf_bn[buf_in]));
buf_bn[buf_in] = next_bn++;
if (buf_out == NOBUF)
buf_out = buf_in;
buf_in = buf_in + 1 ==
N_BUFS ? 0 : buf_in + 1;
}
if (!transfer_is_active) {
while (current_valid()) {
transfer();
if (CURRENT -> nr_sectors == 0)
end_request(CURRENT, 1);
else
break;
}
}
if (current_valid()
&& (CURRENT -> sector / 4 < next_bn ||
CURRENT -> sector / 4 >
next_bn + N_BUFS)) {
state = S_STOP;
loop_again = 1;
break;
}
timeout = READ_TIMEOUT;
if (read_count == 0) {
state = S_STOP;
loop_again = 1;
break;
}
}
break;
case S_STOP:
if (read_count != 0)
printk(KERN_ERR
"optcd: discard data=%x frames\n",
read_count);
flush_data();
if (send_cmd(COMDRVST)) {
state = S_IDLE;
while (current_valid())
end_request(CURRENT, 0);
return;
}
state = S_STOPPING;
timeout = STOP_TIMEOUT;
break;
case S_STOPPING:
status = fetch_status();
if (status < 0 && timeout)
break;
if ((status >= 0) && (status & ST_DSK_CHG)) {
toc_uptodate = 0;
opt_invalidate_buffers();
}
if (current_valid()) {
if (status >= 0) {
state = S_READ;
loop_again = 1;
skip = 1;
break;
} else {
state = S_START;
timeout = 1;
}
} else {
state = S_IDLE;
return;
}
break;
default:
printk(KERN_ERR "optcd: invalid state %d\n", state);
return;
} /* case */
} /* while */
if (!timeout--) {
printk(KERN_ERR "optcd: timeout in state %d\n", state);
state = S_STOP;
if (exec_cmd(COMSTOP) < 0) {
state = S_IDLE;
while (current_valid())
end_request(CURRENT, 0);
return;
}
}
mod_timer(&req_timer, jiffies + HZ/100);
}
static void do_optcd_request(request_queue_t * q)
{
DEBUG((DEBUG_REQUEST, "do_optcd_request(%ld+%ld)",
CURRENT -> sector, CURRENT -> nr_sectors));
if (disk_info.audio) {
printk(KERN_WARNING "optcd: tried to mount an Audio CD\n");
end_request(CURRENT, 0);
return;
}
transfer_is_active = 1;
while (current_valid()) {
transfer(); /* First try to transfer block from buffers */
if (CURRENT -> nr_sectors == 0) {
end_request(CURRENT, 1);
} else { /* Want to read a block not in buffer */
buf_out = NOBUF;
if (state == S_IDLE) {
/* %% Should this block the request queue?? */
if (update_toc() < 0) {
while (current_valid())
end_request(CURRENT, 0);
break;
}
/* Start state machine */
state = S_START;
timeout = READ_TIMEOUT;
tries = 5;
/* %% why not start right away?? */
mod_timer(&req_timer, jiffies + HZ/100);
}
break;
}
}
transfer_is_active = 0;
DEBUG((DEBUG_REQUEST, "next_bn:%d buf_in:%d buf_out:%d buf_bn:%d",
next_bn, buf_in, buf_out, buf_bn[buf_in]));
DEBUG((DEBUG_REQUEST, "do_optcd_request ends"));
}
/* IOCTLs */
static char auto_eject = 0;
static int cdrompause(void)
{
int status;
if (audio_status != CDROM_AUDIO_PLAY)
return -EINVAL;
status = exec_cmd(COMPAUSEON);
if (status < 0) {
DEBUG((DEBUG_VFS, "exec_cmd COMPAUSEON: %02x", -status));
return -EIO;
}
audio_status = CDROM_AUDIO_PAUSED;
return 0;
}
static int cdromresume(void)
{
int status;
if (audio_status != CDROM_AUDIO_PAUSED)
return -EINVAL;
status = exec_cmd(COMPAUSEOFF);
if (status < 0) {
DEBUG((DEBUG_VFS, "exec_cmd COMPAUSEOFF: %02x", -status));
audio_status = CDROM_AUDIO_ERROR;
return -EIO;
}
audio_status = CDROM_AUDIO_PLAY;
return 0;
}
static int cdromplaymsf(void __user *arg)
{
int status;
struct cdrom_msf msf;
if (copy_from_user(&msf, arg, sizeof msf))
return -EFAULT;
bin2bcd(&msf);
status = exec_long_cmd(COMPLAY, &msf);
if (status < 0) {
DEBUG((DEBUG_VFS, "exec_long_cmd COMPLAY: %02x", -status));
audio_status = CDROM_AUDIO_ERROR;
return -EIO;
}
audio_status = CDROM_AUDIO_PLAY;
return 0;
}
static int cdromplaytrkind(void __user *arg)
{
int status;
struct cdrom_ti ti;
struct cdrom_msf msf;
if (copy_from_user(&ti, arg, sizeof ti))
return -EFAULT;
if (ti.cdti_trk0 < disk_info.first
|| ti.cdti_trk0 > disk_info.last
|| ti.cdti_trk1 < ti.cdti_trk0)
return -EINVAL;
if (ti.cdti_trk1 > disk_info.last)
ti.cdti_trk1 = disk_info.last;
msf.cdmsf_min0 = toc[ti.cdti_trk0].cdsc_absaddr.msf.minute;
msf.cdmsf_sec0 = toc[ti.cdti_trk0].cdsc_absaddr.msf.second;
msf.cdmsf_frame0 = toc[ti.cdti_trk0].cdsc_absaddr.msf.frame;
msf.cdmsf_min1 = toc[ti.cdti_trk1 + 1].cdsc_absaddr.msf.minute;
msf.cdmsf_sec1 = toc[ti.cdti_trk1 + 1].cdsc_absaddr.msf.second;
msf.cdmsf_frame1 = toc[ti.cdti_trk1 + 1].cdsc_absaddr.msf.frame;
DEBUG((DEBUG_VFS, "play %02d:%02d.%02d to %02d:%02d.%02d",
msf.cdmsf_min0,
msf.cdmsf_sec0,
msf.cdmsf_frame0,
msf.cdmsf_min1,
msf.cdmsf_sec1,
msf.cdmsf_frame1));
bin2bcd(&msf);
status = exec_long_cmd(COMPLAY, &msf);
if (status < 0) {
DEBUG((DEBUG_VFS, "exec_long_cmd COMPLAY: %02x", -status));
audio_status = CDROM_AUDIO_ERROR;
return -EIO;
}
audio_status = CDROM_AUDIO_PLAY;
return 0;
}
static int cdromreadtochdr(void __user *arg)
{
struct cdrom_tochdr tochdr;
tochdr.cdth_trk0 = disk_info.first;
tochdr.cdth_trk1 = disk_info.last;
return copy_to_user(arg, &tochdr, sizeof tochdr) ? -EFAULT : 0;
}
static int cdromreadtocentry(void __user *arg)
{
struct cdrom_tocentry entry;
struct cdrom_subchnl *tocptr;
if (copy_from_user(&entry, arg, sizeof entry))
return -EFAULT;
if (entry.cdte_track == CDROM_LEADOUT)
tocptr = &toc[disk_info.last + 1];
else if (entry.cdte_track > disk_info.last
|| entry.cdte_track < disk_info.first)
return -EINVAL;
else
tocptr = &toc[entry.cdte_track];
entry.cdte_adr = tocptr->cdsc_adr;
entry.cdte_ctrl = tocptr->cdsc_ctrl;
entry.cdte_addr.msf.minute = tocptr->cdsc_absaddr.msf.minute;
entry.cdte_addr.msf.second = tocptr->cdsc_absaddr.msf.second;
entry.cdte_addr.msf.frame = tocptr->cdsc_absaddr.msf.frame;
/* %% What should go into entry.cdte_datamode? */
if (entry.cdte_format == CDROM_LBA)
msf2lba(&entry.cdte_addr);
else if (entry.cdte_format != CDROM_MSF)
return -EINVAL;
return copy_to_user(arg, &entry, sizeof entry) ? -EFAULT : 0;
}
static int cdromvolctrl(void __user *arg)
{
int status;
struct cdrom_volctrl volctrl;
struct cdrom_msf msf;
if (copy_from_user(&volctrl, arg, sizeof volctrl))
return -EFAULT;
msf.cdmsf_min0 = 0x10;
msf.cdmsf_sec0 = 0x32;
msf.cdmsf_frame0 = volctrl.channel0;
msf.cdmsf_min1 = volctrl.channel1;
msf.cdmsf_sec1 = volctrl.channel2;
msf.cdmsf_frame1 = volctrl.channel3;
status = exec_long_cmd(COMCHCTRL, &msf);
if (status < 0) {
DEBUG((DEBUG_VFS, "exec_long_cmd COMCHCTRL: %02x", -status));
return -EIO;
}
return 0;
}
static int cdromsubchnl(void __user *arg)
{
int status;
struct cdrom_subchnl subchnl;
if (copy_from_user(&subchnl, arg, sizeof subchnl))
return -EFAULT;
if (subchnl.cdsc_format != CDROM_LBA
&& subchnl.cdsc_format != CDROM_MSF)
return -EINVAL;
status = get_q_channel(&subchnl);
if (status < 0) {
DEBUG((DEBUG_VFS, "get_q_channel: %02x", -status));
return -EIO;
}
if (copy_to_user(arg, &subchnl, sizeof subchnl))
return -EFAULT;
return 0;
}
static struct gendisk *optcd_disk;
static int cdromread(void __user *arg, int blocksize, int cmd)
{
int status;
struct cdrom_msf msf;
if (copy_from_user(&msf, arg, sizeof msf))
return -EFAULT;
bin2bcd(&msf);
msf.cdmsf_min1 = 0;
msf.cdmsf_sec1 = 0;
msf.cdmsf_frame1 = 1; /* read only one frame */
status = exec_read_cmd(cmd, &msf);
DEBUG((DEBUG_VFS, "read cmd status 0x%x", status));
if (!sleep_flag_low(FL_DTEN, SLEEP_TIMEOUT))
return -EIO;
fetch_data(optcd_disk->private_data, blocksize);
if (copy_to_user(arg, optcd_disk->private_data, blocksize))
return -EFAULT;
return 0;
}
static int cdromseek(void __user *arg)
{
int status;
struct cdrom_msf msf;
if (copy_from_user(&msf, arg, sizeof msf))
return -EFAULT;
bin2bcd(&msf);
status = exec_seek_cmd(COMSEEK, &msf);
DEBUG((DEBUG_VFS, "COMSEEK status 0x%x", status));
if (status < 0)
return -EIO;
return 0;
}
#ifdef MULTISESSION
static int cdrommultisession(void __user *arg)
{
struct cdrom_multisession ms;
if (copy_from_user(&ms, arg, sizeof ms))
return -EFAULT;
ms.addr.msf.minute = disk_info.last_session.minute;
ms.addr.msf.second = disk_info.last_session.second;
ms.addr.msf.frame = disk_info.last_session.frame;
if (ms.addr_format != CDROM_LBA
&& ms.addr_format != CDROM_MSF)
return -EINVAL;
if (ms.addr_format == CDROM_LBA)
msf2lba(&ms.addr);
ms.xa_flag = disk_info.xa;
if (copy_to_user(arg, &ms, sizeof(struct cdrom_multisession)))
return -EFAULT;
#if DEBUG_MULTIS
if (ms.addr_format == CDROM_MSF)
printk(KERN_DEBUG
"optcd: multisession xa:%d, msf:%02d:%02d.%02d\n",
ms.xa_flag,
ms.addr.msf.minute,
ms.addr.msf.second,
ms.addr.msf.frame);
else
printk(KERN_DEBUG
"optcd: multisession %d, lba:0x%08x [%02d:%02d.%02d])\n",
ms.xa_flag,
ms.addr.lba,
disk_info.last_session.minute,
disk_info.last_session.second,
disk_info.last_session.frame);
#endif /* DEBUG_MULTIS */
return 0;
}
#endif /* MULTISESSION */
static int cdromreset(void)
{
if (state != S_IDLE) {
error = 1;
tries = 0;
}
toc_uptodate = 0;
disk_changed = 1;
opt_invalidate_buffers();
audio_status = CDROM_AUDIO_NO_STATUS;
if (!reset_drive())
return -EIO;
return 0;
}
/* VFS calls */
static int opt_ioctl(struct inode *ip, struct file *fp,
unsigned int cmd, unsigned long arg)
{
int status, err, retval = 0;
void __user *argp = (void __user *)arg;
DEBUG((DEBUG_VFS, "starting opt_ioctl"));
if (!ip)
return -EINVAL;
if (cmd == CDROMRESET)
return cdromreset();
/* is do_optcd_request or another ioctl busy? */
if (state != S_IDLE || in_vfs)
return -EBUSY;
in_vfs = 1;
status = drive_status();
if (status < 0) {
DEBUG((DEBUG_VFS, "drive_status: %02x", -status));
in_vfs = 0;
return -EIO;
}
if (status & ST_DOOR_OPEN)
switch (cmd) { /* Actions that can be taken with door open */
case CDROMCLOSETRAY:
/* We do this before trying to read the toc. */
err = exec_cmd(COMCLOSE);
if (err < 0) {
DEBUG((DEBUG_VFS,
"exec_cmd COMCLOSE: %02x", -err));
in_vfs = 0;
return -EIO;
}
break;
default: in_vfs = 0;
return -EBUSY;
}
err = update_toc();
if (err < 0) {
DEBUG((DEBUG_VFS, "update_toc: %02x", -err));
in_vfs = 0;
return -EIO;
}
DEBUG((DEBUG_VFS, "ioctl cmd 0x%x", cmd));
switch (cmd) {
case CDROMPAUSE: retval = cdrompause(); break;
case CDROMRESUME: retval = cdromresume(); break;
case CDROMPLAYMSF: retval = cdromplaymsf(argp); break;
case CDROMPLAYTRKIND: retval = cdromplaytrkind(argp); break;
case CDROMREADTOCHDR: retval = cdromreadtochdr(argp); break;
case CDROMREADTOCENTRY: retval = cdromreadtocentry(argp); break;
case CDROMSTOP: err = exec_cmd(COMSTOP);
if (err < 0) {
DEBUG((DEBUG_VFS,
"exec_cmd COMSTOP: %02x",
-err));
retval = -EIO;
} else
audio_status = CDROM_AUDIO_NO_STATUS;
break;
case CDROMSTART: break; /* This is a no-op */
case CDROMEJECT: err = exec_cmd(COMUNLOCK);
if (err < 0) {
DEBUG((DEBUG_VFS,
"exec_cmd COMUNLOCK: %02x",
-err));
retval = -EIO;
break;
}
err = exec_cmd(COMOPEN);
if (err < 0) {
DEBUG((DEBUG_VFS,
"exec_cmd COMOPEN: %02x",
-err));
retval = -EIO;
}
break;
case CDROMVOLCTRL: retval = cdromvolctrl(argp); break;
case CDROMSUBCHNL: retval = cdromsubchnl(argp); break;
/* The drive detects the mode and automatically delivers the
correct 2048 bytes, so we don't need these IOCTLs */
case CDROMREADMODE2: retval = -EINVAL; break;
case CDROMREADMODE1: retval = -EINVAL; break;
/* Drive doesn't support reading audio */
case CDROMREADAUDIO: retval = -EINVAL; break;
case CDROMEJECT_SW: auto_eject = (char) arg;
break;
#ifdef MULTISESSION
case CDROMMULTISESSION: retval = cdrommultisession(argp); break;
#endif
case CDROM_GET_MCN: retval = -EINVAL; break; /* not implemented */
case CDROMVOLREAD: retval = -EINVAL; break; /* not implemented */
case CDROMREADRAW:
/* this drive delivers 2340 bytes in raw mode */
retval = cdromread(argp, CD_FRAMESIZE_RAW1, COMREADRAW);
break;
case CDROMREADCOOKED:
retval = cdromread(argp, CD_FRAMESIZE, COMREAD);
break;
case CDROMREADALL:
retval = cdromread(argp, CD_FRAMESIZE_RAWER, COMREADALL);
break;
case CDROMSEEK: retval = cdromseek(argp); break;
case CDROMPLAYBLK: retval = -EINVAL; break; /* not implemented */
case CDROMCLOSETRAY: break; /* The action was taken earlier */
default: retval = -EINVAL;
}
in_vfs = 0;
return retval;
}
static int open_count = 0;
/* Open device special file; check that a disk is in. */
static int opt_open(struct inode *ip, struct file *fp)
{
DEBUG((DEBUG_VFS, "starting opt_open"));
if (!open_count && state == S_IDLE) {
int status;
char *buf;
buf = kmalloc(CD_FRAMESIZE_RAWER, GFP_KERNEL);
if (!buf) {
printk(KERN_INFO "optcd: cannot allocate read buffer\n");
return -ENOMEM;
}
optcd_disk->private_data = buf; /* save read buffer */
toc_uptodate = 0;
opt_invalidate_buffers();
status = exec_cmd(COMCLOSE); /* close door */
if (status < 0) {
DEBUG((DEBUG_VFS, "exec_cmd COMCLOSE: %02x", -status));
}
status = drive_status();
if (status < 0) {
DEBUG((DEBUG_VFS, "drive_status: %02x", -status));
goto err_out;
}
DEBUG((DEBUG_VFS, "status: %02x", status));
if ((status & ST_DOOR_OPEN) || (status & ST_DRVERR)) {
printk(KERN_INFO "optcd: no disk or door open\n");
goto err_out;
}
status = exec_cmd(COMLOCK); /* Lock door */
if (status < 0) {
DEBUG((DEBUG_VFS, "exec_cmd COMLOCK: %02x", -status));
}
status = update_toc(); /* Read table of contents */
if (status < 0) {
DEBUG((DEBUG_VFS, "update_toc: %02x", -status));
status = exec_cmd(COMUNLOCK); /* Unlock door */
if (status < 0) {
DEBUG((DEBUG_VFS,
"exec_cmd COMUNLOCK: %02x", -status));
}
goto err_out;
}
open_count++;
}
DEBUG((DEBUG_VFS, "exiting opt_open"));
return 0;
err_out:
return -EIO;
}
/* Release device special file; flush all blocks from the buffer cache */
static int opt_release(struct inode *ip, struct file *fp)
{
int status;
DEBUG((DEBUG_VFS, "executing opt_release"));
DEBUG((DEBUG_VFS, "inode: %p, device: %s, file: %p\n",
ip, ip->i_bdev->bd_disk->disk_name, fp));
if (!--open_count) {
toc_uptodate = 0;
opt_invalidate_buffers();
status = exec_cmd(COMUNLOCK); /* Unlock door */
if (status < 0) {
DEBUG((DEBUG_VFS, "exec_cmd COMUNLOCK: %02x", -status));
}
if (auto_eject) {
status = exec_cmd(COMOPEN);
DEBUG((DEBUG_VFS, "exec_cmd COMOPEN: %02x", -status));
}
kfree(optcd_disk->private_data);
del_timer(&delay_timer);
del_timer(&req_timer);
}
return 0;
}
/* Check if disk has been changed */
static int opt_media_change(struct gendisk *disk)
{
DEBUG((DEBUG_VFS, "executing opt_media_change"));
DEBUG((DEBUG_VFS, "dev: %s; disk_changed = %d\n",
disk->disk_name, disk_changed));
if (disk_changed) {
disk_changed = 0;
return 1;
}
return 0;
}
/* Driver initialisation */
/* Returns 1 if a drive is detected with a version string
starting with "DOLPHIN". Otherwise 0. */
static int __init version_ok(void)
{
char devname[100];
int count, i, ch, status;
status = exec_cmd(COMVERSION);
if (status < 0) {
DEBUG((DEBUG_VFS, "exec_cmd COMVERSION: %02x", -status));
return 0;
}
if ((count = get_data(1)) < 0) {
DEBUG((DEBUG_VFS, "get_data(1): %02x", -count));
return 0;
}
for (i = 0, ch = -1; count > 0; count--) {
if ((ch = get_data(1)) < 0) {
DEBUG((DEBUG_VFS, "get_data(1): %02x", -ch));
break;
}
if (i < 99)
devname[i++] = ch;
}
devname[i] = '\0';
if (ch < 0)
return 0;
printk(KERN_INFO "optcd: Device %s detected\n", devname);
return ((devname[0] == 'D')
&& (devname[1] == 'O')
&& (devname[2] == 'L')
&& (devname[3] == 'P')
&& (devname[4] == 'H')
&& (devname[5] == 'I')
&& (devname[6] == 'N'));
}
static struct block_device_operations opt_fops = {
.owner = THIS_MODULE,
.open = opt_open,
.release = opt_release,
.ioctl = opt_ioctl,
.media_changed = opt_media_change,
};
#ifndef MODULE
/* Get kernel parameter when used as a kernel driver */
static int optcd_setup(char *str)
{
int ints[4];
(void)get_options(str, ARRAY_SIZE(ints), ints);
if (ints[0] > 0)
optcd_port = ints[1];
return 1;
}
__setup("optcd=", optcd_setup);
#endif /* MODULE */
/* Test for presence of drive and initialize it. Called at boot time
or during module initialisation. */
static int __init optcd_init(void)
{
int status;
if (optcd_port <= 0) {
printk(KERN_INFO
"optcd: no Optics Storage CDROM Initialization\n");
return -EIO;
}
optcd_disk = alloc_disk(1);
if (!optcd_disk) {
printk(KERN_ERR "optcd: can't allocate disk\n");
return -ENOMEM;
}
optcd_disk->major = MAJOR_NR;
optcd_disk->first_minor = 0;
optcd_disk->fops = &opt_fops;
sprintf(optcd_disk->disk_name, "optcd");
if (!request_region(optcd_port, 4, "optcd")) {
printk(KERN_ERR "optcd: conflict, I/O port 0x%x already used\n",
optcd_port);
put_disk(optcd_disk);
return -EIO;
}
if (!reset_drive()) {
printk(KERN_ERR "optcd: drive at 0x%x not ready\n", optcd_port);
release_region(optcd_port, 4);
put_disk(optcd_disk);
return -EIO;
}
if (!version_ok()) {
printk(KERN_ERR "optcd: unknown drive detected; aborting\n");
release_region(optcd_port, 4);
put_disk(optcd_disk);
return -EIO;
}
status = exec_cmd(COMINITDOUBLE);
if (status < 0) {
printk(KERN_ERR "optcd: cannot init double speed mode\n");
release_region(optcd_port, 4);
DEBUG((DEBUG_VFS, "exec_cmd COMINITDOUBLE: %02x", -status));
put_disk(optcd_disk);
return -EIO;
}
if (register_blkdev(MAJOR_NR, "optcd")) {
release_region(optcd_port, 4);
put_disk(optcd_disk);
return -EIO;
}
opt_queue = blk_init_queue(do_optcd_request, &optcd_lock);
if (!opt_queue) {
unregister_blkdev(MAJOR_NR, "optcd");
release_region(optcd_port, 4);
put_disk(optcd_disk);
return -ENOMEM;
}
blk_queue_hardsect_size(opt_queue, 2048);
optcd_disk->queue = opt_queue;
add_disk(optcd_disk);
printk(KERN_INFO "optcd: DOLPHIN 8000 AT CDROM at 0x%x\n", optcd_port);
return 0;
}
static void __exit optcd_exit(void)
{
del_gendisk(optcd_disk);
put_disk(optcd_disk);
if (unregister_blkdev(MAJOR_NR, "optcd") == -EINVAL) {
printk(KERN_ERR "optcd: what's that: can't unregister\n");
return;
}
blk_cleanup_queue(opt_queue);
release_region(optcd_port, 4);
printk(KERN_INFO "optcd: module released.\n");
}
module_init(optcd_init);
module_exit(optcd_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_BLOCKDEV_MAJOR(OPTICS_CDROM_MAJOR);
|
maliyu/SOM2416
|
drivers/cdrom/optcd.c
|
C
|
gpl-2.0
| 51,605
|
/*
* include/linux/backing-dev.h
*
* low-level device information and state which is propagated up through
* to high-level code.
*/
#ifndef _LINUX_BACKING_DEV_H
#define _LINUX_BACKING_DEV_H
#include <linux/percpu_counter.h>
#include <linux/log2.h>
#include <linux/flex_proportions.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/timer.h>
#include <linux/writeback.h>
#include <linux/atomic.h>
#include <linux/sysctl.h>
#include <linux/workqueue.h>
struct page;
struct device;
struct dentry;
/*
* Bits in backing_dev_info.state
*/
enum bdi_state {
BDI_wb_alloc, /* Default embedded wb allocated */
BDI_async_congested, /* The async (write) queue is getting full */
BDI_sync_congested, /* The sync queue is getting full */
BDI_registered, /* bdi_register() was done */
BDI_writeback_running, /* Writeback is in progress */
BDI_unused, /* Available bits start here */
};
typedef int (congested_fn)(void *, int);
enum bdi_stat_item {
BDI_RECLAIMABLE,
BDI_WRITEBACK,
BDI_DIRTIED,
BDI_WRITTEN,
NR_BDI_STAT_ITEMS
};
#define BDI_STAT_BATCH (8*(1+ilog2(nr_cpu_ids)))
struct bdi_writeback {
struct backing_dev_info *bdi; /* our parent bdi */
unsigned int nr;
unsigned long last_old_flush; /* last old data flush */
struct delayed_work dwork; /* work item used for writeback */
struct list_head b_dirty; /* dirty inodes */
struct list_head b_io; /* parked for writeback */
struct list_head b_more_io; /* parked for more writeback */
spinlock_t list_lock; /* protects the b_* lists */
};
struct backing_dev_info {
struct list_head bdi_list;
unsigned long ra_pages; /* max readahead in PAGE_CACHE_SIZE units */
unsigned long state; /* Always use atomic bitops on this */
unsigned int capabilities; /* Device capabilities */
congested_fn *congested_fn; /* Function pointer if device is md/dm */
void *congested_data; /* Pointer to aux data for congested func */
char *name;
struct percpu_counter bdi_stat[NR_BDI_STAT_ITEMS];
unsigned long bw_time_stamp; /* last time write bw is updated */
unsigned long dirtied_stamp;
unsigned long written_stamp; /* pages written at bw_time_stamp */
unsigned long write_bandwidth; /* the estimated write bandwidth */
unsigned long avg_write_bandwidth; /* further smoothed write bw */
/*
* The base dirty throttle rate, re-calculated on every 200ms.
* All the bdi tasks' dirty rate will be curbed under it.
* @dirty_ratelimit tracks the estimated @balanced_dirty_ratelimit
* in small steps and is much more smooth/stable than the latter.
*/
unsigned long dirty_ratelimit;
unsigned long balanced_dirty_ratelimit;
struct fprop_local_percpu completions;
int dirty_exceeded;
unsigned int min_ratio;
unsigned int max_ratio, max_prop_frac;
struct bdi_writeback wb; /* default writeback info for this bdi */
spinlock_t wb_lock; /* protects work_list & wb.dwork scheduling */
struct list_head work_list;
struct device *dev;
struct device *owner;
struct timer_list laptop_mode_wb_timer;
#ifdef CONFIG_DEBUG_FS
struct dentry *debug_dir;
struct dentry *debug_stats;
#endif
};
int __must_check bdi_init(struct backing_dev_info *bdi);
void bdi_destroy(struct backing_dev_info *bdi);
int bdi_register(struct backing_dev_info *bdi, struct device *parent,
const char *fmt, ...);
int bdi_register_dev(struct backing_dev_info *bdi, dev_t dev);
int bdi_register_owner(struct backing_dev_info *bdi, struct device *owner);
void bdi_unregister(struct backing_dev_info *bdi);
int __must_check bdi_setup_and_register(struct backing_dev_info *, char *, unsigned int);
void bdi_start_writeback(struct backing_dev_info *bdi, long nr_pages,
enum wb_reason reason);
void bdi_start_background_writeback(struct backing_dev_info *bdi);
void bdi_writeback_workfn(struct work_struct *work);
int bdi_has_dirty_io(struct backing_dev_info *bdi);
void bdi_wakeup_thread_delayed(struct backing_dev_info *bdi);
void bdi_lock_two(struct bdi_writeback *wb1, struct bdi_writeback *wb2);
extern spinlock_t bdi_lock;
extern struct list_head bdi_list;
extern struct workqueue_struct *bdi_wq;
static inline int wb_has_dirty_io(struct bdi_writeback *wb)
{
return !list_empty(&wb->b_dirty) ||
!list_empty(&wb->b_io) ||
!list_empty(&wb->b_more_io);
}
static inline void __add_bdi_stat(struct backing_dev_info *bdi,
enum bdi_stat_item item, s64 amount)
{
__percpu_counter_add(&bdi->bdi_stat[item], amount, BDI_STAT_BATCH);
}
static inline void __inc_bdi_stat(struct backing_dev_info *bdi,
enum bdi_stat_item item)
{
__add_bdi_stat(bdi, item, 1);
}
static inline void inc_bdi_stat(struct backing_dev_info *bdi,
enum bdi_stat_item item)
{
unsigned long flags;
local_irq_save(flags);
__inc_bdi_stat(bdi, item);
local_irq_restore(flags);
}
static inline void __dec_bdi_stat(struct backing_dev_info *bdi,
enum bdi_stat_item item)
{
__add_bdi_stat(bdi, item, -1);
}
static inline void dec_bdi_stat(struct backing_dev_info *bdi,
enum bdi_stat_item item)
{
unsigned long flags;
local_irq_save(flags);
__dec_bdi_stat(bdi, item);
local_irq_restore(flags);
}
static inline s64 bdi_stat(struct backing_dev_info *bdi,
enum bdi_stat_item item)
{
return percpu_counter_read_positive(&bdi->bdi_stat[item]);
}
static inline s64 __bdi_stat_sum(struct backing_dev_info *bdi,
enum bdi_stat_item item)
{
return percpu_counter_sum_positive(&bdi->bdi_stat[item]);
}
static inline s64 bdi_stat_sum(struct backing_dev_info *bdi,
enum bdi_stat_item item)
{
s64 sum;
unsigned long flags;
local_irq_save(flags);
sum = __bdi_stat_sum(bdi, item);
local_irq_restore(flags);
return sum;
}
extern void bdi_writeout_inc(struct backing_dev_info *bdi);
/*
* maximal error of a stat counter.
*/
static inline unsigned long bdi_stat_error(struct backing_dev_info *bdi)
{
#ifdef CONFIG_SMP
return nr_cpu_ids * BDI_STAT_BATCH;
#else
return 1;
#endif
}
int bdi_set_min_ratio(struct backing_dev_info *bdi, unsigned int min_ratio);
int bdi_set_max_ratio(struct backing_dev_info *bdi, unsigned int max_ratio);
/*
* Flags in backing_dev_info::capability
*
* The first three flags control whether dirty pages will contribute to the
* VM's accounting and whether writepages() should be called for dirty pages
* (something that would not, for example, be appropriate for ramfs)
*
* WARNING: these flags are closely related and should not normally be
* used separately. The BDI_CAP_NO_ACCT_AND_WRITEBACK combines these
* three flags into a single convenience macro.
*
* BDI_CAP_NO_ACCT_DIRTY: Dirty pages shouldn't contribute to accounting
* BDI_CAP_NO_WRITEBACK: Don't write pages back
* BDI_CAP_NO_ACCT_WB: Don't automatically account writeback pages
*
* These flags let !MMU mmap() govern direct device mapping vs immediate
* copying more easily for MAP_PRIVATE, especially for ROM filesystems.
*
* BDI_CAP_MAP_COPY: Copy can be mapped (MAP_PRIVATE)
* BDI_CAP_MAP_DIRECT: Can be mapped directly (MAP_SHARED)
* BDI_CAP_READ_MAP: Can be mapped for reading
* BDI_CAP_WRITE_MAP: Can be mapped for writing
* BDI_CAP_EXEC_MAP: Can be mapped for execution
*
* BDI_CAP_SWAP_BACKED: Count shmem/tmpfs objects as swap-backed.
*
* BDI_CAP_STRICTLIMIT: Keep number of dirty pages below bdi threshold.
*/
#define BDI_CAP_NO_ACCT_DIRTY 0x00000001
#define BDI_CAP_NO_WRITEBACK 0x00000002
#define BDI_CAP_MAP_COPY 0x00000004
#define BDI_CAP_MAP_DIRECT 0x00000008
#define BDI_CAP_READ_MAP 0x00000010
#define BDI_CAP_WRITE_MAP 0x00000020
#define BDI_CAP_EXEC_MAP 0x00000040
#define BDI_CAP_NO_ACCT_WB 0x00000080
#define BDI_CAP_SWAP_BACKED 0x00000100
#define BDI_CAP_STABLE_WRITES 0x00000200
#define BDI_CAP_STRICTLIMIT 0x00000400
#define BDI_CAP_VMFLAGS \
(BDI_CAP_READ_MAP | BDI_CAP_WRITE_MAP | BDI_CAP_EXEC_MAP)
#define BDI_CAP_NO_ACCT_AND_WRITEBACK \
(BDI_CAP_NO_WRITEBACK | BDI_CAP_NO_ACCT_DIRTY | BDI_CAP_NO_ACCT_WB)
#if defined(VM_MAYREAD) && \
(BDI_CAP_READ_MAP != VM_MAYREAD || \
BDI_CAP_WRITE_MAP != VM_MAYWRITE || \
BDI_CAP_EXEC_MAP != VM_MAYEXEC)
#error please change backing_dev_info::capabilities flags
#endif
extern struct backing_dev_info default_backing_dev_info;
extern struct backing_dev_info noop_backing_dev_info;
int writeback_in_progress(struct backing_dev_info *bdi);
static inline int bdi_congested(struct backing_dev_info *bdi, int bdi_bits)
{
if (bdi->congested_fn)
return bdi->congested_fn(bdi->congested_data, bdi_bits);
return (bdi->state & bdi_bits);
}
static inline int bdi_read_congested(struct backing_dev_info *bdi)
{
return bdi_congested(bdi, 1 << BDI_sync_congested);
}
static inline int bdi_write_congested(struct backing_dev_info *bdi)
{
return bdi_congested(bdi, 1 << BDI_async_congested);
}
static inline int bdi_rw_congested(struct backing_dev_info *bdi)
{
return bdi_congested(bdi, (1 << BDI_sync_congested) |
(1 << BDI_async_congested));
}
enum {
BLK_RW_ASYNC = 0,
BLK_RW_SYNC = 1,
};
void clear_bdi_congested(struct backing_dev_info *bdi, int sync);
void set_bdi_congested(struct backing_dev_info *bdi, int sync);
long congestion_wait(int sync, long timeout);
long wait_iff_congested(struct zone *zone, int sync, long timeout);
int pdflush_proc_obsolete(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos);
static inline bool bdi_cap_stable_pages_required(struct backing_dev_info *bdi)
{
return bdi->capabilities & BDI_CAP_STABLE_WRITES;
}
static inline bool bdi_cap_writeback_dirty(struct backing_dev_info *bdi)
{
return !(bdi->capabilities & BDI_CAP_NO_WRITEBACK);
}
static inline bool bdi_cap_account_dirty(struct backing_dev_info *bdi)
{
return !(bdi->capabilities & BDI_CAP_NO_ACCT_DIRTY);
}
static inline bool bdi_cap_account_writeback(struct backing_dev_info *bdi)
{
/* Paranoia: BDI_CAP_NO_WRITEBACK implies BDI_CAP_NO_ACCT_WB */
return !(bdi->capabilities & (BDI_CAP_NO_ACCT_WB |
BDI_CAP_NO_WRITEBACK));
}
static inline bool bdi_cap_swap_backed(struct backing_dev_info *bdi)
{
return bdi->capabilities & BDI_CAP_SWAP_BACKED;
}
static inline bool mapping_cap_writeback_dirty(struct address_space *mapping)
{
return bdi_cap_writeback_dirty(mapping->backing_dev_info);
}
static inline bool mapping_cap_account_dirty(struct address_space *mapping)
{
return bdi_cap_account_dirty(mapping->backing_dev_info);
}
static inline bool mapping_cap_swap_backed(struct address_space *mapping)
{
return bdi_cap_swap_backed(mapping->backing_dev_info);
}
static inline int bdi_sched_wait(void *word)
{
schedule();
return 0;
}
#endif /* _LINUX_BACKING_DEV_H */
|
gsstudios/Dorimanx-SG2-I9100-Kernel
|
include/linux/backing-dev.h
|
C
|
gpl-2.0
| 10,590
|
/*
* Copyright (C) 2008-2013 Trinitycore <http://www.trinitycore.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, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "steam_vault.h"
enum HydromancerThespia
{
SAY_SUMMON = 0,
SAY_AGGRO = 1,
SAY_SLAY = 2,
SAY_DEAD = 3,
SPELL_LIGHTNING_CLOUD = 25033,
SPELL_LUNG_BURST = 31481,
SPELL_ENVELOPING_WINDS = 31718,
SPELL_WATER_BOLT_VOLLEY = 34449,
H_SPELL_WATER_BOLT_VOLLEY = 37924
};
class boss_hydromancer_thespia : public CreatureScript
{
public:
boss_hydromancer_thespia() : CreatureScript("boss_hydromancer_thespia") { }
CreatureAI* GetAI(Creature* creature) const OVERRIDE
{
return new boss_thespiaAI(creature);
}
struct boss_thespiaAI : public ScriptedAI
{
boss_thespiaAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
}
InstanceScript* instance;
uint32 LightningCloud_Timer;
uint32 LungBurst_Timer;
uint32 EnvelopingWinds_Timer;
void Reset() OVERRIDE
{
LightningCloud_Timer = 15000;
LungBurst_Timer = 7000;
EnvelopingWinds_Timer = 9000;
if (instance)
instance->SetBossState(DATA_HYDROMANCER_THESPIA, NOT_STARTED);
}
void JustDied(Unit* /*killer*/) OVERRIDE
{
Talk(SAY_DEAD);
if (instance)
instance->SetBossState(DATA_HYDROMANCER_THESPIA, DONE);
}
void KilledUnit(Unit* /*victim*/) OVERRIDE
{
Talk(SAY_SLAY);
}
void EnterCombat(Unit* /*who*/) OVERRIDE
{
Talk(SAY_AGGRO);
if (instance)
instance->SetBossState(DATA_HYDROMANCER_THESPIA, IN_PROGRESS);
}
void UpdateAI(uint32 diff) OVERRIDE
{
if (!UpdateVictim())
return;
//LightningCloud_Timer
if (LightningCloud_Timer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(target, SPELL_LIGHTNING_CLOUD);
//cast twice in Heroic mode
if (IsHeroic())
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(target, SPELL_LIGHTNING_CLOUD);
LightningCloud_Timer = 15000+rand()%10000;
} else LightningCloud_Timer -=diff;
//LungBurst_Timer
if (LungBurst_Timer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(target, SPELL_LUNG_BURST);
LungBurst_Timer = 7000+rand()%5000;
} else LungBurst_Timer -=diff;
//EnvelopingWinds_Timer
if (EnvelopingWinds_Timer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(target, SPELL_ENVELOPING_WINDS);
//cast twice in Heroic mode
if (IsHeroic())
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(target, SPELL_ENVELOPING_WINDS);
EnvelopingWinds_Timer = 10000+rand()%5000;
} else EnvelopingWinds_Timer -=diff;
DoMeleeAttackIfReady();
}
};
};
class npc_coilfang_waterelemental : public CreatureScript
{
public:
npc_coilfang_waterelemental() : CreatureScript("npc_coilfang_waterelemental") { }
CreatureAI* GetAI(Creature* creature) const OVERRIDE
{
return new npc_coilfang_waterelementalAI(creature);
}
struct npc_coilfang_waterelementalAI : public ScriptedAI
{
npc_coilfang_waterelementalAI(Creature* creature) : ScriptedAI(creature) { }
uint32 WaterBoltVolley_Timer;
void Reset() OVERRIDE
{
WaterBoltVolley_Timer = 3000+rand()%3000;
}
void EnterCombat(Unit* /*who*/) OVERRIDE { }
void UpdateAI(uint32 diff) OVERRIDE
{
if (!UpdateVictim())
return;
if (WaterBoltVolley_Timer <= diff)
{
DoCast(me, SPELL_WATER_BOLT_VOLLEY);
WaterBoltVolley_Timer = 7000+rand()%5000;
} else WaterBoltVolley_Timer -= diff;
DoMeleeAttackIfReady();
}
};
};
void AddSC_boss_hydromancer_thespia()
{
new boss_hydromancer_thespia();
new npc_coilfang_waterelemental();
}
|
InfinityCore/InfinityCore243
|
src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_hydromancer_thespia.cpp
|
C++
|
gpl-2.0
| 5,302
|
//
// VEXT2 Linux SDK Header File
//
// 2013.09.05 ikki Create
#include "SMIMS_define.h"
typedef BOOL (*DEF_SMIMS_VEXT2_ProgramFPGA)(int iBoard, char * BitFile);
typedef BOOL (*DEF_SMIMS_VEXT2_ProgramFPGAFromSD)(int iBoard, int iBitFileIndex);
typedef BOOL (*DEF_SMIMS_VEXT2_AppOpen)(int iBoard, char * SerialNO, int ClkMode);
typedef BOOL (*DEF_SMIMS_VEXT2_AppFIFOReadData)(int iBoard, WORD *Buffer, unsigned size);
typedef BOOL (*DEF_SMIMS_VEXT2_AppFIFOWriteData)(int iBoard, WORD *Buffer, unsigned size);
typedef BOOL (*DEF_SMIMS_VEXT2_AppChannelSelector)(int iBoard, BYTE channel);
typedef BOOL (*DEF_SMIMS_VEXT2_AppClose)(int iBoard);
typedef char *(*DEF_SMIMS_VEXT2_GetLastErrorMsg)(int iBoard);
typedef BOOL (*DEF_SMIMS_VEXT2_Reset)(int iBoard);
typedef BOOL (*DEF_SMIMS_VEXT2_WaitInterrupt)(int iBoard, unsigned TimeOut);
typedef BOOL (*DEF_SMIMS_VEXT2_NBReadData)(int iBoard, WORD *Buffer, unsigned size);
typedef BOOL (*DEF_SMIMS_VEXT2_NBWriteData)(int iBoard, WORD *Buffer, unsigned size);
typedef BOOL (*DEF_SMIMS_VEXT2_WaitReadComplete)(int iBoard, unsigned TimeOut);
typedef BOOL (*DEF_SMIMS_VEXT2_WaitWriteComplete)(int iBoard, unsigned TimeOut);
extern DEF_SMIMS_VEXT2_ProgramFPGA SMIMS_VEXT2_ProgramFPGA;
extern DEF_SMIMS_VEXT2_ProgramFPGAFromSD SMIMS_VEXT2_ProgramFPGAFromSD;
extern DEF_SMIMS_VEXT2_AppOpen SMIMS_VEXT2_AppOpen;
extern DEF_SMIMS_VEXT2_AppFIFOReadData SMIMS_VEXT2_AppFIFOReadData;
extern DEF_SMIMS_VEXT2_AppFIFOWriteData SMIMS_VEXT2_AppFIFOWriteData;
extern DEF_SMIMS_VEXT2_AppChannelSelector SMIMS_VEXT2_AppChannelSelector;
extern DEF_SMIMS_VEXT2_AppClose SMIMS_VEXT2_AppClose;
extern DEF_SMIMS_VEXT2_GetLastErrorMsg SMIMS_VEXT2_GetLastErrorMsg;
extern DEF_SMIMS_VEXT2_Reset SMIMS_VEXT2_Reset;
extern DEF_SMIMS_VEXT2_WaitInterrupt SMIMS_VEXT2_WaitInterrupt;
extern DEF_SMIMS_VEXT2_NBReadData SMIMS_VEXT2_NBReadData;
extern DEF_SMIMS_VEXT2_NBWriteData SMIMS_VEXT2_NBWriteData;
extern DEF_SMIMS_VEXT2_WaitReadComplete SMIMS_VEXT2_WaitReadComplete;
extern DEF_SMIMS_VEXT2_WaitWriteComplete SMIMS_VEXT2_WaitWriteComplete;
bool LoadShareObject();
|
rurume/openrisc_vision_software
|
OPENRISC_API/SMIMS_VEXT2.h
|
C
|
gpl-2.0
| 2,085
|
package org.checkerframework.common.value.qual;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.checkerframework.framework.qual.SubtypeOf;
/**
* An annotation indicating the length of an array type.
* If an expression's type has this annotation, then at run time, the
* expression evaluates to an array whose length is one of the annotation's
* arguments.
*
* @checker_framework.manual #constant-value-checker Constant Value Checker
*/
@SubtypeOf({ UnknownVal.class })
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE_PARAMETER, ElementType.TYPE_USE })
public @interface ArrayLen {
int[] value();
}
|
atomicknight/checker-framework
|
framework/src/org/checkerframework/common/value/qual/ArrayLen.java
|
Java
|
gpl-2.0
| 751
|
#include "pdns/namespaces.hh"
#include <pdns/dns.hh>
#include <pdns/dnsbackend.hh>
#include <pdns/dnspacket.hh>
#include <pdns/ueberbackend.hh>
#include <pdns/pdnsexception.hh>
#include <pdns/logger.hh>
#include <pdns/arguments.hh>
#include <boost/lexical_cast.hpp>
#include <rapidjson/rapidjson.h>
#include <rapidjson/document.h>
#include "pdns/json.hh"
#include "pdns/statbag.hh"
#include "pdns/packetcache.hh"
StatBag S;
PacketCache PC;
ArgvMap &arg()
{
static ArgvMap arg;
return arg;
};
class RemoteLoader
{
public:
RemoteLoader();
};
DNSBackend *be;
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE unit
#include <boost/test/unit_test.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/foreach.hpp>
#include <boost/tuple/tuple.hpp>
struct RemotebackendSetup {
RemotebackendSetup() {
be = 0;
try {
// setup minimum arguments
::arg().set("module-dir")="./.libs";
new RemoteLoader();
BackendMakers().launch("remote");
// then get us a instance of it
::arg().set("remote-connection-string")="http:url=http://localhost:62434/dns/endpoint.json,post=1,post_json=1";
::arg().set("remote-dnssec")="yes";
be = BackendMakers().all()[0];
} catch (PDNSException &ex) {
BOOST_TEST_MESSAGE("Cannot start remotebackend: " << ex.reason );
};
}
~RemotebackendSetup() { }
};
BOOST_GLOBAL_FIXTURE( RemotebackendSetup );
|
fastmailops/pdns
|
modules/remotebackend/test-remotebackend-json.cc
|
C++
|
gpl-2.0
| 1,470
|
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model common\models\SearchSupplierspeople */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="supplierspeople-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'SuppliersPeopleId') ?>
<?= $form->field($model, 'UserId') ?>
<?= $form->field($model, 'SupplierId') ?>
<?= $form->field($model, 'Department') ?>
<?= $form->field($model, 'IsPrimary')->checkbox() ?>
<?php // echo $form->field($model, 'Comment') ?>
<?php // echo $form->field($model, 'created_by') ?>
<?php // echo $form->field($model, 'LastUpdatedBy') ?>
<?php // echo $form->field($model, 'created_at') ?>
<?php // echo $form->field($model, 'updated_at') ?>
<?php // echo $form->field($model, 'deleted_at') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
|
shuk08/test1
|
backend/views/supplierspeople/_search.php
|
PHP
|
gpl-2.0
| 1,154
|
<?php
/**
* JComments plugin for JUserlist
*
* @version 1.0
* @package JComments
* @author Sergey M. Litvinov (smart@joomlatune.ru)
* @copyright (C) 2010 by Sergey M. Litvinov (http://www.joomlatune.ru)
* @license GNU/GPL: http://www.gnu.org/copyleft/gpl.html
**/
class jc_com_juserlist extends JCommentsPlugin
{
function getTitles($ids)
{
$db = & JFactory::getDBO();
$db->setQuery( 'SELECT id, name as title FROM #__users WHERE id IN (' . implode(',', $ids) . ')' );
return $db->loadObjectList('id');
}
function getObjectTitle($id)
{
$db = & JFactory::getDBO();
$db->setQuery( 'SELECT name FROM #__users WHERE id = ' . $id );
return $db->loadResult();
}
function getObjectLink($id)
{
$_Itemid = JCommentsPlugin::getItemid( 'com_juserlist' );
$link = JRoute::_( 'index.php?option=com_juserlist&view=profile&id=' .$id .'&Itemid=' . $_Itemid);
return $link;
}
function getObjectOwner($id)
{
$user = & JFactory::getUser();
return $user->id;
}
}
?>
|
jbelborja/jovenes
|
components/com_jcomments/plugins/com_juserlist.plugin.php
|
PHP
|
gpl-2.0
| 1,005
|
<?php
/*
+---------------------------------------------------------------------------+
| OpenX v2.8 |
| ========== |
| |
| Copyright (c) 2003-2009 OpenX Limited |
| For contact details, see: http://www.openx.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
+---------------------------------------------------------------------------+
$Id: GlobalAdvertiser.php 81772 2012-09-11 00:07:29Z chris.nutting $
*/
require_once MAX_PATH . '/lib/OA/Admin/Statistics/Delivery/CommonEntity.php';
/**
* The class to display the delivery statistcs for the page:
*
* Statistics -> Advertisers & Campaigns
*
* @package OpenXAdmin
* @subpackage StatisticsDelivery
* @author Matteo Beccati <matteo@beccati.com>
* @author Andrew Hill <andrew.hill@openx.org>
*/
class OA_Admin_Statistics_Delivery_Controller_GlobalAdvertiser extends OA_Admin_Statistics_Delivery_CommonEntity
{
/**
* The final "child" implementation of the PHP5-style constructor.
*
* @param array $aParams An array of parameters. The array should
* be indexed by the name of object variables,
* with the values that those variables should
* be set to. For example, the parameter:
* $aParams = array('foo' => 'bar')
* would result in $this->foo = bar.
*/
function __construct($aParams)
{
// Set this page's entity/breakdown values
$this->entity = 'global';
$this->breakdown = 'advertiser';
// This page uses the day span selector element
$this->showDaySpanSelector = true;
parent::__construct($aParams);
}
/**
* PHP4-style constructor
*
* @param array $aParams An array of parameters. The array should
* be indexed by the name of object variables,
* with the values that those variables should
* be set to. For example, the parameter:
* $aParams = array('foo' => 'bar')
* would result in $this->foo = bar.
*/
function OA_Admin_Statistics_Delivery_Controller_GlobalAdvertiser($aParams)
{
$this->__construct($aParams);
}
/**
* The final "child" implementation of the parental abstract method.
*
* @see OA_Admin_Statistics_Common::start()
*/
function start()
{
// Get the preferences
$aPref = $GLOBALS['_MAX']['PREF'];
// Security check
OA_Permission::enforceAccount(OA_ACCOUNT_ADMIN, OA_ACCOUNT_MANAGER);
// HTML Framework
$this->pageId = '2.1';
$this->aPageSections = array('2.1', '2.4', '2.2');
$this->hideInactive = MAX_getStoredValue('hideinactive', ($aPref['ui_hide_inactive'] == true), null, true);
$this->showHideInactive = true;
$this->startLevel = MAX_getStoredValue('startlevel', 0, null, true);
// Init nodes
$this->aNodes = MAX_getStoredArray('nodes', array());
$expand = MAX_getValue('expand', '');
$collapse = MAX_getValue('collapse');
// Adjust which nodes are opened closed...
MAX_adjustNodes($this->aNodes, $expand, $collapse);
$aParams = $this->coreParams;
if (!OA_Permission::isAccount(OA_ACCOUNT_ADMIN)) {
$aParams['agency_id'] = OA_Permission::getAgencyId();
}
switch ($this->startLevel)
{
case 2:
$this->aEntitiesData = $this->getBanners($aParams, $this->startLevel, $expand);
break;
case 1:
$this->aEntitiesData = $this->getCampaigns($aParams, $this->startLevel, $expand);
break;
default:
$this->startLevel = 0;
$this->aEntitiesData = $this->getAdvertisers($aParams, $this->startLevel, $expand);
break;
}
// Summarise the values into a the totals array, & format
$this->_summariseTotalsAndFormat($this->aEntitiesData);
$this->showHideLevels = array();
switch ($this->startLevel)
{
case 2:
$this->showHideLevels = array(
0 => array('text' => $GLOBALS['strShowParentAdvertisers'], 'icon' => 'images/icon-advertiser.gif'),
1 => array('text' => $GLOBALS['strShowParentCampaigns'], 'icon' => 'images/icon-campaign.gif')
);
$this->hiddenEntitiesText = "{$this->hiddenEntities} {$GLOBALS['strInactiveBannersHidden']}";
break;
case 1:
$this->showHideLevels = array(
0 => array('text' => $GLOBALS['strShowParentAdvertisers'], 'icon' => 'images/icon-advertiser.gif'),
2 => array('text' => $GLOBALS['strHideParentCampaigns'], 'icon' => 'images/icon-campaign-d.gif')
);
$this->hiddenEntitiesText = "{$this->hiddenEntities} {$GLOBALS['strInactiveCampaignsHidden']}";
break;
case 0:
$this->showHideLevels = array(
1 => array('text' => $GLOBALS['strHideParentAdvertisers'], 'icon' => 'images/icon-advertiser-d.gif'),
2 => array('text' => $GLOBALS['strHideParentCampaigns'], 'icon' => 'images/icon-campaign-d.gif')
);
$this->hiddenEntitiesText = "{$this->hiddenEntities} {$GLOBALS['strInactiveAdvertisersHidden']}";
break;
}
// Location params
$this->aPageParams['period_preset'] = MAX_getStoredValue('period_preset', 'today');
$this->aPageParams['statsBreakdown'] = htmlspecialchars(MAX_getStoredValue('statsBreakdown', 'day'));
$this->aPageParams['period_start'] = htmlspecialchars(MAX_getStoredValue('period_start', date('Y-m-d')));
$this->aPageParams['period_end'] = htmlspecialchars(MAX_getStoredValue('period_end', date('Y-m-d')));
$this->_loadParams();
unset($this->aPageParams['expand']);
unset($this->aPageParams['clientid']);
unset($this->aPageParams['collapse']);
// Save preferences
$this->aPagePrefs['startlevel'] = $this->startLevel;
$this->aPagePrefs['nodes'] = implode (",", $this->aNodes);
$this->aPagePrefs['hideinactive'] = $this->hideInactive;
$this->aPagePrefs['startlevel'] = $this->startLevel;
}
}
?>
|
webonise/openx
|
lib/OA/Admin/Statistics/Delivery/Controller/GlobalAdvertiser.php
|
PHP
|
gpl-2.0
| 7,854
|
/*
* This file is part of the coreboot project.
*
* Copyright 2015 MediaTek 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; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <boardid.h>
#include <gpio.h>
#include <console/console.h>
#include <stdlib.h>
#include "gpio.h"
static int board_id_value = -1;
static uint8_t get_board_id(void)
{
uint8_t bid = 0;
static gpio_t pins[] = {[2] = BOARD_ID_2, [1] = BOARD_ID_1,
[0] = BOARD_ID_0};
bid = gpio_base2_value(pins, ARRAY_SIZE(pins));
printk(BIOS_INFO, "Board ID %d\n", bid);
return bid;
}
uint32_t board_id(void)
{
if (board_id_value < 0)
board_id_value = get_board_id();
return board_id_value;
}
uint32_t ram_code(void)
{
uint32_t code;
static gpio_t pins[] = {[3] = RAM_ID_3, [2] = RAM_ID_2, [1] = RAM_ID_1,
[0] = RAM_ID_0};
code = gpio_base2_value(pins, ARRAY_SIZE(pins));
printk(BIOS_INFO, "RAM Config: %u\n", code);
return code;
}
|
MattDevo/coreboot
|
src/mainboard/google/oak/boardid.c
|
C
|
gpl-2.0
| 1,293
|
/*
* JMPocket - JuggleMaster for Pocket PC
* Version 1.03
* (C) Per Johan Groland 2002-2004
*
* Using JMLib 2.0 (C) Per Johan Groland 2000-2002
* Based on JuggleMaster Version 1.60
* Copyright (C) 1995-1996 Ken Matsuoka
*
* JMPocket 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.
*
*/
#include "stdafx.h"
#include "resource.h"
#include "entersitedlg.h"
#include "MFCUtil.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
int startChar = 0, endChar = 0;
JMEnterSiteDlg::JMEnterSiteDlg(JMRegPreferences* _prefs, JMLib* _jmlib, CWnd* pParent /*=NULL*/)
: CDialog(JMEnterSiteDlg::IDD, pParent) {
//{{AFX_DATA_INIT(JMEnterSiteDlg)
dwellRatio = DR_DEF;
heightRatio = 0.20f;
site = _T("");
//}}AFX_DATA_INIT
prefs = _prefs;
jmlib = _jmlib;
}
void JMEnterSiteDlg::DoDataExchange(CDataExchange* pDX) {
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(JMEnterSiteDlg)
DDX_Control(pDX, IDC_STYLE, styleList);
DDX_Control(pDX, IDC_SITE, siteList);
DDX_Text(pDX, IDC_DR, dwellRatio);
DDX_Text(pDX, IDC_HR, heightRatio);
DDX_CBString(pDX, IDC_SITE, site);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(JMEnterSiteDlg, CDialog)
//{{AFX_MSG_MAP(JMEnterSiteDlg)
ON_WM_PAINT()
ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_DR, OnDeltaposSpinDr)
ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_HR, OnDeltaposSpinHr)
ON_COMMAND_RANGE(IDC_SHORTCUT1, IDC_SHORTCUT6, OnShortcut)
ON_WM_CTLCOLOR()
ON_CBN_EDITCHANGE(IDC_SITE, OnEditchangeSite)
ON_CBN_SELENDOK(IDC_SITE, OnSelendokSite)
ON_CBN_EDITUPDATE(IDC_SITE, OnEditupdateSite)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
void JMEnterSiteDlg::OnPaint() {
PAINTSTRUCT ps;
CDC* pDC = BeginPaint(&ps);
paintDialogHeader(pDC, _T("Enter Siteswap"));
EndPaint(&ps);
}
void JMEnterSiteDlg::OnDeltaposSpinDr(NMHDR* pNMHDR, LRESULT* pResult) {
UpdateData(TRUE);
NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
float delta = pNMUpDown->iDelta * -0.01F;
dwellRatio += delta;
if (dwellRatio < DR_MIN)
dwellRatio = DR_MIN;
if (dwellRatio > DR_MAX)
dwellRatio = DR_MAX;
UpdateData(FALSE);
*pResult = 0;
}
void JMEnterSiteDlg::OnDeltaposSpinHr(NMHDR* pNMHDR, LRESULT* pResult) {
UpdateData(TRUE);
NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
float delta = pNMUpDown->iDelta * -0.01F;
heightRatio += delta;
if (heightRatio < HR_MIN)
heightRatio = HR_MIN;
if (heightRatio > HR_MAX)
heightRatio = HR_MAX;
UpdateData(FALSE);
*pResult = 0;
}
BOOL JMEnterSiteDlg::OnInitDialog() {
USES_CONVERSION;
CDialog::OnInitDialog();
SET_HEADER;
int i;
#if defined(_WIN32_WCE_PSPC) && (_WIN32_WCE >= 300)
SHSipPreference(GetSafeHwnd(), SIP_UP);
#endif
redColor = RGB(255, 0, 0);
redBrush.CreateSolidBrush(redColor);
greenColor = RGB(0, 255, 0);
greenBrush.CreateSolidBrush(greenColor);
activeColor = redColor;
activeBrush = &redBrush;
//JML_CHAR **getStyles(void);
//JML_INT32 numStyles();
JML_CHAR** styles = jmlib->getStyles();
CString c;
styleList.ResetContent();
for (i = 0; i < jmlib->numStyles(); i++) {
c = styles[i];
styleList.AddString(c);
}
styleList.SetCurSel(0);
/* obsolete manual adding of styles
styleList.ResetContent();
styleList.AddString(_T("Normal"));
styleList.AddString(_T("Reverse"));
styleList.AddString(_T("Shower"));
styleList.AddString(_T("Mills Mess"));
styleList.AddString(_T("Center"));
styleList.AddString(_T("Windmill"));
styleList.AddString(_T("Random"));
styleList.SetCurSel(0);
*/
// Use SetItemData / GetItemData to retrieve the styleList offset
// (style selected) for the site!
siteList.ResetContent();
for (i = 0; i < prefs->getMRULen(); i++) {
CString MRUItem = A2W(prefs->getMRUAt(i));
siteList.AddString(MRUItem);
}
UpdateData(FALSE);
OnEditchangeSite();
GotoDlgCtrl(&siteList);
return FALSE; // return TRUE unless you set the focus to a control
}
void JMEnterSiteDlg::OnShortcut(UINT nID) {
static char inserted[] = { '(', ')', '[', ']', ',', 'x' };
int offset = nID - IDC_SHORTCUT1;
UpdateData(TRUE);
CString newSite;
newSite = site.Mid(0, startChar) + inserted[offset] + site.Mid(endChar);
site = newSite;
startChar++;
endChar = startChar;
UpdateData(FALSE);
}
void JMEnterSiteDlg::OnOK() {
USES_CONVERSION;
// Retrieve data
UpdateData(TRUE);
styleList.GetLBText(styleList.GetCurSel(), style);
char* csite = W2A(site.GetBuffer(0));
// Validate site
if (!JMSiteValidator::validateSite(csite)) {
AfxMessageBox(_T("Invalid siteswap"));
site.ReleaseBuffer();
return;
}
prefs->addToMRU(csite);
site.ReleaseBuffer();
/*
CEdit* siteListEdit = (CEdit*)(GetDlgItem(IDC_SITE)->GetWindow(GW_CHILD));
siteListEdit->GetLine(0, site.GetBuffer(0));
site.ReleaseBuffer();
*/
CDialog::OnOK();
}
HBRUSH JMEnterSiteDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) {
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
if (!prefs->getIntPref(PREF_COLOR_CODES))
return hbr;
CEdit* siteListEdit = (CEdit*)(GetDlgItem(IDC_SITE)->GetWindow(GW_CHILD));
if (pWnd->GetDlgCtrlID() == IDC_SITE) {
pDC->SetBkColor(activeColor);
pDC->SetBkMode(TRANSPARENT);
return *activeBrush;
}
/* setting text color for edit box does not work
if (pWnd->GetSafeHwnd() == siteListEdit->GetSafeHwnd()) {
// Set the text color to red.
pDC->SetTextColor(greenColor);
// Set the background mode for text to transparent
// so background will show thru.
//pDC->SetBkMode(TRANSPARENT);
pDC->SetBkColor(greenColor);
return greenBrush;
}
*/
return hbr;
}
// Trigger color change when the user enters a site
void JMEnterSiteDlg::OnEditchangeSite() {
USES_CONVERSION;
// Retrieve data
UpdateData(TRUE);
char* csite = W2A(site.GetBuffer(0));
// Validate site
if (JMSiteValidator::validateSite(csite)) {
activeColor = greenColor;
activeBrush = &greenBrush;
}
else {
activeColor = redColor;
activeBrush = &redBrush;
}
site.ReleaseBuffer();
siteList.Invalidate();
}
// Trigger color change when the site combo box's selection changes
void JMEnterSiteDlg::OnSelendokSite() {
USES_CONVERSION;
CString lsite;
siteList.GetLBText(siteList.GetCurSel(), lsite);
char* csite = W2A(lsite.GetBuffer(0));
// Validate site
if (JMSiteValidator::validateSite(csite)) {
activeColor = greenColor;
activeBrush = &greenBrush;
}
else {
activeColor = redColor;
activeBrush = &redBrush;
}
lsite.ReleaseBuffer();
siteList.Invalidate();
}
void JMEnterSiteDlg::OnEditupdateSite() {
// Save position in edit box
int foo = siteList.GetEditSel();
startChar = LOWORD(foo);
endChar = HIWORD(foo);
}
|
amiel/jugglemaster
|
src/jmpocket/entersitedlg.cpp
|
C++
|
gpl-2.0
| 7,173
|
from __future__ import absolute_import
from Plugins.Plugin import PluginDescriptor
from Components.PluginComponent import plugins
from enigma import eDBoxLCD
from .qpip import QuadPipScreen, setDecoderMode
def main(session, **kwargs):
session.open(QuadPipScreen)
def autoStart(reason, **kwargs):
if reason == 0:
setDecoderMode("normal")
elif reason == 1:
pass
def Plugins(**kwargs):
list = []
list.append(
PluginDescriptor(name=_("Enable Quad PIP"),
description="Quad Picture in Picture",
where=[PluginDescriptor.WHERE_EXTENSIONSMENU],
fnc=main))
list.append(
PluginDescriptor(
where=[PluginDescriptor.WHERE_AUTOSTART],
fnc=autoStart))
return list
|
openatv/enigma2
|
lib/python/Plugins/Extensions/QuadPip/plugin.py
|
Python
|
gpl-2.0
| 682
|
/*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _WORLDMODEL_H
#define _WORLDMODEL_H
#include <G3D/Vector3.h>
#include <G3D/AABox.h>
#include <G3D/Ray.h>
#include "BoundingIntervalHierarchy.h"
#include "Define.h"
namespace VMAP
{
class TreeNode;
struct AreaInfo;
struct LocationInfo;
enum class ModelIgnoreFlags : uint32;
class TC_COMMON_API MeshTriangle
{
public:
MeshTriangle() : idx0(0), idx1(0), idx2(0) { }
MeshTriangle(uint32 na, uint32 nb, uint32 nc): idx0(na), idx1(nb), idx2(nc) { }
uint32 idx0;
uint32 idx1;
uint32 idx2;
};
class TC_COMMON_API WmoLiquid
{
public:
WmoLiquid(uint32 width, uint32 height, G3D::Vector3 const& corner, uint32 type);
WmoLiquid(WmoLiquid const& other);
~WmoLiquid();
WmoLiquid& operator=(WmoLiquid const& other);
bool GetLiquidHeight(G3D::Vector3 const& pos, float& liqHeight) const;
uint32 GetType() const { return iType; }
float *GetHeightStorage() { return iHeight; }
uint8 *GetFlagsStorage() { return iFlags; }
uint32 GetFileSize();
bool writeToFile(FILE* wf);
static bool readFromFile(FILE* rf, WmoLiquid* &liquid);
void getPosInfo(uint32 &tilesX, uint32 &tilesY, G3D::Vector3 &corner) const;
private:
WmoLiquid() : iTilesX(0), iTilesY(0), iCorner(), iType(0), iHeight(nullptr), iFlags(nullptr) { }
uint32 iTilesX; //!< number of tiles in x direction, each
uint32 iTilesY;
G3D::Vector3 iCorner; //!< the lower corner
uint32 iType; //!< liquid type
float *iHeight; //!< (tilesX + 1)*(tilesY + 1) height values
uint8 *iFlags; //!< info if liquid tile is used
};
/*! holding additional info for WMO group files */
class TC_COMMON_API GroupModel
{
public:
GroupModel() : iBound(), iMogpFlags(0), iGroupWMOID(0), iLiquid(nullptr) { }
GroupModel(GroupModel const& other);
GroupModel(uint32 mogpFlags, uint32 groupWMOID, G3D::AABox const& bound):
iBound(bound), iMogpFlags(mogpFlags), iGroupWMOID(groupWMOID), iLiquid(nullptr) { }
~GroupModel() { delete iLiquid; }
//! pass mesh data to object and create BIH. Passed vectors get get swapped with old geometry!
void setMeshData(std::vector<G3D::Vector3> &vert, std::vector<MeshTriangle> &tri);
void setLiquidData(WmoLiquid*& liquid) { iLiquid = liquid; liquid = nullptr; }
bool IntersectRay(const G3D::Ray &ray, float &distance, bool stopAtFirstHit) const;
bool IsInsideObject(const G3D::Vector3 &pos, const G3D::Vector3 &down, float &z_dist) const;
bool GetLiquidLevel(const G3D::Vector3 &pos, float &liqHeight) const;
uint32 GetLiquidType() const;
bool writeToFile(FILE* wf);
bool readFromFile(FILE* rf);
const G3D::AABox& GetBound() const { return iBound; }
uint32 GetMogpFlags() const { return iMogpFlags; }
uint32 GetWmoID() const { return iGroupWMOID; }
void getMeshData(std::vector<G3D::Vector3>& outVertices, std::vector<MeshTriangle>& outTriangles, WmoLiquid*& liquid);
protected:
G3D::AABox iBound;
uint32 iMogpFlags;// 0x8 outdor; 0x2000 indoor
uint32 iGroupWMOID;
std::vector<G3D::Vector3> vertices;
std::vector<MeshTriangle> triangles;
BIH meshTree;
WmoLiquid* iLiquid;
};
/*! Holds a model (converted M2 or WMO) in its original coordinate space */
class TC_COMMON_API WorldModel
{
public:
WorldModel(): Flags(0), RootWMOID(0) { }
//! pass group models to WorldModel and create BIH. Passed vector is swapped with old geometry!
void setGroupModels(std::vector<GroupModel> &models);
void setRootWmoID(uint32 id) { RootWMOID = id; }
bool IntersectRay(const G3D::Ray &ray, float &distance, bool stopAtFirstHit, ModelIgnoreFlags ignoreFlags) const;
bool IntersectPoint(const G3D::Vector3 &p, const G3D::Vector3 &down, float &dist, AreaInfo &info) const;
bool GetLocationInfo(const G3D::Vector3 &p, const G3D::Vector3 &down, float &dist, LocationInfo &info) const;
bool writeFile(const std::string &filename);
bool readFile(const std::string &filename);
void getGroupModels(std::vector<GroupModel>& outGroupModels);
std::string const& GetName() const { return name; }
void SetName(std::string newName) { name = std::move(newName); }
uint32 Flags;
protected:
uint32 RootWMOID;
std::vector<GroupModel> groupModels;
BIH groupTree;
std::string name;
};
} // namespace VMAP
#endif // _WORLDMODEL_H
|
Shauren/TrinityCore
|
src/common/Collision/Models/WorldModel.h
|
C
|
gpl-2.0
| 5,760
|
/*
* Joe's tiny RCU, for small SMP systems.
*
* See Documentation/RCU/jrcu.txt for theory of operation and design details.
*
* Author: Joe Korty <joe.korty@ccur.com>
*
* Acknowledgements: Paul E. McKenney's 'TinyRCU for uniprocessors' inspired
* the thought that there could could be something similiarly simple for SMP.
* The rcu_list chain operators are from Jim Houston's Alternative RCU.
*
* Copyright Concurrent Computer Corporation, 2011-2012.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/*
* This RCU maintains three callback lists: the current batch (per cpu),
* the previous batch (also per cpu), and the pending list (global).
*/
#include <linux/bug.h>
#include <linux/smp.h>
#include <linux/slab.h>
#include <linux/ctype.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/percpu.h>
#include <linux/stddef.h>
#include <linux/string.h>
#include <linux/preempt.h>
#include <linux/uaccess.h>
#include <linux/compiler.h>
#include <linux/irqflags.h>
#include <linux/rcupdate.h>
#include <asm/system.h>
/*
* Define an rcu list type and operators. An rcu list has only ->next
* pointers for the chain nodes; the list head however is special and
* has pointers to both the first and last nodes of the chain. Tweaked
* so that null head, tail pointers can be used to signify an empty list.
*/
struct rcu_list {
struct rcu_head *head;
struct rcu_head **tail;
int count; /* stats-n-debug */
};
static inline void rcu_list_init(struct rcu_list *l)
{
l->head = NULL;
l->tail = NULL;
l->count = 0;
}
/*
* Add an element to the tail of an rcu list
*/
static inline void rcu_list_add(struct rcu_list *l, struct rcu_head *h)
{
if (unlikely(l->tail == NULL))
l->tail = &l->head;
*l->tail = h;
l->tail = &h->next;
l->count++;
h->next = NULL;
}
/*
* Append the contents of one rcu list to another. The 'from' list is left
* corrupted on exit; the caller must re-initialize it before it can be used
* again.
*/
static inline void rcu_list_join(struct rcu_list *to, struct rcu_list *from)
{
if (from->head) {
if (unlikely(to->tail == NULL)) {
to->tail = &to->head;
to->count = 0;
}
*to->tail = from->head;
to->tail = from->tail;
to->count += from->count;
}
}
/*
* selects, in ->cblist[] below, which is the current callback list and which
* is the previous.
*/
static u8 rcu_which ____cacheline_aligned_in_smp;
struct rcu_data {
u8 wait; /* goes false when this cpu consents to
* the retirement of the current batch */
struct rcu_list cblist[2]; /* current & previous callback lists */
raw_spinlock_t lock; /* protects the above callback lists */
s64 nqueued; /* #callbacks queued (stats-n-debug) */
} ____cacheline_aligned_in_smp;
static struct rcu_data rcu_data[NR_CPUS];
/* debug & statistics stuff */
static struct rcu_stats {
unsigned npasses; /* #passes made */
unsigned nlast; /* #passes since last end-of-batch */
unsigned nbatches; /* #end-of-batches (eobs) seen */
unsigned nmis; /* #passes discarded due to NMI */
atomic_t nbarriers; /* #rcu barriers processed */
atomic_t nsyncs; /* #rcu syncs processed */
s64 ninvoked; /* #invoked (ie, finished) callbacks */
unsigned nforced; /* #forced eobs (should be zero) */
} rcu_stats;
#define RCU_HZ (20)
#define RCU_HZ_PERIOD_US (USEC_PER_SEC / RCU_HZ)
#define RCU_HZ_DELTA_US (USEC_PER_SEC / HZ)
static int rcu_hz_period_us = RCU_HZ_PERIOD_US;
static int rcu_hz_delta_us = RCU_HZ_DELTA_US;
static int rcu_hz_precise;
int rcu_scheduler_active __read_mostly;
int rcu_nmi_seen __read_mostly;
static int rcu_wdog_ctr; /* time since last end-of-batch, in usecs */
static int rcu_wdog_lim = 10 * USEC_PER_SEC; /* rcu watchdog interval */
/*
* Return our CPU id or zero if we are too early in the boot process to
* know what that is. For RCU to work correctly, a cpu named '0' must
* eventually be present (but need not ever be online).
*/
#ifdef HAVE_THREAD_INFO_CPU
static inline int rcu_cpu(void)
{
return current_thread_info()->cpu;
}
#else
static unsigned rcu_cpu_early_flag __read_mostly = 1;
static inline int rcu_cpu(void)
{
if (unlikely(rcu_cpu_early_flag)) {
if (!(rcu_scheduler_active && nr_cpu_ids > 1))
return 0;
rcu_cpu_early_flag = 0;
}
return raw_smp_processor_id();
}
#endif /* HAVE_THREAD_INFO_CPU */
/*
* Invoke whenever the calling CPU consents to end-of-batch. All CPUs
* must so consent before the batch is truly ended.
*/
static inline void rcu_eob(int cpu)
{
struct rcu_data *rd = &rcu_data[cpu];
xchg(&rd->wait, 0);
}
void jrcu_read_unlock(void)
{
if (preempt_count() == 1)
rcu_eob(rcu_cpu());
preempt_enable();
}
EXPORT_SYMBOL_GPL(jrcu_read_unlock);
void rcu_note_context_switch(int cpu)
{
rcu_eob(cpu);
}
EXPORT_SYMBOL_GPL(rcu_note_context_switch);
void rcu_note_might_resched(void)
{
preempt_disable();
rcu_eob(rcu_cpu());
preempt_enable();
}
EXPORT_SYMBOL(rcu_note_might_resched);
void synchronize_sched(void)
{
struct rcu_synchronize rcu;
if (!rcu_scheduler_active)
return;
init_completion(&rcu.completion);
call_rcu(&rcu.head, wakeme_after_rcu);
wait_for_completion(&rcu.completion);
atomic_inc(&rcu_stats.nsyncs);
}
EXPORT_SYMBOL_GPL(synchronize_sched);
void rcu_barrier(void)
{
synchronize_sched();
synchronize_sched();
atomic_inc(&rcu_stats.nbarriers);
}
EXPORT_SYMBOL_GPL(rcu_barrier);
void rcu_force_quiescent_state(void)
{
}
EXPORT_SYMBOL_GPL(rcu_force_quiescent_state);
/*
* Insert an RCU callback onto the calling CPUs list of 'current batch'
* callbacks. Lockless version, can be invoked anywhere except under NMI.
*/
void call_rcu_sched(struct rcu_head *cb, void (*func)(struct rcu_head *rcu))
{
unsigned long flags;
struct rcu_data *rd;
struct rcu_list *cblist;
int which;
cb->func = func;
cb->next = NULL;
raw_local_irq_save(flags);
rd = &rcu_data[rcu_cpu()];
raw_spin_lock(&rd->lock);
which = ACCESS_ONCE(rcu_which);
cblist = &rd->cblist[which];
/* The following is not NMI-safe, therefore call_rcu()
* cannot be invoked under NMI. */
rcu_list_add(cblist, cb);
rd->nqueued++;
raw_spin_unlock(&rd->lock);
raw_local_irq_restore(flags);
}
EXPORT_SYMBOL_GPL(call_rcu_sched);
/*
* Invoke all callbacks on the passed-in list.
*/
static void rcu_invoke_callbacks(struct rcu_list *pending)
{
struct rcu_head *curr, *next;
for (curr = pending->head; curr;) {
unsigned long offset = (unsigned long)curr->func;
next = curr->next;
if (__is_kfree_rcu_offset(offset))
kfree((void *)curr - offset);
else
curr->func(curr);
curr = next;
rcu_stats.ninvoked++;
}
}
/*
* Check if the conditions for ending the current batch are true. If
* so then end it.
*
* Must be invoked periodically, and the periodic invocations must be
* far enough apart in time for the previous batch to become quiescent.
* This is a few tens of microseconds unless NMIs are involved; an NMI
* stretches out the requirement by the duration of the NMI.
*
* "Quiescent" means the owning cpu is no longer appending callbacks
* and has completed execution of a trailing write-memory-barrier insn.
*/
static void __rcu_delimit_batches(struct rcu_list *pending)
{
struct rcu_data *rd;
struct rcu_list *plist;
int cpu, eob, prev;
if (!rcu_scheduler_active)
return;
rcu_stats.nlast++;
/* If an NMI occured then the previous batch may not yet be
* quiescent. Let's wait till it is.
*/
if (rcu_nmi_seen) {
rcu_nmi_seen = 0;
rcu_stats.nmis++;
return;
}
/*
* Find out if the current batch has ended
* (end-of-batch).
*/
eob = 1;
for_each_online_cpu(cpu) {
rd = &rcu_data[cpu];
if (rd->wait) {
rd->wait = preempt_count_cpu(cpu) > idle_cpu(cpu);
if (rd->wait) {
eob = 0;
break;
}
}
}
/*
* Exit if batch has not ended. But first, tickle all non-cooperating
* CPUs if enough time has passed.
*/
if (eob == 0) {
if (rcu_wdog_ctr >= rcu_wdog_lim) {
rcu_wdog_ctr = 0;
rcu_stats.nforced++;
for_each_online_cpu(cpu) {
if (rcu_data[cpu].wait)
force_cpu_resched(cpu);
}
}
rcu_wdog_ctr += rcu_hz_period_us;
return;
}
/*
* End the current RCU batch and start a new one.
*
* This is a two-step operation: move every cpu's previous list
* to the global pending list, then tell every cpu to swap its
* current and pending lists (ie, toggle rcu_which).
*
* We tolerate the cpus taking a bit of time noticing this swap;
* we expect them to continue to put callbacks on the old current
* list (which is now the previous list) for a while. That time,
* however, cannot exceed one RCU_HZ period.
*/
prev = ACCESS_ONCE(rcu_which) ^ 1;
for_each_present_cpu(cpu) {
rd = &rcu_data[cpu];
plist = &rd->cblist[prev];
raw_spin_lock(&rd->lock);
/* Chain previous batch of callbacks, if any, to the pending list */
if (plist->head) {
rcu_list_join(pending, plist);
rcu_list_init(plist);
}
raw_spin_unlock(&rd->lock);
if (cpu_online(cpu)) /* wins race with offlining every time */
rd->wait = preempt_count_cpu(cpu) > idle_cpu(cpu);
else
rd->wait = 0;
}
/*
* Swap current and previous lists. The other cpus must not
* see this out-of-order w.r.t. the above emptying of each cpu's
* previous list. The xchg accomplishes that and, as a side (but
* seemingly unneeded) bonus, keeps this cpu from advancing its insn
* counter until the results of that xchg are visible on other cpus.
*/
xchg(&rcu_which, prev); /* only place where rcu_which is written to */
rcu_stats.nbatches++;
rcu_stats.nlast = 0;
rcu_wdog_ctr = 0;
}
static void rcu_delimit_batches(void)
{
unsigned long flags;
struct rcu_list pending;
raw_local_irq_save(flags);
rcu_list_init(&pending);
rcu_stats.npasses++;
__rcu_delimit_batches(&pending);
raw_local_irq_restore(flags);
if (pending.head)
rcu_invoke_callbacks(&pending);
}
/* ------------------ interrupt driver section ------------------ */
/*
* We drive RCU from a periodic interrupt during most of boot. Once boot
* is complete we (optionally) transition to a daemon.
*/
#include <linux/time.h>
#include <linux/delay.h>
#include <linux/hrtimer.h>
#include <linux/interrupt.h>
#define rcu_hz_period_ns (rcu_hz_period_us * NSEC_PER_USEC)
#define rcu_hz_delta_ns (rcu_hz_delta_us * NSEC_PER_USEC)
static struct hrtimer rcu_timer;
static void rcu_softirq_func(struct softirq_action *h)
{
rcu_delimit_batches();
}
static enum hrtimer_restart rcu_timer_func(struct hrtimer *t)
{
ktime_t next;
raise_softirq(RCU_SOFTIRQ);
next = ktime_add_ns(ktime_get(), rcu_hz_period_ns);
hrtimer_set_expires_range_ns(&rcu_timer, next,
rcu_hz_precise ? 0 : rcu_hz_delta_ns);
return HRTIMER_RESTART;
}
static void rcu_timer_start(void)
{
hrtimer_forward_now(&rcu_timer, ns_to_ktime(rcu_hz_period_ns));
hrtimer_start_expires(&rcu_timer, HRTIMER_MODE_ABS);
}
static __init void rcu_timer_init(void)
{
open_softirq(RCU_SOFTIRQ, rcu_softirq_func);
hrtimer_init(&rcu_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
rcu_timer.function = rcu_timer_func;
}
#ifdef CONFIG_JRCU_DAEMON
static void rcu_timer_stop(void)
{
hrtimer_cancel(&rcu_timer);
}
#endif
void __init rcu_scheduler_starting(void)
{
rcu_timer_init();
}
#ifndef CONFIG_JRCU_DAEMON
void __init int rcu_start_callback_processing(void)
{
int cpu;
for_each_possible_cpu(cpu)
raw_spin_lock_init(&rcu_data[cpu].lock);
rcu_timer_start();
rcu_scheduler_active = 1;
pr_info("JRCU: callback processing via timer has started.\n");
return 0;
}
#else /* CONFIG_JRCU_DAEMON */
/* ------------------ daemon driver section --------------------- */
/*
* Once the system is fully up, we will drive the periodic-polling part
* of JRCU from a kernel daemon, jrcud. Until then it is driven by
* an interrupt.
*/
#include <linux/err.h>
#include <linux/param.h>
#include <linux/kthread.h>
static int rcu_priority;
static struct task_struct *rcu_daemon;
static int jrcu_set_priority(int priority)
{
struct sched_param param;
if (priority == 0) {
set_user_nice(current, -19);
return 0;
}
if (priority < 0)
param.sched_priority = MAX_USER_RT_PRIO + priority;
else
param.sched_priority = priority;
sched_setscheduler_nocheck(current, SCHED_RR, ¶m);
return param.sched_priority;
}
static int jrcud_func(void *arg)
{
current->flags |= PF_NOFREEZE;
rcu_priority = jrcu_set_priority(CONFIG_JRCU_DAEMON_PRIO);
rcu_timer_stop();
pr_info("JRCU: callback processing via daemon started.\n");
while (!kthread_should_stop()) {
if (rcu_hz_precise) {
usleep_range(rcu_hz_period_us,
rcu_hz_period_us);
} else {
usleep_range(rcu_hz_period_us,
rcu_hz_period_us + rcu_hz_delta_us);
}
rcu_delimit_batches();
}
pr_info("JRCU: replaced callback daemon with a timer.\n");
rcu_daemon = NULL;
rcu_timer_start();
return 0;
}
static __init int rcu_start_callback_processing(void)
{
struct task_struct *p;
int cpu;
for_each_possible_cpu(cpu)
raw_spin_lock_init(&rcu_data[cpu].lock);
p = kthread_run(jrcud_func, NULL, "jrcud");
if (IS_ERR(p)) {
pr_warn("JRCU: cannot replace callback timer with a daemon\n");
return -ENODEV;
}
rcu_daemon = p;
rcu_scheduler_active = 1;
pr_info("JRCU: callback processing now allowed.\n");
return 0;
}
#endif /* CONFIG_JRCU_DAEMON */
subsys_initcall_sync(rcu_start_callback_processing);
/* ------------------ debug and statistics section -------------- */
#ifdef CONFIG_DEBUG_FS
#include <linux/debugfs.h>
#include <linux/seq_file.h>
static int rcu_hz = RCU_HZ;
static int rcu_debugfs_show(struct seq_file *m, void *unused)
{
int cpu, q;
s64 nqueued;
nqueued = 0;
for_each_present_cpu(cpu)
nqueued += rcu_data[cpu].nqueued;
seq_printf(m, "%14u: hz, %s\n",
rcu_hz,
rcu_hz_precise ? "precise" : "sloppy");
seq_printf(m, "%14u: watchdog (secs)\n", rcu_wdog_lim / (int)USEC_PER_SEC);
seq_printf(m, "%14d: #secs left on watchdog\n",
(rcu_wdog_lim - rcu_wdog_ctr) / (int)USEC_PER_SEC);
#ifdef CONFIG_JRCU_DAEMON
if (rcu_daemon)
seq_printf(m, "%14u: daemon priority\n", rcu_priority);
else
seq_printf(m, "%14s: daemon priority\n", "none, no daemon");
#endif
seq_printf(m, "\n");
seq_printf(m, "%14u: #passes\n",
rcu_stats.npasses);
seq_printf(m, "%14u: #passes discarded due to NMI\n",
rcu_stats.nmis);
seq_printf(m, "%14u: #passes resulting in end-of-batch\n",
rcu_stats.nbatches);
seq_printf(m, "%14u: #passes not resulting in end-of-batch\n",
rcu_stats.npasses - rcu_stats.nbatches);
seq_printf(m, "%14u: #passes since last end-of-batch\n",
rcu_stats.nlast);
seq_printf(m, "%14u: #passes forced (0 is best)\n",
rcu_stats.nforced);
seq_printf(m, "\n");
seq_printf(m, "%14u: #barriers\n",
atomic_read(&rcu_stats.nbarriers));
seq_printf(m, "%14u: #syncs\n",
atomic_read(&rcu_stats.nsyncs));
seq_printf(m, "%14llu: #callbacks invoked\n",
rcu_stats.ninvoked);
seq_printf(m, "%14d: #callbacks left to invoke\n",
(int)(nqueued - rcu_stats.ninvoked));
seq_printf(m, "\n");
for_each_online_cpu(cpu)
seq_printf(m, "%4d ", cpu);
seq_printf(m, " CPU\n");
for_each_online_cpu(cpu) {
struct rcu_data *rd = &rcu_data[cpu];
seq_printf(m, "--%c%c ",
idle_cpu(cpu) ? 'I' : '-',
rd->wait ? 'W' : '-');
}
seq_printf(m, " FLAGS\n");
for (q = 0; q < 2; q++) {
int w = ACCESS_ONCE(rcu_which);
for_each_online_cpu(cpu) {
struct rcu_data *rd = &rcu_data[cpu];
struct rcu_list *l = &rd->cblist[q];
seq_printf(m, "%4d ", l->count);
}
seq_printf(m, " Q%d%c\n", q, " *"[q == w]);
}
seq_printf(m, "\nFLAGS:\n");
seq_printf(m, " I - cpu idle, W - cpu waiting for end-of-batch,\n");
seq_printf(m, " * - the current Q, other is the previous Q.\n");
return 0;
}
static ssize_t rcu_debugfs_write(struct file *file,
const char __user *buffer, size_t count, loff_t *ppos)
{
int i, j, c;
char token[32];
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (count <= 0)
return count;
if (!access_ok(VERIFY_READ, buffer, count))
return -EFAULT;
i = 0;
if (__get_user(c, &buffer[i++]))
return -EFAULT;
next:
/* Token extractor -- first, skip leading whitepace */
while (c && isspace(c) && i < count) {
if (__get_user(c, &buffer[i++]))
return -EFAULT;
}
if (i >= count || c == 0)
return count; /* all done, no more tokens */
j = 0;
do {
if (j == (sizeof(token) - 1))
return -EINVAL;
token[j++] = c;
if (__get_user(c, &buffer[i++]))
return -EFAULT;
} while (c && !isspace(c) && i < count); /* extract next token */
token[j++] = 0;
if (!strncmp(token, "hz=", 3)) {
int rcu_hz_wanted = -1;
sscanf(&token[3], "%d", &rcu_hz_wanted);
if (rcu_hz_wanted < 2 || rcu_hz_wanted > 1000)
return -EINVAL;
rcu_hz = rcu_hz_wanted;
rcu_hz_period_us = USEC_PER_SEC / rcu_hz;
} else if (!strncmp(token, "precise=", 8)) {
sscanf(&token[8], "%d", &rcu_hz_precise);
} else if (!strncmp(token, "wdog=", 5)) {
int wdog = -1;
sscanf(&token[5], "%d", &wdog);
if (wdog < 3 || wdog > 1000)
return -EINVAL;
rcu_wdog_lim = wdog * USEC_PER_SEC;
} else
return -EINVAL;
goto next;
}
static int rcu_debugfs_open(struct inode *inode, struct file *file)
{
return single_open(file, rcu_debugfs_show, NULL);
}
static const struct file_operations rcu_debugfs_fops = {
.owner = THIS_MODULE,
.open = rcu_debugfs_open,
.read = seq_read,
.write = rcu_debugfs_write,
.llseek = seq_lseek,
.release = single_release,
};
static struct dentry *rcudir;
static int __init rcu_debugfs_init(void)
{
struct dentry *retval;
rcudir = debugfs_create_dir("rcu", NULL);
if (!rcudir)
goto error;
retval = debugfs_create_file("rcudata", 0644, rcudir,
NULL, &rcu_debugfs_fops);
if (!retval)
goto error;
return 0;
error:
debugfs_remove_recursive(rcudir);
pr_warn("JRCU: Could not create debugfs files.\n");
return -ENOSYS;
}
late_initcall(rcu_debugfs_init);
#endif /* CONFIG_DEBUG_FS */
|
JoinTheRealms/TF700-dualboot-hunds
|
kernel/jrcu.c
|
C
|
gpl-2.0
| 21,948
|
/*
* Copyright (C) 2012-2021 52°North Spatial Information Research GmbH
*
* 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.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* License version 2 and the aforementioned licenses.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*/
package org.n52.sos.ds.hibernate.util.procedure.create;
import java.util.Locale;
import org.hibernate.Session;
import org.n52.series.db.beans.ProcedureEntity;
import org.n52.shetland.ogc.ows.exception.OwsExceptionReport;
import org.n52.shetland.ogc.sos.SosProcedureDescription;
import org.n52.sos.ds.hibernate.util.procedure.HibernateProcedureCreationContext;
import com.google.common.base.Predicate;
/**
* Strategy pattern to create {@link SosProcedureDescription}.
*/
public interface DescriptionCreationStrategy extends Predicate<ProcedureEntity> {
SosProcedureDescription<?> create(ProcedureEntity p, String descriptionFormat, Locale i18n,
HibernateProcedureCreationContext ctx, Session s) throws OwsExceptionReport;
}
|
EHJ-52n/SOS
|
hibernate/common/src/main/java/org/n52/sos/ds/hibernate/util/procedure/create/DescriptionCreationStrategy.java
|
Java
|
gpl-2.0
| 2,030
|
<?php
/*
Template Name: Full Width
*/
?>
<?php get_header(); ?>
<div id="content">
<div id="contentwide">
<div class="postareawide">
<?php include(TEMPLATEPATH."/breadcrumbwide.php");?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<h1><?php the_title(); ?></h1><br />
<?php the_content(__('Read more'));?><div style="clear:both;"></div><?php edit_post_link('(Edit)', '', ''); ?>
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p><?php endif; ?>
</div>
</div>
</div>
<!-- The main column ends -->
<?php get_footer(); ?>
|
puchimatto/wp_jgl
|
wp-content/themes/lifestyle_30/page_fullwidth.php
|
PHP
|
gpl-2.0
| 627
|
/*
*
* Copyright (c) International Business Machines Corp., 2002
*
* 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
*/
/* 11/12/2002 Port to LTP robbiew@us.ibm.com */
/* 06/30/2001 Port to Linux nsharoff@us.ibm.com */
/*
* NAME
* rename14.c - create and rename files
*
* CALLS
* create, unlink, rename
*
* ALGORITHM
* Creates two processes. One creates and unlinks a file.
* The other renames that file.
*
*/
#include <stdio.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
/** LTP Port **/
#include "test.h"
#include "usctest.h"
#define FAILED 0
#define PASSED 1
int local_flag = PASSED;
char *TCID = "rename14";
int TST_TOTAL = 1;
/**************/
#define RUNTIME 45
int kidpid[2];
int parent_pid;
int main(int argc, char *argv[])
{
int pid;
sigset_t set;
struct sigaction act, oact;
int term();
int al();
void dochild1();
void dochild2();
#ifdef UCLINUX
const char *msg;
if ((msg = parse_opts(argc, argv, NULL, NULL)) != NULL)
tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg);
maybe_run_child(&dochild1, "n", 1);
maybe_run_child(&dochild2, "n", 2);
#endif
sigemptyset(&set);
act.sa_handler = (void (*)())term;
act.sa_mask = set;
act.sa_flags = 0;
if (sigaction(SIGTERM, &act, &oact)) {
tst_brkm(TBROK, NULL, "Sigaction(SIGTERM)");
}
sigemptyset(&set);
act.sa_handler = (void (*)())al;
act.sa_mask = set;
act.sa_flags = 0;
if (sigaction(SIGALRM, &act, 0)) {
tst_brkm(TBROK, NULL, "Sigaction(SIGALRM)");
}
parent_pid = getpid();
tst_tmpdir();
/*--------------------------------------------------------------*/
pid = FORK_OR_VFORK();
if (pid < 0) {
tst_brkm(TBROK, NULL, "fork() returned %d", pid);
}
if (pid == 0) {
#ifdef UCLINUX
if (self_exec(argv[0], "n", 1) < 0) {
tst_resm(TBROK, "self_exec failed");
}
#else
dochild1();
#endif
}
kidpid[0] = pid;
pid = FORK_OR_VFORK();
if (pid < 0) {
(void)kill(kidpid[0], SIGTERM);
(void)unlink("./rename14");
tst_brkm(TBROK, NULL, "fork() returned %d", pid);
}
if (pid == 0) {
#ifdef UCLINUX
if (self_exec(argv[0], "n", 1) < 0) {
tst_resm(TBROK, "self_exec failed");
}
#else
dochild2();
#endif
}
kidpid[1] = pid;
alarm(RUNTIME);
/* Collect child processes. */
/* Wait for timeout */
pause();
kill(kidpid[0], SIGTERM);
kill(kidpid[1], SIGTERM);
waitpid(kidpid[0], NULL, 0);
waitpid(kidpid[1], NULL, 0);
unlink("./rename14");
unlink("./rename14xyz");
(local_flag == PASSED) ? tst_resm(TPASS, "Test Passed")
: tst_resm(TFAIL, "Test Failed");
tst_rmdir();
tst_exit();
}
/* FUNCTIONS GO HERE */
int term(void)
{
if (parent_pid != getpid())
exit(0);
if (kidpid[0])
return (kill(kidpid[0], SIGTERM));
if (kidpid[1])
return (kill(kidpid[1], SIGTERM));
return 0;
}
int al(void)
{
if (kidpid[0])
return (kill(kidpid[0], SIGTERM));
if (kidpid[1])
return (kill(kidpid[1], SIGTERM));
return 0;
}
void dochild1(void)
{
int fd;
for (;;) {
fd = creat("./rename14", 0666);
unlink("./rename14");
close(fd);
}
}
void dochild2(void)
{
for (;;) {
rename("./rename14", "./rename14xyz");
}
}
|
heluxie/LTP
|
testcases/kernel/syscalls/rename/rename14.c
|
C
|
gpl-2.0
| 3,894
|
<?php
/**
* The template for displaying comments.
*
* The area of the page that contains both current comments
* and the comment form.
*
* @package Tria
*/
/*
* If the current post is protected by a password and
* the visitor has not yet entered the password we will
* return early without loading the comments.
*/
if ( post_password_required() ) {
return;
}
?>
<div id="comments" class="comments-area">
<?php // You can start editing here -- including this comment! ?>
<?php if ( have_comments() ) : ?>
<h2 class="comments-title">
<?php
printf( _nx( 'One thought on “%2$s”', '%1$s thoughts on “%2$s”', get_comments_number(), 'comments title', 'tria' ),
number_format_i18n( get_comments_number() ), '<span>' . get_the_title() . '</span>' );
?>
</h2>
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
<nav id="comment-nav-above" class="comment-navigation" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'tria' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '← Older Comments', 'tria' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments →', 'tria' ) ); ?></div>
</nav><!-- #comment-nav-above -->
<?php endif; // check for comment navigation ?>
<ol class="comment-list">
<?php
wp_list_comments( array(
'style' => 'ol',
'short_ping' => true,
) );
?>
</ol><!-- .comment-list -->
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
<nav id="comment-nav-below" class="comment-navigation" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'tria' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '← Older Comments', 'tria' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments →', 'tria' ) ); ?></div>
</nav><!-- #comment-nav-below -->
<?php endif; // check for comment navigation ?>
<?php endif; // have_comments() ?>
<?php
// If comments are closed and there are comments, let's leave a little note, shall we?
if ( ! comments_open() && '0' != get_comments_number() && post_type_supports( get_post_type(), 'comments' ) ) :
?>
<p class="no-comments"><?php _e( 'Comments are closed.', 'tria' ); ?></p>
<?php endif; ?>
<?php comment_form(); ?>
</div><!-- #comments -->
|
nikolapopov/Tria
|
wp-content/themes/tria/comments.php
|
PHP
|
gpl-2.0
| 2,539
|
/* Definitions for CPP library.
Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002
Free Software Foundation, Inc.
Written by Per Bothner, 1994-95.
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, 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, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
In other words, you are welcome to use, share and improve this program.
You are forbidden to forbid anyone else to use, share and improve
what you give them. Help stamp out software-hoarding! */
#ifndef GCC_CPPLIB_H
#define GCC_CPPLIB_H
#include <sys/types.h>
#include "hashtable.h"
#include "line-map.h"
#ifdef __cplusplus
extern "C" {
#endif
/* For complex reasons, cpp_reader is also typedefed in c-pragma.h. */
#ifndef GCC_C_PRAGMA_H
typedef struct cpp_reader cpp_reader;
#endif
typedef struct cpp_buffer cpp_buffer;
typedef struct cpp_options cpp_options;
typedef struct cpp_token cpp_token;
typedef struct cpp_string cpp_string;
typedef struct cpp_hashnode cpp_hashnode;
typedef struct cpp_macro cpp_macro;
typedef struct cpp_callbacks cpp_callbacks;
struct answer;
struct file_name_map_list;
/* The first two groups, apart from '=', can appear in preprocessor
expressions. This allows a lookup table to be implemented in
_cpp_parse_expr.
The first group, to CPP_LAST_EQ, can be immediately followed by an
'='. The lexer needs operators ending in '=', like ">>=", to be in
the same order as their counterparts without the '=', like ">>". */
/* Positions in the table. */
#define CPP_LAST_EQ CPP_MAX
#define CPP_FIRST_DIGRAPH CPP_HASH
#define CPP_LAST_PUNCTUATOR CPP_DOT_STAR
#define TTYPE_TABLE \
OP(CPP_EQ = 0, "=") \
OP(CPP_NOT, "!") \
OP(CPP_GREATER, ">") /* compare */ \
OP(CPP_LESS, "<") \
OP(CPP_PLUS, "+") /* math */ \
OP(CPP_MINUS, "-") \
OP(CPP_MULT, "*") \
OP(CPP_DIV, "/") \
OP(CPP_MOD, "%") \
OP(CPP_AND, "&") /* bit ops */ \
OP(CPP_OR, "|") \
OP(CPP_XOR, "^") \
OP(CPP_RSHIFT, ">>") \
OP(CPP_LSHIFT, "<<") \
OP(CPP_MIN, "<?") /* extension */ \
OP(CPP_MAX, ">?") \
\
OP(CPP_COMPL, "~") \
OP(CPP_AND_AND, "&&") /* logical */ \
OP(CPP_OR_OR, "||") \
OP(CPP_QUERY, "?") \
OP(CPP_COLON, ":") \
OP(CPP_COMMA, ",") /* grouping */ \
OP(CPP_OPEN_PAREN, "(") \
OP(CPP_CLOSE_PAREN, ")") \
OP(CPP_EQ_EQ, "==") /* compare */ \
OP(CPP_NOT_EQ, "!=") \
OP(CPP_GREATER_EQ, ">=") \
OP(CPP_LESS_EQ, "<=") \
\
OP(CPP_PLUS_EQ, "+=") /* math */ \
OP(CPP_MINUS_EQ, "-=") \
OP(CPP_MULT_EQ, "*=") \
OP(CPP_DIV_EQ, "/=") \
OP(CPP_MOD_EQ, "%=") \
OP(CPP_AND_EQ, "&=") /* bit ops */ \
OP(CPP_OR_EQ, "|=") \
OP(CPP_XOR_EQ, "^=") \
OP(CPP_RSHIFT_EQ, ">>=") \
OP(CPP_LSHIFT_EQ, "<<=") \
OP(CPP_MIN_EQ, "<?=") /* extension */ \
OP(CPP_MAX_EQ, ">?=") \
/* Digraphs together, beginning with CPP_FIRST_DIGRAPH. */ \
OP(CPP_HASH, "#") /* digraphs */ \
OP(CPP_PASTE, "##") \
OP(CPP_OPEN_SQUARE, "[") \
OP(CPP_CLOSE_SQUARE, "]") \
OP(CPP_OPEN_BRACE, "{") \
OP(CPP_CLOSE_BRACE, "}") \
/* The remainder of the punctuation. Order is not significant. */ \
OP(CPP_SEMICOLON, ";") /* structure */ \
OP(CPP_ELLIPSIS, "...") \
OP(CPP_PLUS_PLUS, "++") /* increment */ \
OP(CPP_MINUS_MINUS, "--") \
OP(CPP_DEREF, "->") /* accessors */ \
OP(CPP_DOT, ".") \
OP(CPP_SCOPE, "::") \
OP(CPP_DEREF_STAR, "->*") \
OP(CPP_DOT_STAR, ".*") \
OP(CPP_ATSIGN, "@") /* used in Objective C */ \
\
TK(CPP_NAME, SPELL_IDENT) /* word */ \
TK(CPP_NUMBER, SPELL_NUMBER) /* 34_be+ta */ \
\
TK(CPP_CHAR, SPELL_STRING) /* 'char' */ \
TK(CPP_WCHAR, SPELL_STRING) /* L'char' */ \
TK(CPP_OTHER, SPELL_CHAR) /* stray punctuation */ \
\
TK(CPP_STRING, SPELL_STRING) /* "string" */ \
TK(CPP_WSTRING, SPELL_STRING) /* L"string" */ \
TK(CPP_HEADER_NAME, SPELL_STRING) /* <stdio.h> in #include */ \
\
TK(CPP_COMMENT, SPELL_NUMBER) /* Only if output comments. */ \
/* SPELL_NUMBER happens to DTRT. */ \
TK(CPP_MACRO_ARG, SPELL_NONE) /* Macro argument. */ \
TK(CPP_PADDING, SPELL_NONE) /* Whitespace for cpp0. */ \
TK(CPP_EOF, SPELL_NONE) /* End of line or file. */
#define OP(e, s) e,
#define TK(e, s) e,
enum cpp_ttype
{
TTYPE_TABLE
N_TTYPES
};
#undef OP
#undef TK
/* C language kind, used when calling cpp_reader_init. */
enum c_lang {CLK_GNUC89 = 0, CLK_GNUC99, CLK_STDC89, CLK_STDC94, CLK_STDC99,
CLK_GNUCXX, CLK_CXX98, CLK_OBJC, CLK_OBJCXX, CLK_ASM};
/* Payload of a NUMBER, STRING, CHAR or COMMENT token. */
struct cpp_string
{
unsigned int len;
const unsigned char *text;
};
/* Flags for the cpp_token structure. */
#define PREV_WHITE (1 << 0) /* If whitespace before this token. */
#define DIGRAPH (1 << 1) /* If it was a digraph. */
#define STRINGIFY_ARG (1 << 2) /* If macro argument to be stringified. */
#define PASTE_LEFT (1 << 3) /* If on LHS of a ## operator. */
#define NAMED_OP (1 << 4) /* C++ named operators. */
#define NO_EXPAND (1 << 5) /* Do not macro-expand this token. */
#define BOL (1 << 6) /* Token at beginning of line. */
/* A preprocessing token. This has been carefully packed and should
occupy 16 bytes on 32-bit hosts and 24 bytes on 64-bit hosts. */
struct cpp_token
{
unsigned int line; /* Logical line of first char of token. */
unsigned short col; /* Column of first char of token. */
ENUM_BITFIELD(cpp_ttype) type : CHAR_BIT; /* token type */
unsigned char flags; /* flags - see above */
union
{
cpp_hashnode *node; /* An identifier. */
const cpp_token *source; /* Inherit padding from this token. */
struct cpp_string str; /* A string, or number. */
unsigned int arg_no; /* Argument no. for a CPP_MACRO_ARG. */
unsigned char c; /* Character represented by CPP_OTHER. */
} val;
};
/* A standalone character. We may want to make it unsigned for the
same reason we use unsigned char - to avoid signedness issues. */
typedef int cppchar_t;
/* Values for opts.dump_macros.
dump_only means inhibit output of the preprocessed text
and instead output the definitions of all user-defined
macros in a form suitable for use as input to cpp.
dump_names means pass #define and the macro name through to output.
dump_definitions means pass the whole definition (plus #define) through
*/
enum { dump_none = 0, dump_only, dump_names, dump_definitions };
/* This structure is nested inside struct cpp_reader, and
carries all the options visible to the command line. */
struct cpp_options
{
/* Name of input and output files. */
const char *in_fname;
const char *out_fname;
/* Characters between tab stops. */
unsigned int tabstop;
/* Pending options - -D, -U, -A, -I, -ixxx. */
struct cpp_pending *pending;
/* File name which deps are being written to. This is 0 if deps are
being written to stdout. */
const char *deps_file;
/* Search paths for include files. */
struct search_path *quote_include; /* "" */
struct search_path *bracket_include; /* <> */
/* Map between header names and file names, used only on DOS where
file names are limited in length. */
struct file_name_map_list *map_list;
/* Directory prefix that should replace `/usr/lib/gcc-lib/TARGET/VERSION'
in the standard include file directories. */
const char *include_prefix;
unsigned int include_prefix_len;
/* -fleading_underscore sets this to "_". */
const char *user_label_prefix;
/* The language we're preprocessing. */
enum c_lang lang;
/* Non-0 means -v, so print the full set of include dirs. */
unsigned char verbose;
/* Nonzero means chars are signed. */
unsigned char signed_char;
/* Nonzero means use extra default include directories for C++. */
unsigned char cplusplus;
/* Nonzero means handle cplusplus style comments */
unsigned char cplusplus_comments;
/* Nonzero means handle #import, for objective C. */
unsigned char objc;
/* Nonzero means don't copy comments into the output file. */
unsigned char discard_comments;
/* Nonzero means process the ISO trigraph sequences. */
unsigned char trigraphs;
/* Nonzero means process the ISO digraph sequences. */
unsigned char digraphs;
/* Nonzero means to allow hexadecimal floats and LL suffixes. */
unsigned char extended_numbers;
/* Nonzero means print the names of included files rather than the
preprocessed output. 1 means just the #include "...", 2 means
#include <...> as well. */
unsigned char print_deps;
/* Nonzero if phony targets are created for each header. */
unsigned char deps_phony_targets;
/* Nonzero if missing .h files in -M output are assumed to be
generated files and not errors. */
unsigned char print_deps_missing_files;
/* If true, fopen (deps_file, "a") else fopen (deps_file, "w"). */
unsigned char print_deps_append;
/* If true, no dependency is generated on the main file. */
unsigned char deps_ignore_main_file;
/* Nonzero means print names of header files (-H). */
unsigned char print_include_names;
/* Nonzero means cpp_pedwarn causes a hard error. */
unsigned char pedantic_errors;
/* Nonzero means don't print warning messages. */
unsigned char inhibit_warnings;
/* Nonzero means don't suppress warnings from system headers. */
unsigned char warn_system_headers;
/* Nonzero means don't print error messages. Has no option to
select it, but can be set by a user of cpplib (e.g. fix-header). */
unsigned char inhibit_errors;
/* Nonzero means warn if slash-star appears in a comment. */
unsigned char warn_comments;
/* Nonzero means warn if there are any trigraphs. */
unsigned char warn_trigraphs;
/* Nonzero means warn if #import is used. */
unsigned char warn_import;
/* Nonzero means warn about various incompatibilities with
traditional C. */
unsigned char warn_traditional;
/* Nonzero means turn warnings into errors. */
unsigned char warnings_are_errors;
/* Nonzero causes output not to be done, but directives such as
#define that have side effects are still obeyed. */
unsigned char no_output;
/* Nonzero means we should look for header.gcc files that remap file
names. */
unsigned char remap;
/* Nonzero means don't output line number information. */
unsigned char no_line_commands;
/* Nonzero means -I- has been seen, so don't look for #include "foo"
the source-file directory. */
unsigned char ignore_srcdir;
/* Zero means dollar signs are punctuation. */
unsigned char dollars_in_ident;
/* Nonzero means warn if undefined identifiers are evaluated in an #if. */
unsigned char warn_undef;
/* Nonzero for the 1999 C Standard, including corrigenda and amendments. */
unsigned char c99;
/* Nonzero if conforming to some particular standard. */
unsigned char std;
/* Nonzero means give all the error messages the ANSI standard requires. */
unsigned char pedantic;
/* Nonzero means we're looking at already preprocessed code, so don't
bother trying to do macro expansion and whatnot. */
unsigned char preprocessed;
/* Nonzero disables all the standard directories for headers. */
unsigned char no_standard_includes;
/* Nonzero disables the C++-specific standard directories for headers. */
unsigned char no_standard_cplusplus_includes;
/* Nonzero means dump macros in some fashion - see above. */
unsigned char dump_macros;
/* Nonzero means pass #include lines through to the output. */
unsigned char dump_includes;
/* Print column number in error messages. */
unsigned char show_column;
/* Nonzero means handle C++ alternate operator names. */
unsigned char operator_names;
/* True if --help, --version or --target-help appeared in the
options. Stand-alone CPP should then bail out after option
parsing; drivers might want to continue printing help. */
unsigned char help_only;
};
/* Call backs. */
struct cpp_callbacks
{
/* Called when a new line of preprocessed output is started. */
void (*line_change) PARAMS ((cpp_reader *, const cpp_token *, int));
void (*file_change) PARAMS ((cpp_reader *, const struct line_map *));
void (*include) PARAMS ((cpp_reader *, unsigned int,
const unsigned char *, const cpp_token *));
void (*define) PARAMS ((cpp_reader *, unsigned int, cpp_hashnode *));
void (*undef) PARAMS ((cpp_reader *, unsigned int, cpp_hashnode *));
void (*ident) PARAMS ((cpp_reader *, unsigned int, const cpp_string *));
void (*def_pragma) PARAMS ((cpp_reader *, unsigned int));
};
#define CPP_FATAL_LIMIT 1000
/* True if we have seen a "fatal" error. */
#define CPP_FATAL_ERRORS(PFILE) (cpp_errors (PFILE) >= CPP_FATAL_LIMIT)
/* Name under which this program was invoked. */
extern const char *progname;
/* The structure of a node in the hash table. The hash table has
entries for all identifiers: either macros defined by #define
commands (type NT_MACRO), assertions created with #assert
(NT_ASSERTION), or neither of the above (NT_VOID). Builtin macros
like __LINE__ are flagged NODE_BUILTIN. Poisioned identifiers are
flagged NODE_POISONED. NODE_OPERATOR (C++ only) indicates an
identifier that behaves like an operator such as "xor".
NODE_DIAGNOSTIC is for speed in lex_token: it indicates a
diagnostic may be required for this node. Currently this only
applies to __VA_ARGS__ and poisoned identifiers. */
/* Hash node flags. */
#define NODE_OPERATOR (1 << 0) /* C++ named operator. */
#define NODE_POISONED (1 << 1) /* Poisoned identifier. */
#define NODE_BUILTIN (1 << 2) /* Builtin macro. */
#define NODE_DIAGNOSTIC (1 << 3) /* Possible diagnostic when lexed. */
#define NODE_WARN (1 << 4) /* Warn if redefined or undefined. */
#define NODE_DISABLED (1 << 5) /* A disabled macro. */
/* Different flavors of hash node. */
enum node_type
{
NT_VOID = 0, /* No definition yet. */
NT_MACRO, /* A macro of some form. */
NT_ASSERTION /* Predicate for #assert. */
};
/* Different flavors of builtin macro. _Pragma is an operator, but we
handle it with the builtin code for efficiency reasons. */
enum builtin_type
{
BT_SPECLINE = 0, /* `__LINE__' */
BT_DATE, /* `__DATE__' */
BT_FILE, /* `__FILE__' */
BT_BASE_FILE, /* `__BASE_FILE__' */
BT_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
BT_TIME, /* `__TIME__' */
BT_STDC, /* `__STDC__' */
BT_PRAGMA /* `_Pragma' operator */
};
#define CPP_HASHNODE(HNODE) ((cpp_hashnode *) (HNODE))
#define HT_NODE(NODE) ((ht_identifier *) (NODE))
#define NODE_LEN(NODE) HT_LEN (&(NODE)->ident)
#define NODE_NAME(NODE) HT_STR (&(NODE)->ident)
/* The common part of an identifier node shared amongst all 3 C front
ends. Also used to store CPP identifiers, which are a superset of
identifiers in the grammatical sense. */
struct cpp_hashnode
{
struct ht_identifier ident;
unsigned short arg_index; /* Macro argument index. */
unsigned char directive_index; /* Index into directive table. */
unsigned char rid_code; /* Rid code - for front ends. */
ENUM_BITFIELD(node_type) type : 8; /* CPP node type. */
unsigned char flags; /* CPP flags. */
union
{
cpp_macro *macro; /* If a macro. */
struct answer *answers; /* Answers to an assertion. */
enum cpp_ttype operator; /* Code for a named operator. */
enum builtin_type builtin; /* Code for a builtin macro. */
} value;
};
/* Call this first to get a handle to pass to other functions. */
extern cpp_reader *cpp_create_reader PARAMS ((enum c_lang));
/* Call these to get pointers to the options and callback structures
for a given reader. These pointers are good until you call
cpp_finish on that reader. You can either edit the callbacks
through the pointer returned from cpp_get_callbacks, or set them
with cpp_set_callbacks. */
extern cpp_options *cpp_get_options PARAMS ((cpp_reader *));
extern const struct line_maps *cpp_get_line_maps PARAMS ((cpp_reader *));
extern cpp_callbacks *cpp_get_callbacks PARAMS ((cpp_reader *));
extern void cpp_set_callbacks PARAMS ((cpp_reader *, cpp_callbacks *));
/* Now call cpp_handle_option[s] to handle 1[or more] switches. The
return value is the number of arguments used. If
cpp_handle_options returns without using all arguments, it couldn't
understand the next switch. When there are no switches left, you
must call cpp_post_options before calling cpp_read_main_file. Only
after cpp_post_options are the contents of the cpp_options
structure reliable. Options processing is not completed until you
call cpp_finish_options. */
extern int cpp_handle_options PARAMS ((cpp_reader *, int, char **));
extern int cpp_handle_option PARAMS ((cpp_reader *, int, char **, int));
extern void cpp_post_options PARAMS ((cpp_reader *));
/* This function reads the file, but does not start preprocessing. It
returns the name of the original file; this is the same as the
input file, except for preprocessed input. This will generate at
least one file change callback, and possibly a line change callback
too. If there was an error opening the file, it returns NULL.
If you want cpplib to manage its own hashtable, pass in a NULL
pointer. Otherise you should pass in an initialised hash table
that cpplib will share; this technique is used by the C front
ends. */
extern const char *cpp_read_main_file PARAMS ((cpp_reader *, const char *,
struct ht *));
/* Deferred handling of command line options that can generate debug
callbacks, such as -D and -imacros. Call this after
cpp_read_main_file. The front ends need this separation so they
can initialize debug output with the original file name, returned
from cpp_read_main_file, before they get debug callbacks. */
extern void cpp_finish_options PARAMS ((cpp_reader *));
/* Call this to release the handle at the end of preprocessing. Any
use of the handle after this function returns is invalid. Returns
cpp_errors (pfile). */
extern int cpp_destroy PARAMS ((cpp_reader *));
/* Error count. */
extern unsigned int cpp_errors PARAMS ((cpp_reader *));
extern unsigned int cpp_token_len PARAMS ((const cpp_token *));
extern unsigned char *cpp_token_as_text PARAMS ((cpp_reader *,
const cpp_token *));
extern unsigned char *cpp_spell_token PARAMS ((cpp_reader *, const cpp_token *,
unsigned char *));
extern void cpp_register_pragma PARAMS ((cpp_reader *,
const char *, const char *,
void (*) PARAMS ((cpp_reader *))));
extern void cpp_finish PARAMS ((cpp_reader *));
extern int cpp_avoid_paste PARAMS ((cpp_reader *, const cpp_token *,
const cpp_token *));
extern const cpp_token *cpp_get_token PARAMS ((cpp_reader *));
extern const unsigned char *cpp_macro_definition PARAMS ((cpp_reader *,
const cpp_hashnode *));
extern void _cpp_backup_tokens PARAMS ((cpp_reader *, unsigned int));
/* Evaluate a CPP_CHAR or CPP_WCHAR token. */
extern HOST_WIDE_INT
cpp_interpret_charconst PARAMS ((cpp_reader *, const cpp_token *,
int, int, unsigned int *));
extern void cpp_define PARAMS ((cpp_reader *, const char *));
extern void cpp_assert PARAMS ((cpp_reader *, const char *));
extern void cpp_undef PARAMS ((cpp_reader *, const char *));
extern void cpp_unassert PARAMS ((cpp_reader *, const char *));
extern cpp_buffer *cpp_push_buffer PARAMS ((cpp_reader *,
const unsigned char *, size_t,
int, int));
extern int cpp_defined PARAMS ((cpp_reader *, const unsigned char *, int));
/* N.B. The error-message-printer prototypes have not been nicely
formatted because exgettext needs to see 'msgid' on the same line
as the name of the function in order to work properly. Only the
string argument gets a name in an effort to keep the lines from
getting ridiculously oversized. */
extern void cpp_ice PARAMS ((cpp_reader *, const char *msgid, ...))
ATTRIBUTE_PRINTF_2;
extern void cpp_fatal PARAMS ((cpp_reader *, const char *msgid, ...))
ATTRIBUTE_PRINTF_2;
extern void cpp_error PARAMS ((cpp_reader *, const char *msgid, ...))
ATTRIBUTE_PRINTF_2;
extern void cpp_warning PARAMS ((cpp_reader *, const char *msgid, ...))
ATTRIBUTE_PRINTF_2;
extern void cpp_pedwarn PARAMS ((cpp_reader *, const char *msgid, ...))
ATTRIBUTE_PRINTF_2;
extern void cpp_notice PARAMS ((cpp_reader *, const char *msgid, ...))
ATTRIBUTE_PRINTF_2;
extern void cpp_error_with_line PARAMS ((cpp_reader *, int, int, const char *msgid, ...))
ATTRIBUTE_PRINTF_4;
extern void cpp_warning_with_line PARAMS ((cpp_reader *, int, int, const char *msgid, ...))
ATTRIBUTE_PRINTF_4;
extern void cpp_pedwarn_with_line PARAMS ((cpp_reader *, int, int, const char *msgid, ...))
ATTRIBUTE_PRINTF_4;
extern void cpp_error_from_errno PARAMS ((cpp_reader *, const char *));
extern void cpp_notice_from_errno PARAMS ((cpp_reader *, const char *));
/* In cpplex.c */
extern int cpp_ideq PARAMS ((const cpp_token *,
const char *));
extern void cpp_output_line PARAMS ((cpp_reader *, FILE *));
extern void cpp_output_token PARAMS ((const cpp_token *, FILE *));
extern const char *cpp_type2name PARAMS ((enum cpp_ttype));
extern unsigned int cpp_parse_escape PARAMS ((cpp_reader *,
const unsigned char **,
const unsigned char *,
unsigned HOST_WIDE_INT, int));
/* In cpphash.c */
/* Lookup an identifier in the hashtable. Puts the identifier in the
table if it is not already there. */
extern cpp_hashnode *cpp_lookup PARAMS ((cpp_reader *,
const unsigned char *,
unsigned int));
typedef int (*cpp_cb) PARAMS ((cpp_reader *, cpp_hashnode *, void *));
extern void cpp_forall_identifiers PARAMS ((cpp_reader *,
cpp_cb, void *));
/* In cppmacro.c */
extern void cpp_scan_nooutput PARAMS ((cpp_reader *));
extern int cpp_sys_macro_p PARAMS ((cpp_reader *));
extern unsigned char *cpp_quote_string PARAMS ((unsigned char *,
const unsigned char *,
unsigned int));
/* In cppfiles.c */
extern int cpp_included PARAMS ((cpp_reader *, const char *));
extern void cpp_make_system_header PARAMS ((cpp_reader *, int, int));
#ifdef __cplusplus
}
#endif
#endif /* ! GCC_CPPLIB_H */
|
nslu2/Build-gcc-3.2.1
|
gcc/cpplib.h
|
C
|
gpl-2.0
| 22,885
|
/*
Copyright (C) SYSTAP, LLC 2006-2015. All rights reserved.
Contact:
SYSTAP, LLC
2501 Calvert ST NW #106
Washington, DC 20008
licenses@systap.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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Created on Apr 16, 2009
*/
package com.bigdata.service.ndx.pipeline;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import com.bigdata.btree.keys.KVO;
import com.bigdata.relation.accesspath.BlockingBuffer;
import com.bigdata.util.concurrent.DaemonThreadFactory;
/**
* Unit tests of the idle timeout behavior for {@link AbstractMasterTask} and
* friends.
*
* @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a>
* @version $Id$
*/
public class TestMasterTaskIdleTimeout extends AbstractMasterTestCase {
public TestMasterTaskIdleTimeout() {
}
public TestMasterTaskIdleTimeout(String name) {
super(name);
}
/**
* Unit test to verify that output buffers are not closed too quickly. This
* also verifies that a buffer automatically re-opened if it was closed by a
* timeout.
*/
public void test_idleTimeout() throws InterruptedException,
ExecutionException {
final H masterStats = new H();
final BlockingBuffer<KVO<O>[]> masterBuffer = new BlockingBuffer<KVO<O>[]>(
masterQueueCapacity);
final M master = new M(masterStats, masterBuffer, executorService,
TimeUnit.MILLISECONDS.toNanos(2000)/* sinkIdleTimeout */,
M.DEFAULT_SINK_POLL_TIMEOUT) {
protected BlockingBuffer<KVO<O>[]> newSubtaskBuffer() {
return new BlockingBuffer<KVO<O>[]>(
new ArrayBlockingQueue<KVO<O>[]>(subtaskQueueCapacity), //
10,// chunkSize
20,// chunkTimeout
TimeUnit.MILLISECONDS,// chunkTimeoutUnit
true // ordered
);
}
};
// Wrap computation as FutureTask.
final FutureTask<H> ft = new FutureTask<H>(master);
// Set Future on BlockingBuffer.
masterBuffer.setFuture(ft);
// Start the consumer.
executorService.submit(ft);
/*
* write a chunk on the buffer. this will cause an output buffer to be
* created.
*/
final long beforeWrite = System.nanoTime();
{
final KVO<O>[] a = new KVO[] { //
new KVO<O>(new byte[] { 1 }, new byte[] { 2 }, null/* val */), };
masterBuffer.add(a);
}
// wait just a bit for that chunk to be output by the sink.
awaitChunksOut(master, 1, 100/* MUST be GT sink's chunkTimeout */,
TimeUnit.MILLISECONDS);
// verify chunk was output by the sink.
assertEquals("elementsIn", 1, masterStats.elementsIn.get());
assertEquals("chunksIn", 1, masterStats.chunksIn.get());
assertEquals("elementsOut", 1, masterStats.elementsOut.get());
assertEquals("chunksOut", 1, masterStats.chunksOut.get());
assertEquals("partitionCount", 1, masterStats.getMaximumPartitionCount());
// make sure that the subtask is still running.
assertEquals("subtaskStartCount", 1, masterStats.subtaskStartCount.get());
assertEquals("subtaskEndCount", 0, masterStats.subtaskEndCount.get());
final long elapsed1 = System.nanoTime() - beforeWrite;
/*
* Sleep for up to 1/2 of the remaining idle timeout.
*
* Note: If the idle timeout is too short then Thread#sleep() will not
* return before the timeout has expired.
*/
Thread.sleep(Math.max(1,TimeUnit.NANOSECONDS.toMillis(master.sinkIdleTimeoutNanos
/ 2 - elapsed1)));
final long elapsed2 = System.nanoTime() - beforeWrite;
if (elapsed2 > master.sinkIdleTimeoutNanos) {
fail("Sleep too long - idle timeout may have expired.");
}
// the original subtask should still be running.
assertEquals("subtaskStartCount", 1, masterStats.subtaskStartCount.get());
assertEquals("subtaskEndCount", 0, masterStats.subtaskEndCount.get());
// now sleep for the entire idle timeout (this give us some padding).
Thread
.sleep(TimeUnit.NANOSECONDS
.toMillis(master.sinkIdleTimeoutNanos));
// the subtask should have terminated and no other subtask should have started.
assertEquals("subtaskStartCount", 1, masterStats.subtaskStartCount.get());
assertEquals("subtaskEndCount", 1, masterStats.subtaskEndCount.get());
assertEquals("subtaskIdleTimeout", 1, masterStats.subtaskIdleTimeoutCount.get());
/*
* write another chunk onto the same output buffer.
*/
{
final KVO<O>[] a = new KVO[] { //
new KVO<O>(new byte[] { 1 }, new byte[] { 3 }, null/* val */), };
masterBuffer.add(a);
}
// close the master
masterBuffer.close();
// and await its future.
masterBuffer.getFuture().get();
// verify 2nd chunk was output by the sink.
assertEquals("elementsIn", 2, masterStats.elementsIn.get());
assertEquals("chunksIn", 2, masterStats.chunksIn.get());
assertEquals("elementsOut", 2, masterStats.elementsOut.get());
assertEquals("chunksOut", 2, masterStats.chunksOut.get());
assertEquals("partitionCount", 1, masterStats.getMaximumPartitionCount());
// verify that another subtask was started by the 2nd write.
assertEquals("subtaskStartCount", 2, masterStats.subtaskStartCount.get());
assertEquals("subtaskEndCount", 2, masterStats.subtaskEndCount.get());
/*
* The idle timeout count should still be one since the 2nd instance of
* the sink should have been closed when the master was exhausted not by
* an idle timeout.
*/
assertEquals("subtaskIdleTimeout", 1, masterStats.subtaskIdleTimeoutCount.get());
// verify writes on each expected partition.
{
final HS subtaskStats = masterStats.getSubtaskStats(new L(1));
assertNotNull(subtaskStats);
assertEquals("chunksOut", 2, subtaskStats.chunksOut.get());
assertEquals("elementsOut", 2, subtaskStats.elementsOut.get());
}
}
/**
* Unit test verifies that an idle timeout may be LT the chunk timeout and
* that the sink will be closed by the idle timeout if chunks do not appear
* in a timely manner.
*
* @throws InterruptedException
* @throws ExecutionException
*/
public void test_idleTimeout_LT_chunkTimeout() throws InterruptedException, ExecutionException {
final H masterStats = new H();
final long sinkIdleTimeoutNanos = TimeUnit.MILLISECONDS.toNanos(50);
final long sinkChunkTimeoutNanos = TimeUnit.MILLISECONDS.toNanos(140);
// make sure there is enough room for the test to succeed.
assertTrue(sinkIdleTimeoutNanos * 2 <= sinkChunkTimeoutNanos);
final BlockingBuffer<KVO<O>[]> masterBuffer = new BlockingBuffer<KVO<O>[]>(
masterQueueCapacity);
final M master = new M(masterStats, masterBuffer, executorService,
sinkIdleTimeoutNanos,
M.DEFAULT_SINK_POLL_TIMEOUT) {
protected BlockingBuffer<KVO<O>[]> newSubtaskBuffer() {
return new BlockingBuffer<KVO<O>[]>(
new ArrayBlockingQueue<KVO<O>[]>(subtaskQueueCapacity), //
10,// chunkSize
sinkChunkTimeoutNanos, TimeUnit.NANOSECONDS,// chunkTimeoutUnit
true // ordered
);
}
};
// Wrap computation as FutureTask.
final FutureTask<H> ft = new FutureTask<H>(master);
// Set Future on BlockingBuffer
masterBuffer.setFuture(ft);
// Start the consumer.
executorService.submit(ft);
/*
* write a chunk on the buffer. this will cause a sink to be created.
*/
final long beginWrite = System.nanoTime();
{
final KVO<O>[] a = new KVO[] { //
new KVO<O>(new byte[] { 1 }, new byte[] { 2 }, null/* val */), };
masterBuffer.add(a);
}
// wait just a bit for that chunk to be output by the sink.
awaitChunksOut(master, 1, sinkIdleTimeoutNanos
+ (sinkIdleTimeoutNanos / 2), TimeUnit.NANOSECONDS);
final long elapsed = System.nanoTime() - beginWrite;
if (log.isInfoEnabled())
log.info("elapsed=" + elapsed + " "
+ (elapsed < sinkChunkTimeoutNanos ? "LT" : "GTE")
+ " chunkTimeout=" + sinkChunkTimeoutNanos);
// verify chunk was output by the sink.
assertEquals("elementsIn", 1, masterStats.elementsIn.get());
assertEquals("chunksIn", 1, masterStats.chunksIn.get());
assertEquals("elementsOut", 1, masterStats.elementsOut.get());
assertEquals("chunksOut", 1, masterStats.chunksOut.get());
assertEquals("partitionCount", 1, masterStats.getMaximumPartitionCount());
// verify the sink was closed by an idle timeout.
assertEquals("subtaskIdleTimeout", 1, masterStats.subtaskIdleTimeoutCount.get());
/*
* Verify that the sink was closed before a chunk timeout would have
* occurred.
*
* Note: if this assertion is triggered then you might have to adjust
* the chunk timeout to be longer. For example, this could be triggered
* if the host was swapping since the timings would be far off their
* nominal values.
*/
assertTrue("test did not complete before chunk timeout: elapsed="
+ elapsed + ", chunkTimeout=" + sinkChunkTimeoutNanos,
elapsed <= sinkChunkTimeoutNanos);
// close the master
masterBuffer.close();
// and await its future.
masterBuffer.getFuture().get();
// verify only one sink started/ended
assertEquals("subtaskStartCount", 1, masterStats.subtaskStartCount.get());
assertEquals("subtaskEndCount", 1, masterStats.subtaskEndCount.get());
}
/**
* Used to recognize the a scheduled task which halts based on our signal
* rather than for some error condition.
*
* @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan
* Thompson</a>
* @version $Id$
*/
private static class HaltedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public HaltedException() {
super();
}
}
/**
* Unit test verifies that a sink whose source iterator is not empty always
* resets the idle timeout (that is, if chunks continue to appear in a
* timely manner than the sink will not be closed by an idle timeout).
*
* @throws InterruptedException
* @throws ExecutionException
*
* @todo test when {@link AbstractSubtask#handleChunk(Object[])} has a
* latency in excess of the idle timeout and verify that we test for
* an available chunk before concluding that the sink is idle.
*/
public void test_idleTimeout_LT_chunkTimeout2() throws InterruptedException, ExecutionException {
// how long to run this test.
final long testDurationMillis = 5000;
/*
* The ratio of sinkChunkTimeout to sinkIdleTimeout.
*/
final int N = 10;
/*
* The fraction of the idle timeout between chunks written onto the
* master's input buffer.
*/
final double O = 1.5;
final long sinkIdleTimeoutNanos = TimeUnit.MILLISECONDS.toNanos(50);
final long sinkChunkTimeoutNanos = sinkIdleTimeoutNanos * N;
/*
* The fixed delay between chunks written onto the master.
*
* Note: Unless the master blocks (it should not if the sink is running)
* this will determine the rate of arrival of chunks at the sink. E.g.,
* if the idle timeout is 50ms and M = 2, then one chunk arrives every
* 50ms/2 = 25ms.
*
* Note: For simplicity, this test was designed such that each chunk
* written onto the master's input buffer had exactly one element.
*
* Note: This MUST be LT the sink idle timeout be a margin sufficient
* for new chunks to arrive at the sink before an idle timeout is
* reported.
*/
final long scheduledDelayNanos = (long) (sinkIdleTimeoutNanos / O);
/*
* The expected sink output chunk size (assuming that the sink can
* combine elements together into chunks of this size without reaching
* its chunkSize limit).
*/
final double expectedAverageOutputChunkSize = N * O;
final H masterStats = new H();
/*
* Override the [masterBuffer] so that we can disable its chunk
* combiner. This way only the sink will be combining chunks together
* which makes the behavior of the system more predictable.
*
* Note: this hides the field by the same name on our base class!
*/
final BlockingBuffer<KVO<O>[]> masterBuffer = new BlockingBuffer<KVO<O>[]>(
masterQueueCapacity,//
1, // chunkSize
0L/*
* Note: a chunkTimeout of ZERO (0) disables the chunk
* combiner for the master.
*/, TimeUnit.NANOSECONDS);
final M master = new M(masterStats, masterBuffer, executorService,
sinkIdleTimeoutNanos,
M.DEFAULT_SINK_POLL_TIMEOUT) {
protected BlockingBuffer<KVO<O>[]> newSubtaskBuffer() {
return new BlockingBuffer<KVO<O>[]>(
new ArrayBlockingQueue<KVO<O>[]>(subtaskQueueCapacity), //
100, // chunkSize
sinkChunkTimeoutNanos, TimeUnit.NANOSECONDS,// chunkTimeoutUnit
true // ordered
);
}
};
// Wrap computation as FutureTask.
final FutureTask<H> ft = new FutureTask<H>(master);
// Set Future on BlockingBuffer.
masterBuffer.setFuture(ft);
// Start the consumer.
executorService.submit(ft);
// scheduled service used to write on the master.
final ScheduledExecutorService scheduledExecutorService = Executors
.newScheduledThreadPool(1, DaemonThreadFactory
.defaultThreadFactory());
try {
/*
* Submit scheduled task which writes a chunk on the master each
* time it runs. The task is scheduled to run with a frequency 2x
* that of the idle timeout so the sink SHOULD NOT timeout.
*
* Note: The master/sink we are testing DO NOT perform duplicate
* elimination so the #of chunks/elements written onto the master
* MUST directly correspond to the #of chunks/elements written onto
* the sink(s). For this test we direct all element to the same sink
* by virtue of using the same key for all elements.
*/
// #of chunks written on the master.
final AtomicInteger counter = new AtomicInteger(0);
/*
* This is used to halt execution without interrupting the task
* (interrupts make the behavior of master#add() less predictable since
* we can not know whether a chunk was fully written before the task was
* interrupted and so the counters can be off by one).
*/
final AtomicBoolean halt = new AtomicBoolean(false);
// start scheduled task.
final ScheduledFuture<?> f = scheduledExecutorService
.scheduleWithFixedDelay(
new Runnable() {
public void run() {
// halt?
if(halt.get())
throw new HaltedException();
/*
* Verify the sink WAS NOT closed by an idle
* timeout.
*
* TODO I have seen this assertion
* triggered occasionally. However, on
* re-trial it generally succeeds [I think
* that this was related to the visibility
* of the state change in the field. It is
* now an AtomicLong, which may fix this.
* Nope. Still occasionally fails] [I've
* modified this to log @ ERROR to see if
* the test will pass now on those occasions
* when it would have failed before. BT
* 6/21/2011]
*/
// assertEquals("subtaskIdleTimeout", 0,
// masterStats.subtaskIdleTimeoutCount.get());
final long tmp = masterStats.subtaskIdleTimeoutCount
.get();
if (0L != tmp) {
log
.error("subtaskIdleTimeout: expected ZERO (0) but was "
+ tmp);
}
// add chunk to master's input buffer.
final KVO<O>[] a = new KVO[] { //
new KVO<O>(new byte[] { 1 },
new byte[] { 2 }, null/* val */),//
};
masterBuffer.add(a);
// increment counter.
counter.incrementAndGet();
}
}, 0L/* initialDelay */,
scheduledDelayNanos,
TimeUnit.NANOSECONDS);
/*
* Sleep a while giving the scheduled task time to write data onto
* the master, the master time to move chunks onto the sink, and the
* sink time to output those chunks.
*/
Thread.sleep(testDurationMillis);
// should not be done.
if(f.isDone()) {
// should throw out the exception.
f.get();
// otherwise something very weird.
fail("Scheduled task aborted? : counter=" + counter + " : "
+ masterStats);
}
// cancel the scheduled future.
halt.set(true);
/*
* wait for the scheduled task to terminate and verify that it
* terminated in response to our signal and not for any other
* reason.
*/
try {
// wait for the future.
f.get();
// should have thrown an exception.
fail("Expecting: " + ExecutionException.class + " wrapping "
+ HaltedException.class);
} catch (ExecutionException ex) {
// verify correct exception was thrown.
final Throwable cause = ex.getCause();
if (cause == null || (!(cause instanceof HaltedException))) {
fail("Expecting: " + HaltedException.class);
}
if (log.isInfoEnabled())
log.info("Ignoring expected exception: " + ex);
}
// close the master
masterBuffer.close();
// and await its future.
masterBuffer.getFuture().get();
// verify data in/out.
// chunks/elements in for the buffer.
assertEquals("masterBuffer.elementsIn", counter.get(), masterBuffer
.getElementsAddedCount());
assertEquals("masterBuffer.chunksIn", counter.get(), masterBuffer
.getChunksAddedCount());
/*
* Note: chunks/elements in for the master can not be known since
* the master can combine chunks when reading from its buffer.
*/
// assertEquals("elementsIn", counter.get(), masterStats.elementsIn);
// assertEquals("chunksIn", counter.get(), masterStats.chunksIn);
// elements out for the master (aggregated across all sinks).
assertEquals("elementsOut", counter.get(), masterStats.elementsOut.get());
// only a single sink key was used (one index partition).
assertEquals("partitionCount", 1, masterStats.getMaximumPartitionCount());
/*
* verify that the sink was not closed by an idle timeout before the
* master was closed (this verifies that we only had a single sink
* running for the entire test).
*
* Note: Rare CI failure at the next line.
*
* junit.framework.AssertionFailedError: subtaskStartCount expected:<1> but was:<2>
* at com.bigdata.service.ndx.pipeline.TestMasterTaskIdleTimeout.test_idleTimeout_LT_chunkTimeout2(TestMasterTaskIdleTimeout.java:572)
*/
assertEquals("subtaskStartCount", 1, masterStats.subtaskStartCount.get());
assertEquals("subtaskEndCount", 1, masterStats.subtaskEndCount.get());
/*
* verify that chunks were combined until they had on average ~ N
* elements per sink since the rate of chunk arrival should have
* been ~ N times the chunk timeout.
*/
final double actualAverageOutputChunkSize = (double) masterStats.elementsOut
.get() / (double) masterStats.chunksOut.get();
final double r = actualAverageOutputChunkSize
/ expectedAverageOutputChunkSize;
final String msg = "average elements per output chunk: "
+ actualAverageOutputChunkSize + ", N=" + N + ", O=" + O
+ ", " + expectedAverageOutputChunkSize+", ratio="+r;
if(log.isInfoEnabled())
log.info(msg);
if (r < .8 || r > 1.1) {
/*
* The ration between the expected and observed average chunk
* sizes is not within some reasonable bounds on its
* performance. [It is more likely that this will report an
* error for a short run, but the values should be quite close
* on a longer run.]
*/
fail(msg);
}
// assertTrue(elementsPerChunk>masterState.chunks)
} finally {
scheduledExecutorService.shutdownNow();
}
}
/**
* Unit test verifies correct shutdown when writing chunks onto a master
* whose subtask has an infinite chunk timeout and an infinite idle timeout.
* In this situation the subtask must notice that the master's input buffer
* has been closed and close its input buffer so that it will process any
* elements remaining in that buffer and then terminate.
*
* @throws InterruptedException
* @throws ExecutionException
*/
public void test_idleTimeoutInfinite_chunkTimeoutInfinite() throws InterruptedException,
ExecutionException {
final H masterStats = new H();
final BlockingBuffer<KVO<O>[]> masterBuffer = new BlockingBuffer<KVO<O>[]>(
masterQueueCapacity);
final M master = new M(masterStats, masterBuffer, executorService,
Long.MAX_VALUE/* sinkIdleTimeout */, M.DEFAULT_SINK_POLL_TIMEOUT) {
/**
* The subtask will use a buffer with an infinite chunk timeout.
*/
@Override
protected BlockingBuffer<KVO<O>[]> newSubtaskBuffer() {
return new BlockingBuffer<KVO<O>[]>(
new ArrayBlockingQueue<KVO<O>[]>(subtaskQueueCapacity), //
BlockingBuffer.DEFAULT_MINIMUM_CHUNK_SIZE,//
Long.MAX_VALUE, TimeUnit.SECONDS,// chunkTimeout
true // ordered
);
}
};
// Wrap computation as FutureTask.
final FutureTask<H> ft = new FutureTask<H>(master);
// Set Future on BlockingBuffer.
masterBuffer.setFuture(ft);
// Start the consumer.
executorService.submit(ft);
// write a chunk on the master.
{
final KVO<O>[] a = new KVO[] {
new KVO<O>(new byte[] { 1 }, new byte[] { 1 }, null/* val */)
};
masterBuffer.add(a);
}
/*
* Sleep long enough that we may assume that the chunk has been
* propagated by the master to the subtask.
*/
Thread.sleep(1000/* ms */);
// verify that the master has accepted the 1st chunk.
assertEquals("elementsIn", 1, masterStats.elementsIn.get());
assertEquals("chunksIn", 1, masterStats.chunksIn.get());
// verify that nothing has been output yet.
assertEquals("elementsOut", 0, masterStats.elementsOut.get());
assertEquals("chunksOut", 0, masterStats.chunksOut.get());
// write another chunk on the master (distinct values).
{
final KVO<O>[] a = new KVO[] {
new KVO<O>(new byte[] { 1 }, new byte[] { 2 }, null/* val */)
};
masterBuffer.add(a);
}
// sleep some more.
Thread.sleep(1000/* ms */);
// verify that the master has accepted the 2nd chunk.
assertEquals("elementsIn", 2, masterStats.elementsIn.get());
assertEquals("chunksIn", 2, masterStats.chunksIn.get());
// verify that nothing has been output yet.
assertEquals("elementsOut", 0, masterStats.elementsOut.get());
assertEquals("chunksOut", 0, masterStats.chunksOut.get());
// close the master - the output sink should now emit a chunk.
masterBuffer.close();
// await the future.
masterBuffer.getFuture().get();
// verify elements in/out; chunks in/out
assertEquals("elementsIn", 2, masterStats.elementsIn.get());
assertEquals("chunksIn", 2, masterStats.chunksIn.get());
assertEquals("elementsOut", 2, masterStats.elementsOut.get());
assertEquals("chunksOut", 1, masterStats.chunksOut.get());
assertEquals("partitionCount", 1, masterStats.getMaximumPartitionCount());
}
/**
* Unit test verifies that an idle timeout will cause a sink to flush its
* buffer without waiting to combine additional chunks even though it has an
* infinite chunkTimeout.
*
* @throws InterruptedException
* @throws ExecutionException
* @throws TimeoutException
*/
public void test_idleTimeout_with_infiniteChunkTimeout()
throws InterruptedException, ExecutionException, TimeoutException {
final long sinkIdleTimeoutNanos = TimeUnit.MILLISECONDS.toNanos(100);
final H masterStats = new H();
final BlockingBuffer<KVO<O>[]> masterBuffer = new BlockingBuffer<KVO<O>[]>(
masterQueueCapacity);
final M master = new M(masterStats, masterBuffer, executorService,
sinkIdleTimeoutNanos, M.DEFAULT_SINK_POLL_TIMEOUT) {
/**
* The subtask will use a buffer with an infinite chunk timeout.
*/
@Override
protected BlockingBuffer<KVO<O>[]> newSubtaskBuffer() {
return new BlockingBuffer<KVO<O>[]>(
new ArrayBlockingQueue<KVO<O>[]>(subtaskQueueCapacity), //
BlockingBuffer.DEFAULT_MINIMUM_CHUNK_SIZE,//
Long.MAX_VALUE, TimeUnit.SECONDS,// chunkTimeout (infinite)
true // ordered
);
}
};
// Wrap computation as FutureTask.
final FutureTask<H> ft = new FutureTask<H>(master);
// Set Future on BlockingBuffer.
masterBuffer.setFuture(ft);
// Start the consumer.
executorService.submit(ft);
// write a chunk on the master.
{
final KVO<O>[] a = new KVO[] {
new KVO<O>(new byte[] { 1 }, new byte[] { 1 }, null/* val */)
};
masterBuffer.add(a);
}
/*
* Sleep long enough that we may assume that the chunk has been
* propagated by the master to the subtask but less than the subtask
* idle timeout.
*/
Thread.sleep(TimeUnit.NANOSECONDS.toMillis(sinkIdleTimeoutNanos) / 2);
// verify that the master has accepted the 1st chunk.
assertEquals("elementsIn", 1, masterStats.elementsIn.get());
assertEquals("chunksIn", 1, masterStats.chunksIn.get());
// verify that nothing has been output yet.
assertEquals("elementsOut", 0, masterStats.elementsOut.get());
assertEquals("chunksOut", 0, masterStats.chunksOut.get());
// verify subtask has started but not yet ended.
assertEquals("subtaskStartCount", 1, masterStats.subtaskStartCount.get());
assertEquals("subtaskEndCount", 0, masterStats.subtaskEndCount.get());
assertEquals("subtaskIdleTimeout", 0, masterStats.subtaskIdleTimeoutCount.get());
assertEquals("partitionCount", 1, masterStats.getMaximumPartitionCount());
// write another chunk on the master (distinct values).
{
final KVO<O>[] a = new KVO[] {
new KVO<O>(new byte[] { 1 }, new byte[] { 2 }, null/* val */)
};
masterBuffer.add(a);
}
// sleep some more, again not exceeding the subtask idle timeout.
Thread.sleep(TimeUnit.NANOSECONDS.toMillis(sinkIdleTimeoutNanos) / 2);
// verify that the master has accepted the 2nd chunk.
assertEquals("elementsIn", 2, masterStats.elementsIn.get());
assertEquals("chunksIn", 2, masterStats.chunksIn.get());
// verify that nothing has been output yet.
assertEquals("elementsOut", 0, masterStats.elementsOut.get());
assertEquals("chunksOut", 0, masterStats.chunksOut.get());
// verify the same subtask is still running.
assertEquals("subtaskStartCount", 1, masterStats.subtaskStartCount.get());
assertEquals("subtaskEndCount", 0, masterStats.subtaskEndCount.get());
assertEquals("subtaskIdleTimeout", 0, masterStats.subtaskIdleTimeoutCount.get());
assertEquals("partitionCount", 1, masterStats.getMaximumPartitionCount());
/*
* Sleep long enough for the subtask idle timeout to be exceeded. The
* subtask should emit a chunk which combines the two chunks written on
* it by the master and then close itself.
*/
Thread.sleep(TimeUnit.NANOSECONDS.toMillis(sinkIdleTimeoutNanos) * 2);
// verify elements in/out; chunks in/out
assertEquals("elementsIn", 2, masterStats.elementsIn.get());
assertEquals("chunksIn", 2, masterStats.chunksIn.get());
assertEquals("elementsOut", 2, masterStats.elementsOut.get());
assertEquals("chunksOut", 1, masterStats.chunksOut.get());
/*
* Verify only one subtask started, that it is now ended, and that it
* ended via an idle timeout.
*/
assertEquals("subtaskStartCount", 1, masterStats.subtaskStartCount.get());
assertEquals("subtaskEndCount", 1, masterStats.subtaskEndCount.get());
assertEquals("subtaskIdleTimeout", 1, masterStats.subtaskIdleTimeoutCount.get());
assertEquals("partitionCount", 1, masterStats.getMaximumPartitionCount());
// close the master.
masterBuffer.close();
/*
* await the future, but only for a little while in case the subtask
* does not terminate correctly.
*/
masterBuffer.getFuture().get(1, TimeUnit.SECONDS);
/*
* Note: These tests are the same as those before we close the master.
* None of these asserts should be violated by closing the master.
*/
// verify elements in/out; chunks in/out
assertEquals("elementsIn", 2, masterStats.elementsIn.get());
assertEquals("chunksIn", 2, masterStats.chunksIn.get());
assertEquals("elementsOut", 2, masterStats.elementsOut.get());
assertEquals("chunksOut", 1, masterStats.chunksOut.get());
/*
* Verify only one subtask started, that it is now ended, and that it
* ended via an idle timeout.
*/
assertEquals("subtaskStartCount", 1, masterStats.subtaskStartCount.get());
assertEquals("subtaskEndCount", 1, masterStats.subtaskEndCount.get());
assertEquals("subtaskIdleTimeout", 1, masterStats.subtaskIdleTimeoutCount.get());
assertEquals("partitionCount", 1, masterStats.getMaximumPartitionCount());
}
}
|
smalyshev/blazegraph
|
bigdata/src/test/com/bigdata/service/ndx/pipeline/TestMasterTaskIdleTimeout.java
|
Java
|
gpl-2.0
| 36,679
|
/*
* Copyright (C) 2012 Red Hat, Inc.
*
* Nautilus 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.
*
* Nautilus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; see the file COPYING. If not,
* see <http://www.gnu.org/licenses/>.
*
*/
#ifndef NAUTILUS_SEARCH_HIT_H
#define NAUTILUS_SEARCH_HIT_H
#include <glib-object.h>
#include "nautilus-query.h"
G_BEGIN_DECLS
#define NAUTILUS_TYPE_SEARCH_HIT (nautilus_search_hit_get_type ())
G_DECLARE_FINAL_TYPE (NautilusSearchHit, nautilus_search_hit, NAUTILUS, SEARCH_HIT, GObject);
NautilusSearchHit * nautilus_search_hit_new (const char *uri);
void nautilus_search_hit_set_fts_rank (NautilusSearchHit *hit,
gdouble fts_rank);
void nautilus_search_hit_set_modification_time (NautilusSearchHit *hit,
GDateTime *date);
void nautilus_search_hit_set_access_time (NautilusSearchHit *hit,
GDateTime *date);
void nautilus_search_hit_compute_scores (NautilusSearchHit *hit,
NautilusQuery *query);
const char * nautilus_search_hit_get_uri (NautilusSearchHit *hit);
gdouble nautilus_search_hit_get_relevance (NautilusSearchHit *hit);
G_END_DECLS
#endif /* NAUTILUS_SEARCH_HIT_H */
|
daschuer/nautilus
|
src/nautilus-search-hit.h
|
C
|
gpl-2.0
| 1,835
|
/* global tinymce */
tinymce.PluginManager.add( 'wpeditimage', function( editor ) {
var toolbar, serializer,
each = tinymce.each,
trim = tinymce.trim,
iOS = tinymce.Env.iOS;
function isPlaceholder( node ) {
return !! ( editor.dom.getAttrib( node, 'data-mce-placeholder' ) || editor.dom.getAttrib( node, 'data-mce-object' ) );
}
editor.addButton( 'wp_img_remove', {
tooltip: 'Remove',
icon: 'dashicon dashicons-no',
onclick: function() {
removeImage( editor.selection.getNode() );
}
} );
editor.addButton( 'wp_img_edit', {
tooltip: 'Edit ', // trailing space is needed, used for context
icon: 'dashicon dashicons-edit',
onclick: function() {
editImage( editor.selection.getNode() );
}
} );
each( {
alignleft: 'Align left',
aligncenter: 'Align center',
alignright: 'Align right',
alignnone: 'No alignment'
}, function( tooltip, name ) {
var direction = name.slice( 5 );
editor.addButton( 'wp_img_' + name, {
tooltip: tooltip,
icon: 'dashicon dashicons-align-' + direction,
cmd: 'alignnone' === name ? 'wpAlignNone' : 'Justify' + direction.slice( 0, 1 ).toUpperCase() + direction.slice( 1 ),
onPostRender: function() {
var self = this;
editor.on( 'NodeChange', function( event ) {
var node;
// Don't bother.
if ( event.element.nodeName !== 'IMG' ) {
return;
}
node = editor.dom.getParent( event.element, '.wp-caption' ) || event.element;
if ( 'alignnone' === name ) {
self.active( ! /\balign(left|center|right)\b/.test( node.className ) );
} else {
self.active( editor.dom.hasClass( node, name ) );
}
} );
}
} );
} );
editor.once( 'preinit', function() {
if ( editor.wp && editor.wp._createToolbar ) {
toolbar = editor.wp._createToolbar( [
'wp_img_alignleft',
'wp_img_aligncenter',
'wp_img_alignright',
'wp_img_alignnone',
'wp_img_edit',
'wp_img_remove'
] );
}
} );
editor.on( 'wptoolbar', function( event ) {
if ( event.element.nodeName === 'IMG' && ! isPlaceholder( event.element ) ) {
event.toolbar = toolbar;
}
} );
// Safari on iOS fails to select image nodes in contentEditoble mode on touch/click.
// Select them again.
if ( iOS ) {
editor.on( 'click', function( event ) {
if ( event.target.nodeName === 'IMG' ) {
var node = event.target;
window.setTimeout( function() {
editor.selection.select( node );
editor.nodeChanged();
}, 200 );
} else if ( toolbar ) {
toolbar.hide();
}
} );
}
function parseShortcode( content ) {
return content.replace( /(?:<p>)?\[(?:wp_)?caption([^\]]+)\]([\s\S]+?)\[\/(?:wp_)?caption\](?:<\/p>)?/g, function( a, b, c ) {
var id, align, classes, caption, img, width;
id = b.match( /id=['"]([^'"]*)['"] ?/ );
if ( id ) {
b = b.replace( id[0], '' );
}
align = b.match( /align=['"]([^'"]*)['"] ?/ );
if ( align ) {
b = b.replace( align[0], '' );
}
classes = b.match( /class=['"]([^'"]*)['"] ?/ );
if ( classes ) {
b = b.replace( classes[0], '' );
}
width = b.match( /width=['"]([0-9]*)['"] ?/ );
if ( width ) {
b = b.replace( width[0], '' );
}
c = trim( c );
img = c.match( /((?:<a [^>]+>)?<img [^>]+>(?:<\/a>)?)([\s\S]*)/i );
if ( img && img[2] ) {
caption = trim( img[2] );
img = trim( img[1] );
} else {
// old captions shortcode style
caption = trim( b ).replace( /caption=['"]/, '' ).replace( /['"]$/, '' );
img = c;
}
id = ( id && id[1] ) ? id[1].replace( /[<>&]+/g, '' ) : '';
align = ( align && align[1] ) ? align[1] : 'alignnone';
classes = ( classes && classes[1] ) ? ' ' + classes[1].replace( /[<>&]+/g, '' ) : '';
if ( ! width && img ) {
width = img.match( /width=['"]([0-9]*)['"]/ );
}
if ( width && width[1] ) {
width = width[1];
}
if ( ! width || ! caption ) {
return c;
}
width = parseInt( width, 10 );
if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
width += 10;
}
return '<div class="mceTemp"><dl id="' + id + '" class="wp-caption ' + align + classes + '" style="width: ' + width + 'px">' +
'<dt class="wp-caption-dt">'+ img +'</dt><dd class="wp-caption-dd">'+ caption +'</dd></dl></div>';
});
}
function getShortcode( content ) {
return content.replace( /<div (?:id="attachment_|class="mceTemp)[^>]*>([\s\S]+?)<\/div>/g, function( a, b ) {
var out = '';
if ( b.indexOf('<img ') === -1 ) {
// Broken caption. The user managed to drag the image out?
// Try to return the caption text as a paragraph.
out = b.match( /<dd [^>]+>([\s\S]+?)<\/dd>/i );
if ( out && out[1] ) {
return '<p>' + out[1] + '</p>';
}
return '';
}
out = b.replace( /\s*<dl ([^>]+)>\s*<dt [^>]+>([\s\S]+?)<\/dt>\s*<dd [^>]+>([\s\S]*?)<\/dd>\s*<\/dl>\s*/gi, function( a, b, c, caption ) {
var id, classes, align, width;
width = c.match( /width="([0-9]*)"/ );
width = ( width && width[1] ) ? width[1] : '';
classes = b.match( /class="([^"]*)"/ );
classes = ( classes && classes[1] ) ? classes[1] : '';
align = classes.match( /align[a-z]+/i ) || 'alignnone';
if ( ! width || ! caption ) {
if ( 'alignnone' !== align[0] ) {
c = c.replace( /><img/, ' class="' + align[0] + '"><img' );
}
return c;
}
id = b.match( /id="([^"]*)"/ );
id = ( id && id[1] ) ? id[1] : '';
classes = classes.replace( /wp-caption ?|align[a-z]+ ?/gi, '' );
if ( classes ) {
classes = ' class="' + classes + '"';
}
caption = caption.replace( /\r\n|\r/g, '\n' ).replace( /<[a-zA-Z0-9]+( [^<>]+)?>/g, function( a ) {
// no line breaks inside HTML tags
return a.replace( /[\r\n\t]+/, ' ' );
});
// convert remaining line breaks to <br>
caption = caption.replace( /\s*\n\s*/g, '<br />' );
return '[caption id="' + id + '" align="' + align + '" width="' + width + '"' + classes + ']' + c + ' ' + caption + '[/caption]';
});
if ( out.indexOf('[caption') === -1 ) {
// the caption html seems broken, try to find the image that may be wrapped in a link
// and may be followed by <p> with the caption text.
out = b.replace( /[\s\S]*?((?:<a [^>]+>)?<img [^>]+>(?:<\/a>)?)(<p>[\s\S]*<\/p>)?[\s\S]*/gi, '<p>$1</p>$2' );
}
return out;
});
}
function extractImageData( imageNode ) {
var classes, extraClasses, metadata, captionBlock, caption, link, width, height,
captionClassName = [],
dom = editor.dom,
isIntRegExp = /^\d+$/;
// default attributes
metadata = {
attachment_id: false,
size: 'custom',
caption: '',
align: 'none',
extraClasses: '',
link: false,
linkUrl: '',
linkClassName: '',
linkTargetBlank: false,
linkRel: '',
title: ''
};
metadata.url = dom.getAttrib( imageNode, 'src' );
metadata.alt = dom.getAttrib( imageNode, 'alt' );
metadata.title = dom.getAttrib( imageNode, 'title' );
width = dom.getAttrib( imageNode, 'width' );
height = dom.getAttrib( imageNode, 'height' );
if ( ! isIntRegExp.test( width ) || parseInt( width, 10 ) < 1 ) {
width = imageNode.naturalWidth || imageNode.width;
}
if ( ! isIntRegExp.test( height ) || parseInt( height, 10 ) < 1 ) {
height = imageNode.naturalHeight || imageNode.height;
}
metadata.customWidth = metadata.width = width;
metadata.customHeight = metadata.height = height;
classes = tinymce.explode( imageNode.className, ' ' );
extraClasses = [];
tinymce.each( classes, function( name ) {
if ( /^wp-image/.test( name ) ) {
metadata.attachment_id = parseInt( name.replace( 'wp-image-', '' ), 10 );
} else if ( /^align/.test( name ) ) {
metadata.align = name.replace( 'align', '' );
} else if ( /^size/.test( name ) ) {
metadata.size = name.replace( 'size-', '' );
} else {
extraClasses.push( name );
}
} );
metadata.extraClasses = extraClasses.join( ' ' );
// Extract caption
captionBlock = dom.getParents( imageNode, '.wp-caption' );
if ( captionBlock.length ) {
captionBlock = captionBlock[0];
classes = captionBlock.className.split( ' ' );
tinymce.each( classes, function( name ) {
if ( /^align/.test( name ) ) {
metadata.align = name.replace( 'align', '' );
} else if ( name && name !== 'wp-caption' ) {
captionClassName.push( name );
}
} );
metadata.captionClassName = captionClassName.join( ' ' );
caption = dom.select( 'dd.wp-caption-dd', captionBlock );
if ( caption.length ) {
caption = caption[0];
metadata.caption = editor.serializer.serialize( caption )
.replace( /<br[^>]*>/g, '$&\n' ).replace( /^<p>/, '' ).replace( /<\/p>$/, '' );
}
}
// Extract linkTo
if ( imageNode.parentNode && imageNode.parentNode.nodeName === 'A' ) {
link = imageNode.parentNode;
metadata.linkUrl = dom.getAttrib( link, 'href' );
metadata.linkTargetBlank = dom.getAttrib( link, 'target' ) === '_blank' ? true : false;
metadata.linkRel = dom.getAttrib( link, 'rel' );
metadata.linkClassName = link.className;
}
return metadata;
}
function hasTextContent( node ) {
return node && !! ( node.textContent || node.innerText );
}
// Verify HTML in captions
function verifyHTML( caption ) {
if ( ! caption || ( caption.indexOf( '<' ) === -1 && caption.indexOf( '>' ) === -1 ) ) {
return caption;
}
if ( ! serializer ) {
serializer = new tinymce.html.Serializer( {}, editor.schema );
}
return serializer.serialize( editor.parser.parse( caption, { forced_root_block: false } ) );
}
function updateImage( imageNode, imageData ) {
var classes, className, node, html, parent, wrap, linkNode,
captionNode, dd, dl, id, attrs, linkAttrs, width, height, align,
dom = editor.dom;
classes = tinymce.explode( imageData.extraClasses, ' ' );
if ( ! classes ) {
classes = [];
}
if ( ! imageData.caption ) {
classes.push( 'align' + imageData.align );
}
if ( imageData.attachment_id ) {
classes.push( 'wp-image-' + imageData.attachment_id );
if ( imageData.size && imageData.size !== 'custom' ) {
classes.push( 'size-' + imageData.size );
}
}
width = imageData.width;
height = imageData.height;
if ( imageData.size === 'custom' ) {
width = imageData.customWidth;
height = imageData.customHeight;
}
attrs = {
src: imageData.url,
width: width || null,
height: height || null,
alt: imageData.alt,
title: imageData.title || null,
'class': classes.join( ' ' ) || null
};
dom.setAttribs( imageNode, attrs );
linkAttrs = {
href: imageData.linkUrl,
rel: imageData.linkRel || null,
target: imageData.linkTargetBlank ? '_blank': null,
'class': imageData.linkClassName || null
};
if ( imageNode.parentNode && imageNode.parentNode.nodeName === 'A' && ! hasTextContent( imageNode.parentNode ) ) {
// Update or remove an existing link wrapped around the image
if ( imageData.linkUrl ) {
dom.setAttribs( imageNode.parentNode, linkAttrs );
} else {
dom.remove( imageNode.parentNode, true );
}
} else if ( imageData.linkUrl ) {
if ( linkNode = dom.getParent( imageNode, 'a' ) ) {
// The image is inside a link together with other nodes,
// or is nested in another node, move it out
dom.insertAfter( imageNode, linkNode );
}
// Add link wrapped around the image
linkNode = dom.create( 'a', linkAttrs );
imageNode.parentNode.insertBefore( linkNode, imageNode );
linkNode.appendChild( imageNode );
}
captionNode = editor.dom.getParent( imageNode, '.mceTemp' );
if ( imageNode.parentNode && imageNode.parentNode.nodeName === 'A' && ! hasTextContent( imageNode.parentNode ) ) {
node = imageNode.parentNode;
} else {
node = imageNode;
}
if ( imageData.caption ) {
imageData.caption = verifyHTML( imageData.caption );
id = imageData.attachment_id ? 'attachment_' + imageData.attachment_id : null;
align = 'align' + ( imageData.align || 'none' );
className = 'wp-caption ' + align;
if ( imageData.captionClassName ) {
className += ' ' + imageData.captionClassName.replace( /[<>&]+/g, '' );
}
if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
width = parseInt( width, 10 );
width += 10;
}
if ( captionNode ) {
dl = dom.select( 'dl.wp-caption', captionNode );
if ( dl.length ) {
dom.setAttribs( dl, {
id: id,
'class': className,
style: 'width: ' + width + 'px'
} );
}
dd = dom.select( '.wp-caption-dd', captionNode );
if ( dd.length ) {
dom.setHTML( dd[0], imageData.caption );
}
} else {
id = id ? 'id="'+ id +'" ' : '';
// should create a new function for generating the caption markup
html = '<dl ' + id + 'class="' + className +'" style="width: '+ width +'px">' +
'<dt class="wp-caption-dt"></dt><dd class="wp-caption-dd">'+ imageData.caption +'</dd></dl>';
wrap = dom.create( 'div', { 'class': 'mceTemp' }, html );
if ( parent = dom.getParent( node, 'p' ) ) {
parent.parentNode.insertBefore( wrap, parent );
} else {
node.parentNode.insertBefore( wrap, node );
}
editor.$( wrap ).find( 'dt.wp-caption-dt' ).append( node );
if ( parent && dom.isEmpty( parent ) ) {
dom.remove( parent );
}
}
} else if ( captionNode ) {
// Remove the caption wrapper and place the image in new paragraph
parent = dom.create( 'p' );
captionNode.parentNode.insertBefore( parent, captionNode );
parent.appendChild( node );
dom.remove( captionNode );
}
if ( wp.media.events ) {
wp.media.events.trigger( 'editor:image-update', {
editor: editor,
metadata: imageData,
image: imageNode
} );
}
editor.nodeChanged();
}
function editImage( img ) {
var frame, callback, metadata;
if ( typeof wp === 'undefined' || ! wp.media ) {
editor.execCommand( 'mceImage' );
return;
}
metadata = extractImageData( img );
// Manipulate the metadata by reference that is fed into the PostImage model used in the media modal
wp.media.events.trigger( 'editor:image-edit', {
editor: editor,
metadata: metadata,
image: img
} );
frame = wp.media({
frame: 'image',
state: 'image-details',
metadata: metadata
} );
wp.media.events.trigger( 'editor:frame-create', { frame: frame } );
callback = function( imageData ) {
editor.focus();
editor.undoManager.transact( function() {
updateImage( img, imageData );
} );
frame.detach();
};
frame.state('image-details').on( 'update', callback );
frame.state('replace-image').on( 'replace', callback );
frame.on( 'close', function() {
editor.focus();
frame.detach();
});
frame.open();
}
function removeImage( node ) {
var wrap = editor.dom.getParent( node, 'div.mceTemp' );
if ( ! wrap && node.nodeName === 'IMG' ) {
wrap = editor.dom.getParent( node, 'a' );
}
if ( wrap ) {
if ( wrap.nextSibling ) {
editor.selection.select( wrap.nextSibling );
} else if ( wrap.previousSibling ) {
editor.selection.select( wrap.previousSibling );
} else {
editor.selection.select( wrap.parentNode );
}
editor.selection.collapse( true );
editor.dom.remove( wrap );
} else {
editor.dom.remove( node );
}
editor.nodeChanged();
editor.undoManager.add();
}
editor.on( 'init', function() {
var dom = editor.dom,
captionClass = editor.getParam( 'wpeditimage_html5_captions' ) ? 'html5-captions' : 'html4-captions';
dom.addClass( editor.getBody(), captionClass );
// Add caption field to the default image dialog
editor.on( 'wpLoadImageForm', function( event ) {
if ( editor.getParam( 'wpeditimage_disable_captions' ) ) {
return;
}
var captionField = {
type: 'textbox',
flex: 1,
name: 'caption',
minHeight: 60,
multiline: true,
scroll: true,
label: 'Image caption'
};
event.data.splice( event.data.length - 1, 0, captionField );
});
// Fix caption parent width for images added from URL
editor.on( 'wpNewImageRefresh', function( event ) {
var parent, captionWidth;
if ( parent = dom.getParent( event.node, 'dl.wp-caption' ) ) {
if ( ! parent.style.width ) {
captionWidth = parseInt( event.node.clientWidth, 10 ) + 10;
captionWidth = captionWidth ? captionWidth + 'px' : '50%';
dom.setStyle( parent, 'width', captionWidth );
}
}
});
editor.on( 'wpImageFormSubmit', function( event ) {
var data = event.imgData.data,
imgNode = event.imgData.node,
caption = event.imgData.caption,
captionId = '',
captionAlign = '',
captionWidth = '',
wrap, parent, node, html, imgId;
// Temp image id so we can find the node later
data.id = '__wp-temp-img-id';
// Cancel the original callback
event.imgData.cancel = true;
if ( ! data.style ) {
data.style = null;
}
if ( ! data.src ) {
// Delete the image and the caption
if ( imgNode ) {
if ( wrap = dom.getParent( imgNode, 'div.mceTemp' ) ) {
dom.remove( wrap );
} else if ( imgNode.parentNode.nodeName === 'A' ) {
dom.remove( imgNode.parentNode );
} else {
dom.remove( imgNode );
}
editor.nodeChanged();
}
return;
}
if ( caption ) {
caption = caption.replace( /\r\n|\r/g, '\n' ).replace( /<\/?[a-zA-Z0-9]+( [^<>]+)?>/g, function( a ) {
// No line breaks inside HTML tags
return a.replace( /[\r\n\t]+/, ' ' );
});
// Convert remaining line breaks to <br>
caption = caption.replace( /(<br[^>]*>)\s*\n\s*/g, '$1' ).replace( /\s*\n\s*/g, '<br />' );
caption = verifyHTML( caption );
}
if ( ! imgNode ) {
// New image inserted
html = dom.createHTML( 'img', data );
if ( caption ) {
node = editor.selection.getNode();
if ( data.width ) {
captionWidth = parseInt( data.width, 10 );
if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
captionWidth += 10;
}
captionWidth = ' style="width: ' + captionWidth + 'px"';
}
html = '<dl class="wp-caption alignnone"' + captionWidth + '>' +
'<dt class="wp-caption-dt">'+ html +'</dt><dd class="wp-caption-dd">'+ caption +'</dd></dl>';
if ( node.nodeName === 'P' ) {
parent = node;
} else {
parent = dom.getParent( node, 'p' );
}
if ( parent && parent.nodeName === 'P' ) {
wrap = dom.create( 'div', { 'class': 'mceTemp' }, html );
parent.parentNode.insertBefore( wrap, parent );
editor.selection.select( wrap );
editor.nodeChanged();
if ( dom.isEmpty( parent ) ) {
dom.remove( parent );
}
} else {
editor.selection.setContent( '<div class="mceTemp">' + html + '</div>' );
}
} else {
editor.selection.setContent( html );
}
} else {
// Edit existing image
// Store the original image id if any
imgId = imgNode.id || null;
// Update the image node
dom.setAttribs( imgNode, data );
wrap = dom.getParent( imgNode, 'dl.wp-caption' );
if ( caption ) {
if ( wrap ) {
if ( parent = dom.select( 'dd.wp-caption-dd', wrap )[0] ) {
parent.innerHTML = caption;
}
} else {
if ( imgNode.className ) {
captionId = imgNode.className.match( /wp-image-([0-9]+)/ );
captionAlign = imgNode.className.match( /align(left|right|center|none)/ );
}
if ( captionAlign ) {
captionAlign = captionAlign[0];
imgNode.className = imgNode.className.replace( /align(left|right|center|none)/g, '' );
} else {
captionAlign = 'alignnone';
}
captionAlign = ' class="wp-caption ' + captionAlign + '"';
if ( captionId ) {
captionId = ' id="attachment_' + captionId[1] + '"';
}
captionWidth = data.width || imgNode.clientWidth;
if ( captionWidth ) {
captionWidth = parseInt( captionWidth, 10 );
if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
captionWidth += 10;
}
captionWidth = ' style="width: '+ captionWidth +'px"';
}
if ( imgNode.parentNode && imgNode.parentNode.nodeName === 'A' ) {
node = imgNode.parentNode;
} else {
node = imgNode;
}
html = '<dl ' + captionId + captionAlign + captionWidth + '>' +
'<dt class="wp-caption-dt"></dt><dd class="wp-caption-dd">'+ caption +'</dd></dl>';
wrap = dom.create( 'div', { 'class': 'mceTemp' }, html );
if ( parent = dom.getParent( node, 'p' ) ) {
parent.parentNode.insertBefore( wrap, parent );
} else {
node.parentNode.insertBefore( wrap, node );
}
editor.$( wrap ).find( 'dt.wp-caption-dt' ).append( node );
if ( parent && dom.isEmpty( parent ) ) {
dom.remove( parent );
}
}
} else {
if ( wrap ) {
// Remove the caption wrapper and place the image in new paragraph
if ( imgNode.parentNode.nodeName === 'A' ) {
html = dom.getOuterHTML( imgNode.parentNode );
} else {
html = dom.getOuterHTML( imgNode );
}
parent = dom.create( 'p', {}, html );
dom.insertAfter( parent, wrap.parentNode );
editor.selection.select( parent );
editor.nodeChanged();
dom.remove( wrap.parentNode );
}
}
}
imgNode = dom.get('__wp-temp-img-id');
dom.setAttrib( imgNode, 'id', imgId );
event.imgData.node = imgNode;
});
editor.on( 'wpLoadImageData', function( event ) {
var parent,
data = event.imgData.data,
imgNode = event.imgData.node;
if ( parent = dom.getParent( imgNode, 'dl.wp-caption' ) ) {
parent = dom.select( 'dd.wp-caption-dd', parent )[0];
if ( parent ) {
data.caption = editor.serializer.serialize( parent )
.replace( /<br[^>]*>/g, '$&\n' ).replace( /^<p>/, '' ).replace( /<\/p>$/, '' );
}
}
});
dom.bind( editor.getDoc(), 'dragstart', function( event ) {
var node = editor.selection.getNode();
// Prevent dragging images out of the caption elements
if ( node.nodeName === 'IMG' && dom.getParent( node, '.wp-caption' ) ) {
event.preventDefault();
}
});
// Prevent IE11 from making dl.wp-caption resizable
if ( tinymce.Env.ie && tinymce.Env.ie > 10 ) {
// The 'mscontrolselect' event is supported only in IE11+
dom.bind( editor.getBody(), 'mscontrolselect', function( event ) {
if ( event.target.nodeName === 'IMG' && dom.getParent( event.target, '.wp-caption' ) ) {
// Hide the thick border with resize handles around dl.wp-caption
editor.getBody().focus(); // :(
} else if ( event.target.nodeName === 'DL' && dom.hasClass( event.target, 'wp-caption' ) ) {
// Trigger the thick border with resize handles...
// This will make the caption text editable.
event.target.focus();
}
});
}
});
editor.on( 'ObjectResized', function( event ) {
var node = event.target;
if ( node.nodeName === 'IMG' ) {
editor.undoManager.transact( function() {
var parent, width,
dom = editor.dom;
node.className = node.className.replace( /\bsize-[^ ]+/, '' );
if ( parent = dom.getParent( node, '.wp-caption' ) ) {
width = event.width || dom.getAttrib( node, 'width' );
if ( width ) {
width = parseInt( width, 10 );
if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
width += 10;
}
dom.setStyle( parent, 'width', width + 'px' );
}
}
});
}
});
editor.on( 'BeforeExecCommand', function( event ) {
var node, p, DL, align, replacement,
cmd = event.command,
dom = editor.dom;
if ( cmd === 'mceInsertContent' ) {
// When inserting content, if the caret is inside a caption create new paragraph under
// and move the caret there
if ( node = dom.getParent( editor.selection.getNode(), 'div.mceTemp' ) ) {
p = dom.create( 'p' );
dom.insertAfter( p, node );
editor.selection.setCursorLocation( p, 0 );
editor.nodeChanged();
}
} else if ( cmd === 'JustifyLeft' || cmd === 'JustifyRight' || cmd === 'JustifyCenter' || cmd === 'wpAlignNone' ) {
node = editor.selection.getNode();
align = 'align' + cmd.slice( 7 ).toLowerCase();
DL = editor.dom.getParent( node, '.wp-caption' );
if ( node.nodeName !== 'IMG' && ! DL ) {
return;
}
node = DL || node;
if ( editor.dom.hasClass( node, align ) ) {
replacement = ' alignnone';
} else {
replacement = ' ' + align;
}
node.className = trim( node.className.replace( / ?align(left|center|right|none)/g, '' ) + replacement );
editor.nodeChanged();
event.preventDefault();
if ( toolbar ) {
toolbar.reposition();
}
editor.fire( 'ExecCommand', {
command: cmd,
ui: event.ui,
value: event.value
} );
}
});
editor.on( 'keydown', function( event ) {
var node, wrap, P, spacer,
selection = editor.selection,
keyCode = event.keyCode,
dom = editor.dom,
VK = tinymce.util.VK;
if ( keyCode === VK.ENTER ) {
// When pressing Enter inside a caption move the caret to a new parapraph under it
node = selection.getNode();
wrap = dom.getParent( node, 'div.mceTemp' );
if ( wrap ) {
dom.events.cancel( event ); // Doesn't cancel all :(
// Remove any extra dt and dd cleated on pressing Enter...
tinymce.each( dom.select( 'dt, dd', wrap ), function( element ) {
if ( dom.isEmpty( element ) ) {
dom.remove( element );
}
});
spacer = tinymce.Env.ie && tinymce.Env.ie < 11 ? '' : '<br data-mce-bogus="1" />';
P = dom.create( 'p', null, spacer );
if ( node.nodeName === 'DD' ) {
dom.insertAfter( P, wrap );
} else {
wrap.parentNode.insertBefore( P, wrap );
}
editor.nodeChanged();
selection.setCursorLocation( P, 0 );
}
} else if ( keyCode === VK.DELETE || keyCode === VK.BACKSPACE ) {
node = selection.getNode();
if ( node.nodeName === 'DIV' && dom.hasClass( node, 'mceTemp' ) ) {
wrap = node;
} else if ( node.nodeName === 'IMG' || node.nodeName === 'DT' || node.nodeName === 'A' ) {
wrap = dom.getParent( node, 'div.mceTemp' );
}
if ( wrap ) {
dom.events.cancel( event );
removeImage( node );
return false;
}
}
});
// After undo/redo FF seems to set the image height very slowly when it is set to 'auto' in the CSS.
// This causes image.getBoundingClientRect() to return wrong values and the resize handles are shown in wrong places.
// Collapse the selection to remove the resize handles.
if ( tinymce.Env.gecko ) {
editor.on( 'undo redo', function() {
if ( editor.selection.getNode().nodeName === 'IMG' ) {
editor.selection.collapse();
}
});
}
editor.wpSetImgCaption = function( content ) {
return parseShortcode( content );
};
editor.wpGetImgCaption = function( content ) {
return getShortcode( content );
};
editor.on( 'BeforeSetContent', function( event ) {
if ( event.format !== 'raw' ) {
event.content = editor.wpSetImgCaption( event.content );
}
});
editor.on( 'PostProcess', function( event ) {
if ( event.get ) {
event.content = editor.wpGetImgCaption( event.content );
}
});
// Add to editor.wp
editor.wp = editor.wp || {};
editor.wp.isPlaceholder = isPlaceholder;
// Back-compat.
return {
_do_shcode: parseShortcode,
_get_shcode: getShortcode
};
});
|
casedot/AllYourBaseTemplate
|
wp-includes/js/tinymce/plugins/wpeditimage/plugin.js
|
JavaScript
|
gpl-2.0
| 28,308
|
/*
* linux/arch/arm/kernel/arch_timer.c
*
* Copyright (C) 2011 ARM Ltd.
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/timex.h>
#include <linux/device.h>
#include <linux/smp.h>
#include <linux/cpu.h>
#include <linux/cpu_pm.h>
#include <linux/jiffies.h>
#include <linux/clockchips.h>
#include <linux/interrupt.h>
#include <linux/of_irq.h>
#include <linux/of_address.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/export.h>
#include <linux/slab.h>
#include <linux/sched_clock.h>
#include <asm/cputype.h>
#include <asm/delay.h>
#include <asm/localtimer.h>
#include <asm/arch_timer.h>
#include <asm/hardware/gic.h>
#include <asm/system_info.h>
static unsigned long arch_timer_rate;
static int arch_timer_spi;
static int arch_timer_ppi;
static int arch_timer_ppi2;
static struct clock_event_device __percpu **arch_timer_evt;
static void __iomem *timer_base;
static struct delay_timer arch_delay_timer;
/*
* Architected system timer support.
*/
#define ARCH_TIMER_CTRL_ENABLE (1 << 0)
#define ARCH_TIMER_CTRL_IT_MASK (1 << 1)
#define ARCH_TIMER_CTRL_IT_STAT (1 << 2)
#define ARCH_TIMER_REG_CTRL 0
#define ARCH_TIMER_REG_FREQ 1
#define ARCH_TIMER_REG_TVAL 2
/* Iomapped Register Offsets */
#define QTIMER_CNTP_LOW_REG 0x000
#define QTIMER_CNTP_HIGH_REG 0x004
#define QTIMER_CNTV_LOW_REG 0x008
#define QTIMER_CNTV_HIGH_REG 0x00C
#define QTIMER_CTRL_REG 0x02C
#define QTIMER_FREQ_REG 0x010
#define QTIMER_CNTP_TVAL_REG 0x028
#define QTIMER_CNTV_TVAL_REG 0x038
static inline void timer_reg_write_mem(int reg, u32 val)
{
switch (reg) {
case ARCH_TIMER_REG_CTRL:
__raw_writel(val, timer_base + QTIMER_CTRL_REG);
break;
case ARCH_TIMER_REG_TVAL:
__raw_writel(val, timer_base + QTIMER_CNTP_TVAL_REG);
break;
}
}
static inline void timer_reg_write_cp15(int reg, u32 val)
{
switch (reg) {
case ARCH_TIMER_REG_CTRL:
asm volatile("mcr p15, 0, %0, c14, c2, 1" : : "r" (val));
break;
case ARCH_TIMER_REG_TVAL:
asm volatile("mcr p15, 0, %0, c14, c2, 0" : : "r" (val));
break;
}
isb();
}
static inline void arch_timer_reg_write(int cp15, int reg, u32 val)
{
if (cp15)
timer_reg_write_cp15(reg, val);
else
timer_reg_write_mem(reg, val);
}
static inline u32 timer_reg_read_mem(int reg)
{
u32 val;
switch (reg) {
case ARCH_TIMER_REG_CTRL:
val = __raw_readl(timer_base + QTIMER_CTRL_REG);
break;
case ARCH_TIMER_REG_FREQ:
val = __raw_readl(timer_base + QTIMER_FREQ_REG);
break;
case ARCH_TIMER_REG_TVAL:
val = __raw_readl(timer_base + QTIMER_CNTP_TVAL_REG);
break;
default:
BUG();
}
return val;
}
static inline u32 timer_reg_read_cp15(int reg)
{
u32 val;
switch (reg) {
case ARCH_TIMER_REG_CTRL:
asm volatile("mrc p15, 0, %0, c14, c2, 1" : "=r" (val));
break;
case ARCH_TIMER_REG_FREQ:
asm volatile("mrc p15, 0, %0, c14, c0, 0" : "=r" (val));
break;
case ARCH_TIMER_REG_TVAL:
asm volatile("mrc p15, 0, %0, c14, c2, 0" : "=r" (val));
break;
default:
BUG();
}
return val;
}
static inline u32 arch_timer_reg_read(int cp15, int reg)
{
if (cp15)
return timer_reg_read_cp15(reg);
else
return timer_reg_read_mem(reg);
}
static inline irqreturn_t arch_timer_handler(int cp15,
struct clock_event_device *evt)
{
unsigned long ctrl;
ctrl = arch_timer_reg_read(cp15, ARCH_TIMER_REG_CTRL);
if (ctrl & ARCH_TIMER_CTRL_IT_STAT) {
ctrl |= ARCH_TIMER_CTRL_IT_MASK;
arch_timer_reg_write(cp15, ARCH_TIMER_REG_CTRL, ctrl);
evt->event_handler(evt);
return IRQ_HANDLED;
}
return IRQ_NONE;
}
static irqreturn_t arch_timer_handler_cp15(int irq, void *dev_id)
{
struct clock_event_device *evt = *(struct clock_event_device **)dev_id;
return arch_timer_handler(1, evt);
}
static irqreturn_t arch_timer_handler_mem(int irq, void *dev_id)
{
return arch_timer_handler(0, dev_id);
}
static inline void arch_timer_set_mode(int cp15, enum clock_event_mode mode,
struct clock_event_device *clk)
{
unsigned long ctrl;
switch (mode) {
case CLOCK_EVT_MODE_UNUSED:
case CLOCK_EVT_MODE_SHUTDOWN:
ctrl = arch_timer_reg_read(cp15, ARCH_TIMER_REG_CTRL);
ctrl &= ~ARCH_TIMER_CTRL_ENABLE;
arch_timer_reg_write(cp15, ARCH_TIMER_REG_CTRL, ctrl);
break;
case CLOCK_EVT_MODE_ONESHOT:
ctrl = arch_timer_reg_read(cp15, ARCH_TIMER_REG_CTRL);
ctrl |= ARCH_TIMER_CTRL_ENABLE;
arch_timer_reg_write(cp15, ARCH_TIMER_REG_CTRL, ctrl);
default:
break;
}
}
static void arch_timer_set_mode_cp15(enum clock_event_mode mode,
struct clock_event_device *clk)
{
arch_timer_set_mode(1, mode, clk);
}
static void arch_timer_set_mode_mem(enum clock_event_mode mode,
struct clock_event_device *clk)
{
arch_timer_set_mode(0, mode, clk);
}
static int arch_timer_set_next_event(int cp15, unsigned long evt,
struct clock_event_device *unused)
{
unsigned long ctrl;
ctrl = arch_timer_reg_read(cp15, ARCH_TIMER_REG_CTRL);
ctrl &= ~ARCH_TIMER_CTRL_IT_MASK;
arch_timer_reg_write(cp15, ARCH_TIMER_REG_CTRL, ctrl);
arch_timer_reg_write(cp15, ARCH_TIMER_REG_TVAL, evt);
return 0;
}
static int arch_timer_set_next_event_cp15(unsigned long evt,
struct clock_event_device *unused)
{
return arch_timer_set_next_event(1, evt, unused);
}
static int arch_timer_set_next_event_mem(unsigned long evt,
struct clock_event_device *unused)
{
return arch_timer_set_next_event(0, evt, unused);
}
static int __cpuinit arch_timer_setup(struct clock_event_device *clk)
{
/* setup clock event only once for CPU 0 */
if (!smp_processor_id() && clk->irq == arch_timer_ppi)
return 0;
clk->features = CLOCK_EVT_FEAT_ONESHOT | CLOCK_EVT_FEAT_C3STOP;
clk->name = "arch_sys_timer";
clk->rating = 450;
clk->set_mode = arch_timer_set_mode_cp15;
clk->set_next_event = arch_timer_set_next_event_cp15;
clk->irq = arch_timer_ppi;
/* Be safe... */
clk->set_mode(CLOCK_EVT_MODE_SHUTDOWN, clk);
clockevents_config_and_register(clk, arch_timer_rate,
0xf, 0x7fffffff);
*__this_cpu_ptr(arch_timer_evt) = clk;
enable_percpu_irq(clk->irq, 0);
if (arch_timer_ppi2)
enable_percpu_irq(arch_timer_ppi2, 0);
arch_counter_set_user_access();
return 0;
}
/* Is the optional system timer available? */
static int local_timer_is_architected(void)
{
return (cpu_architecture() >= CPU_ARCH_ARMv7) &&
((read_cpuid_ext(CPUID_EXT_PFR1) >> 16) & 0xf) == 1;
}
static int arch_timer_available(void)
{
unsigned long freq;
if (arch_timer_rate == 0) {
arch_timer_reg_write(1, ARCH_TIMER_REG_CTRL, 0);
freq = arch_timer_reg_read(1, ARCH_TIMER_REG_FREQ);
/* Check the timer frequency. */
if (freq == 0) {
pr_warn("Architected timer frequency not available\n");
return -EINVAL;
}
arch_timer_rate = freq;
pr_info("Architected local timer running at %lu.%02luMHz.\n",
freq / 1000000, (freq / 10000) % 100);
}
return 0;
}
static inline cycle_t notrace counter_get_cntpct_mem(void)
{
u32 cvall, cvalh, thigh;
do {
cvalh = __raw_readl(timer_base + QTIMER_CNTP_HIGH_REG);
cvall = __raw_readl(timer_base + QTIMER_CNTP_LOW_REG);
thigh = __raw_readl(timer_base + QTIMER_CNTP_HIGH_REG);
} while (cvalh != thigh);
return ((cycle_t) cvalh << 32) | cvall;
}
static inline cycle_t notrace counter_get_cntpct_cp15(void)
{
u32 cvall, cvalh;
asm volatile("mrrc p15, 0, %0, %1, c14" : "=r" (cvall), "=r" (cvalh));
return ((cycle_t) cvalh << 32) | cvall;
}
static inline cycle_t notrace counter_get_cntvct_mem(void)
{
u32 cvall, cvalh, thigh;
do {
cvalh = __raw_readl(timer_base + QTIMER_CNTV_HIGH_REG);
cvall = __raw_readl(timer_base + QTIMER_CNTV_LOW_REG);
thigh = __raw_readl(timer_base + QTIMER_CNTV_HIGH_REG);
} while (cvalh != thigh);
return ((cycle_t) cvalh << 32) | cvall;
}
static inline cycle_t notrace counter_get_cntvct_cp15(void)
{
u32 cvall, cvalh;
asm volatile("mrrc p15, 1, %0, %1, c14" : "=r" (cvall), "=r" (cvalh));
return ((cycle_t) cvalh << 32) | cvall;
}
static cycle_t (*get_cntpct_func)(void) = counter_get_cntpct_cp15;
static cycle_t (*get_cntvct_func)(void) = counter_get_cntvct_cp15;
cycle_t arch_counter_get_cntpct(void)
{
return get_cntpct_func();
}
EXPORT_SYMBOL(arch_counter_get_cntpct);
static cycle_t arch_counter_read(struct clocksource *cs)
{
return arch_counter_get_cntpct();
}
static unsigned long arch_timer_read_current_timer(void)
{
return arch_counter_get_cntpct();
}
static struct clocksource clocksource_counter = {
.name = "arch_sys_counter",
.rating = 400,
.read = arch_counter_read,
.mask = CLOCKSOURCE_MASK(56),
.flags = CLOCK_SOURCE_IS_CONTINUOUS | CLOCK_SOURCE_SUSPEND_NONSTOP,
};
static u32 arch_counter_get_cntvct32(void)
{
cycle_t cntvct;
cntvct = get_cntvct_func();
/*
* The sched_clock infrastructure only knows about counters
* with at most 32bits. Forget about the upper 24 bits for the
* time being...
*/
return (u32)(cntvct & (u32)~0);
}
static u32 notrace arch_timer_update_sched_clock(void)
{
return arch_counter_get_cntvct32();
}
static void __cpuinit arch_timer_stop(struct clock_event_device *clk)
{
pr_debug("arch_timer_teardown disable IRQ%d cpu #%d\n",
clk->irq, smp_processor_id());
disable_percpu_irq(clk->irq);
if (arch_timer_ppi2)
disable_percpu_irq(arch_timer_ppi2);
clk->set_mode(CLOCK_EVT_MODE_UNUSED, clk);
}
static struct local_timer_ops arch_timer_ops __cpuinitdata = {
.setup = arch_timer_setup,
.stop = arch_timer_stop,
};
static struct clock_event_device arch_timer_global_evt;
static void __init arch_timer_counter_init(void)
{
clocksource_register_hz(&clocksource_counter, arch_timer_rate);
setup_sched_clock(arch_timer_update_sched_clock, 32, arch_timer_rate);
/* Use the architected timer for the delay loop. */
arch_delay_timer.read_current_timer = &arch_timer_read_current_timer;
arch_delay_timer.freq = arch_timer_rate;
register_current_timer_delay(&arch_delay_timer);
}
#ifdef CONFIG_CPU_PM
static unsigned int saved_cntkctl;
static int arch_timer_cpu_pm_notify(struct notifier_block *self,
unsigned long action, void *hcpu)
{
if (action == CPU_PM_ENTER)
saved_cntkctl = arch_timer_get_cntkctl();
else if (action == CPU_PM_ENTER_FAILED || action == CPU_PM_EXIT)
arch_timer_set_cntkctl(saved_cntkctl);
return NOTIFY_OK;
}
static struct notifier_block arch_timer_cpu_pm_notifier = {
.notifier_call = arch_timer_cpu_pm_notify,
};
static int __init arch_timer_cpu_pm_init(void)
{
return cpu_pm_register_notifier(&arch_timer_cpu_pm_notifier);
}
#else
static int __init arch_timer_cpu_pm_init(void)
{
return 0;
}
#endif
static int __init arch_timer_common_register(void)
{
int err;
if (!local_timer_is_architected())
return -ENXIO;
err = arch_timer_available();
if (err)
return err;
arch_timer_evt = alloc_percpu(struct clock_event_device *);
if (!arch_timer_evt)
return -ENOMEM;
err = request_percpu_irq(arch_timer_ppi, arch_timer_handler_cp15,
"arch_timer", arch_timer_evt);
if (err) {
pr_err("arch_timer: can't register interrupt %d (%d)\n",
arch_timer_ppi, err);
goto out_free;
}
if (arch_timer_ppi2) {
err = request_percpu_irq(arch_timer_ppi2,
arch_timer_handler_cp15,
"arch_timer", arch_timer_evt);
if (err) {
pr_err("arch_timer: can't register interrupt %d (%d)\n",
arch_timer_ppi2, err);
arch_timer_ppi2 = 0;
goto out_free_irq;
}
}
err = arch_timer_cpu_pm_init();
if (err)
goto out_free_irq;
err = local_timer_register(&arch_timer_ops);
if (err) {
/*
* We couldn't register as a local timer (could be
* because we're on a UP platform, or because some
* other local timer is already present...). Try as a
* global timer instead.
*/
arch_timer_global_evt.cpumask = cpumask_of(0);
err = arch_timer_setup(&arch_timer_global_evt);
}
if (err)
goto out_unreg_notify;
return 0;
out_unreg_notify:
cpu_pm_unregister_notifier(&arch_timer_cpu_pm_notifier);
out_free_irq:
free_percpu_irq(arch_timer_ppi, arch_timer_evt);
if (arch_timer_ppi2)
free_percpu_irq(arch_timer_ppi2, arch_timer_evt);
out_free:
free_percpu(arch_timer_evt);
return err;
}
static int __init arch_timer_mem_register(void)
{
int err;
struct clock_event_device *clk;
clk = kzalloc(sizeof(*clk), GFP_KERNEL);
if (!clk)
return -ENOMEM;
clk->features = CLOCK_EVT_FEAT_ONESHOT | CLOCK_EVT_FEAT_DYNIRQ;
clk->name = "arch_mem_timer";
clk->rating = 400;
clk->set_mode = arch_timer_set_mode_mem;
clk->set_next_event = arch_timer_set_next_event_mem;
clk->irq = arch_timer_spi;
clk->cpumask = cpu_all_mask;
clk->set_mode(CLOCK_EVT_MODE_SHUTDOWN, clk);
clockevents_config_and_register(clk, arch_timer_rate,
0xf, 0x7fffffff);
err = request_irq(arch_timer_spi, arch_timer_handler_mem, 0,
"arch_timer", clk);
return err;
}
int __init arch_timer_register(struct arch_timer *at)
{
if (at->res[0].start <= 0 || !(at->res[0].flags & IORESOURCE_IRQ))
return -EINVAL;
arch_timer_ppi = at->res[0].start;
if (at->res[1].start > 0 && (at->res[1].flags & IORESOURCE_IRQ))
arch_timer_ppi2 = at->res[1].start;
if (at->res[2].start > 0 && at->res[2].end > 0 &&
(at->res[2].flags & IORESOURCE_MEM))
timer_base = ioremap(at->res[2].start,
resource_size(&at->res[2]));
if (!timer_base) {
pr_err("arch_timer: cant map timer base\n");
return -ENOMEM;
}
return arch_timer_common_register();
}
#ifdef CONFIG_OF
static const struct of_device_id arch_timer_of_match[] __initconst = {
{ .compatible = "arm,armv7-timer", },
{},
};
static const struct of_device_id arch_timer_mem_of_match[] __initconst = {
{ .compatible = "arm,armv7-timer-mem", },
{},
};
int __init arch_timer_of_register(void)
{
struct device_node *np, *frame;
u32 freq;
int ret;
int has_cp15 = false, has_mem = false;
np = of_find_matching_node(NULL, arch_timer_of_match);
if (np) {
has_cp15 = true;
/*
* Try to determine the frequency from the device tree
*/
if (!of_property_read_u32(np, "clock-frequency", &freq))
arch_timer_rate = freq;
ret = irq_of_parse_and_map(np, 0);
if (ret <= 0) {
pr_err("arch_timer: interrupt not specified in timer node\n");
return -ENODEV;
}
arch_timer_ppi = ret;
ret = irq_of_parse_and_map(np, 1);
if (ret > 0)
arch_timer_ppi2 = ret;
ret = arch_timer_common_register();
if (ret)
return ret;
}
np = of_find_matching_node(NULL, arch_timer_mem_of_match);
if (np) {
has_mem = true;
if (!has_cp15) {
get_cntpct_func = counter_get_cntpct_mem;
get_cntvct_func = counter_get_cntvct_mem;
}
/*
* Try to determine the frequency from the device tree
*/
if (!of_property_read_u32(np, "clock-frequency", &freq))
arch_timer_rate = freq;
frame = of_get_next_child(np, NULL);
if (!frame) {
pr_err("arch_timer: no child frame\n");
return -EINVAL;
}
timer_base = of_iomap(frame, 0);
if (!timer_base) {
pr_err("arch_timer: cant map timer base\n");
return -ENOMEM;
}
arch_timer_spi = irq_of_parse_and_map(frame, 0);
if (!arch_timer_spi) {
pr_err("arch_timer: no physical timer irq\n");
return -EINVAL;
}
ret = arch_timer_mem_register();
if (ret)
return ret;
}
if (!has_cp15 && !has_mem) {
pr_err("arch_timer: can't find DT node\n");
return -ENODEV;
}
arch_timer_counter_init();
return 0;
}
#endif
|
MikePach/Alucard-Kernel-jfltexx
|
arch/arm/kernel/arch_timer.c
|
C
|
gpl-2.0
| 15,414
|
cmd_drivers/usb/storage/ums-isd200.o := /home/friedrich420/kernel/Toolchain/arm-eabi-4.7/bin/arm-eabi-ld -EL -r -o drivers/usb/storage/ums-isd200.o drivers/usb/storage/isd200.o
|
friedrich420/Note-3-AEL-Kernel
|
drivers/usb/storage/.ums-isd200.o.cmd
|
Batchfile
|
gpl-2.0
| 181
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "util++.H"
// An integer multiplier on the test length. 1 is pretty quick, but
// 10 is the default.
//
#define TEST_LENGTH (10 * 1024 * 1024)
// We test
//
// 1) binary encoding/decoding
//
// 2) pre/post increment of binary encoding
//
// 3) Perform some testing on the fibonacci encoded bit-packed stream
// -- encode a bunch of random 64-bit numbers, make sure we can
// decode back to the same number.
//
// NOTES: pre/post increment/decrement work modulo whatever size they
// are. So, if you have a 6-bit value of zero, and you decrement,
// you end up with a 6-bit value of all 1's, or 63.
void
testBinaryEncoding(void) {
time_t mtseed = time(0L);
mt_s *mtctx = 0L;
uint32 iterations = TEST_LENGTH;
uint64 *bits = new uint64 [iterations + 2];
uint64 bpos = uint64ZERO;
uint64 *V = new uint64 [iterations];
uint64 *C = new uint64 [iterations];
uint64 *S = new uint64 [iterations];
uint32 failed = 0;
uint32 errors = 0;
fprintf(stderr, "Starting test of binary encoding\n");
bpos = uint64ZERO;
mtctx = mtInit(mtseed);
// Build some values to stuff into the bits
for (uint32 j=0; j < iterations; j++) {
S[j] = (mtRandom32(mtctx) % 63) + 1;
V[j] = mtRandom64(mtctx) & uint64MASK(S[j]);
//fprintf(stderr, "[%2d] S="uint64FMT" V="uint64HEX"\n", j, S[j], V[j]);
}
// Stuff them in, in blocks of some size. At the same time, decode
// (this has found bugs in the past).
failed = 0;
for (uint32 j=0; j < iterations; ) {
uint64 num = (mtRandom32(mtctx) % 8);
if (j + num > iterations)
num = iterations - j;
if (num == 0) {
setDecodedValue(bits, bpos, S[j], V[j]);
C[j] = getDecodedValue(bits, bpos, S[j]);
//fprintf(stderr, "[%2d] V="uint64HEX" C="uint64HEX" single\n", j, V[j], C[j]);
bpos += S[j];
} else {
uint64 newp1 = setDecodedValues(bits, bpos, num, S+j, V+j);
uint64 newp2 = getDecodedValues(bits, bpos, num, S+j, C+j);
if (newp1 != newp2) {
// not perfect; we should be checking the values too, but we do that later.
for (uint32 x=0; x<num; x++)
fprintf(stderr, "[%2d] #1 V="uint64HEX" C="uint64HEX" multiple "uint32FMT" %s\n",
j+x, V[j+x], C[j+x], num, (V[j+x] == C[j+x]) ? "" : "FAILED");
failed++;
}
bpos = newp2;
}
j += num;
if (num == 0)
j++;
}
if (failed) {
fprintf(stderr, "binEncoding #1 failed encoding "uint32FMT" times.\n", failed);
errors++;
}
// Check that V == C
failed = 0;
for (uint32 j=0; j<iterations; j++) {
if (V[j] != C[j]) {
fprintf(stderr, "[%2d] #2 V="uint64HEX" C="uint64HEX" S="uint32FMT"\n",
j, V[j], C[j], S[j]);
failed++;
}
}
if (failed) {
fprintf(stderr, "binEncoding #2 failed encode/decode "uint32FMT" times.\n", failed);
errors++;
}
// Decode independently, with different nums
bpos = 0; // reset to start of bits
for (uint32 j=0; j < iterations; ) {
uint64 num = (mtRandom32(mtctx) % 8);
if (j + num > iterations)
num = iterations - j;
if (num == 0) {
C[j] = getDecodedValue(bits, bpos, S[j]);
bpos += S[j];
} else {
bpos = getDecodedValues(bits, bpos, num, S+j, C+j);
}
j += num;
if (num == 0)
j++;
}
// Check that V == C
failed = 0;
for (uint32 j=0; j<iterations; j++) {
if (V[j] != C[j]) {
fprintf(stderr, "[%2d] #3 V="uint64HEX" C="uint64HEX" S="uint32FMT"\n",
j, V[j], C[j], S[j]);
failed++;
}
}
if (failed) {
fprintf(stderr, "binEncoding #3 failed decoding "uint32FMT" times.\n", failed);
errors++;
}
// Clean.
delete [] bits;
delete [] V;
delete [] C;
delete [] S;
if (errors)
exit(1);
}
void
testBinaryEncodingPrePost(void) {
time_t mtseed = time(0L);
mt_s *mtctx = 0L;
uint32 iterations = TEST_LENGTH;
uint64 *bits = new uint64 [2 * iterations];
uint64 bpos = uint64ZERO;
uint32 siz1 = uint64ZERO;
uint64 val1 = uint64ZERO;
uint64 val2 = uint64ZERO;
fprintf(stderr, "Starting test of binary encoding pre/post increment\n");
bpos = uint64ZERO;
mtctx = mtInit(mtseed);
for (uint32 j=0; j < iterations; j++) {
siz1 = (mtRandom32(mtctx) % 63) + 1;
val1 = mtRandom64(mtctx) & uint64MASK(siz1);
setDecodedValue(bits, bpos, siz1, val1);
val2 = postDecrementDecodedValue(bits, bpos, siz1);
if (val2 != val1) {
fprintf(stderr, "postDec1 failed: got "uint64FMT" expected "uint64FMT" siz="uint32FMT"\n",
val2, val1, siz1);
exit(1);
}
val2 = getDecodedValue(bits, bpos, siz1) + 1;
val2 &= uint64MASK(siz1);
if (val2 != val1) {
fprintf(stderr, "postDec2 failed: got "uint64FMT" expected "uint64FMT" siz="uint32FMT"\n",
val2, val1, siz1);
exit(1);
}
val2 = preDecrementDecodedValue(bits, bpos, siz1) + 2;
val2 &= uint64MASK(siz1);
if (val2 != val1) {
fprintf(stderr, "preDec failed: got "uint64FMT" expected "uint64FMT" siz="uint32FMT"\n",
val2, val1, siz1);
exit(1);
}
val2 = postIncrementDecodedValue(bits, bpos, siz1) + 2;
val2 &= uint64MASK(siz1);
if (val2 != val1) {
fprintf(stderr, "postInc failed: got "uint64FMT" expected "uint64FMT"\n", val2+2, val1-2);
exit(1);
}
val2 = getDecodedValue(bits, bpos, siz1) + 1;
val2 &= uint64MASK(siz1);
if (val2 != val1) {
fprintf(stderr, "postInc2 failed: got "uint64FMT" expected "uint64FMT" siz="uint32FMT"\n",
val2, val1, siz1);
exit(1);
}
val2 = preIncrementDecodedValue(bits, bpos, siz1);
// Should be back to original value, so no mask
if (val2 != val1) {
fprintf(stderr, "preInc failed: got "uint64FMT" expected "uint64FMT"\n", val2, val1);
exit(1);
}
switch (j % 4) {
case 0:
val2 = postDecrementDecodedValue(bits, bpos, siz1);
break;
case 1:
val2 = preDecrementDecodedValue(bits, bpos, siz1);
break;
case 2:
val2 = postIncrementDecodedValue(bits, bpos, siz1);
break;
case 3:
val2 = preIncrementDecodedValue(bits, bpos, siz1);
break;
}
bpos += siz1;
}
bpos = uint64ZERO;
mtctx = mtInit(mtseed);
//for (j=0; j < iterations; j++) {
//}
delete [] bits;
}
void
testFibonacciEncoding(void) {
time_t mtseed = time(0L);
mt_s *mtctx = 0L;
uint32 iterations = TEST_LENGTH / 4;
uint64 *bits = new uint64 [3 * iterations];
uint64 bpos = uint64ZERO;
uint32 failed = 0;
uint32 errors = 0;
fprintf(stderr, "Starting test of fibonacci encoding\n");
bpos = uint64ZERO;
mtctx = mtInit(mtseed);
failed = 0;
for (uint32 j=0; j < iterations; j++) {
uint64 siz1 = (mtRandom32(mtctx) % 63) + 1;
uint64 val1 = mtRandom64(mtctx) & uint64MASK(siz1);
uint64 siz2 = siz1;
setFibonacciEncodedNumber(bits, bpos, &siz1, val1);
uint64 val2 = getFibonacciEncodedNumber(bits, bpos, &siz2);
if ((val1 != val2) || (siz1 != siz2)) {
fprintf(stderr, "fibEnc #1 failed on "uint32FMT": got "uint64FMT" expected "uint64FMT"\n", j, val2, val1);
failed++;
}
bpos += siz1;
}
if (failed) {
fprintf(stderr, "fibEnc #1 failed "uint32FMT" times.\n", failed);
errors++;
}
bpos = uint64ZERO;
mtctx = mtInit(mtseed);
failed = 0;
for (uint32 j=0; j < iterations; j++) {
uint64 siz1 = (mtRandom32(mtctx) % 63) + 1;
uint64 val1 = mtRandom64(mtctx) & uint64MASK(siz1);
uint64 val2 = getFibonacciEncodedNumber(bits, bpos, &siz1);
if (val1 != val2) {
fprintf(stderr, "fibEnc #2 failed on "uint32FMT": got "uint64FMT" expected "uint64FMT"\n", j, val2, val1);
failed++;
}
bpos += siz1;
}
if (failed) {
fprintf(stderr, "fibEnc #2 failed "uint32FMT" times.\n", failed);
errors++;
}
delete [] bits;
if (errors)
exit(1);
}
int
main(int argc, char **argv) {
testBinaryEncoding();
testBinaryEncodingPrePost();
testFibonacciEncoding();
return(0);
}
|
macmanes-lab/wgs-assembler
|
kmer/libutil/test/test-bitPacking.C
|
C++
|
gpl-2.0
| 8,424
|
package cn.sharesdk.demo.apshare;
import cn.sharesdk.alipay.share.AlipayHandlerActivity;
public class ShareEntryActivity extends AlipayHandlerActivity{
}
|
chosener/ProjectRes
|
运营/Mob/ShareSDK-Android-2.6.6/ShareSDK for Android/Src/apshare/ShareEntryActivity.java
|
Java
|
gpl-2.0
| 157
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.tests.java.net;
import junit.framework.TestCase;
import tests.support.resource.Support_Resources;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.ArrayList;
import java.util.List;
public class URLTest extends TestCase {
public static class MyHandler extends URLStreamHandler {
protected URLConnection openConnection(URL u)
throws IOException {
return null;
}
}
URL u;
URL u1;
URL u2;
URL u3;
URL u4;
URL u5;
URL u6;
boolean caught = false;
static boolean isSelectCalled;
/**
* java.net.URL#URL(java.lang.String)
*/
public void test_ConstructorLjava_lang_String() throws IOException {
// Tests for multiple URL instantiation basic parsing test
u = new URL(
"http://www.yahoo1.com:8080/dir1/dir2/test.cgi?point1.html#anchor1");
assertEquals("u returns a wrong protocol", "http", u.getProtocol());
assertEquals("u returns a wrong host", "www.yahoo1.com", u.getHost());
assertEquals("u returns a wrong port", 8080, u.getPort());
assertEquals("u returns a wrong file",
"/dir1/dir2/test.cgi?point1.html", u.getFile());
assertEquals("u returns a wrong anchor", "anchor1", u.getRef());
// test for no file
u1 = new URL("http://www.yahoo2.com:9999");
assertEquals("u1 returns a wrong protocol", "http", u1.getProtocol());
assertEquals("u1 returns a wrong host", "www.yahoo2.com", u1.getHost());
assertEquals("u1 returns a wrong port", 9999, u1.getPort());
assertTrue("u1 returns a wrong file", u1.getFile().equals(""));
assertNull("u1 returns a wrong anchor", u1.getRef());
// test for no port
u2 = new URL(
"http://www.yahoo3.com/dir1/dir2/test.cgi?point1.html#anchor1");
assertEquals("u2 returns a wrong protocol", "http", u2.getProtocol());
assertEquals("u2 returns a wrong host", "www.yahoo3.com", u2.getHost());
assertEquals("u2 returns a wrong port", -1, u2.getPort());
assertEquals("u2 returns a wrong file",
"/dir1/dir2/test.cgi?point1.html", u2.getFile());
assertEquals("u2 returns a wrong anchor", "anchor1", u2.getRef());
// test for no port
URL u2a = new URL("file://www.yahoo3.com/dir1/dir2/test.cgi#anchor1");
assertEquals("u2a returns a wrong protocol", "file", u2a.getProtocol());
assertEquals("u2a returns a wrong host", "www.yahoo3.com", u2a
.getHost());
assertEquals("u2a returns a wrong port", -1, u2a.getPort());
assertEquals("u2a returns a wrong file", "/dir1/dir2/test.cgi", u2a
.getFile());
assertEquals("u2a returns a wrong anchor", "anchor1", u2a.getRef());
// test for no file, no port
u3 = new URL("http://www.yahoo4.com/");
assertEquals("u3 returns a wrong protocol", "http", u3.getProtocol());
assertEquals("u3 returns a wrong host", "www.yahoo4.com", u3.getHost());
assertEquals("u3 returns a wrong port", -1, u3.getPort());
assertEquals("u3 returns a wrong file", "/", u3.getFile());
assertNull("u3 returns a wrong anchor", u3.getRef());
// test for no file, no port
URL u3a = new URL("file://www.yahoo4.com/");
assertEquals("u3a returns a wrong protocol", "file", u3a.getProtocol());
assertEquals("u3a returns a wrong host", "www.yahoo4.com", u3a
.getHost());
assertEquals("u3a returns a wrong port", -1, u3a.getPort());
assertEquals("u3a returns a wrong file", "/", u3a.getFile());
assertNull("u3a returns a wrong anchor", u3a.getRef());
// test for no file, no port
URL u3b = new URL("file://www.yahoo4.com");
assertEquals("u3b returns a wrong protocol", "file", u3b.getProtocol());
assertEquals("u3b returns a wrong host", "www.yahoo4.com", u3b
.getHost());
assertEquals("u3b returns a wrong port", -1, u3b.getPort());
assertTrue("u3b returns a wrong file", u3b.getFile().equals(""));
assertNull("u3b returns a wrong anchor", u3b.getRef());
// test for non-port ":" and wierd characters occurrences
u4 = new URL(
"http://www.yahoo5.com/di!@$%^&*()_+r1/di:::r2/test.cgi?point1.html#anchor1");
assertEquals("u4 returns a wrong protocol", "http", u4.getProtocol());
assertEquals("u4 returns a wrong host", "www.yahoo5.com", u4.getHost());
assertEquals("u4 returns a wrong port", -1, u4.getPort());
assertEquals("u4 returns a wrong file",
"/di!@$%^&*()_+r1/di:::r2/test.cgi?point1.html", u4.getFile());
assertEquals("u4 returns a wrong anchor", "anchor1", u4.getRef());
u5 = new URL("file:/testing.tst");
assertEquals("u5 returns a wrong protocol", "file", u5.getProtocol());
assertTrue("u5 returns a wrong host", u5.getHost().equals(""));
assertEquals("u5 returns a wrong port", -1, u5.getPort());
assertEquals("u5 returns a wrong file", "/testing.tst", u5.getFile());
assertNull("u5 returns a wrong anchor", u5.getRef());
URL u5a = new URL("file:testing.tst");
assertEquals("u5a returns a wrong protocol", "file", u5a.getProtocol());
assertTrue("u5a returns a wrong host", u5a.getHost().equals(""));
assertEquals("u5a returns a wrong port", -1, u5a.getPort());
assertEquals("u5a returns a wrong file", "testing.tst", u5a.getFile());
assertNull("u5a returns a wrong anchor", u5a.getRef());
URL u6 = new URL("http://host:/file");
assertEquals("u6 return a wrong port", -1, u6.getPort());
URL u7 = new URL("file:../../file.txt");
assertTrue("u7 returns a wrong file: " + u7.getFile(), u7.getFile()
.equals("../../file.txt"));
URL u8 = new URL("http://[fec0::1:20d:60ff:fe24:7410]:35/file.txt");
assertTrue("u8 returns a wrong protocol " + u8.getProtocol(), u8
.getProtocol().equals("http"));
assertTrue("u8 returns a wrong host " + u8.getHost(), u8.getHost()
.equals("[fec0::1:20d:60ff:fe24:7410]"));
assertTrue("u8 returns a wrong port " + u8.getPort(),
u8.getPort() == 35);
assertTrue("u8 returns a wrong file " + u8.getFile(), u8.getFile()
.equals("/file.txt"));
assertNull("u8 returns a wrong anchor " + u8.getRef(), u8.getRef());
URL u9 = new URL("file://[fec0::1:20d:60ff:fe24:7410]/file.txt#sogood");
assertTrue("u9 returns a wrong protocol " + u9.getProtocol(), u9
.getProtocol().equals("file"));
assertTrue("u9 returns a wrong host " + u9.getHost(), u9.getHost()
.equals("[fec0::1:20d:60ff:fe24:7410]"));
assertTrue("u9 returns a wrong port " + u9.getPort(),
u9.getPort() == -1);
assertTrue("u9 returns a wrong file " + u9.getFile(), u9.getFile()
.equals("/file.txt"));
assertTrue("u9 returns a wrong anchor " + u9.getRef(), u9.getRef()
.equals("sogood"));
URL u10 = new URL("file://[fec0::1:20d:60ff:fe24:7410]");
assertTrue("u10 returns a wrong protocol " + u10.getProtocol(), u10
.getProtocol().equals("file"));
assertTrue("u10 returns a wrong host " + u10.getHost(), u10.getHost()
.equals("[fec0::1:20d:60ff:fe24:7410]"));
assertTrue("u10 returns a wrong port " + u10.getPort(),
u10.getPort() == -1);
URL u11 = new URL("file:////file.txt");
// Harmony returned null here
assertEquals("u11 returns a wrong authority", "", u11.getAuthority());
assertEquals("u11 returns a wrong file " + u11.getFile(), "//file.txt",
u11.getFile());
URL u12 = new URL("file:///file.txt");
assertTrue("u12 returns a wrong authority", u12.getAuthority().equals(
""));
assertTrue("u12 returns a wrong file " + u12.getFile(), u12.getFile()
.equals("/file.txt"));
// test for error catching
// Bad HTTP format - no "//"
u = new URL(
"http:www.yahoo5.com::22/dir1/di:::r2/test.cgi?point1.html#anchor1");
caught = false;
try {
u = new URL(
"http://www.yahoo5.com::22/dir1/di:::r2/test.cgi?point1.html#anchor1");
} catch (MalformedURLException e) {
caught = true;
}
assertTrue("Should have throw MalformedURLException", caught);
// unknown protocol
try {
u = new URL("myProtocol://www.yahoo.com:22");
} catch (MalformedURLException e) {
caught = true;
}
assertTrue("3 Failed to throw MalformedURLException", caught);
caught = false;
// no protocol
try {
u = new URL("www.yahoo.com");
} catch (MalformedURLException e) {
caught = true;
}
assertTrue("4 Failed to throw MalformedURLException", caught);
caught = false;
URL u1 = null;
try {
// No leading or trailing spaces.
u1 = new URL("file:/some/path");
assertEquals("5 got wrong file length1", 10, u1.getFile().length());
// Leading spaces.
u1 = new URL(" file:/some/path");
assertEquals("5 got wrong file length2", 10, u1.getFile().length());
// Trailing spaces.
u1 = new URL("file:/some/path ");
assertEquals("5 got wrong file length3", 10, u1.getFile().length());
// Leading and trailing.
u1 = new URL(" file:/some/path ");
assertEquals("5 got wrong file length4", 10, u1.getFile().length());
// in-place spaces.
u1 = new URL(" file: /some/path ");
assertEquals("5 got wrong file length5", 12, u1.getFile().length());
} catch (MalformedURLException e) {
fail("5 Did not expect the exception " + e);
}
// testing jar protocol with relative path
// to make sure it's not canonicalized
try {
String file = "file:/a!/b/../d";
u = new URL("jar:" + file);
assertEquals("Wrong file (jar protocol, relative path)", file, u
.getFile());
} catch (MalformedURLException e) {
fail("Unexpected exception (jar protocol, relative path)" + e);
}
}
/**
* java.net.URL#URL(java.net.URL, java.lang.String)
*/
public void test_ConstructorLjava_net_URLLjava_lang_String()
throws Exception {
// Test for method java.net.URL(java.net.URL, java.lang.String)
u = new URL("http://www.yahoo.com");
URL uf = new URL("file://www.yahoo.com");
// basic ones
u1 = new URL(u, "file.java");
assertEquals("1 returns a wrong protocol", "http", u1.getProtocol());
assertEquals("1 returns a wrong host", "www.yahoo.com", u1.getHost());
assertEquals("1 returns a wrong port", -1, u1.getPort());
assertEquals("1 returns a wrong file", "/file.java", u1.getFile());
assertNull("1 returns a wrong anchor", u1.getRef());
URL u1f = new URL(uf, "file.java");
assertEquals("1f returns a wrong protocol", "file", u1f.getProtocol());
assertEquals("1f returns a wrong host", "www.yahoo.com", u1f.getHost());
assertEquals("1f returns a wrong port", -1, u1f.getPort());
assertEquals("1f returns a wrong file", "/file.java", u1f.getFile());
assertNull("1f returns a wrong anchor", u1f.getRef());
u1 = new URL(u, "dir1/dir2/../file.java");
assertEquals("3 returns a wrong protocol", "http", u1.getProtocol());
assertTrue("3 returns a wrong host: " + u1.getHost(), u1.getHost()
.equals("www.yahoo.com"));
assertEquals("3 returns a wrong port", -1, u1.getPort());
assertEquals("3 returns a wrong file", "/dir1/file.java", u1
.getFile());
assertNull("3 returns a wrong anchor", u1.getRef());
u1 = new URL(u, "http:dir1/dir2/../file.java");
assertEquals("3a returns a wrong protocol", "http", u1.getProtocol());
assertEquals("3a returns a wrong host: " + u1.getHost(), "www.yahoo.com", u1.getHost());
assertEquals("3a returns a wrong port", -1, u1.getPort());
assertEquals("3a returns a wrong file", "/dir1/file.java", u1
.getFile());
assertNull("3a returns a wrong anchor", u1.getRef());
u = new URL("http://www.apache.org/testing/");
u1 = new URL(u, "file.java");
assertEquals("4 returns a wrong protocol", "http", u1.getProtocol());
assertEquals("4 returns a wrong host", "www.apache.org", u1.getHost());
assertEquals("4 returns a wrong port", -1, u1.getPort());
assertEquals("4 returns a wrong file", "/testing/file.java", u1
.getFile());
assertNull("4 returns a wrong anchor", u1.getRef());
uf = new URL("file://www.apache.org/testing/");
u1f = new URL(uf, "file.java");
assertEquals("4f returns a wrong protocol", "file", u1f.getProtocol());
assertEquals("4f returns a wrong host", "www.apache.org", u1f.getHost());
assertEquals("4f returns a wrong port", -1, u1f.getPort());
assertEquals("4f returns a wrong file", "/testing/file.java", u1f
.getFile());
assertNull("4f returns a wrong anchor", u1f.getRef());
uf = new URL("file:/testing/");
u1f = new URL(uf, "file.java");
assertEquals("4fa returns a wrong protocol", "file", u1f.getProtocol());
assertTrue("4fa returns a wrong host", u1f.getHost().equals(""));
assertEquals("4fa returns a wrong port", -1, u1f.getPort());
assertEquals("4fa returns a wrong file", "/testing/file.java", u1f
.getFile());
assertNull("4fa returns a wrong anchor", u1f.getRef());
uf = new URL("file:testing/");
u1f = new URL(uf, "file.java");
assertEquals("4fb returns a wrong protocol", "file", u1f.getProtocol());
assertTrue("4fb returns a wrong host", u1f.getHost().equals(""));
assertEquals("4fb returns a wrong port", -1, u1f.getPort());
assertEquals("4fb returns a wrong file", "testing/file.java", u1f
.getFile());
assertNull("4fb returns a wrong anchor", u1f.getRef());
u1f = new URL(uf, "file:file.java");
assertEquals("4fc returns a wrong protocol", "file", u1f.getProtocol());
assertTrue("4fc returns a wrong host", u1f.getHost().equals(""));
assertEquals("4fc returns a wrong port", -1, u1f.getPort());
assertEquals("4fc returns a wrong file", "testing/file.java", u1f.getFile());
assertNull("4fc returns a wrong anchor", u1f.getRef());
u1f = new URL(uf, "file:");
assertEquals("4fd returns a wrong protocol", "file", u1f.getProtocol());
assertTrue("4fd returns a wrong host", u1f.getHost().equals(""));
assertEquals("4fd returns a wrong port", -1, u1f.getPort());
assertEquals("4fd returns a wrong file", "testing/", u1f.getFile());
assertNull("4fd returns a wrong anchor", u1f.getRef());
u = new URL("http://www.apache.org/testing");
u1 = new URL(u, "file.java");
assertEquals("5 returns a wrong protocol", "http", u1.getProtocol());
assertEquals("5 returns a wrong host", "www.apache.org", u1.getHost());
assertEquals("5 returns a wrong port", -1, u1.getPort());
assertEquals("5 returns a wrong file", "/file.java", u1.getFile());
assertNull("5 returns a wrong anchor", u1.getRef());
uf = new URL("file://www.apache.org/testing");
u1f = new URL(uf, "file.java");
assertEquals("5f returns a wrong protocol", "file", u1f.getProtocol());
assertEquals("5f returns a wrong host", "www.apache.org", u1f.getHost());
assertEquals("5f returns a wrong port", -1, u1f.getPort());
assertEquals("5f returns a wrong file", "/file.java", u1f.getFile());
assertNull("5f returns a wrong anchor", u1f.getRef());
uf = new URL("file:/testing");
u1f = new URL(uf, "file.java");
assertEquals("5fa returns a wrong protocol", "file", u1f.getProtocol());
assertTrue("5fa returns a wrong host", u1f.getHost().equals(""));
assertEquals("5fa returns a wrong port", -1, u1f.getPort());
assertEquals("5fa returns a wrong file", "/file.java", u1f.getFile());
assertNull("5fa returns a wrong anchor", u1f.getRef());
uf = new URL("file:testing");
u1f = new URL(uf, "file.java");
assertEquals("5fb returns a wrong protocol", "file", u1f.getProtocol());
assertTrue("5fb returns a wrong host", u1f.getHost().equals(""));
assertEquals("5fb returns a wrong port", -1, u1f.getPort());
assertEquals("5fb returns a wrong file", "file.java", u1f.getFile());
assertNull("5fb returns a wrong anchor", u1f.getRef());
u = new URL("http://www.apache.org/testing/foobaz");
u1 = new URL(u, "/file.java");
assertEquals("6 returns a wrong protocol", "http", u1.getProtocol());
assertEquals("6 returns a wrong host", "www.apache.org", u1.getHost());
assertEquals("6 returns a wrong port", -1, u1.getPort());
assertEquals("6 returns a wrong file", "/file.java", u1.getFile());
assertNull("6 returns a wrong anchor", u1.getRef());
uf = new URL("file://www.apache.org/testing/foobaz");
u1f = new URL(uf, "/file.java");
assertEquals("6f returns a wrong protocol", "file", u1f.getProtocol());
assertEquals("6f returns a wrong host", "www.apache.org", u1f.getHost());
assertEquals("6f returns a wrong port", -1, u1f.getPort());
assertEquals("6f returns a wrong file", "/file.java", u1f.getFile());
assertNull("6f returns a wrong anchor", u1f.getRef());
u = new URL("http://www.apache.org:8000/testing/foobaz");
u1 = new URL(u, "/file.java");
assertEquals("7 returns a wrong protocol", "http", u1.getProtocol());
assertEquals("7 returns a wrong host", "www.apache.org", u1.getHost());
assertEquals("7 returns a wrong port", 8000, u1.getPort());
assertEquals("7 returns a wrong file", "/file.java", u1.getFile());
assertNull("7 returns a wrong anchor", u1.getRef());
u = new URL("http://www.apache.org/index.html");
u1 = new URL(u, "#bar");
assertEquals("8 returns a wrong host", "www.apache.org", u1.getHost());
assertEquals("8 returns a wrong file", "/index.html", u1.getFile());
assertEquals("8 returns a wrong anchor", "bar", u1.getRef());
u = new URL("http://www.apache.org/index.html#foo");
u1 = new URL(u, "http:#bar");
assertEquals("9 returns a wrong host", "www.apache.org", u1.getHost());
assertEquals("9 returns a wrong file", "/index.html", u1.getFile());
assertEquals("9 returns a wrong anchor", "bar", u1.getRef());
u = new URL("http://www.apache.org/index.html");
u1 = new URL(u, "");
assertEquals("10 returns a wrong host", "www.apache.org", u1.getHost());
assertEquals("10 returns a wrong file", "/index.html", u1.getFile());
assertNull("10 returns a wrong anchor", u1.getRef());
uf = new URL("file://www.apache.org/index.html");
u1f = new URL(uf, "");
assertEquals("10f returns a wrong host", "www.apache.org", u1.getHost());
assertEquals("10f returns a wrong file", "/index.html", u1.getFile());
assertNull("10f returns a wrong anchor", u1.getRef());
u = new URL("http://www.apache.org/index.html");
u1 = new URL(u, "http://www.apache.org");
assertEquals("11 returns a wrong host", "www.apache.org", u1.getHost());
assertTrue("11 returns a wrong file", u1.getFile().equals(""));
assertNull("11 returns a wrong anchor", u1.getRef());
// test for question mark processing
u = new URL("http://www.foo.com/d0/d1/d2/cgi-bin?foo=bar/baz");
// test for relative file and out of bound "/../" processing
u1 = new URL(u, "../dir1/./dir2/../file.java");
assertTrue("A) returns a wrong file: " + u1.getFile(), u1.getFile()
.equals("/d0/d1/dir1/file.java"));
// test for absolute and relative file processing
u1 = new URL(u, "/../dir1/./dir2/../file.java");
assertEquals("B) returns a wrong file", "/dir1/file.java",
u1.getFile());
try {
// u should raise a MalFormedURLException because u, the context is
// null
u = null;
u1 = new URL(u, "file.java");
fail("didn't throw the expected MalFormedURLException");
} catch (MalformedURLException e) {
// valid
}
// Regression test for HARMONY-3258
// testing jar context url with relative file
try {
// check that relative path with null context is not canonicalized
String spec = "jar:file:/a!/b/../d";
URL ctx = null;
u = new URL(ctx, spec);
assertEquals("1 Wrong file (jar protocol, relative path)", spec, u
.toString());
spec = "../d";
ctx = new URL("jar:file:/a!/b");
u = new URL(ctx, spec);
assertEquals("2 Wrong file (jar protocol, relative path)",
"file:/a!/d", u.getFile());
spec = "../d";
ctx = new URL("jar:file:/a!/b/c");
u = new URL(ctx, spec);
assertEquals("3 Wrong file (jar protocol, relative path)",
"file:/a!/d", u.getFile());
spec = "../d";
ctx = new URL("jar:file:/a!/b/c/d");
u = new URL(ctx, spec);
assertEquals("4 Wrong file (jar protocol, relative path)",
"file:/a!/b/d", u.getFile());
// added the real example
spec = "../pdf/PDF.settings";
ctx = new URL(
"jar:file:/C:/Program%20Files/Netbeans-5.5/ide7/modules/org-netbeans-modules-utilities.jar!/org/netbeans/modules/utilities/Layer.xml");
u = new URL(ctx, spec);
assertEquals(
"5 Wrong file (jar protocol, relative path)",
"file:/C:/Program%20Files/Netbeans-5.5/ide7/modules/org-netbeans-modules-utilities.jar!/org/netbeans/modules/pdf/PDF.settings",
u.getFile());
} catch (MalformedURLException e) {
fail("Testing jar protocol, relative path failed: " + e);
}
}
/**
* java.net.URL#URL(java.net.URL, java.lang.String,
*java.net.URLStreamHandler)
*/
public void test_ConstructorLjava_net_URLLjava_lang_StringLjava_net_URLStreamHandler()
throws Exception {
// Test for method java.net.URL(java.net.URL, java.lang.String,
// java.net.URLStreamHandler)
u = new URL("http://www.yahoo.com");
// basic ones
u1 = new URL(u, "file.java", new MyHandler());
assertEquals("1 returns a wrong protocol", "http", u1.getProtocol());
assertEquals("1 returns a wrong host", "www.yahoo.com", u1.getHost());
assertEquals("1 returns a wrong port", -1, u1.getPort());
assertEquals("1 returns a wrong file", "/file.java", u1.getFile());
assertNull("1 returns a wrong anchor", u1.getRef());
u1 = new URL(u, "systemresource:/+/FILE0/test.java", new MyHandler());
assertEquals("2 returns a wrong protocol", "systemresource", u1
.getProtocol());
assertTrue("2 returns a wrong host", u1.getHost().equals(""));
assertEquals("2 returns a wrong port", -1, u1.getPort());
assertEquals("2 returns a wrong file", "/+/FILE0/test.java", u1
.getFile());
assertNull("2 returns a wrong anchor", u1.getRef());
u1 = new URL(u, "dir1/dir2/../file.java", null);
assertEquals("3 returns a wrong protocol", "http", u1.getProtocol());
assertEquals("3 returns a wrong host", "www.yahoo.com", u1.getHost());
assertEquals("3 returns a wrong port", -1, u1.getPort());
assertEquals("3 returns a wrong file", "/dir1/file.java", u1
.getFile());
assertNull("3 returns a wrong anchor", u1.getRef());
// test for question mark processing
u = new URL("http://www.foo.com/d0/d1/d2/cgi-bin?foo=bar/baz");
// test for relative file and out of bound "/../" processing
u1 = new URL(u, "../dir1/dir2/../file.java", new MyHandler());
assertTrue("A) returns a wrong file: " + u1.getFile(), u1.getFile()
.equals("/d0/d1/dir1/file.java"));
// test for absolute and relative file processing
u1 = new URL(u, "/../dir1/dir2/../file.java", null);
assertEquals("B) returns a wrong file", "/dir1/file.java",
u1.getFile());
URL one;
try {
one = new URL("http://www.ibm.com");
} catch (MalformedURLException ex) {
// Should not happen.
throw new RuntimeException(ex.getMessage());
}
try {
new URL(one, (String) null);
fail("Specifying null spec on URL constructor should throw MalformedURLException");
} catch (MalformedURLException e) {
// expected
}
try {
// u should raise a MalFormedURLException because u, the context is
// null
u = null;
u1 = new URL(u, "file.java", new MyHandler());
} catch (MalformedURLException e) {
return;
}
fail("didn't throw expected MalFormedURLException");
}
/**
* java.net.URL#URL(java.lang.String, java.lang.String,
*java.lang.String)
*/
public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String()
throws MalformedURLException {
u = new URL("http", "www.yahoo.com", "test.html#foo");
assertEquals("http", u.getProtocol());
assertEquals("www.yahoo.com", u.getHost());
assertEquals(-1, u.getPort());
assertEquals("/test.html", u.getFile());
assertEquals("foo", u.getRef());
// Strange behavior in reference, the hostname contains a ':' so it gets
// wrapped in '[', ']'
URL testURL = new URL("http", "www.apache.org:8080", "test.html#anch");
assertEquals("wrong protocol", "http", testURL.getProtocol());
assertEquals("wrong host", "[www.apache.org:8080]", testURL.getHost());
assertEquals("wrong port", -1, testURL.getPort());
assertEquals("wrong file", "/test.html", testURL.getFile());
assertEquals("wrong anchor", "anch", testURL.getRef());
}
/**
* java.net.URL#URL(java.lang.String, java.lang.String, int,
*java.lang.String)
*/
public void test_ConstructorLjava_lang_StringLjava_lang_StringILjava_lang_String()
throws MalformedURLException {
u = new URL("http", "www.yahoo.com", 8080, "test.html#foo");
assertEquals("SSIS returns a wrong protocol", "http", u.getProtocol());
assertEquals("SSIS returns a wrong host", "www.yahoo.com", u.getHost());
assertEquals("SSIS returns a wrong port", 8080, u.getPort());
// Libcore adds a leading "/"
assertEquals("SSIS returns a wrong file", "/test.html", u.getFile());
assertTrue("SSIS returns a wrong anchor: " + u.getRef(), u.getRef()
.equals("foo"));
// Regression for HARMONY-83
new URL("http", "apache.org", 123456789, "file");
try {
new URL("http", "apache.org", -123, "file");
fail("Assert 0: Negative port should throw exception");
} catch (MalformedURLException e) {
// expected
}
}
/**
* java.net.URL#URL(java.lang.String, java.lang.String, int,
*java.lang.String, java.net.URLStreamHandler)
*/
public void test_ConstructorLjava_lang_StringLjava_lang_StringILjava_lang_StringLjava_net_URLStreamHandler()
throws Exception {
// Test for method java.net.URL(java.lang.String, java.lang.String, int,
// java.lang.String, java.net.URLStreamHandler)
u = new URL("http", "www.yahoo.com", 8080, "test.html#foo", null);
assertEquals("SSISH1 returns a wrong protocol", "http", u.getProtocol());
assertEquals("SSISH1 returns a wrong host", "www.yahoo.com", u
.getHost());
assertEquals("SSISH1 returns a wrong port", 8080, u.getPort());
assertEquals("SSISH1 returns a wrong file", "/test.html", u.getFile());
assertTrue("SSISH1 returns a wrong anchor: " + u.getRef(), u.getRef()
.equals("foo"));
u = new URL("http", "www.yahoo.com", 8080, "test.html#foo",
new MyHandler());
assertEquals("SSISH2 returns a wrong protocol", "http", u.getProtocol());
assertEquals("SSISH2 returns a wrong host", "www.yahoo.com", u
.getHost());
assertEquals("SSISH2 returns a wrong port", 8080, u.getPort());
assertEquals("SSISH2 returns a wrong file", "/test.html", u.getFile());
assertTrue("SSISH2 returns a wrong anchor: " + u.getRef(), u.getRef()
.equals("foo"));
}
/**
* java.net.URL#equals(java.lang.Object)
*/
public void test_equalsLjava_lang_Object() throws MalformedURLException {
u = new URL("http://www.apache.org:8080/dir::23??????????test.html");
u1 = new URL("http://www.apache.org:8080/dir::23??????????test.html");
assertTrue("A) equals returns false for two identical URLs", u
.equals(u1));
assertTrue("return true for null comparison", !u1.equals(null));
u = new URL("ftp://www.apache.org:8080/dir::23??????????test.html");
assertTrue("Returned true for non-equal URLs", !u.equals(u1));
// Regression for HARMONY-6556
u = new URL("file", null, 0, "/test.txt");
u1 = new URL("file", null, 0, "/test.txt");
assertEquals(u, u1);
u = new URL("file", "first.invalid", 0, "/test.txt");
u1 = new URL("file", "second.invalid", 0, "/test.txt");
assertFalse(u.equals(u1));
u = new URL("file", "harmony.apache.org", 0, "/test.txt");
u1 = new URL("file", "www.apache.org", 0, "/test.txt");
assertFalse(u.equals(u1));
}
/**
* java.net.URL#sameFile(java.net.URL)
*/
public void test_sameFileLjava_net_URL() throws Exception {
// Test for method boolean java.net.URL.sameFile(java.net.URL)
u = new URL("http://www.yahoo.com");
u1 = new URL("http", "www.yahoo.com", "");
assertTrue("Should be the same1", u.sameFile(u1));
u = new URL("http://www.yahoo.com/dir1/dir2/test.html#anchor1");
u1 = new URL("http://www.yahoo.com/dir1/dir2/test.html#anchor2");
assertTrue("Should be the same ", u.sameFile(u1));
// regression test for Harmony-1040
u = new URL("file", null, -1, "/d:/somedir/");
u1 = new URL("file:/d:/somedir/");
assertFalse(u.sameFile(u1));
// regression test for Harmony-2136
URL url1 = new URL("file:///anyfile");
URL url2 = new URL("file://localhost/anyfile");
assertTrue(url1.sameFile(url2));
url1 = new URL("http:///anyfile");
url2 = new URL("http://localhost/anyfile");
assertFalse(url1.sameFile(url2));
url1 = new URL("ftp:///anyfile");
url2 = new URL("ftp://localhost/anyfile");
assertFalse(url1.sameFile(url2));
url1 = new URL("jar:file:///anyfile.jar!/");
url2 = new URL("jar:file://localhost/anyfile.jar!/");
assertFalse(url1.sameFile(url2));
}
/**
* java.net.URL#getContent()
*/
public void test_getContent() {
// Test for method java.lang.Object java.net.URL.getContent()
byte[] ba;
InputStream is;
String s;
File resources = Support_Resources.createTempFolder();
try {
Support_Resources.copyFile(resources, null, "hyts_htmltest.html");
u = new URL("file", "", resources.getAbsolutePath()
+ "/hyts_htmltest.html");
u.openConnection();
is = (InputStream) u.getContent();
is.read(ba = new byte[4096]);
s = new String(ba);
assertTrue(
"Incorrect content "
+ u
+ " does not contain: \" A Seemingly Non Important String \"",
s.indexOf("A Seemingly Non Important String") >= 0);
} catch (IOException e) {
fail("IOException thrown : " + e.getMessage());
} finally {
// Support_Resources.deleteTempFolder(resources);
}
}
/**
* java.net.URL#getContent(class[])
*/
public void test_getContent_LJavaLangClass() throws Exception {
byte[] ba;
InputStream is;
String s;
File resources = Support_Resources.createTempFolder();
Support_Resources.copyFile(resources, null, "hyts_htmltest.html");
u = new URL("file", "", resources.getAbsolutePath()
+ "/hyts_htmltest.html");
u.openConnection();
is = (InputStream) u.getContent(new Class[] { Object.class });
is.read(ba = new byte[4096]);
s = new String(ba);
assertTrue("Incorrect content " + u
+ " does not contain: \" A Seemingly Non Important String \"",
s.indexOf("A Seemingly Non Important String") >= 0);
}
/**
* java.net.URL#openConnection()
*/
public void test_openConnection() {
// Test for method java.net.URLConnection java.net.URL.openConnection()
try {
u = new URL("systemresource:/FILE4/+/types.properties");
URLConnection uConn = u.openConnection();
assertNotNull("u.openConnection() returns null", uConn);
} catch (Exception e) {
}
}
/**
* java.net.URL#toString()
*/
public void test_toString() {
// Test for method java.lang.String java.net.URL.toString()
try {
u1 = new URL("http://www.yahoo2.com:9999");
u = new URL(
"http://www.yahoo1.com:8080/dir1/dir2/test.cgi?point1.html#anchor1");
assertEquals(
"a) Does not return the right url string",
"http://www.yahoo1.com:8080/dir1/dir2/test.cgi?point1.html#anchor1",
u.toString());
assertEquals("b) Does not return the right url string",
"http://www.yahoo2.com:9999", u1.toString());
assertTrue("c) Does not return the right url string", u
.equals(new URL(u.toString())));
} catch (Exception e) {
}
}
/**
* java.net.URL#toExternalForm()
*/
public void test_toExternalForm() {
// Test for method java.lang.String java.net.URL.toExternalForm()
try {
u1 = new URL("http://www.yahoo2.com:9999");
u = new URL(
"http://www.yahoo1.com:8080/dir1/dir2/test.cgi?point1.html#anchor1");
assertEquals(
"a) Does not return the right url string",
"http://www.yahoo1.com:8080/dir1/dir2/test.cgi?point1.html#anchor1",
u.toString());
assertEquals("b) Does not return the right url string",
"http://www.yahoo2.com:9999", u1.toString());
assertTrue("c) Does not return the right url string", u
.equals(new URL(u.toString())));
u = new URL("http:index");
assertEquals("2 wrong external form", "http:index", u
.toExternalForm());
u = new URL("http", null, "index");
assertEquals("2 wrong external form", "http:index", u
.toExternalForm());
} catch (Exception e) {
}
}
/**
* java.net.URL#getFile()
*/
public void test_getFile() throws Exception {
// Test for method java.lang.String java.net.URL.getFile()
u = new URL("http", "www.yahoo.com:8080", 1233,
"test/!@$%^&*/test.html#foo");
assertEquals("returns a wrong file", "/test/!@$%^&*/test.html", u
.getFile());
u = new URL("http", "www.yahoo.com:8080", 1233, "");
assertTrue("returns a wrong file", u.getFile().equals(""));
}
/**
* java.net.URL#getHost()
*/
public void test_getHost() throws MalformedURLException {
// Regression for HARMONY-60
String ipv6Host = "FEDC:BA98:7654:3210:FEDC:BA98:7654:3210";
URL url = new URL("http", ipv6Host, -1, "myfile");
assertEquals(("[" + ipv6Host + "]"), url.getHost());
}
/**
* java.net.URL#getPort()
*/
public void test_getPort() throws Exception {
// Test for method int java.net.URL.getPort()
u = new URL("http://member12.c++.com:9999");
assertTrue("return wrong port number " + u.getPort(),
u.getPort() == 9999);
u = new URL("http://member12.c++.com:9999/");
assertEquals("return wrong port number", 9999, u.getPort());
}
/**
* @throws MalformedURLException
* java.net.URL#getDefaultPort()
*/
public void test_getDefaultPort() throws MalformedURLException {
u = new URL("http://member12.c++.com:9999");
assertEquals(80, u.getDefaultPort());
u = new URL("ftp://member12.c++.com:9999/");
assertEquals(21, u.getDefaultPort());
}
/**
* java.net.URL#getProtocol()
*/
public void test_getProtocol() throws Exception {
// Test for method java.lang.String java.net.URL.getProtocol()
u = new URL("http://www.yahoo2.com:9999");
assertTrue("u returns a wrong protocol: " + u.getProtocol(), u
.getProtocol().equals("http"));
}
/**
* java.net.URL#getRef()
*/
public void test_getRef() {
// Test for method java.lang.String java.net.URL.getRef()
try {
u1 = new URL("http://www.yahoo2.com:9999");
u = new URL(
"http://www.yahoo1.com:8080/dir1/dir2/test.cgi?point1.html#anchor1");
assertEquals("returns a wrong anchor1", "anchor1", u.getRef());
assertNull("returns a wrong anchor2", u1.getRef());
u1 = new URL("http://www.yahoo2.com#ref");
assertEquals("returns a wrong anchor3", "ref", u1.getRef());
u1 = new URL("http://www.yahoo2.com/file#ref1#ref2");
assertEquals("returns a wrong anchor4", "ref1#ref2", u1.getRef());
} catch (MalformedURLException e) {
fail("Incorrect URL format : " + e.getMessage());
}
}
/**
* java.net.URL#getAuthority()
*/
public void test_getAuthority() throws MalformedURLException {
URL testURL = new URL("http", "hostname", 80, "/java?q1#ref");
assertEquals("hostname:80", testURL.getAuthority());
assertEquals("hostname", testURL.getHost());
assertNull(testURL.getUserInfo());
assertEquals("/java?q1", testURL.getFile());
assertEquals("/java", testURL.getPath());
assertEquals("q1", testURL.getQuery());
assertEquals("ref", testURL.getRef());
testURL = new URL("http", "u:p@home", 80, "/java?q1#ref");
assertEquals("[u:p@home]:80", testURL.getAuthority());
assertEquals("[u:p@home]", testURL.getHost());
assertNull(testURL.getUserInfo());
assertEquals("/java?q1", testURL.getFile());
assertEquals("/java", testURL.getPath());
assertEquals("q1", testURL.getQuery());
assertEquals("ref", testURL.getRef());
testURL = new URL("http", "home", -1, "/java");
assertEquals("wrong authority2", "home", testURL.getAuthority());
assertNull("wrong userInfo2", testURL.getUserInfo());
assertEquals("wrong host2", "home", testURL.getHost());
assertEquals("wrong file2", "/java", testURL.getFile());
assertEquals("wrong path2", "/java", testURL.getPath());
assertNull("wrong query2", testURL.getQuery());
assertNull("wrong ref2", testURL.getRef());
}
/**
* java.net.URL#toURL()
*/
public void test_toURI() throws Exception {
u = new URL("http://www.apache.org");
URI uri = u.toURI();
assertTrue(u.equals(uri.toURL()));
}
/**
* java.net.URL#openConnection()
*/
public void test_openConnection_FileProtocol() throws Exception {
// Regression test for Harmony-5779
String basedir = new File("temp.java").getAbsolutePath();
String fileUrlString = "file://localhost/" + basedir;
URLConnection conn = new URL(fileUrlString).openConnection();
assertEquals("file", conn.getURL().getProtocol());
assertEquals(new File(basedir), new File(conn.getURL().getFile()));
String nonLocalUrlString = "file://anything/" + basedir;
conn = new URL(nonLocalUrlString).openConnection();
assertEquals("ftp", conn.getURL().getProtocol());
assertEquals(new File(basedir), new File(conn.getURL().getFile()));
}
/**
* URLStreamHandler implementation class necessary for tests.
*/
private class TestURLStreamHandler extends URLStreamHandler {
public URLConnection openConnection(URL arg0) throws IOException {
try {
return arg0.openConnection();
} catch (Throwable e) {
return null;
}
}
public URLConnection openConnection(URL arg0, Proxy proxy)
throws IOException {
return super.openConnection(u, proxy);
}
}
/**
* Check NPE throwing in constructor when protocol argument is null and
* URLStreamHandler argument is initialized.
*/
public void test_ConstructorLnullLjava_lang_StringILjava_lang_StringLjava_net_URLStreamHandler()
throws Exception {
// Regression for HARMONY-1131
TestURLStreamHandler lh = new TestURLStreamHandler();
try {
new URL(null, "1", 0, "file", lh);
fail("NullPointerException expected, but nothing was thrown!");
} catch (NullPointerException e) {
// Expected NullPointerException
}
}
/**
* Check NPE throwing in constructor when protocol argument is null and
* URLStreamHandler argument is null.
*/
public void test_ConstructorLnullLjava_lang_StringILjava_lang_StringLnull()
throws Exception {
// Regression for HARMONY-1131
try {
new URL(null, "1", 0, "file", null);
fail("NullPointerException expected, but nothing was thrown!");
} catch (NullPointerException e) {
// Expected NullPointerException
}
}
/**
* Check NPE throwing in constructor with 4 params when protocol argument is
* null.
*/
public void test_ConstructorLnullLjava_lang_StringILjava_lang_String()
throws Exception {
// Regression for HARMONY-1131
try {
new URL(null, "1", 0, "file");
fail("NullPointerException expected, but nothing was thrown!");
} catch (NullPointerException e) {
// Expected NullPointerException
}
}
/**
* Check NPE throwing in constructor with 3 params when protocol argument is
* null.
*/
public void test_ConstructorLnullLjava_lang_StringLjava_lang_String()
throws Exception {
// Regression for HARMONY-1131
try {
new URL(null, "1", "file");
fail("NullPointerException expected, but nothing was thrown!");
} catch (NullPointerException e) {
// Expected NullPointerException
}
}
public void test_toExternalForm_Absolute() throws MalformedURLException {
String strURL = "http://localhost?name=value";
URL url = new URL(strURL);
assertEquals(strURL, url.toExternalForm());
strURL = "http://localhost?name=value/age=12";
url = new URL(strURL);
assertEquals(strURL, url.toExternalForm());
}
public void test_toExternalForm_Relative() throws MalformedURLException {
String strURL = "http://a/b/c/d;p?q";
String ref = "?y";
URL url = new URL(new URL(strURL), ref);
assertEquals("http://a/b/c/d;p?y", url.toExternalForm());
}
// Regression test for HARMONY-6254
// Bogus handler forces file part of URL to be null
static class MyHandler2 extends URLStreamHandler {
@Override
protected URLConnection openConnection(URL arg0) throws IOException {
return null;
}
@Override
protected void setURL(URL u, String protocol, String host, int port,
String authority, String userInfo, String file, String query,
String ref) {
super.setURL(u, protocol, host, port, authority, userInfo,
(String) null, query, ref);
}
}
// Test special case of external form with null file part (HARMONY-6254)
public void test_toExternalForm_Null() throws IOException {
URLStreamHandler myHandler = new MyHandler2();
URL url = new URL(null, "foobar://example.com/foobar", myHandler);
String s = url.toExternalForm();
assertEquals("Got wrong URL external form", "foobar://example.com", s);
}
static class MockProxySelector extends ProxySelector {
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
System.out.println("connection failed");
}
public List<Proxy> select(URI uri) {
isSelectCalled = true;
ArrayList<Proxy> proxyList = new ArrayList<Proxy>(1);
proxyList.add(Proxy.NO_PROXY);
return proxyList;
}
}
static class MyURLStreamHandler extends URLStreamHandler {
@Override
protected URLConnection openConnection(URL arg0) throws IOException {
return null;
}
public void parse(URL url, String spec, int start, int end) {
parseURL(url, spec, start, end);
}
}
/**
* java.net.URL#URL(String, String, String)
*/
public void test_java_protocol_handler_pkgs_prop()
throws MalformedURLException {
// Regression test for Harmony-3094
final String HANDLER_PKGS = "java.protocol.handler.pkgs";
String pkgs = System.getProperty(HANDLER_PKGS);
System.setProperty(HANDLER_PKGS,
"fake|org.apache.harmony.luni.tests.java.net");
try {
new URL("test_protocol", "", "fake.jar");
} finally {
if (pkgs == null) {
System.clearProperty(HANDLER_PKGS);
} else {
System.setProperty(HANDLER_PKGS, pkgs);
}
}
}
}
|
google/desugar_jdk_libs
|
jdk11/src/libcore/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/URLTest.java
|
Java
|
gpl-2.0
| 48,856
|
<!DOCTYPE html>
<html>
<head>
<title>Przyk³ad</title>
</head>
<body>
<form>
Imiê: <input type="text" name="name" accesskey="i"/>
<p/>
Has³o: <input type="password" name="password" accesskey="h"/>
<p/>
<input type="submit" value="Zaloguj" accesskey="z"/>
</form>
</body>
</html>
|
JedrzMar/avr
|
ch03/14 - AccessKey.html
|
HTML
|
gpl-2.0
| 291
|
#include "../qcommon/q_shared.h"
#include "cg_local.h"
#include <jsapi.h>
static JSClass vector3_class = {
"Vec3", 0,
JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub
};
static JSClass vector4_class = {
"Vec4", 0,
JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub
};
static JSBool vector3_constructor(JSContext *cx, unsigned argc, jsval *vp)
{
JSObject *returnObject;
jsval returnValue;
double x, y, z;
jsval r, g, b;
if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "ddd", &x, &y, &z))
return JS_FALSE;
returnObject = JS_NewObject(cx, &vector3_class, NULL, NULL);
returnValue = OBJECT_TO_JSVAL(returnObject);
JS_NewNumberValue(cx, x, &r);
JS_NewNumberValue(cx, y, &g);
JS_NewNumberValue(cx, z, &b);
JS_SetProperty(cx, returnObject, "X", &r);
JS_SetProperty(cx, returnObject, "Y", &g);
JS_SetProperty(cx, returnObject, "Z", &b);
JS_SET_RVAL(cx, vp, returnValue);
return JS_TRUE;
}
static JSBool vector4_constructor(JSContext *cx, unsigned argc, jsval *vp)
{
JSObject *returnObject;
jsval returnValue;
double w, x, y, z;
jsval r, g, b, a;
if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "dddd", &w, &x, &y, &z))
return JS_FALSE;
returnObject = JS_NewObject(cx, &vector4_class, NULL, NULL);
returnValue = OBJECT_TO_JSVAL(returnObject);
JS_NewNumberValue(cx, w, &r);
JS_NewNumberValue(cx, x, &g);
JS_NewNumberValue(cx, y, &b);
JS_NewNumberValue(cx, z, &a);
JS_SetProperty(cx, returnObject, "R", &r);
JS_SetProperty(cx, returnObject, "G", &g);
JS_SetProperty(cx, returnObject, "G", &b);
JS_SetProperty(cx, returnObject, "A", &b);
JS_SET_RVAL(cx, vp, returnValue);
return JS_TRUE;
}
void CG_JS_Vector_Init(JSContext *ctx, JSObject *global)
{
JS_InitClass(ctx, global, NULL, &vector3_class, vector3_constructor, 3, NULL, NULL, NULL, NULL);
JS_InitClass(ctx, global, NULL, &vector4_class, vector4_constructor, 4, NULL, NULL, NULL, NULL);
}
JSBool JS_NewVector3Value(JSContext *cx, vec3_t v, jsval *rval)
{
JSObject *obj;
jsval a,b,c;
if (!JS_NewNumberValue(cx,v[0],&a))
{
JS_ReportError(cx,"NewVector3_Value: Failed to get X\n");
return JS_FALSE;
}
if (!JS_NewNumberValue(cx,v[1],&b))
{
JS_ReportError(cx,"NewVector3_Value: Failed to get Y\n");
return JS_FALSE;
}
if (!JS_NewNumberValue(cx,v[2],&c))
{
JS_ReportError(cx,"NewVector3_Value: Failed to get Z\n");
return JS_FALSE;
}
obj = JS_NewObject(cx, &vector3_class, NULL, NULL);
*rval = OBJECT_TO_JSVAL(obj);
JS_SetProperty(cx, obj, "X", &a);
JS_SetProperty(cx, obj, "Y", &b);
JS_SetProperty(cx, obj, "Z", &c);
return JS_TRUE;
}
JSBool JS_NewVector4Value(JSContext *cx, vec4_t v, jsval *rval)
{
JSObject *obj;
jsval a,b,c,d;
if (!JS_NewNumberValue(cx,v[0],&a))
{
JS_ReportError(cx,"NewVector4_Value: Failed to get R\n");
return JS_FALSE;
}
if (!JS_NewNumberValue(cx,v[1],&b))
{
JS_ReportError(cx,"NewVector4_Value: Failed to get G\n");
return JS_FALSE;
}
if (!JS_NewNumberValue(cx,v[2],&c))
{
JS_ReportError(cx,"NewVector4_Value: Failed to get B\n");
return JS_FALSE;
}
if (!JS_NewNumberValue(cx,v[3],&d))
{
JS_ReportError(cx,"NewVector4_Value: Failed to get A\n");
return JS_FALSE;
}
obj = JS_NewObject(cx, &vector4_class, NULL, NULL);
*rval = OBJECT_TO_JSVAL(obj);
JS_SetProperty(cx, obj, "R", &a);
JS_SetProperty(cx, obj, "G", &b);
JS_SetProperty(cx, obj, "B", &c);
JS_SetProperty(cx, obj, "A", &d);
return JS_TRUE;
}
|
tectronics/battle-of-the-sexes
|
code/cgame/cg_js_vec.c
|
C
|
gpl-2.0
| 3,716
|
#ifndef __STMMAC_H__
#define __STMMAC_H__
#include <common.h>
#include <command.h>
#include <linux/list.h>
#include <asm/io.h>
#include <malloc.h> /* malloc, free, realloc*/
#include <net.h>
#include <miiphy.h>
#define print_mac(mac) do { int i;\
printf("MAC: ");\
for (i = 0; i < MAC_LEN; i++)\
printf("%c%02X", i ? '-' : ' ', *(((unsigned char *)mac)+i));\
printf("\n");\
} while (0)
#define MAC_LEN 6
#define MAX_PHY_NAME_LEN 6
#define MIN_PKG_LEN (42)
#define MAX_PKG_LEN (1600)
#define STMMAC_INVALID_RXPKG_LEN(len) \
(!(((len) >= MIN_PKG_LEN) && ((len) <= MAX_PKG_LEN)))
#define PORT_MOD_10M_MII 0
#define PORT_MOD_100M_MII 1
#define PORT_MOD_1000M_GMII 2
#define PORT_MOD_10M_RGMII 3
#define PORT_MOD_100M_RGMII 4
#define PORT_MOD_1000M_RGMII 5
#define DEFAULT_PHY_LINK_TIMES 20000
#define STMMAC_LINKED (1 << 0)
#define STMMAC_DUP_FULL (1 << 1)
#define STMMAC_SPD_10M (1 << 2)
#define STMMAC_SPD_100M (1 << 3)
#define STMMAC_SPD_1000M (1 << 4)
#define GMAC0_PORT 0
#ifndef STMMAC_SINGLE_MAC
#define GMAC1_PORT 1
#endif
#define STMMAC_IOBASE STMMAC_GMACADDR
#define STMMAC_IOBASE_DMA STMMAC_DMAADDR
#define STMMAC_PHYID STMMAC_PHYADDR
#define SZ_1K 1024
#define STMMAC_HW_QUEUE_DEPTH 1
#define STMMAC_MAX_FRAME_SIZE (SZ_1K*2)
#define SKB_SIZE (STMMAC_MAX_FRAME_SIZE)
struct dma_desc_tx {
unsigned int volatile status;
unsigned int volatile length;
unsigned int volatile buffer1;
unsigned int volatile buffer2;
};
struct dma_desc_rx {
unsigned int volatile status_0;
unsigned int volatile length_0;
unsigned int volatile buffer1_0;
unsigned int volatile buffer2_0;
unsigned int volatile status_1;
unsigned int volatile length_1;
unsigned int volatile buffer1_1;
unsigned int volatile buffer2_1;
};
struct stmmac_netdev_local {
/* gmac addr */
unsigned long iobase_gmac;
/* dma addr */
unsigned long iobase_dma;
/* 0 => GMAC0, 1 => GMAC1 */
int port;
struct dma_desc_rx *rx_addr;
struct dma_desc_tx *tx_addr;
char *phy_name;
int link_stat;
};
#endif
|
csolg/hi35xx-buildroot
|
boot/uboot/u-boot-2010.06/drivers/net/stmmac/stmmac.h
|
C
|
gpl-2.0
| 2,029
|
package edu.umd.cs.findbugs.ml;
import java.util.Collection;
import junit.framework.Assert;
import junit.framework.TestCase;
import edu.umd.cs.findbugs.util.SplitCamelCaseIdentifier;
public class SplitCamelCaseIdentifierTest extends TestCase {
SplitCamelCaseIdentifier splitter;
SplitCamelCaseIdentifier splitter2;
SplitCamelCaseIdentifier splitterLong;
SplitCamelCaseIdentifier allLower;
SplitCamelCaseIdentifier allUpper;
SplitCamelCaseIdentifier capitalized;
@Override
protected void setUp() throws Exception {
splitter = new SplitCamelCaseIdentifier("displayGUIWindow");
splitter2 = new SplitCamelCaseIdentifier("DisplayGUIWindow");
splitterLong = new SplitCamelCaseIdentifier("nowIsTheWINTEROfOURDiscontent");
allLower = new SplitCamelCaseIdentifier("foobar");
allUpper = new SplitCamelCaseIdentifier("NSA");
capitalized = new SplitCamelCaseIdentifier("Maryland");
}
public void testSplit() {
Collection<String> words = splitter.split();
checkContents(words, new String[] { "display", "gui", "window" });
}
public void testSplit2() {
Collection<String> words = splitter2.split();
checkContents(words, new String[] { "display", "gui", "window" });
}
public void testSplitLong() {
Collection<String> words = splitterLong.split();
checkContents(words, new String[] { "now", "is", "the", "winter", "of", "our", "discontent" });
}
public void testAllLower() {
Collection<String> words = allLower.split();
checkContents(words, new String[] { "foobar" });
}
public void testAllUpper() {
Collection<String> words = allUpper.split();
checkContents(words, new String[] { "nsa" });
}
public void testCapitalized() {
Collection<String> words = capitalized.split();
checkContents(words, new String[] { "maryland" });
}
private void checkContents(Collection<String> words, String[] expected) {
Assert.assertEquals(expected.length, words.size());
for (String anExpected : expected) {
Assert.assertTrue(words.contains(anExpected));
}
}
}
|
jesusaplsoft/FindAllBugs
|
findbugs/src/junit/edu/umd/cs/findbugs/ml/SplitCamelCaseIdentifierTest.java
|
Java
|
gpl-2.0
| 2,215
|
/* file generated by oo2c -- do not edit */
#include "__oo2c.h"
#include "__libc.h"
#include "CharClass.d"
static _ModId _mid;
unsigned char CharClass__IsNumeric(unsigned char ch) {
register int i0;
i0 = (int)ch < 48;
if (i0) goto l0;
i0 = (int)ch <= 57;
if (i0) goto l1;
l0:
i0 = 0;
goto l2;
l1:
i0 = 1;
l2:
return (unsigned char)i0;
}
unsigned char CharClass__IsLetter(unsigned char ch) {
register int i0;
i0 = (int)ch < 97;
if (i0) goto l0;
i0 = (int)ch <= 122;
if (i0) goto l2;
l0:
i0 = (int)ch >= 65;
if (!(i0)) goto l1;
i0 = (int)ch <= 90;
if (i0) goto l2;
l1:
i0 = 0;
goto l3;
l2:
i0 = 1;
l3:
return (unsigned char)i0;
}
unsigned char CharClass__IsUpper(unsigned char ch) {
register int i0;
i0 = (int)ch < 65;
if (i0) goto l0;
i0 = (int)ch <= 90;
if (i0) goto l1;
l0:
i0 = 0;
goto l2;
l1:
i0 = 1;
l2:
return (unsigned char)i0;
}
unsigned char CharClass__IsLower(unsigned char ch) {
register int i0;
i0 = (int)ch < 97;
if (i0) goto l0;
i0 = (int)ch <= 122;
if (i0) goto l1;
l0:
i0 = 0;
goto l2;
l1:
i0 = 1;
l2:
return (unsigned char)i0;
}
unsigned char CharClass__IsControl(unsigned char ch) {
register int i0;
i0 = (int)ch < 32;
return (unsigned char)i0;
}
unsigned char CharClass__IsWhiteSpace(unsigned char ch) {
register int i0;
i0 = (int)ch == 32;
if (i0) goto l0;
i0 = (int)ch == 12;
if (i0) goto l0;
i0 = (int)ch == 10;
if (i0) goto l0;
i0 = (int)ch == 13;
if (i0) goto l0;
i0 = (int)ch == 9;
if (i0) goto l0;
i0 = (int)ch == 11;
if (i0) goto l0;
i0 = 0;
goto l1;
l0:
i0 = 1;
l1:
return (unsigned char)i0;
}
unsigned char CharClass__IsEol(unsigned char ch) {
register int i0;
i0 = (int)ch == 10;
return (unsigned char)i0;
}
void CharClass_init(void) {
register int i0;
_mid = _register_module(&CharClass_md.md, NULL);
i0 = (int)CharClass__systemEol + 1;
*(unsigned char*)(int)CharClass__systemEol = 10;
*(unsigned char*)i0 = 0;
}
|
ngospina/ooc-gsa
|
src.c/CharClass.c
|
C
|
gpl-2.0
| 1,988
|
/*
* This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef MANGOS_DBCSTRUCTURE_H
#define MANGOS_DBCSTRUCTURE_H
#include "Server/DBCEnums.h"
#include "MotionGenerators/Path.h"
#include "Platform/Define.h"
#include "Globals/SharedDefines.h"
#include <map>
#include <set>
#include <vector>
// Structures using to access raw DBC data and required packing to portability
// GCC have alternative #pragma pack(N) syntax and old gcc version not support pack(push,N), also any gcc version not support it at some platform
#if defined( __GNUC__ )
#pragma pack(1)
#else
#pragma pack(push,1)
#endif
struct AchievementEntry
{
uint32 ID; // 0 m_ID
uint32 factionFlag; // 1 m_faction -1=all, 0=horde, 1=alliance
uint32 mapID; // 2 m_instance_id -1=none
// uint32 parentAchievement; // 3 m_supercedes its Achievement parent (can`t start while parent uncomplete, use its Criteria if don`t have own, use its progress on begin)
char* name[16]; // 4-19 m_title_lang
// uint32 name_flags; // 20 string flags
// char *description[16]; // 21-36 m_description_lang
// uint32 desc_flags; // 37 string flags
uint32 categoryId; // 38 m_category
uint32 points; // 39 m_points
// uint32 OrderInCategory; // 40 m_ui_order
uint32 flags; // 41 m_flags
// uint32 icon; // 42 m_iconID
// char *titleReward[16]; // 43-58 m_reward_lang
// uint32 titleReward_flags; // 59 string flags
uint32 count; // 60 m_minimum_criteria - need this count of completed criterias (own or referenced achievement criterias)
uint32 refAchievement; // 61 m_shares_criteria - referenced achievement (counting of all completed criterias)
};
struct AchievementCategoryEntry
{
uint32 ID; // 0 m_ID
uint32 parentCategory; // 1 m_parent -1 for main category
// char *name[16]; // 2-17 m_name_lang
// uint32 name_flags; // 18 string flags
// uint32 sortOrder; // 19 m_ui_order
};
struct AchievementCriteriaEntry
{
uint32 ID; // 0 m_ID
uint32 referredAchievement; // 1 m_achievement_id
uint32 requiredType; // 2 m_type
union
{
// ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE = 0
// TODO: also used for player deaths..
struct
{
uint32 creatureID; // 3
uint32 creatureCount; // 4
} kill_creature;
// ACHIEVEMENT_CRITERIA_TYPE_WIN_BG = 1
struct
{
uint32 bgMapID; // 3
uint32 winCount; // 4
uint32 additionalRequirement1_type; // 5
uint32 additionalRequirement1_value; // 6
uint32 additionalRequirement2_type; // 7
uint32 additionalRequirement2_value; // 8
} win_bg;
// ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL = 5
struct
{
uint32 unused; // 3
uint32 level; // 4
} reach_level;
// ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL = 7
struct
{
uint32 skillID; // 3
uint32 skillLevel; // 4
} reach_skill_level;
// ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT = 8
struct
{
uint32 linkedAchievement; // 3
} complete_achievement;
// ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT = 9
struct
{
uint32 unused; // 3
uint32 totalQuestCount; // 4
} complete_quest_count;
// ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY = 10
struct
{
uint32 unused; // 3
uint32 numberOfDays; // 4
} complete_daily_quest_daily;
// ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE = 11
struct
{
uint32 zoneID; // 3
uint32 questCount; // 4
} complete_quests_in_zone;
// ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST = 14
struct
{
uint32 unused; // 3
uint32 questCount; // 4
} complete_daily_quest;
// ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND = 15
struct
{
uint32 mapID; // 3
} complete_battleground;
// ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP = 16
struct
{
uint32 mapID; // 3
} death_at_map;
// ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON = 18
struct
{
uint32 manLimit; // 3
} death_in_dungeon;
// ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_RAID = 19
struct
{
uint32 groupSize; // 3 can be 5, 10 or 25
} complete_raid;
// ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE = 20
struct
{
uint32 creatureEntry; // 3
} killed_by_creature;
// ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING = 24
struct
{
uint32 unused; // 3
uint32 fallHeight; // 4
} fall_without_dying;
// ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM = 26
struct
{
uint32 type; // 3, see enum EnviromentalDamage
} death_from;
// ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST = 27
struct
{
uint32 questID; // 3
uint32 questCount; // 4
} complete_quest;
// ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET = 28
// ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2 = 69
struct
{
uint32 spellID; // 3
uint32 spellCount; // 4
} be_spell_target;
// ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL = 29
// ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2 = 110
struct
{
uint32 spellID; // 3
uint32 castCount; // 4
} cast_spell;
// ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA = 31
struct
{
uint32 areaID; // 3 Reference to AreaTable.dbc
uint32 killCount; // 4
} honorable_kill_at_area;
// ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA = 32
struct
{
uint32 mapID; // 3 Reference to Map.dbc
} win_arena;
// ACHIEVEMENT_CRITERIA_TYPE_PLAY_ARENA = 33
struct
{
uint32 mapID; // 3 Reference to Map.dbc
} play_arena;
// ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL = 34
struct
{
uint32 spellID; // 3 Reference to Map.dbc
} learn_spell;
// ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM = 36
struct
{
uint32 itemID; // 3
uint32 itemCount; // 4
} own_item;
// ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA = 37
struct
{
uint32 unused; // 3
uint32 count; // 4
uint32 flag; // 5 4=in a row
} win_rated_arena;
// ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING = 38
struct
{
uint32 teamtype; // 3 {2,3,5}
} highest_team_rating;
// ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING= 39
struct
{
uint32 teamtype; // 3 {2,3,5}
uint32 teamrating; // 4
} highest_personal_rating;
// ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL = 40
struct
{
uint32 skillID; // 3
uint32 skillLevel; // 4 apprentice=1, journeyman=2, expert=3, artisan=4, master=5, grand master=6
} learn_skill_level;
// ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM = 41
struct
{
uint32 itemID; // 3
uint32 itemCount; // 4
} use_item;
// ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM = 42
struct
{
uint32 itemID; // 3
uint32 itemCount; // 4
} loot_item;
// ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA = 43
struct
{
// TODO: This rank is _NOT_ the index from AreaTable.dbc
uint32 areaReference; // 3
} explore_area;
// ACHIEVEMENT_CRITERIA_TYPE_OWN_RANK = 44
struct
{
// TODO: This rank is _NOT_ the index from CharTitles.dbc
uint32 rank; // 3
} own_rank;
// ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT = 45
struct
{
uint32 unused; // 3
uint32 numberOfSlots; // 4
} buy_bank_slot;
// ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION = 46
struct
{
uint32 factionID; // 3
uint32 reputationAmount; // 4 Total reputation amount, so 42000 = exalted
} gain_reputation;
// ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION= 47
struct
{
uint32 unused; // 3
uint32 numberOfExaltedFactions; // 4
} gain_exalted_reputation;
// ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP = 48
struct
{
uint32 unused; // 3
uint32 numberOfVisits; // 4
} visit_barber;
// ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM = 49
// TODO: where is the required itemlevel stored?
struct
{
uint32 itemSlot; // 3
uint32 count; // 4
} equip_epic_item;
// ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT = 50
struct
{
uint32 rollValue; // 3
uint32 count; // 4
} roll_need_on_loot;
// ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT = 51
struct
{
uint32 rollValue; // 3
uint32 count; // 4
} roll_greed_on_loot;
// ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS = 52
struct
{
uint32 classID; // 3
uint32 count; // 4
} hk_class;
// ACHIEVEMENT_CRITERIA_TYPE_HK_RACE = 53
struct
{
uint32 raceID; // 3
uint32 count; // 4
} hk_race;
// ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE = 54
// TODO: where is the information about the target stored?
struct
{
uint32 emoteID; // 3 enum TextEmotes
uint32 count; // 4 count of emotes, always required special target or requirements
} do_emote;
// ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE = 13
// ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE = 55
// ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS = 56
struct
{
uint32 unused; // 3
uint32 count; // 4
uint32 flag; // 5 =3 for battleground healing
uint32 mapid; // 6
} healing_done;
// ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM = 57
struct
{
uint32 itemID; // 3
uint32 count; // 4
} equip_item;
// ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD= 62
struct
{
uint32 unused; // 3
uint32 goldInCopper; // 4
} quest_reward_money;
// ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY = 67
struct
{
uint32 unused; // 3
uint32 goldInCopper; // 4
} loot_money;
// ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT = 68
struct
{
uint32 goEntry; // 3
uint32 useCount; // 4
} use_gameobject;
// ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL = 70
// TODO: are those special criteria stored in the dbc or do we have to add another sql table?
struct
{
uint32 unused; // 3
uint32 killCount; // 4
} special_pvp_kill;
// ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT = 72
struct
{
uint32 goEntry; // 3
uint32 lootCount; // 4
} fish_in_gameobject;
// ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS = 75
struct
{
uint32 skillLine; // 3
uint32 spellCount; // 4
} learn_skillline_spell;
// ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL = 76
struct
{
uint32 unused; // 3
uint32 duelCount; // 4
} win_duel;
// ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_POWER = 96
struct
{
uint32 powerType; // 3 mana=0, 1=rage, 3=energy, 6=runic power
} highest_power;
// ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_STAT = 97
struct
{
uint32 statType; // 3 4=spirit, 3=int, 2=stamina, 1=agi, 0=strength
} highest_stat;
// ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_SPELLPOWER = 98
struct
{
uint32 spellSchool; // 3
} highest_spellpower;
// ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_RATING = 100
struct
{
uint32 ratingType; // 3
} highest_rating;
// ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE = 109
struct
{
uint32 lootType; // 3 3=fishing, 2=pickpocket, 4=disentchant
uint32 lootTypeCount; // 4
} loot_type;
// ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE = 112
struct
{
uint32 skillLine; // 3
uint32 spellCount; // 4
} learn_skill_line;
// ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL = 113
struct
{
uint32 unused; // 3
uint32 killCount; // 4
} honorable_kill;
struct
{
uint32 value; // 3 m_asset_id
uint32 count; // 4 m_quantity
uint32 additionalRequirement1_type; // 5 m_start_event
uint32 additionalRequirement1_value; // 6 m_start_asset
uint32 additionalRequirement2_type; // 7 m_fail_event
uint32 additionalRequirement2_value; // 8 m_fail_asset
} raw;
};
char* name[16]; // 9-24 m_description_lang
// uint32 name_flags; // 25
uint32 completionFlag; // 26 m_flags
// uint32 timedCriteriaStartType; // 27 m_timer_start_event Only appears with timed achievements, seems to be the type of starting a timed Achievement, only type 1 and some of type 6 need manual starting: 1: ByEventId(?) (serverside IDs), 2: ByQuestId, 5: ByCastSpellId(?), 6: BySpellIdTarget(some of these are unknown spells, some not, some maybe spells), 7: ByKillNpcId, 9: ByUseItemId
uint32 timedCriteriaMiscId; // 28 m_timer_asset_id Alway appears with timed events, used internally to start the achievement, store
uint32 timeLimit; // 29 m_timer_time
uint32 showOrder; // 30 m_ui_order also used in achievement shift-links as index in state bitmask
// helpers
bool IsExplicitlyStartedTimedCriteria() const
{
if (!timeLimit)
return false;
// in case raw.value == timedCriteriaMiscId in timedCriteriaMiscId stored spellid/itemids for cast/use, so repeating aura start at first cast/use until fails
return requiredType == ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST || raw.value != timedCriteriaMiscId;
}
};
struct AreaTableEntry
{
uint32 ID; // 0 m_ID
uint32 mapid; // 1 m_ContinentID
uint32 zone; // 2 m_ParentAreaID
uint32 exploreFlag; // 3 m_AreaBit
uint32 flags; // 4 m_flags
// 5 m_SoundProviderPref
// 6 m_SoundProviderPrefUnderwater
// 7 m_AmbienceID
// 8 m_ZoneMusic
// 9 m_IntroSound
int32 area_level; // 10 m_ExplorationLevel
char* area_name[16]; // 11-26 m_AreaName_lang
// 27 string flags
uint32 team; // 28 m_factionGroupMask
uint32 LiquidTypeOverride[4]; // 29-32 m_liquidTypeID[4]
// 33 m_minElevation
// 34 m_ambient_multiplier
// 35 m_lightid
};
struct AreaGroupEntry
{
uint32 AreaGroupId; // 0 m_ID
uint32 AreaId[6]; // 1-6 m_areaID
uint32 nextGroup; // 7 m_nextAreaID
};
struct AreaTriggerEntry
{
uint32 id; // 0 m_ID
uint32 mapid; // 1 m_ContinentID
float x; // 2 m_x
float y; // 3 m_y
float z; // 4 m_z
float radius; // 5 m_radius
float box_x; // 6 m_box_length
float box_y; // 7 m_box_width
float box_z; // 8 m_box_heigh
float box_orientation; // 9 m_box_yaw
};
struct AuctionHouseEntry
{
uint32 houseId; // 0 m_ID
uint32 faction; // 1 m_factionID
uint32 depositPercent; // 2 m_depositRate
uint32 cutPercent; // 3 m_consignmentRate
// char* name[16]; // 4-19 m_name_lang
// 20 string flags
};
struct BankBagSlotPricesEntry
{
uint32 ID; // 0 m_ID
uint32 price; // 1 m_Cost
};
struct BarberShopStyleEntry
{
uint32 Id; // 0 m_ID
uint32 type; // 1 m_type
// char* name[16]; // 2-17 m_DisplayName_lang
// uint32 name_flags; // 18 string flags
// uint32 unk_name[16]; // 19-34 m_Description_lang
// uint32 unk_flags; // 35 string flags
// float CostMultiplier; // 36 m_Cost_Modifier
uint32 race; // 37 m_race
uint32 gender; // 38 m_sex
uint32 hair_id; // 39 m_data (real ID to hair/facial hair)
};
struct BattlemasterListEntry
{
uint32 id; // 0 m_ID
int32 mapid[8]; // 1-8 m_mapID[8]
uint32 type; // 9 m_instanceType
// uint32 canJoinAsGroup; // 10 m_groupsAllowed
char* name[16]; // 11-26 m_name_lang
// uint32 nameFlags // 27 string flags
uint32 maxGroupSize; // 28 m_maxGroupSize
uint32 HolidayWorldStateId; // 29 m_holidayWorldState
uint32 minLevel; // 30 m_minlevel (sync with PvPDifficulty.dbc content)
uint32 maxLevel; // 31 m_maxlevel (sync with PvPDifficulty.dbc content)
};
/*struct Cfg_CategoriesEntry
{
uint32 Index; // m_ID categoryId (sent in RealmList packet)
uint32 Unk1; // m_localeMask
uint32 Unk2; // m_charsetMask
uint32 IsTournamentRealm; // m_flags
char *categoryName[16]; // m_name_lang
uint32 categoryNameFlags;
}*/
/*struct Cfg_ConfigsEntry
{
uint32 Id; // m_ID
uint32 Type; // m_realmType (sent in RealmList packet)
uint32 IsPvp; // m_playerKillingAllowed
uint32 IsRp; // m_roleplaying
};*/
#define MAX_OUTFIT_ITEMS 24
struct CharStartOutfitEntry
{
// uint32 Id; // 0 m_ID
uint32 RaceClassGender; // 1 m_raceID m_classID m_sexID m_outfitID (UNIT_FIELD_BYTES_0 & 0x00FFFFFF) comparable (0 byte = race, 1 byte = class, 2 byte = gender)
int32 ItemId[MAX_OUTFIT_ITEMS]; // 2-25 m_ItemID
// int32 ItemDisplayId[MAX_OUTFIT_ITEMS]; // 26-29 m_DisplayItemID not required at server side
// int32 ItemInventorySlot[MAX_OUTFIT_ITEMS]; // 50-73 m_InventoryType not required at server side
// uint32 Unknown1; // 74 unique values (index-like with gaps ordered in other way as ids)
// uint32 Unknown2; // 75
// uint32 Unknown3; // 76
};
struct CharTitlesEntry
{
uint32 ID; // 0, m_ID
// uint32 unk1; // 1 m_Condition_ID
char* name[16]; // 2-17 m_name_lang
// 18 string flags
// char* name2[16]; // 19-34 m_name1_lang
// 35 string flags
uint32 bit_index; // 36 m_mask_ID used in PLAYER_CHOSEN_TITLE and 1<<index in PLAYER__FIELD_KNOWN_TITLES
};
struct ChatChannelsEntry
{
uint32 ChannelID; // 0 m_ID
uint32 flags; // 1 m_flags
// 2 m_factionGroup
char* pattern[16]; // 3-18 m_name_lang
// 19 string flags
// char* name[16]; // 20-35 m_shortcut_lang
// 36 string flags
};
struct ChrClassesEntry
{
uint32 ClassID; // 0 m_ID
// uint32 flags; // 1 unknown
uint32 powerType; // 2 m_DisplayPower
// 3 m_petNameToken
char const* name[16]; // 4-19 m_name_lang
// 20 string flags
// char* nameFemale[16]; // 21-36 m_name_female_lang
// 37 string flags
// char* nameNeutralGender[16]; // 38-53 m_name_male_lang
// 54 string flags
// 55 m_filename
uint32 spellfamily; // 56 m_spellClassSet
// uint32 flags2; // 57 m_flags (0x08 HasRelicSlot)
uint32 CinematicSequence; // 58 m_cinematicSequenceID
uint32 expansion; // 59 m_required_expansion
};
struct ChrRacesEntry
{
uint32 RaceID; // 0 m_ID
// 1 m_flags
uint32 FactionID; // 2 m_factionID
// 3 m_ExplorationSoundID
uint32 model_m; // 4 m_MaleDisplayId
uint32 model_f; // 5 m_FemaleDisplayId
// 6 m_ClientPrefix
uint32 TeamID; // 7 m_BaseLanguage (7-Alliance 1-Horde)
// 8 m_creatureType
// 9 m_ResSicknessSpellID
// 10 m_SplashSoundID
// 11 m_clientFileString
uint32 CinematicSequence; // 12 m_cinematicSequenceID
// uint32 unk_322; // 13 m_alliance (0 alliance, 1 horde, 2 not available?)
char* name[16]; // 14-29 m_name_lang used for DBC language detection/selection
// 30 string flags
// char* nameFemale[16]; // 31-46 m_name_female_lang
// 47 string flags
// char* nameNeutralGender[16]; // 48-63 m_name_male_lang
// 64 string flags
// 65-66 m_facialHairCustomization[2]
// 67 m_hairCustomization
uint32 expansion; // 68 m_required_expansion
};
/*struct CinematicCameraEntry
{
uint32 id; // 0 m_ID
char* filename; // 1 m_model
uint32 soundid; // 2 m_soundID
float start_x; // 3 m_originX
float start_y; // 4 m_originY
float start_z; // 5 m_originZ
float unk6; // 6 m_originFacing
};*/
struct CinematicSequencesEntry
{
uint32 Id; // 0 m_ID
// uint32 unk1; // 1 m_soundID
// uint32 cinematicCamera; // 2 m_camera[8]
};
struct CreatureDisplayInfoEntry
{
uint32 Displayid; // 0 m_ID
uint32 ModelId;
// 2 m_soundID
uint32 ExtendedDisplayInfoID; // 3 m_extendedDisplayInfoID -> CreatureDisplayInfoExtraEntry::DisplayExtraId
float scale; // 4 m_creatureModelScale
// 5 m_creatureModelAlpha
// 6-8 m_textureVariation[3]
// 9 m_portraitTextureName
// 10 m_sizeClass
// 11 m_bloodID
// 12 m_NPCSoundID
// 13 m_particleColorID
// 14 m_creatureGeosetData
// 15 m_objectEffectPackageID
};
struct CreatureModelDataEntry
{
uint32 Id;
uint32 Flags;
// char* ModelPath[16]
// uint32 Unk1;
float Scale; // Used in calculation of unit collision data
// int32 Unk2
// int32 Unk3
// uint32 Unk4
// uint32 Unk5
// float Unk6
// uint32 Unk7
// float Unk8
// uint32 Unk9
// uint32 Unk10
// float CollisionWidth;
float CollisionHeight;
float MountHeight; // Used in calculation of unit collision data when mounted
// float Unks[11]
};
struct CreatureDisplayInfoExtraEntry
{
uint32 DisplayExtraId; // 0 m_ID CreatureDisplayInfoEntry::m_extendedDisplayInfoID
uint32 Race; // 1 m_DisplayRaceID
// uint32 Gender; // 2 m_DisplaySexID
// uint32 SkinColor; // 3 m_SkinID
// uint32 FaceType; // 4 m_FaceID
// uint32 HairType; // 5 m_HairStyleID
// uint32 HairStyle; // 6 m_HairColorID
// uint32 BeardStyle; // 7 m_FacialHairID
// uint32 Equipment[11]; // 8-18 m_NPCItemDisplay equipped static items EQUIPMENT_SLOT_HEAD..EQUIPMENT_SLOT_HANDS, client show its by self
// uint32 CanEquip; // 19 m_flags 0..1 Can equip additional things when used for players
// char* // 20 m_BakeName CreatureDisplayExtra-*.blp
};
struct CreatureFamilyEntry
{
uint32 ID; // 0 m_ID
float minScale; // 1 m_minScale
uint32 minScaleLevel; // 2 m_minScaleLevel
float maxScale; // 3 m_maxScale
uint32 maxScaleLevel; // 4 m_maxScaleLevel
uint32 skillLine[2]; // 5-6 m_skillLine
uint32 petFoodMask; // 7 m_petFoodMask
int32 petTalentType; // 8 m_petTalentType
// 9 m_categoryEnumID
char* Name[16]; // 10-25 m_name_lang
// 26 string flags
// 27 m_iconFile
};
#define MAX_CREATURE_SPELL_DATA_SLOT 4
struct CreatureSpellDataEntry
{
uint32 ID; // 0 m_ID
uint32 spellId[MAX_CREATURE_SPELL_DATA_SLOT]; // 1-4 m_spells[4]
// uint32 availability[MAX_CREATURE_SPELL_DATA_SLOT];// 4-7 m_availability[4]
};
struct CreatureTypeEntry
{
uint32 ID; // 0 m_ID
// char* Name[16]; // 1-16 m_name_lang
// 17 string flags
// uint32 no_expirience; // 18 m_flags
};
/* not used
struct CurrencyCategoryEntry
{
uint32 ID; // 0 m_ID
uint32 Unk1; // 1 m_flags 0 for known categories and 3 for unknown one (3.0.9)
char* Name[16]; // 2-17 m_name_lang
// // 18 string flags
};
*/
struct CurrencyTypesEntry
{
// uint32 ID; // 0 m_ID
uint32 ItemId; // 1 m_itemID used as real index
// uint32 Category; // 2 m_categoryID may be category
uint32 BitIndex; // 3 m_bitIndex bit index in PLAYER_FIELD_KNOWN_CURRENCIES (1 << (index-1))
};
struct DestructibleModelDataEntry
{
uint32 m_ID; // 0 m_ID
// uint32 unk1; // 1
// uint32 unk2; // 2
uint32 damagedDisplayId; // 3
// uint32 unk4; // 4
// uint32 unk5; // 5
// uint32 unk6; // 6
uint32 destroyedDisplayId; // 7
// uint32 unk8; // 8
// uint32 unk9; // 9
// uint32 unk10; // 10
uint32 rebuildingDisplayId; // 11 // Maybe rebuildingDisplayIdWhileDestroyed
// uint32 unk12; // 12
// uint32 unk13; // 13
// uint32 unk14; // 14
// uint32 unk15; // 15
// uint32 unk16; // 16
// uint32 unk17; // 17
// uint32 unk18; // 18
};
struct DungeonEncounterEntry
{
uint32 Id; // 0 m_ID
uint32 mapId; // 1 m_mapID
uint32 Difficulty; // 2 m_difficulty
uint32 encounterData; // 3 m_orderIndex
uint32 encounterIndex; // 4 m_Bit
char* encounterName[16]; // 5-20 m_name_lang
// uint32 nameLangFlags; // 21 m_name_lang_flags
// uint32 spellIconID; // 22 m_spellIconID
};
struct DurabilityCostsEntry
{
uint32 Itemlvl; // 0 m_ID
uint32 multiplier[29]; // 1-29 m_weaponSubClassCost m_armorSubClassCost
};
struct DurabilityQualityEntry
{
uint32 Id; // 0 m_ID
float quality_mod; // 1 m_data
};
struct EmotesEntry
{
uint32 Id; // 0 m_ID
// char* Name; // 1 m_EmoteSlashCommand
// uint32 AnimationId; // 2 m_AnimID
uint32 Flags; // 3 m_EmoteFlags
uint32 EmoteType; // 4 m_EmoteSpecProc (determine how emote are shown)
uint32 UnitStandState; // 5 m_EmoteSpecProcParam
// uint32 SoundId; // 6 m_EventSoundID
};
struct EmotesTextEntry
{
uint32 Id; // m_ID
// m_name
uint32 textid; // m_emoteID
// m_emoteText
};
struct FactionEntry
{
uint32 ID; // 0 m_ID
int32 reputationListID; // 1 m_reputationIndex
uint32 BaseRepRaceMask[4]; // 2-5 m_reputationRaceMask
uint32 BaseRepClassMask[4]; // 6-9 m_reputationClassMask
int32 BaseRepValue[4]; // 10-13 m_reputationBase
uint32 ReputationFlags[4]; // 14-17 m_reputationFlags
uint32 team; // 18 m_parentFactionID
float spilloverRateIn; // 19 m_parentFactionMod[2] Faction gains incoming rep * spilloverRateIn
float spilloverRateOut; // 20 Faction outputs rep * spilloverRateOut as spillover reputation
uint32 spilloverMaxRankIn; // 21 m_parentFactionCap[2] The highest rank the faction will profit from incoming spillover
// uint32 spilloverRank_unk; // 22 It does not seem to be the max standing at which a faction outputs spillover ...so no idea
char* name[16]; // 23-38 m_name_lang
// 39 string flags
// char* description[16]; // 40-55 m_description_lang
// 56 string flags
// helpers
int GetIndexFitTo(uint32 raceMask, uint32 classMask) const
{
for (int i = 0; i < 4; ++i)
{
if ((BaseRepRaceMask[i] == 0 || (BaseRepRaceMask[i] & raceMask)) &&
(BaseRepClassMask[i] == 0 || (BaseRepClassMask[i] & classMask)))
return i;
}
return -1;
}
bool HasReputation() const { return reputationListID >= 0; }
};
/*
// NOTE: FactionGroup.dbc - currently unused, please refer to related hardcoded enum FactionGroupMask
struct FactionGroupEntry
{
uint32 ID; // 0 m_ID
uint32 maskID; // 1 m_maskID index of the bit to check for in the faction group mask
char* internalName; // 2 m_internalName
// char* name[16]; // 3-18 m_name_lang localized display name in the UI
// 19 string flags
};
*/
struct FactionTemplateEntry
{
uint32 ID; // 0 m_ID
uint32 faction; // 1 m_faction
uint32 factionFlags; // 2 m_flags
uint32 factionGroupMask; // 3 m_factionGroup
uint32 friendGroupMask; // 4 m_friendGroup
uint32 enemyGroupMask; // 5 m_enemyGroup
uint32 enemyFaction[4]; // 6 m_enemies[4]
uint32 friendFaction[4]; // 10 m_friend[4]
//------------------------------------------------------- end structure
// helpers
bool IsFriendlyTo(FactionTemplateEntry const& entry) const
{
if (entry.faction)
{
for (int i = 0; i < 4; ++i)
if (enemyFaction[i] == entry.faction)
return false;
for (int i = 0; i < 4; ++i)
if (friendFaction[i] == entry.faction)
return true;
}
return (friendGroupMask & entry.factionGroupMask) || (factionGroupMask & entry.friendGroupMask);
}
bool IsHostileTo(FactionTemplateEntry const& entry) const
{
if (entry.faction)
{
for (int i = 0; i < 4; ++i)
if (enemyFaction[i] == entry.faction)
return true;
for (int i = 0; i < 4; ++i)
if (friendFaction[i] == entry.faction)
return false;
}
return (enemyGroupMask & entry.factionGroupMask) != 0;
}
bool IsHostileToPlayers() const { return (enemyGroupMask & FACTION_GROUP_MASK_PLAYER) != 0; }
bool IsNeutralToAll() const
{
for (int i = 0; i < 4; ++i)
if (enemyFaction[i] != 0)
return false;
return enemyGroupMask == 0 && friendGroupMask == 0;
}
bool IsContestedGuardFaction() const { return (factionFlags & FACTION_TEMPLATE_FLAG_CONTESTED_GUARD) != 0; }
};
struct GameObjectDisplayInfoEntry
{
uint32 Displayid; // 0 m_ID
char* filename; // 1 m_modelName
// uint32 unknown2[10]; // 2-11 m_Sound
float geoBoxMinX; // 12 m_geoBoxMinX (use first value as interact dist, mostly in hacks way)
float geoBoxMinY; // 13 m_geoBoxMinY
float geoBoxMinZ; // 14 m_geoBoxMinZ
float geoBoxMaxX; // 15 m_geoBoxMaxX
float geoBoxMaxY; // 16 m_geoBoxMaxY
float geoBoxMaxZ; // 17 m_geoBoxMaxZ
// uint32 unknown18; // 18 m_objectEffectPackageID
};
struct GemPropertiesEntry
{
uint32 ID; // m_id
uint32 spellitemenchantement; // m_enchant_id
// m_maxcount_inv
// m_maxcount_item
uint32 color; // m_type
};
struct GlyphPropertiesEntry
{
uint32 Id; // m_id
uint32 SpellId; // m_spellID
uint32 TypeFlags; // m_glyphSlotFlags
uint32 Unk1; // m_spellIconID
};
struct GlyphSlotEntry
{
uint32 Id; // m_id
uint32 TypeFlags; // m_type
uint32 Order; // m_tooltip
};
// All Gt* DBC store data for 100 levels, some by 100 per class/race
#define GT_MAX_LEVEL 100
// gtOCTClassCombatRatingScalar.dbc stores data for 32 ratings, look at MAX_COMBAT_RATING for real used amount
#define GT_MAX_RATING 32
struct GtBarberShopCostBaseEntry
{
float cost;
};
struct GtCombatRatingsEntry
{
float ratio;
};
struct GtChanceToMeleeCritBaseEntry
{
float base;
};
struct GtChanceToMeleeCritEntry
{
float ratio;
};
struct GtChanceToSpellCritBaseEntry
{
float base;
};
struct GtChanceToSpellCritEntry
{
float ratio;
};
struct GtOCTClassCombatRatingScalarEntry
{
float ratio;
};
struct GtOCTRegenHPEntry
{
float ratio;
};
struct GtNPCManaCostScalerEntry
{
float ratio;
};
// struct GtOCTRegenMPEntry
//{
// float ratio;
//};
struct GtRegenHPPerSptEntry
{
float ratio;
};
struct GtRegenMPPerSptEntry
{
float ratio;
};
/*struct HolidayDescriptionsEntry
{
uint32 ID; // 0 m_ID this is NOT holiday id
// char* name[16] // 1-16 m_name_lang
// 17 string flags
};*/
/* no used
struct HolidayNamesEntry
{
uint32 ID; // 0 m_ID this is NOT holiday id
// char* name[16] // 1-16 m_name_lang
// 17 string flags
};
*/
struct HolidaysEntry
{
uint32 ID; // 0 m_ID
// uint32 duration[10]; // 1-10 m_duration
// uint32 date[26]; // 11-36 m_date (dates in unix time starting at January, 1, 2000)
// uint32 region; // 37 m_region (wow region)
// uint32 looping; // 38 m_looping
// uint32 calendarFlags[10]; // 39-48 m_calendarFlags
// uint32 holidayNameId; // 49 m_holidayNameID (HolidayNames.dbc)
// uint32 holidayDescriptionId; // 50 m_holidayDescriptionID (HolidayDescriptions.dbc)
// char *textureFilename; // 51 m_textureFilename
// uint32 priority; // 52 m_priority
// uint32 calendarFilterType; // 53 m_calendarFilterType (-1,0,1 or 2)
// uint32 flags; // 54 m_flags
};
struct ItemEntry
{
uint32 ID; // 0 m_ID
uint32 Class; // 1 m_classID
uint32 SubClass; // 2 m_subclassID (some items have strange subclasses)
int32 Unk0; // 3 m_sound_override_subclassid
int32 Material; // 4 m_material
uint32 DisplayId; // 5 m_displayInfoID
uint32 InventoryType; // 6 m_inventoryType
uint32 Sheath; // 7 m_sheatheType
};
struct ItemBagFamilyEntry
{
uint32 ID; // 0 m_ID
// char* name[16] // 1-16 m_name_lang
// // 17 name flags
};
struct ItemClassEntry
{
uint32 ID; // 0 m_ID
// uint32 unk1; // 1
// uint32 unk2; // 2 only weapon have 1 in field, other 0
char* name[16]; // 3-19 m_name_lang
// // 20 name flags
};
struct ItemDisplayInfoEntry
{
uint32 ID; // 0 m_ID
// 1 m_modelName[2]
// 2 m_modelTexture[2]
// 3 m_inventoryIcon
// 4 m_geosetGroup[3]
// 5 m_flags
// 6 m_spellVisualID
// 7 m_groupSoundIndex
// 8 m_helmetGeosetVis[2]
// 9 m_texture[2]
// 10 m_itemVisual[8]
// 11 m_particleColorID
};
// struct ItemCondExtCostsEntry
//{
// uint32 ID;
// uint32 condExtendedCost; // ItemPrototype::CondExtendedCost
// uint32 itemextendedcostentry; // ItemPrototype::ExtendedCost
// uint32 arenaseason; // arena season number(1-4)
//};
#define MAX_EXTENDED_COST_ITEMS 5
struct ItemExtendedCostEntry
{
uint32 ID; // 0 m_ID
uint32 reqhonorpoints; // 1 m_honorPoints
uint32 reqarenapoints; // 2 m_arenaPoints
uint32 reqarenaslot; // 4 m_arenaBracket
uint32 reqitem[MAX_EXTENDED_COST_ITEMS]; // 5-8 m_itemID
uint32 reqitemcount[MAX_EXTENDED_COST_ITEMS]; // 9-13 m_itemCount
uint32 reqpersonalarenarating; // 14 m_requiredArenaRating
// 15 m_itemPurchaseGroup
};
struct ItemLimitCategoryEntry
{
uint32 ID; // 0 Id m_ID
// char* name[16] // 1-16 m_name_lang
// 17 string flags
uint32 maxCount; // 18 m_quantity max allowed equipped as item or in gem slot
uint32 mode; // 19 m_flags 0 = have, 1 = equip (enum ItemLimitCategoryMode)
};
struct ItemRandomPropertiesEntry
{
uint32 ID; // 0 m_ID
// char* internalName // 1 m_Name
uint32 enchant_id[5]; // 2-6 m_Enchantment
char* nameSuffix[16]; // 7-22 m_name_lang
// 23 string flags
};
struct ItemRandomSuffixEntry
{
uint32 ID; // 0 m_ID
char* nameSuffix[16]; // 1-16 m_name_lang
// 17 string flags
// 18 m_internalName
uint32 enchant_id[5]; // 19-21 m_enchantment
uint32 prefix[5]; // 22-24 m_allocationPct
};
struct ItemSetEntry
{
// uint32 id // 0 m_ID
char* name[16]; // 1-16 m_name_lang
// 17 string flags
// uint32 itemId[17]; // 18-34 m_itemID
uint32 spells[8]; // 35-42 m_setSpellID
uint32 items_to_triggerspell[8]; // 43-50 m_setThreshold
uint32 required_skill_id; // 51 m_requiredSkill
uint32 required_skill_value; // 52 m_requiredSkillRank
};
/*struct LfgDungeonsEntry
{
m_ID
m_name_lang
m_minLevel
m_maxLevel
m_target_level
m_target_level_min
m_target_level_max
m_mapID
m_difficulty
m_flags
m_typeID
m_faction
m_textureFilename
m_expansionLevel
m_order_index
m_group_id
m_description_lang
};*/
/*struct LfgDungeonGroupEntry
{
m_ID
m_name_lang
m_order_index
m_parent_group_id
m_typeid
};*/
/*struct LfgDungeonExpansionEntry
{
m_ID
m_lfg_id
m_expansion_level
m_random_id
m_hard_level_min
m_hard_level_max
m_target_level_min
m_target_level_max
};*/
struct LiquidTypeEntry
{
uint32 Id; // 0
//char* Name; // 1
//uint32 Flags; // 2 Water: 1|2|4|8, Magma: 8|16|32|64, Slime: 2|64|256, WMO Ocean: 1|2|4|8|512
uint32 Type; // 3 0: Water, 1: Ocean, 2: Magma, 3: Slime
//uint32 SoundId; // 4 Reference to SoundEntries.dbc
uint32 SpellId; // 5 Reference to Spell.dbc
//float MaxDarkenDepth; // 6 Only oceans got values here!
//float FogDarkenIntensity; // 7 Only oceans got values here!
//float AmbDarkenIntensity; // 8 Only oceans got values here!
//float DirDarkenIntensity; // 9 Only oceans got values here!
//uint32 LightID; // 10 Only Slime (6) and Magma (7)
//float ParticleScale; // 11 0: Slime, 1: Water/Ocean, 4: Magma
//uint32 ParticleMovement; // 12
//uint32 ParticleTexSlots; // 13
//uint32 LiquidMaterialID; // 14
//char* Texture[6]; // 15-20
//uint32 Color[2]; // 21-22
//float Unk1[18]; // 23-40 Most likely these are attributes for the shaders. Water: (23, TextureTilesPerBlock),(24, Rotation) Magma: (23, AnimationX),(24, AnimationY)
//uint32 Unk2[4]; // 41-44
};
#define MAX_LOCK_CASE 8
struct LockEntry
{
uint32 ID; // 0 m_ID
uint32 Type[MAX_LOCK_CASE]; // 1-8 m_Type
uint32 Index[MAX_LOCK_CASE]; // 9-16 m_Index
uint32 Skill[MAX_LOCK_CASE]; // 17-24 m_Skill
// uint32 Action[MAX_LOCK_CASE]; // 25-32 m_Action
};
struct MailTemplateEntry
{
uint32 ID; // 0 m_ID
// char* subject[16]; // 1-16 m_subject_lang
// 17 string flags
char* content[16]; // 18-33 m_body_lang
};
struct MapEntry
{
uint32 MapID; // 0 m_ID
// char* internalname; // 1 m_Directory
uint32 map_type; // 2 m_InstanceType
// uint32 mapFlags; // 3 m_Flags (0x100 - CAN_CHANGE_PLAYER_DIFFICULTY)
// uint32 isPvP; // 4 m_PVP 0 or 1 for battlegrounds (not arenas)
char* name[16]; // 5-20 m_MapName_lang
// 21 string flags
uint32 linked_zone; // 22 m_areaTableID
// char* hordeIntro[16]; // 23-38 m_MapDescription0_lang
// 39 string flags
// char* allianceIntro[16]; // 40-55 m_MapDescription1_lang
// 56 string flags
uint32 multimap_id; // 57 m_LoadingScreenID (LoadingScreens.dbc)
// float BattlefieldMapIconScale; // 58 m_minimapIconScale
int32 ghost_entrance_map; // 59 m_corpseMapID map_id of entrance map in ghost mode (continent always and in most cases = normal entrance)
float ghost_entrance_x; // 60 m_corpseX entrance x coordinate in ghost mode (in most cases = normal entrance)
float ghost_entrance_y; // 61 m_corpseY entrance y coordinate in ghost mode (in most cases = normal entrance)
// uint32 timeOfDayOverride; // 62 m_timeOfDayOverride
uint32 addon; // 63 m_expansionID
// 64 m_raidOffset
// uint32 maxPlayers; // 65 m_maxPlayers
// Helpers
uint32 Expansion() const { return addon; }
bool IsDungeon() const { return map_type == MAP_INSTANCE || map_type == MAP_RAID; }
bool IsNonRaidDungeon() const { return map_type == MAP_INSTANCE; }
bool Instanceable() const { return map_type == MAP_INSTANCE || map_type == MAP_RAID || map_type == MAP_BATTLEGROUND || map_type == MAP_ARENA; }
bool IsRaid() const { return map_type == MAP_RAID; }
bool IsBattleGround() const { return map_type == MAP_BATTLEGROUND; }
bool IsBattleArena() const { return map_type == MAP_ARENA; }
bool IsBattleGroundOrArena() const { return map_type == MAP_BATTLEGROUND || map_type == MAP_ARENA; }
bool IsContinent() const
{
return MapID == 0 || MapID == 1 || MapID == 530 || MapID == 571;
}
};
struct MapDifficultyEntry
{
// uint32 Id; // 0 m_ID
uint32 MapId; // 1 m_mapID
uint32 Difficulty; // 2 m_difficulty (for arenas: arena slot)
// char* areaTriggerText[16]; // 3-18 m_message_lang (text showed when transfer to map failed)
// uint32 textFlags; // 19
uint32 resetTime; // 20 m_raidDuration in secs, 0 if no fixed reset time
uint32 maxPlayers; // 21 m_maxPlayers some heroic versions have 0 when expected same amount as in normal version
// char* difficultyString; // 22 m_difficultystring
};
struct MovieEntry
{
uint32 Id; // 0 m_ID
// char* filename; // 1 m_filename
// uint32 unk2; // 2 m_volume
};
#define MAX_OVERRIDE_SPELLS 10
struct OverrideSpellDataEntry
{
uint32 Id; // 0 m_ID
uint32 Spells[MAX_OVERRIDE_SPELLS]; // 1-10 m_spells
// uint32 unk2; // 11 m_flags
};
struct PowerDisplayEntry
{
uint32 id; // 0 m_ID
uint32 power; // 1 m_power
// uint32 unk1 // 2
// float unk2 // 3
// float unk3 // 4
// float unk4 // 5
};
struct PvPDifficultyEntry
{
// uint32 id; // 0 m_ID
uint32 mapId; // 1 m_mapID
uint32 bracketId; // 2 m_rangeIndex
uint32 minLevel; // 3 m_minLevel
uint32 maxLevel; // 4 m_maxLevel
uint32 difficulty; // 5 m_difficulty
// helpers
BattleGroundBracketId GetBracketId() const { return BattleGroundBracketId(bracketId); }
};
struct QuestFactionRewardEntry
{
uint32 id; // 0 m_ID
int32 rewardValue[10]; // 1-10 m_Difficulty
};
struct QuestSortEntry
{
uint32 id; // 0 m_ID
// char* name[16]; // 1-16 m_SortName_lang
// 17 string flags
};
struct QuestXPLevel
{
uint32 questLevel; // 0 m_ID
uint32 xpIndex[10]; // 1-10 m_difficulty[10]
};
struct RandomPropertiesPointsEntry
{
// uint32 Id; // 0 m_ID
uint32 itemLevel; // 1 m_ItemLevel
uint32 EpicPropertiesPoints[5]; // 2-6 m_Epic
uint32 RarePropertiesPoints[5]; // 7-11 m_Superior
uint32 UncommonPropertiesPoints[5]; // 12-16 m_Good
};
struct ScalingStatDistributionEntry
{
uint32 Id; // 0 m_ID
int32 StatMod[10]; // 1-10 m_statID
uint32 Modifier[10]; // 11-20 m_bonus
uint32 MaxLevel; // 21 m_maxlevel
};
struct ScalingStatValuesEntry
{
uint32 Id; // 0 m_ID
uint32 Level; // 1 m_charlevel
uint32 ssdMultiplier[4]; // 2-5 Multiplier for ScalingStatDistribution
uint32 armorMod[4]; // 6-9 Armor for level
uint32 dpsMod[6]; // 10-15 DPS mod for level
uint32 spellBonus; // 16 spell power for level
uint32 ssdMultiplier2; // 17 there's data from 3.1 dbc ssdMultiplier[3]
uint32 ssdMultiplier3; // 18 3.3
// uint32 unk2; // 19 unk, probably also Armor for level (flag 0x80000?)
uint32 armorMod2[4]; // 20-23 Armor for level
/*struct ScalingStatValuesEntry
{
m_ID
m_charlevel
m_shoulderBudget
m_trinketBudget
m_weaponBudget1H
m_rangedBudget
m_clothShoulderArmor
m_leatherShoulderArmor
m_mailShoulderArmor
m_plateShoulderArmor
m_weaponDPS1H
m_weaponDPS2H
m_spellcasterDPS1H
m_spellcasterDPS2H
m_rangedDPS
m_wandDPS
m_spellPower
m_primaryBudget
m_tertiaryBudget
m_clothCloakArmor
m_clothChestArmor
m_leatherChestArmor
m_mailChestArmor
m_plateChestArmor
};*/
uint32 getssdMultiplier(uint32 mask) const
{
if (mask & 0x4001F)
{
if (mask & 0x00000001) return ssdMultiplier[0];
if (mask & 0x00000002) return ssdMultiplier[1];
if (mask & 0x00000004) return ssdMultiplier[2];
if (mask & 0x00000008) return ssdMultiplier2;
if (mask & 0x00000010) return ssdMultiplier[3];
if (mask & 0x00040000) return ssdMultiplier3;
}
return 0;
}
uint32 getArmorMod(uint32 mask) const
{
if (mask & 0x00F001E0)
{
if (mask & 0x00000020) return armorMod[0];
if (mask & 0x00000040) return armorMod[1];
if (mask & 0x00000080) return armorMod[2];
if (mask & 0x00000100) return armorMod[3];
if (mask & 0x00100000) return armorMod2[0]; // cloth
if (mask & 0x00200000) return armorMod2[1]; // leather
if (mask & 0x00400000) return armorMod2[2]; // mail
if (mask & 0x00800000) return armorMod2[3]; // plate
}
return 0;
}
uint32 getDPSMod(uint32 mask) const
{
if (mask & 0x7E00)
{
if (mask & 0x00000200) return dpsMod[0];
if (mask & 0x00000400) return dpsMod[1];
if (mask & 0x00000800) return dpsMod[2];
if (mask & 0x00001000) return dpsMod[3];
if (mask & 0x00002000) return dpsMod[4];
if (mask & 0x00004000) return dpsMod[5]; // not used?
}
return 0;
}
uint32 getSpellBonus(uint32 mask) const
{
if (mask & 0x00008000)
return spellBonus;
return 0;
}
uint32 getFeralBonus(uint32 mask) const // removed in 3.2.x?
{
if (mask & 0x00010000) // not used?
return 0;
return 0;
}
};
/*struct SkillLineCategoryEntry
{
uint32 id; // 0 m_ID
char* name[16]; // 1-17 m_name_lang
// 18 string flags
uint32 displayOrder; // 19 m_sortIndex
};*/
struct SkillRaceClassInfoEntry
{
// uint32 id; // 0 m_ID
uint32 skillId; // 1 m_skillID
uint32 raceMask; // 2 m_raceMask
uint32 classMask; // 3 m_classMask
uint32 flags; // 4 m_flags
uint32 reqLevel; // 5 m_minLevel
// uint32 skillTierId; // 6 m_skillTierID
// uint32 skillCostID; // 7 m_skillCostIndex
};
/*struct SkillTiersEntry{
uint32 id; // 0 m_ID
uint32 skillValue[16]; // 1-17 m_cost
uint32 maxSkillValue[16]; // 18-3 m_valueMax
};*/
struct SkillLineEntry
{
uint32 id; // 0 m_ID
int32 categoryId; // 1 m_categoryID
// uint32 skillCostID; // 2 m_skillCostsID
char* name[16]; // 3-18 m_displayName_lang
// 19 string flags
// char* description[16]; // 20-35 m_description_lang
// 36 string flags
uint32 spellIcon; // 37 m_spellIconID
// char* alternateVerb[16]; // 38-53 m_alternateVerb_lang
// 54 string flags
uint32 canLink; // 55 m_canLink (prof. with recipes)
};
struct SkillLineAbilityEntry
{
uint32 id; // 0 m_ID
uint32 skillId; // 1 m_skillLine
uint32 spellId; // 2 m_spell
uint32 racemask; // 3 m_raceMask
uint32 classmask; // 4 m_classMask
// uint32 racemaskNot; // 5 m_excludeRace
// uint32 classmaskNot; // 6 m_excludeClass
uint32 req_skill_value; // 7 m_minSkillLineRank
uint32 forward_spellid; // 8 m_supercededBySpell
uint32 learnOnGetSkill; // 9 m_acquireMethod
uint32 max_value; // 10 m_trivialSkillLineRankHigh
uint32 min_value; // 11 m_trivialSkillLineRankLow
// uint32 characterPoints[2]; // 12-13 m_characterPoints[2]
};
struct SoundEntriesEntry
{
uint32 Id; // 0 m_ID
// uint32 Type; // 1 m_soundType
// char* InternalName; // 2 m_name
// char* FileName[10]; // 3-12 m_File[10]
// uint32 Unk13[10]; // 13-22 m_Freq[10]
// char* Path; // 23 m_DirectoryBase
// 24 m_volumeFloat
// 25 m_flags
// 26 m_minDistance
// 27 m_distanceCutoff
// 28 m_EAXDef
// 29 m_soundEntriesAdvancedID
};
struct ClassFamilyMask
{
uint64 Flags;
uint32 Flags2;
ClassFamilyMask() : Flags(0), Flags2(0) {}
explicit ClassFamilyMask(uint64 familyFlags, uint32 familyFlags2 = 0) : Flags(familyFlags), Flags2(familyFlags2) {}
bool Empty() const { return Flags == 0 && Flags2 == 0; }
bool operator!() const { return Empty(); }
operator void const* () const { return Empty() ? nullptr : this; }// for allow normal use in if(mask)
bool IsFitToFamilyMask(uint64 familyFlags, uint32 familyFlags2 = 0) const
{
return (Flags & familyFlags) || (Flags2 & familyFlags2);
}
bool IsFitToFamilyMask(ClassFamilyMask const& mask) const
{
return (Flags & mask.Flags) || (Flags2 & mask.Flags2);
}
uint64 operator& (uint64 mask) const // possible will removed at finish convertion code use IsFitToFamilyMask
{
return Flags & mask;
}
ClassFamilyMask& operator|= (ClassFamilyMask const& mask)
{
Flags |= mask.Flags;
Flags2 |= mask.Flags2;
return *this;
}
};
#define MAX_SPELL_REAGENTS 8
#define MAX_SPELL_TOTEMS 2
#define MAX_SPELL_TOTEM_CATEGORIES 2
struct SpellEntry
{
uint32 Id; // 0 m_ID
uint32 Category; // 1 m_category
uint32 Dispel; // 2 m_dispelType
uint32 Mechanic; // 3 m_mechanic
uint32 Attributes; // 4 m_attributes
uint32 AttributesEx; // 5 m_attributesEx
uint32 AttributesEx2; // 6 m_attributesExB
uint32 AttributesEx3; // 7 m_attributesExC
uint32 AttributesEx4; // 8 m_attributesExD
uint32 AttributesEx5; // 9 m_attributesExE
uint32 AttributesEx6; // 10 m_attributesExF
uint32 AttributesEx7; // 11 m_attributesExG (0x20 - totems, 0x4 - paladin auras, etc...)
uint32 Stances; // 12 m_shapeshiftMask
// uint32 unk_320_1; // 13 3.2.0
uint32 StancesNot; // 14 m_shapeshiftExclude
// uint32 unk_320_2; // 15 3.2.0
uint32 Targets; // 16 m_targets
uint32 TargetCreatureType; // 17 m_targetCreatureType
uint32 RequiresSpellFocus; // 18 m_requiresSpellFocus
uint32 FacingCasterFlags; // 19 m_facingCasterFlags
uint32 CasterAuraState; // 20 m_casterAuraState
uint32 TargetAuraState; // 21 m_targetAuraState
uint32 CasterAuraStateNot; // 22 m_excludeCasterAuraState
uint32 TargetAuraStateNot; // 23 m_excludeTargetAuraState
uint32 casterAuraSpell; // 24 m_casterAuraSpell
uint32 targetAuraSpell; // 25 m_targetAuraSpell
uint32 excludeCasterAuraSpell; // 26 m_excludeCasterAuraSpell
uint32 excludeTargetAuraSpell; // 27 m_excludeTargetAuraSpell
uint32 CastingTimeIndex; // 28 m_castingTimeIndex
uint32 RecoveryTime; // 29 m_recoveryTime
uint32 CategoryRecoveryTime; // 30 m_categoryRecoveryTime
uint32 InterruptFlags; // 31 m_interruptFlags
uint32 AuraInterruptFlags; // 32 m_auraInterruptFlags
uint32 ChannelInterruptFlags; // 33 m_channelInterruptFlags
uint32 procFlags; // 34 m_procTypeMask
uint32 procChance; // 35 m_procChance
uint32 procCharges; // 36 m_procCharges
uint32 maxLevel; // 37 m_maxLevel
uint32 baseLevel; // 38 m_baseLevel
uint32 spellLevel; // 39 m_spellLevel
uint32 DurationIndex; // 40 m_durationIndex
uint32 powerType; // 41 m_powerType
uint32 manaCost; // 42 m_manaCost
uint32 manaCostPerlevel; // 43 m_manaCostPerLevel
uint32 manaPerSecond; // 44 m_manaPerSecond
uint32 manaPerSecondPerLevel; // 45 m_manaPerSecondPerLevel
uint32 rangeIndex; // 46 m_rangeIndex
float speed; // 47 m_speed
// uint32 modalNextSpell; // 48 m_modalNextSpell not used
uint32 StackAmount; // 49 m_cumulativeAura
uint32 Totem[MAX_SPELL_TOTEMS]; // 50-51 m_totem
int32 Reagent[MAX_SPELL_REAGENTS]; // 52-59 m_reagent
uint32 ReagentCount[MAX_SPELL_REAGENTS]; // 60-67 m_reagentCount
int32 EquippedItemClass; // 68 m_equippedItemClass (value)
int32 EquippedItemSubClassMask; // 69 m_equippedItemSubclass (mask)
int32 EquippedItemInventoryTypeMask; // 70 m_equippedItemInvTypes (mask)
uint32 Effect[MAX_EFFECT_INDEX]; // 71-73 m_effect
int32 EffectDieSides[MAX_EFFECT_INDEX]; // 74-76 m_effectDieSides
float EffectRealPointsPerLevel[MAX_EFFECT_INDEX]; // 77-79 m_effectRealPointsPerLevel
int32 EffectBasePoints[MAX_EFFECT_INDEX]; // 80-82 m_effectBasePoints (don't must be used in spell/auras explicitly, must be used cached Spell::m_currentBasePoints)
uint32 EffectMechanic[MAX_EFFECT_INDEX]; // 83-85 m_effectMechanic
uint32 EffectImplicitTargetA[MAX_EFFECT_INDEX]; // 86-88 m_implicitTargetA
uint32 EffectImplicitTargetB[MAX_EFFECT_INDEX]; // 89-91 m_implicitTargetB
uint32 EffectRadiusIndex[MAX_EFFECT_INDEX]; // 92-94 m_effectRadiusIndex - spellradius.dbc
uint32 EffectApplyAuraName[MAX_EFFECT_INDEX]; // 95-97 m_effectAura
uint32 EffectAmplitude[MAX_EFFECT_INDEX]; // 98-100 m_effectAuraPeriod
float EffectMultipleValue[MAX_EFFECT_INDEX]; // 101-103 m_effectAmplitude
uint32 EffectChainTarget[MAX_EFFECT_INDEX]; // 104-106 m_effectChainTargets
uint32 EffectItemType[MAX_EFFECT_INDEX]; // 107-109 m_effectItemType
int32 EffectMiscValue[MAX_EFFECT_INDEX]; // 110-112 m_effectMiscValue
int32 EffectMiscValueB[MAX_EFFECT_INDEX]; // 113-115 m_effectMiscValueB
uint32 EffectTriggerSpell[MAX_EFFECT_INDEX]; // 116-118 m_effectTriggerSpell
float EffectPointsPerComboPoint[MAX_EFFECT_INDEX]; // 119-121 m_effectPointsPerCombo
ClassFamilyMask EffectSpellClassMask[MAX_EFFECT_INDEX]; // 122-130 m_effectSpellClassMaskA/B/C, effect 0/1/2
uint32 SpellVisual[2]; // 131-132 m_spellVisualID
uint32 SpellIconID; // 133 m_spellIconID
uint32 activeIconID; // 134 m_activeIconID
uint32 spellPriority; // 135 m_spellPriority not used
char* SpellName[16]; // 136-151 m_name_lang
// uint32 SpellNameFlag; // 152 m_name_flag not used
char* Rank[16]; // 153-168 m_nameSubtext_lang
// uint32 RankFlags; // 169 m_nameSubtext_flag not used
// char* Description[16]; // 170-185 m_description_lang not used
// uint32 DescriptionFlags; // 186 m_description_flag not used
// char* ToolTip[16]; // 187-202 m_auraDescription_lang not used
// uint32 ToolTipFlags; // 203 m_auraDescription_flag not used
uint32 ManaCostPercentage; // 204 m_manaCostPct
uint32 StartRecoveryCategory; // 205 m_startRecoveryCategory
uint32 StartRecoveryTime; // 206 m_startRecoveryTime
uint32 MaxTargetLevel; // 207 m_maxTargetLevel
uint32 SpellFamilyName; // 208 m_spellClassSet
ClassFamilyMask SpellFamilyFlags; // 209-211 m_spellClassMask NOTE: size is 12 bytes!!!
uint32 MaxAffectedTargets; // 212 m_maxTargets
uint32 DmgClass; // 213 m_defenseType
uint32 PreventionType; // 214 m_preventionType
// uint32 StanceBarOrder; // 215 m_stanceBarOrder not used
float DmgMultiplier[MAX_EFFECT_INDEX]; // 216-218 m_effectChainAmplitude
// uint32 MinFactionId; // 219 m_minFactionID not used
// uint32 MinReputation; // 220 m_minReputation not used
// uint32 RequiredAuraVision; // 221 m_requiredAuraVision not used
uint32 TotemCategory[MAX_SPELL_TOTEM_CATEGORIES];// 222-223 m_requiredTotemCategoryID
int32 AreaGroupId; // 224 m_requiredAreasId
uint32 SchoolMask; // 225 m_schoolMask
uint32 runeCostID; // 226 m_runeCostID
// uint32 spellMissileID; // 227 m_spellMissileID
// uint32 PowerDisplayId; // 228 m_powerDisplayID (PowerDisplay.dbc)
// float effectBonusCoefficient[3]; // 229-231 m_effectBonusCoefficient
// uint32 spellDescriptionVariableID; // 232 m_descriptionVariablesID
uint32 SpellDifficultyId; // 233 m_difficulty (SpellDifficulty.dbc)
uint32 IsServerSide;
// helpers
int32 CalculateSimpleValue(SpellEffectIndex eff) const { return EffectBasePoints[eff] + int32(1); }
ClassFamilyMask const& GetEffectSpellClassMask(SpellEffectIndex effect) const
{
return EffectSpellClassMask[effect];
}
bool IsFitToFamilyMask(uint64 familyFlags, uint32 familyFlags2 = 0) const
{
return SpellFamilyFlags.IsFitToFamilyMask(familyFlags, familyFlags2);
}
bool IsFitToFamily(SpellFamily family, uint64 familyFlags, uint32 familyFlags2 = 0) const
{
return SpellFamily(SpellFamilyName) == family && IsFitToFamilyMask(familyFlags, familyFlags2);
}
bool IsFitToFamilyMask(ClassFamilyMask const& mask) const
{
return SpellFamilyFlags.IsFitToFamilyMask(mask);
}
bool IsFitToFamily(SpellFamily family, ClassFamilyMask const& mask) const
{
return SpellFamily(SpellFamilyName) == family && IsFitToFamilyMask(mask);
}
inline bool HasAttribute(SpellAttributes attribute) const { return !!(Attributes & attribute); }
inline bool HasAttribute(SpellAttributesEx attribute) const { return !!(AttributesEx & attribute); }
inline bool HasAttribute(SpellAttributesEx2 attribute) const { return !!(AttributesEx2 & attribute); }
inline bool HasAttribute(SpellAttributesEx3 attribute) const { return !!(AttributesEx3 & attribute); }
inline bool HasAttribute(SpellAttributesEx4 attribute) const { return !!(AttributesEx4 & attribute); }
inline bool HasAttribute(SpellAttributesEx5 attribute) const { return !!(AttributesEx5 & attribute); }
inline bool HasAttribute(SpellAttributesEx6 attribute) const { return !!(AttributesEx6 & attribute); }
inline bool HasAttribute(SpellAttributesEx7 attribute) const { return !!(AttributesEx7 & attribute); }
private:
// prevent creating custom entries (copy data from original in fact)
SpellEntry(SpellEntry const&); // DON'T must have implementation
// catch wrong uses
template<typename T>
bool IsFitToFamilyMask(SpellFamily family, T t) const;
};
// A few fields which are required for automated convertion
// NOTE that these fields are count by _skipping_ the fields that are unused!
#define LOADED_SPELLDBC_FIELD_POS_EQUIPPED_ITEM_CLASS 65 // Must be converted to -1
#define LOADED_SPELLDBC_FIELD_POS_SPELLNAME_0 132 // Links to "MaNGOS server-side spell"
struct SpellCastTimesEntry
{
uint32 ID; // 0 m_ID
int32 CastTime; // 1 m_base
// float CastTimePerLevel; // 2 m_perLevel
// int32 MinCastTime; // 3 m_minimum
};
struct SpellFocusObjectEntry
{
uint32 ID; // 0 m_ID
// char* Name[16]; // 1-15 m_name_lang
// 16 string flags
};
struct SpellRadiusEntry
{
uint32 ID; // m_ID
float Radius; // m_radius
// m_radiusPerLevel
// float RadiusMax; // m_radiusMax
};
struct SpellRangeEntry
{
uint32 ID; // 0 m_ID
float minRange; // 1 m_rangeMin[2]
float minRangeFriendly; // 2
float maxRange; // 3 m_rangeMax[2]
float maxRangeFriendly; // 4
// uint32 Flags; // 5 m_flags
// char* Name[16]; // 6-21 m_displayName_lang
// uint32 NameFlags; // 22 string flags
// char* ShortName[16]; // 23-38 m_displayNameShort_lang
// uint32 NameFlags; // 39 string flags
};
struct SpellRuneCostEntry
{
uint32 ID; // 0 m_ID
uint32 RuneCost[3]; // 1-3 m_blood m_unholy m_frost (0=blood, 1=frost, 2=unholy)
uint32 runePowerGain; // 4 m_runicPower
bool NoRuneCost() const { return RuneCost[0] == 0 && RuneCost[1] == 0 && RuneCost[2] == 0; }
bool NoRunicPowerGain() const { return runePowerGain == 0; }
};
struct SpellShapeshiftFormEntry
{
uint32 ID; // 0 m_ID
// uint32 buttonPosition; // 1 m_bonusActionBar
// char* Name[16]; // 2-17 m_name_lang
// uint32 NameFlags; // 18 string flags
uint32 flags1; // 19 m_flags
int32 creatureType; // 20 m_creatureType <=0 humanoid, other normal creature types
// uint32 unk1; // 21 m_attackIconID
uint32 attackSpeed; // 22 m_combatRoundTime
uint32 modelID_A; // 23 m_creatureDisplayID[4]
uint32 modelID_H; // 24
// uint32 unk3; // 25
// uint32 unk4; // 26
uint32 spellId[8]; // 27-34 m_presetSpellID[8]
};
struct SpellDifficultyEntry
{
uint32 ID; // 0 m_ID
uint32 spellId[MAX_DIFFICULTY]; // 1-4 m_difficultySpellID[4]
};
struct SpellDurationEntry
{
uint32 ID; // m_ID
int32 Duration[3]; // m_duration, m_durationPerLevel, m_maxDuration
};
struct SpellItemEnchantmentEntry
{
uint32 ID; // 0 m_ID
// uint32 charges; // 1 m_charges
uint32 type[3]; // 2-4 m_effect[3]
uint32 amount[3]; // 5-7 m_effectPointsMin[3]
// uint32 amount2[3] // 8-10 m_effectPointsMax[3]
uint32 spellid[3]; // 11-13 m_effectArg[3]
char* description[16]; // 14-29 m_name_lang[16]
// uint32 descriptionFlags; // 30 string flags
uint32 aura_id; // 31 m_itemVisual
uint32 slot; // 32 m_flags
uint32 GemID; // 33 m_src_itemID
uint32 EnchantmentCondition; // 34 m_condition_id
// uint32 requiredSkill; // 35 m_requiredSkillID
// uint32 requiredSkillValue; // 36 m_requiredSkillRank
// 37 m_minLevel
};
struct SpellItemEnchantmentConditionEntry
{
uint32 ID; // 0 m_ID
uint8 Color[5]; // 1-5 m_lt_operandType[5]
// uint32 LT_Operand[5]; // 6-10 m_lt_operand[5]
uint8 Comparator[5]; // 11-15 m_operator[5]
uint8 CompareColor[5]; // 15-20 m_rt_operandType[5]
uint32 Value[5]; // 21-25 m_rt_operand[5]
// uint8 Logic[5] // 25-30 m_logic[5]
};
struct StableSlotPricesEntry
{
uint32 Slot; // m_ID
uint32 Price; // m_cost
};
struct SummonPropertiesEntry
{
uint32 Id; // 0 m_id
uint32 Group; // 1 m_control (enum SummonPropGroup)
uint32 FactionId; // 2 m_faction
uint32 Title; // 3 m_title (enum UnitNameSummonTitle)
uint32 Slot; // 4 m_slot if title = UNITNAME_SUMMON_TITLE_TOTEM, its actual slot (0-6).
// if title = UNITNAME_SUMMON_TITLE_COMPANION, slot=6 -> defensive guardian, in other cases criter/minipet
// Slot may have other uses, selection of pet type in some cases?
uint32 Flags; // 5 m_flags (enum SummonPropFlags)
};
#define MAX_TALENT_RANK 5
#define MAX_PET_TALENT_RANK 3 // use in calculations, expected <= MAX_TALENT_RANK
struct TalentEntry
{
uint32 TalentID; // 0 m_ID
uint32 TalentTab; // 1 m_tabID (TalentTab.dbc)
uint32 Row; // 2 m_tierID
uint32 Col; // 3 m_columnIndex
uint32 RankID[MAX_TALENT_RANK]; // 4-8 m_spellRank
// 9-12 part of prev field
uint32 DependsOn; // 13 m_prereqTalent (Talent.dbc)
// 14-15 part of prev field
uint32 DependsOnRank; // 16 m_prereqRank
// 17-18 part of prev field
// uint32 needAddInSpellBook; // 19 m_flags also need disable higest ranks on reset talent tree
// uint32 unk2; // 20 m_requiredSpellID
// uint64 allowForPet; // 21 m_categoryMask its a 64 bit mask for pet 1<<m_categoryEnumID in CreatureFamily.dbc
};
struct TalentTabEntry
{
uint32 TalentTabID; // 0 m_ID
// char* name[16]; // 1-16 m_name_lang
// uint32 nameFlags; // 17 string flags
// unit32 spellicon; // 18 m_spellIconID
// 19 m_raceMask
uint32 ClassMask; // 20 m_classMask
uint32 petTalentMask; // 21 m_petTalentMask
uint32 tabpage; // 22 m_orderIndex
// char* internalname; // 23 m_backgroundFile
};
struct TaxiNodesEntry
{
uint32 ID; // 0 m_ID
uint32 map_id; // 1 m_ContinentID
float x; // 2 m_x
float y; // 3 m_y
float z; // 4 m_z
char* name[16]; // 5-21 m_Name_lang
// 22 string flags
uint32 MountCreatureID[2]; // 23-24 m_MountCreatureID[2]
};
struct TaxiPathEntry
{
uint32 ID; // 0 m_ID
uint32 from; // 1 m_FromTaxiNode
uint32 to; // 2 m_ToTaxiNode
uint32 price; // 3 m_Cost
};
struct TaxiPathNodeEntry
{
// 0 m_ID
uint32 path; // 1 m_PathID
uint32 index; // 2 m_NodeIndex
uint32 mapid; // 3 m_ContinentID
float x; // 4 m_LocX
float y; // 5 m_LocY
float z; // 6 m_LocZ
uint32 actionFlag; // 7 m_flags
uint32 delay; // 8 m_delay
uint32 arrivalEventID; // 9 m_arrivalEventID
uint32 departureEventID; // 10 m_departureEventID
};
struct TeamContributionPoints
{
// uint32 Entry; // 0 m_ID
float Value; // 1 m_data
};
struct TotemCategoryEntry
{
uint32 ID; // 0 m_ID
// char* name[16]; // 1-16 m_name_lang
// 17 string flags
uint32 categoryType; // 18 m_totemCategoryType (one for specialization)
uint32 categoryMask; // 19 m_totemCategoryMask (compatibility mask for same type: different for totems, compatible from high to low for rods)
};
#define MAX_VEHICLE_SEAT 8
struct VehicleEntry
{
uint32 m_ID; // 0
uint32 m_flags; // 1
float m_turnSpeed; // 2
float m_pitchSpeed; // 3
float m_pitchMin; // 4
float m_pitchMax; // 5
uint32 m_seatID[MAX_VEHICLE_SEAT]; // 6-13
float m_mouseLookOffsetPitch; // 14
float m_cameraFadeDistScalarMin; // 15
float m_cameraFadeDistScalarMax; // 16
float m_cameraPitchOffset; // 17
float m_facingLimitRight; // 18
float m_facingLimitLeft; // 19
float m_msslTrgtTurnLingering; // 20
float m_msslTrgtPitchLingering; // 21
float m_msslTrgtMouseLingering; // 22
float m_msslTrgtEndOpacity; // 23
float m_msslTrgtArcSpeed; // 24
float m_msslTrgtArcRepeat; // 25
float m_msslTrgtArcWidth; // 26
float m_msslTrgtImpactRadius[2]; // 27-28
char* m_msslTrgtArcTexture; // 29
char* m_msslTrgtImpactTexture; // 30
char* m_msslTrgtImpactModel[2]; // 31-32
float m_cameraYawOffset; // 33
uint32 m_uiLocomotionType; // 34
float m_msslTrgtImpactTexRadius; // 35
uint32 m_uiSeatIndicatorType; // 36 m_vehicleUIIndicatorID
uint32 m_powerDisplayID; // 37
// 38 new in 3.1
// 39 new in 3.1
};
struct VehicleSeatEntry
{
uint32 m_ID; // 0
uint32 m_flags; // 1
int32 m_attachmentID; // 2
float m_attachmentOffsetX; // 3
float m_attachmentOffsetY; // 4
float m_attachmentOffsetZ; // 5
float m_enterPreDelay; // 6
float m_enterSpeed; // 7
float m_enterGravity; // 8
float m_enterMinDuration; // 9
float m_enterMaxDuration; // 10
float m_enterMinArcHeight; // 11
float m_enterMaxArcHeight; // 12
int32 m_enterAnimStart; // 13
int32 m_enterAnimLoop; // 14
int32 m_rideAnimStart; // 15
int32 m_rideAnimLoop; // 16
int32 m_rideUpperAnimStart; // 17
int32 m_rideUpperAnimLoop; // 18
float m_exitPreDelay; // 19
float m_exitSpeed; // 20
float m_exitGravity; // 21
float m_exitMinDuration; // 22
float m_exitMaxDuration; // 23
float m_exitMinArcHeight; // 24
float m_exitMaxArcHeight; // 25
int32 m_exitAnimStart; // 26
int32 m_exitAnimLoop; // 27
int32 m_exitAnimEnd; // 28
float m_passengerYaw; // 29
float m_passengerPitch; // 30
float m_passengerRoll; // 31
int32 m_passengerAttachmentID; // 32
int32 m_vehicleEnterAnim; // 33
int32 m_vehicleExitAnim; // 34
int32 m_vehicleRideAnimLoop; // 35
int32 m_vehicleEnterAnimBone; // 36
int32 m_vehicleExitAnimBone; // 37
int32 m_vehicleRideAnimLoopBone; // 38
float m_vehicleEnterAnimDelay; // 39
float m_vehicleExitAnimDelay; // 40
uint32 m_vehicleAbilityDisplay; // 41
uint32 m_enterUISoundID; // 42
uint32 m_exitUISoundID; // 43
int32 m_uiSkin; // 44
uint32 m_flagsB; // 45
// 46 m_cameraEnteringDelay
// 47 m_cameraEnteringDuration
// 48 m_cameraExitingDelay
// 49 m_cameraExitingDuration
// 50 m_cameraOffsetX
// 51 m_cameraOffsetY
// 52 m_cameraOffsetZ
// 53 m_cameraPosChaseRate
// 54 m_cameraFacingChaseRate
// 55 m_cameraEnteringZoom"
// 56 m_cameraSeatZoomMin
// 57 m_cameraSeatZoomMax
};
struct WMOAreaTableEntry
{
uint32 Id; // 0 m_ID index
int32 rootId; // 1 m_WMOID used in root WMO
int32 adtId; // 2 m_NameSetID used in adt file
int32 groupId; // 3 m_WMOGroupID used in group WMO
// uint32 field4; // 4 m_SoundProviderPref
// uint32 field5; // 5 m_SoundProviderPrefUnderwater
// uint32 field6; // 6 m_AmbienceID
// uint32 field7; // 7 m_ZoneMusic
// uint32 field8; // 8 m_IntroSound
uint32 Flags; // 9 m_flags (used for indoor/outdoor determination)
uint32 areaId; // 10 m_AreaTableID (AreaTable.dbc)
// char *Name[16]; // m_AreaName_lang
// uint32 nameFlags;
};
struct WorldMapAreaEntry
{
// uint32 ID; // 0 m_ID
uint32 map_id; // 1 m_mapID
uint32 area_id; // 2 m_areaID index (continent 0 areas ignored)
// char* internal_name // 3 m_areaName
float y1; // 4 m_locLeft
float y2; // 5 m_locRight
float x1; // 6 m_locTop
float x2; // 7 m_locBottom
int32 virtual_map_id; // 8 m_displayMapID -1 (map_id have correct map) other: virtual map where zone show (map_id - where zone in fact internally)
// int32 dungeonMap_id; // 9 m_defaultDungeonFloor (DungeonMap.dbc)
// uint32 someMapID; // 10 m_parentWorldMapID
};
#define MAX_WORLD_MAP_OVERLAY_AREA_IDX 4
struct WorldMapOverlayEntry
{
uint32 ID; // 0 m_ID
// uint32 worldMapAreaId; // 1 m_mapAreaID (WorldMapArea.dbc)
uint32 areatableID[MAX_WORLD_MAP_OVERLAY_AREA_IDX]; // 2-5 m_areaID
// 6 m_mapPointX
// 7 m_mapPointY
// char* internal_name // 8 m_textureName
// 9 m_textureWidth
// 10 m_textureHeight
// 11 m_offsetX
// 12 m_offsetY
// 13 m_hitRectTop
// 14 m_hitRectLeft
// 15 m_hitRectBottom
// 16 m_hitRectRight
};
struct WorldSafeLocsEntry
{
uint32 ID; // 0 m_ID
uint32 map_id; // 1 m_continent
float x; // 2 m_locX
float y; // 3 m_locY
float z; // 4 m_locZ
// char* name[16] // 5-20 m_AreaName_lang
// 21 string flags
};
// GCC have alternative #pragma pack() syntax and old gcc version not support pack(pop), also any gcc version not support it at some platform
#if defined( __GNUC__ )
#pragma pack()
#else
#pragma pack(pop)
#endif
struct ItemCategorySpellPair
{
uint32 spellId;
uint32 itemId;
ItemCategorySpellPair(uint32 _spellId, uint32 _itemId) : spellId(_spellId), itemId(_itemId) {}
bool operator <(ItemCategorySpellPair const &pair) const { return spellId == pair.spellId ? itemId < pair.itemId : spellId < pair.spellId; }
};
typedef std::set<ItemCategorySpellPair> ItemSpellCategorySet;
typedef std::map<uint32, ItemSpellCategorySet > ItemSpellCategoryStore;
typedef std::set<uint32> SpellCategorySet;
typedef std::map<uint32, SpellCategorySet> SpellCategoryStore;
typedef std::set<uint32> PetFamilySpellsSet;
typedef std::map<uint32, PetFamilySpellsSet > PetFamilySpellsStore;
// Structures not used for casting to loaded DBC data and not required then packing
struct TalentSpellPos
{
TalentSpellPos() : talent_id(0), rank(0) {}
TalentSpellPos(uint16 _talent_id, uint8 _rank) : talent_id(_talent_id), rank(_rank) {}
uint16 talent_id;
uint8 rank;
};
typedef std::map<uint32, TalentSpellPos> TalentSpellPosMap;
struct TaxiPathBySourceAndDestination
{
TaxiPathBySourceAndDestination() : ID(0), price(0) {}
TaxiPathBySourceAndDestination(uint32 _id, uint32 _price) : ID(_id), price(_price) {}
uint32 ID;
uint32 price;
};
typedef std::map<uint32, TaxiPathBySourceAndDestination> TaxiPathSetForSource;
typedef std::map<uint32, TaxiPathSetForSource> TaxiPathSetBySource;
typedef std::vector<TaxiPathNodeEntry const*> TaxiPathNodeList;
typedef std::vector<TaxiPathNodeList> TaxiPathNodesByPath;
#define TaxiMaskSize 14
typedef uint32 TaxiMask[TaxiMaskSize];
#endif
|
blueboy/portal
|
src/game/Server/DBCStructure.h
|
C
|
gpl-2.0
| 107,339
|
/*
* software RGB to RGB converter
* pluralize by Software PAL8 to RGB converter
* Software YUV to YUV converter
* Software YUV to RGB converter
* Written by Nick Kurshev.
* palette & YUV & runtime CPU stuff by Michael (michaelni@gmx.at)
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef SWSCALE_RGB2RGB_H
#define SWSCALE_RGB2RGB_H
#include <inttypes.h>
/* A full collection of RGB to RGB(BGR) converters */
extern void (*rgb24tobgr32)(const uint8_t *src, uint8_t *dst, long src_size);
extern void (*rgb24tobgr16)(const uint8_t *src, uint8_t *dst, long src_size);
extern void (*rgb24tobgr15)(const uint8_t *src, uint8_t *dst, long src_size);
extern void (*rgb32tobgr24)(const uint8_t *src, uint8_t *dst, long src_size);
extern void (*rgb32to16) (const uint8_t *src, uint8_t *dst, long src_size);
extern void (*rgb32to15) (const uint8_t *src, uint8_t *dst, long src_size);
extern void (*rgb15to16) (const uint8_t *src, uint8_t *dst, long src_size);
extern void (*rgb15tobgr24)(const uint8_t *src, uint8_t *dst, long src_size);
extern void (*rgb15to32) (const uint8_t *src, uint8_t *dst, long src_size);
extern void (*rgb16to15) (const uint8_t *src, uint8_t *dst, long src_size);
extern void (*rgb16tobgr24)(const uint8_t *src, uint8_t *dst, long src_size);
extern void (*rgb16to32) (const uint8_t *src, uint8_t *dst, long src_size);
extern void (*rgb24tobgr24)(const uint8_t *src, uint8_t *dst, long src_size);
extern void (*rgb24to16) (const uint8_t *src, uint8_t *dst, long src_size);
extern void (*rgb24to15) (const uint8_t *src, uint8_t *dst, long src_size);
extern void (*rgb32tobgr32)(const uint8_t *src, uint8_t *dst, long src_size);
extern void (*rgb32tobgr16)(const uint8_t *src, uint8_t *dst, long src_size);
extern void (*rgb32tobgr15)(const uint8_t *src, uint8_t *dst, long src_size);
void rgb24to32 (const uint8_t *src, uint8_t *dst, long src_size);
void rgb32to24 (const uint8_t *src, uint8_t *dst, long src_size);
void rgb16tobgr32(const uint8_t *src, uint8_t *dst, long src_size);
void rgb16to24 (const uint8_t *src, uint8_t *dst, long src_size);
void rgb16tobgr16(const uint8_t *src, uint8_t *dst, long src_size);
void rgb16tobgr15(const uint8_t *src, uint8_t *dst, long src_size);
void rgb15tobgr32(const uint8_t *src, uint8_t *dst, long src_size);
void rgb15to24 (const uint8_t *src, uint8_t *dst, long src_size);
void rgb15tobgr16(const uint8_t *src, uint8_t *dst, long src_size);
void rgb15tobgr15(const uint8_t *src, uint8_t *dst, long src_size);
void bgr8torgb8 (const uint8_t *src, uint8_t *dst, long src_size);
void palette8topacked32(const uint8_t *src, uint8_t *dst, long num_pixels, const uint8_t *palette);
void palette8topacked24(const uint8_t *src, uint8_t *dst, long num_pixels, const uint8_t *palette);
void palette8torgb16(const uint8_t *src, uint8_t *dst, long num_pixels, const uint8_t *palette);
void palette8tobgr16(const uint8_t *src, uint8_t *dst, long num_pixels, const uint8_t *palette);
void palette8torgb15(const uint8_t *src, uint8_t *dst, long num_pixels, const uint8_t *palette);
void palette8tobgr15(const uint8_t *src, uint8_t *dst, long num_pixels, const uint8_t *palette);
/**
* Height should be a multiple of 2 and width should be a multiple of 16.
* (If this is a problem for anyone then tell me, and I will fix it.)
* Chrominance data is only taken from every second line, others are ignored.
* FIXME: Write high quality version.
*/
//void uyvytoyv12(const uint8_t *src, uint8_t *ydst, uint8_t *udst, uint8_t *vdst,
/**
* Height should be a multiple of 2 and width should be a multiple of 16.
* (If this is a problem for anyone then tell me, and I will fix it.)
*/
extern void (*yv12toyuy2)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,
long width, long height,
long lumStride, long chromStride, long dstStride);
/**
* Width should be a multiple of 16.
*/
extern void (*yuv422ptoyuy2)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,
long width, long height,
long lumStride, long chromStride, long dstStride);
/**
* Height should be a multiple of 2 and width should be a multiple of 16.
* (If this is a problem for anyone then tell me, and I will fix it.)
*/
extern void (*yuy2toyv12)(const uint8_t *src, uint8_t *ydst, uint8_t *udst, uint8_t *vdst,
long width, long height,
long lumStride, long chromStride, long srcStride);
/**
* Height should be a multiple of 2 and width should be a multiple of 16.
* (If this is a problem for anyone then tell me, and I will fix it.)
*/
extern void (*yv12touyvy)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,
long width, long height,
long lumStride, long chromStride, long dstStride);
/**
* Width should be a multiple of 16.
*/
extern void (*yuv422ptouyvy)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,
long width, long height,
long lumStride, long chromStride, long dstStride);
/**
* Height should be a multiple of 2 and width should be a multiple of 2.
* (If this is a problem for anyone then tell me, and I will fix it.)
* Chrominance data is only taken from every second line, others are ignored.
* FIXME: Write high quality version.
*/
extern void (*rgb24toyv12)(const uint8_t *src, uint8_t *ydst, uint8_t *udst, uint8_t *vdst,
long width, long height,
long lumStride, long chromStride, long srcStride);
extern void (*planar2x)(const uint8_t *src, uint8_t *dst, long width, long height,
long srcStride, long dstStride);
extern void (*interleaveBytes)(uint8_t *src1, uint8_t *src2, uint8_t *dst,
long width, long height, long src1Stride,
long src2Stride, long dstStride);
extern void (*vu9_to_vu12)(const uint8_t *src1, const uint8_t *src2,
uint8_t *dst1, uint8_t *dst2,
long width, long height,
long srcStride1, long srcStride2,
long dstStride1, long dstStride2);
extern void (*yvu9_to_yuy2)(const uint8_t *src1, const uint8_t *src2, const uint8_t *src3,
uint8_t *dst,
long width, long height,
long srcStride1, long srcStride2,
long srcStride3, long dstStride);
extern void (*uyvytoyuv420)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,
long width, long height,
long lumStride, long chromStride, long srcStride);
extern void (*uyvytoyuv422)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,
long width, long height,
long lumStride, long chromStride, long srcStride);
extern void (*yuyvtoyuv420)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,
long width, long height,
long lumStride, long chromStride, long srcStride);
extern void (*yuyvtoyuv422)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,
long width, long height,
long lumStride, long chromStride, long srcStride);
void sws_rgb2rgb_init(int flags);
#endif /* SWSCALE_RGB2RGB_H */
|
azuwis/mplayer-fork
|
libswscale/rgb2rgb.h
|
C
|
gpl-2.0
| 8,403
|
<?php // $Id$
// This file keeps track of upgrades to
// the shortanswer qtype plugin
//
// Sometimes, changes between versions involve
// alterations to database structures and other
// major things that may break installations.
//
// The upgrade function in this file will attempt
// to perform all the necessary actions to upgrade
// your older installtion to the current version.
//
// If there's something it cannot do itself, it
// will tell you what you need to do.
//
// The commands in here will all be database-neutral,
// using the methods of database_manager class
//
// Please do not forget to use upgrade_set_timeout()
// before any action that may take longer time to finish.
function xmldb_qtype_shortanswer_upgrade($oldversion) {
global $CFG, $DB;
$dbman = $DB->get_manager();
$result = true;
/// And upgrade begins here. For each one, you'll need one
/// block of code similar to the next one. Please, delete
/// this comment lines once this file start handling proper
/// upgrade code.
/// if ($result && $oldversion < YYYYMMDD00) { //New version in version.php
/// $result = result of database_manager methods
/// }
return $result;
}
?>
|
ajv/Offline-Caching
|
question/type/shortanswer/db/upgrade.php
|
PHP
|
gpl-2.0
| 1,188
|
/*
* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef WLAN_QCT_MSG_MAP_H
#define WLAN_QCT_MSG_MAP_H
/*===========================================================================
W L A N DEVICE ADAPTATION L A Y E R
MSG MAPPING
DESCRIPTION
This file contains the external API exposed by the wlan adaptation layer
Copyright (c) 2008 QUALCOMM Incorporated. All Rights Reserved.
Qualcomm Confidential and Proprietary
===========================================================================*/
/*
*/
/* */
#include "wlan_qct_pack_align.h"
#define WDA_CONFIG_PARAM_UPDATE_REQ SIR_CFG_PARAM_UPDATE_IND
#define ALIGNED_WORD_SIZE 4
/* */
WPT_PACK_START
typedef WPT_PACK_PRE struct
{
/*
*/
tANI_U16 type;
/*
*/
tANI_U16 length;
/* */
tANI_U16 padBytes;
/* */
tANI_U16 reserved;
/*
*/
}WPT_PACK_POST tHalCfg, *tpHalCfg;
WPT_PACK_END
//
#ifdef WDA_UT
#define WDA_WDI_EVENT_MSG 0x00FF
void WDI_processEvent(void *wdiEventData, void *pUserData);
#endif
#endif
|
aicjofs/android_kernel_lge_v500
|
drivers/staging/prima/CORE/WDA/inc/wlan_qct_wda_msg.h
|
C
|
gpl-2.0
| 3,001
|
/* This file is part of the KDE project
Copyright (C) 2009 KO GmbH <jos.van.den.oever@kogmbh.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 "pictures.h"
#include <zlib.h>
#include <cstdio>
#include <iostream>
#include <QtCore/QDebug>
// Use anonymous namespace to cover following functions
namespace
{
static inline quint16 readU16(const void* p)
{
const unsigned char* ptr = (const unsigned char*) p;
return ptr[0] + (ptr[1] << 8);
}
static inline quint32 readU32(const void* p)
{
const unsigned char* ptr = (const unsigned char*) p;
return ptr[0] + (ptr[1] << 8) + (ptr[2] << 16) + (ptr[3] << 24);
}
void
saveStream(POLE::Stream& stream, quint32 size, KoStore* out)
{
const quint16 bufferSize = 1024;
unsigned char buffer[bufferSize];
unsigned long nread = stream.read(buffer,
(bufferSize < size) ? bufferSize : size);
while (nread > 0) {
out->write((char*)buffer, nread);
size -= nread;
nread = stream.read(buffer, (bufferSize < size) ? bufferSize : size);
}
}
bool
saveDecompressedStream(POLE::Stream& stream, quint32 size, KoStore* out)
{
const quint16 bufferSize = 1024;
unsigned char bufin[bufferSize];
unsigned char bufout[bufferSize];
// initialize for decompressing ZLIB format
z_stream_s zstream;
zstream.zalloc = Z_NULL;
zstream.zfree = Z_NULL;
zstream.opaque = Z_NULL;
zstream.avail_in = 0;
zstream.next_in = Z_NULL;
int r = inflateInit(&zstream);
if (r != Z_OK) {
inflateEnd(&zstream);
return false;
}
unsigned long nread = stream.read(bufin,
(bufferSize < size) ? bufferSize : size);
while (nread > 0) { // loop over the available data
size -= nread;
zstream.next_in = (Bytef*)bufin;
zstream.avail_in = nread;
do { // loop until the data in bufin has all been decompressed
zstream.next_out = (Bytef*)bufout;
zstream.avail_out = bufferSize;
int r = inflate(&zstream, Z_SYNC_FLUSH);
qint32 nwritten = bufferSize - zstream.avail_out;
if (r != Z_STREAM_END && r != Z_OK) {
inflateEnd(&zstream);
return false;
}
out->write((char*)bufout, nwritten);
if (r == Z_STREAM_END) {
inflateEnd(&zstream);
return true; // successfully reached the end
}
} while (zstream.avail_in > 0);
nread = stream.read(bufin, (bufferSize < size) ? bufferSize : size);
}
inflateEnd(&zstream);
return false; // the stream was incomplete
}
const char*
getMimetype(quint16 type)
{
switch (type) {
case 0xF01A: return "application/octet-stream";
case 0xF01B: return "application/octet-stream";
case 0xF01C: return "image/pict";
case 0xF01D: return "image/jpeg";
case 0xF01E: return "image/png";
case 0xF01F: return "application/octet-stream";
case 0xF029: return "image/tiff";
case 0xF02A: return "image/jpeg";
}
return "";
}
const char*
getSuffix(quint16 type)
{
switch (type) {
case 0xF01A: return ".emf";
case 0xF01B: return ".wmf";
case 0xF01C: return ".pict";
case 0xF01D: return ".jpg";
case 0xF01E: return ".png";
case 0xF01F: return ".dib";
case 0xF029: return ".tiff";
case 0xF02A: return ".jpg";
}
return "";
}
template<class T>
void
savePicture(PictureReference& ref, const T* a, KoStore* out)
{
if (!a) return;
ref.uid = a->rgbUid1 + a->rgbUid2;
ref.name = ref.uid.toHex() + getSuffix(a->rh.recType);
if (!out->open(ref.name.toLocal8Bit())) {
ref.name.clear();
ref.uid.clear();
return; // empty name reports an error
}
out->write(a->BLIPFileData.data(), a->BLIPFileData.size());
ref.mimetype = getMimetype(a->rh.recType);
out->close();
}
template<class T>
void
saveDecompressedPicture(PictureReference& ref, const T* a, KoStore* store)
{
if (!a) return;
QByteArray buff = a->BLIPFileData;
bool compressed = a->metafileHeader.compression == 0;
if (compressed) {
quint32 cbSize = a->metafileHeader.cbSize;
char tmp[4];
//big-endian byte order required
tmp[3] = (cbSize & 0x000000ff);
tmp[2] = ((cbSize >> 8) & 0x0000ff);
tmp[1] = ((cbSize >> 16) & 0x00ff);
tmp[0] = (cbSize >> 24);
buff.prepend((char*) tmp, 4);
buff = qUncompress(buff);
if (buff.size() != cbSize) {
qDebug() << "Warning: uncompressed size of the metafile differs";
}
}
//reuse the savePicture code
ref.uid = a->rgbUid1 + a->rgbUid2;
ref.name = ref.uid.toHex() + getSuffix(a->rh.recType);
if (!store->open(ref.name.toLocal8Bit())) {
ref.name.clear();
ref.uid.clear();
return; // empty name reports an error
}
store->write(buff.data(), buff.size());
ref.mimetype = getMimetype(a->rh.recType);
store->close();
}
PictureReference
savePicture(const MSO::OfficeArtBlip& a, KoStore* store)
{
PictureReference ref;
// only one of these calls will actually save a picture
saveDecompressedPicture(ref, a.anon.get<MSO::OfficeArtBlipEMF>(), store);
saveDecompressedPicture(ref, a.anon.get<MSO::OfficeArtBlipWMF>(), store);
saveDecompressedPicture(ref, a.anon.get<MSO::OfficeArtBlipPICT>(), store);
savePicture(ref, a.anon.get<MSO::OfficeArtBlipJPEG>(), store);
savePicture(ref, a.anon.get<MSO::OfficeArtBlipPNG>(), store);
savePicture(ref, a.anon.get<MSO::OfficeArtBlipDIB>(), store);
savePicture(ref, a.anon.get<MSO::OfficeArtBlipTIFF>(), store);
return ref;
}
}
PictureReference
savePicture(POLE::Stream& stream, KoStore* out)
{
PictureReference ref;
const quint16 bufferSize = 1024;
unsigned char buffer[bufferSize];
if (stream.read(buffer, 8) != 8) return ref;
quint16 instance = readU16(buffer) >> 4;
quint16 type = readU16(buffer + 2);
quint32 size = readU32(buffer + 4);
if (type == 0xF007) { // OfficeArtFBSE
if (stream.read(buffer, 36) != 36) return ref;
quint16 cbName = *(buffer + 33);
if (cbName > bufferSize || stream.read(buffer, cbName) != cbName) {
return ref;
}
size = size - 36 - cbName;
// read embedded BLIP
if (stream.read(buffer, 8) != 8) return ref;
instance = readU16(buffer) >> 4;
type = readU16(buffer + 2);
size = readU32(buffer + 4);
}
// Image data is stored raw in the Pictures stream
// The offset to the data differs per image type.
quint16 offset;
switch (type) {
case 0xF01A: offset = (instance == 0x3D4) ? 50 : 66; break;
case 0xF01B: offset = (instance == 0x216) ? 50 : 66; break;
case 0xF01C: offset = (instance == 0x542) ? 50 : 66; break;
case 0xF01D: offset = (instance == 0x46A) ? 17 : 33; break;
case 0xF01E: offset = (instance == 0x6E0) ? 17 : 33; break;
case 0xF01F: offset = (instance == 0x7A8) ? 17 : 33; break;
case 0xF029: offset = (instance == 0x6E4) ? 17 : 33; break;
case 0xF02A: offset = (instance == 0x46A) ? 17 : 33; break;
default: return ref;
}
const char* namesuffix = getSuffix(type);
ref.mimetype = getMimetype(type);
// skip offset
if (offset != 0 && stream.read(buffer, offset) != offset) return ref;
size -= offset;
bool compressed = false;
if (type == 0xF01A || type == 0xF01B || type == 0xF01C) {
// read the compressed field from the OfficeArtMetafileHeader
compressed = buffer[offset-2] == 0;
}
ref.uid = QByteArray((const char*)buffer, 16);
ref.name = ref.uid.toHex() + namesuffix;
if (!out->open(ref.name.toLocal8Bit())) {
ref.name.clear();
ref.uid.clear();
return ref; // empty name reports an error
}
unsigned long next = stream.tell() + size;
if (compressed) {
saveDecompressedStream(stream, size, out);
} else {
saveStream(stream, size, out);
}
stream.seek(next);
out->close();
return ref;
}
PictureReference
savePicture(const MSO::OfficeArtBStoreContainerFileBlock& a, KoStore* store)
{
const MSO::OfficeArtBlip* blip = a.anon.get<MSO::OfficeArtBlip>();
const MSO::OfficeArtFBSE* fbse = a.anon.get<MSO::OfficeArtFBSE>();
if (blip) {
return savePicture(*blip, store);
}
if (fbse && fbse->embeddedBlip) {
return savePicture(*fbse->embeddedBlip, store);
}
return PictureReference();
}
|
TheTypoMaster/calligra-history
|
filters/libmso/pictures.cpp
|
C++
|
gpl-2.0
| 9,324
|
# -*- cperl -*-
# Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# This is a library file used by the Perl version of myblockchain-test-run,
# and is part of the translation of the Bourne shell script with the
# same name.
use strict;
use warnings;
sub mtr_report_test_name($);
sub mtr_report_test_passed($);
sub mtr_report_test_failed($);
sub mtr_report_test_skipped($);
sub mtr_report_test_not_skipped_though_disabled($);
sub mtr_report_stats ($);
sub mtr_print_line ();
sub mtr_print_thick_line ();
sub mtr_print_header ();
sub mtr_report (@);
sub mtr_warning (@);
sub mtr_error (@);
sub mtr_child_error (@);
sub mtr_debug (@);
sub mtr_verbose (@);
my $tot_real_time= 0;
##############################################################################
#
#
#
##############################################################################
sub mtr_report_test_name ($) {
my $tinfo= shift;
my $tname= $tinfo->{name};
$tname.= " '$tinfo->{combination}'"
if defined $tinfo->{combination};
_mtr_log($tname);
printf "%-30s ", $tname;
}
sub mtr_report_test_skipped ($) {
my $tinfo= shift;
$tinfo->{'result'}= 'MTR_RES_SKIPPED';
if ( $tinfo->{'disable'} )
{
mtr_report("[ disabled ] $tinfo->{'comment'}");
}
elsif ( $tinfo->{'comment'} )
{
mtr_report("[ skipped ] $tinfo->{'comment'}");
}
else
{
mtr_report("[ skipped ]");
}
}
sub mtr_report_tests_not_skipped_though_disabled ($) {
my $tests= shift;
if ( $::opt_enable_disabled )
{
my @disabled_tests= grep {$_->{'dont_skip_though_disabled'}} @$tests;
if ( @disabled_tests )
{
print "\nTest(s) which will be run though they are marked as disabled:\n";
foreach my $tinfo ( sort {$a->{'name'} cmp $b->{'name'}} @disabled_tests )
{
printf " %-20s : %s\n", $tinfo->{'name'}, $tinfo->{'comment'};
}
}
}
}
sub mtr_report_test_passed ($) {
my $tinfo= shift;
my $timer= "";
if ( $::opt_timer and -f "$::opt_vardir/log/timer" )
{
$timer= mtr_fromfile("$::opt_vardir/log/timer");
$tot_real_time += ($timer/1000);
$timer= sprintf "%12s", $timer;
}
$tinfo->{'result'}= 'MTR_RES_PASSED';
mtr_report("[ pass ] $timer");
}
sub mtr_report_test_failed ($) {
my $tinfo= shift;
$tinfo->{'result'}= 'MTR_RES_FAILED';
if ( defined $tinfo->{'timeout'} )
{
mtr_report("[ fail ] timeout");
return;
}
else
{
mtr_report("[ fail ]");
}
if ( $tinfo->{'comment'} )
{
# The test failure has been detected by myblockchain-test-run.pl
# when starting the servers or due to other error, the reason for
# failing the test is saved in "comment"
mtr_report("\nERROR: $tinfo->{'comment'}");
}
elsif ( -f $::path_timefile )
{
# Test failure was detected by test tool and it's report
# about what failed has been saved to file. Display the report.
print "\n";
print mtr_fromfile($::path_timefile); # FIXME print_file() instead
print "\n";
}
else
{
# Neither this script or the test tool has recorded info
# about why the test has failed. Should be debugged.
mtr_report("\nUnexpected termination, probably when starting myblockchaind");;
}
}
sub mtr_report_stats ($) {
my $tests= shift;
# ----------------------------------------------------------------------
# Find out how we where doing
# ----------------------------------------------------------------------
my $tot_skiped= 0;
my $tot_passed= 0;
my $tot_failed= 0;
my $tot_tests= 0;
my $tot_restarts= 0;
my $found_problems= 0; # Some warnings in the logfiles are errors...
foreach my $tinfo (@$tests)
{
if ( $tinfo->{'result'} eq 'MTR_RES_SKIPPED' )
{
$tot_skiped++;
}
elsif ( $tinfo->{'result'} eq 'MTR_RES_PASSED' )
{
$tot_tests++;
$tot_passed++;
}
elsif ( $tinfo->{'result'} eq 'MTR_RES_FAILED' )
{
$tot_tests++;
$tot_failed++;
}
if ( $tinfo->{'restarted'} )
{
$tot_restarts++;
}
}
# ----------------------------------------------------------------------
# Print out a summary report to screen
# ----------------------------------------------------------------------
if ( ! $tot_failed )
{
print "All $tot_tests tests were successful.\n";
}
else
{
my $ratio= $tot_passed * 100 / $tot_tests;
print "Failed $tot_failed/$tot_tests tests, ";
printf("%.2f", $ratio);
print "\% were successful.\n\n";
print
"The log files in var/log may give you some hint\n",
"of what went wrong.\n",
"If you want to report this error, please read first ",
"the documentation at\n",
"http://dev.myblockchain.com/doc/myblockchain/en/myblockchain-test-suite.html\n";
}
if (!$::opt_extern)
{
print "The servers were restarted $tot_restarts times\n";
}
if ( $::opt_timer )
{
use English;
mtr_report("Spent", sprintf("%.3f", $tot_real_time),"of",
time - $BASETIME, "seconds executing testcases");
}
# ----------------------------------------------------------------------
# If a debug run, there might be interesting information inside
# the "var/log/*.err" files. We save this info in "var/log/warnings"
# ----------------------------------------------------------------------
if ( ! $::glob_use_running_server )
{
# Save and report if there was any fatal warnings/errors in err logs
my $warnlog= "$::opt_vardir/log/warnings";
unless ( open(WARN, ">$warnlog") )
{
mtr_warning("can't write to the file \"$warnlog\": $!");
}
else
{
# We report different types of problems in order
foreach my $pattern ( "^Warning:",
"\\[Warning\\]",
"\\[ERROR\\]",
"^Error:", "^==.* at 0x",
"InnoDB: Warning",
"InnoDB: Error",
"^safe_mutex:",
"missing DBUG_RETURN",
"myblockchaind: Warning",
"allocated at line",
"Attempting backtrace", "Assertion .* failed" )
{
foreach my $errlog ( sort glob("$::opt_vardir/log/*.err") )
{
my $testname= "";
unless ( open(ERR, $errlog) )
{
mtr_warning("can't read $errlog");
next;
}
while ( <ERR> )
{
# Skip some non fatal warnings from the log files
if (
/\"SELECT UNIX_TIMESTAMP\(\)\" failed on master/ or
/Aborted connection/ or
/Client requested master to start replication from impossible position/ or
/Could not find first log file name in binary log/ or
/Enabling keys got errno/ or
/Error reading master configuration/ or
/Error reading packet/ or
/Event Scheduler/ or
/Failed to open log/ or
/Failed to open the existing master info file/ or
/Forcing shutdown of [0-9]* plugins/ or
/Can't open shared library .*\bha_example\b/ or
/Couldn't load plugin .*\bha_example\b/ or
# Due to timing issues, it might be that this warning
# is printed when the server shuts down and the
# computer is loaded.
/Forcing close of thread \d+ user: '.*?'/ or
/Got error [0-9]* when reading table/ or
/Incorrect definition of table/ or
/Incorrect information in file/ or
/InnoDB: Warning: we did not need to do crash recovery/ or
/Invalid \(old\?\) table or blockchain name/ or
/Lock wait timeout exceeded/ or
/Log entry on master is longer than max_allowed_packet/ or
/unknown option '--loose-/ or
/unknown variable 'loose-/ or
/You have forced lower_case_table_names to 0 through a command-line option/ or
/Setting lower_case_table_names=2/ or
/NDB Binlog:/ or
/NDB: failed to setup table/ or
/NDB: only row based binary logging/ or
/Neither --relay-log nor --relay-log-index were used/ or
/Query partially completed/ or
/Slave I.O thread aborted while waiting for relay log/ or
/Slave SQL thread is stopped because UNTIL condition/ or
/Slave SQL thread retried transaction/ or
/Slave \(additional info\)/ or
/Slave: .*Duplicate column name/ or
/Slave: .*master may suffer from/ or
/Slave: According to the master's version/ or
/Slave: Column [0-9]* type mismatch/ or
/Slave: Error .* doesn't exist/ or
/Slave: Deadlock found/ or
/Slave: Error .*Unknown table/ or
/Slave: Error in Write_rows event: / or
/Slave: Field .* of table .* has no default value/ or
/Slave: Field .* doesn't have a default value/ or
/Slave: Query caused different errors on master and slave/ or
/Slave: Table .* doesn't exist/ or
/Slave: Table width mismatch/ or
/Slave: The incident LOST_EVENTS occured on the master/ or
/Slave: Unknown error.* 1105/ or
/Slave: Can't drop blockchain.* blockchain doesn't exist/ or
/Slave SQL:.*(?:Error_code: \d+|Query:.*)/ or
/Sort aborted/ or
/Time-out in NDB/ or
/One can only use the --user.*root/ or
/Table:.* on (delete|rename)/ or
/You have an error in your SQL syntax/ or
/deprecated/ or
/description of time zone/ or
/equal MyBlockchain server ids/ or
/error .*connecting to master/ or
/error reading log entry/ or
/lower_case_table_names is set/ or
/skip-name-resolve mode/ or
/slave SQL thread aborted/ or
/Slave: .*Duplicate entry/ or
# Special case for Bug #26402 in show_check.test
# Question marks are not valid file name parts
# on Windows platforms. Ignore this error message.
/\QCan't find file: '.\test\????????.frm'\E/ or
# Special case, made as specific as possible, for:
# Bug #28436: Incorrect position in SHOW BINLOG EVENTS causes
# server coredump
/\QError in Log_event::read_log_event(): 'Sanity check failed', data_len: 258, event_type: 49\E/ or
/Statement is not safe to log in statement format/ or
# test case for Bug#bug29807 copies a stray frm into blockchain
/InnoDB: Error: table `test`.`bug29807` does not exist in the InnoDB internal/ or
/InnoDB: Cannot open table test\/bug29807 from/ or
# innodb foreign key tests that fail in ALTER or RENAME produce this
/InnoDB: Error: in ALTER TABLE `test`.`t[12]`/ or
/InnoDB: Error: in RENAME TABLE table `test`.`t1`/ or
/InnoDB: Error: table `test`.`t[12]` does not exist in the InnoDB internal/ or
# Test case for Bug#14233 produces the following warnings:
/Stored routine 'test'.'bug14233_1': invalid value in column myblockchain.proc/ or
/Stored routine 'test'.'bug14233_2': invalid value in column myblockchain.proc/ or
/Stored routine 'test'.'bug14233_3': invalid value in column myblockchain.proc/ or
# BUG#29839 - lowercase_table3.test: Cannot find table test/T1
# from the internal data dictiona
/Cannot find table test\/BUG29839 from the internal data dictionary/ or
# BUG#32080 - Excessive warnings on Solaris: setrlimit could not
# change the size of core files
/setrlimit could not change the size of core files to 'infinity'/ or
# rpl_extrColmaster_*.test, the slave thread produces warnings
# when it get updates to a table that has more columns on the
# master
/Slave: Unknown column 'c7' in 't15' Error_code: 1054/ or
/Slave: Can't DROP 'c7'.* 1091/ or
/Slave: Key column 'c6'.* 1072/ or
# rpl_idempotency.test produces warnings for the slave.
($testname eq 'rpl.rpl_idempotency' and
(/Slave: Can\'t find record in \'t1\' Error_code: 1032/ or
/Slave: Cannot add or update a child row: a foreign key constraint fails .* Error_code: 1452/
)) or
# These tests does "kill" on queries, causing sporadic errors when writing to logs
(($testname eq 'rpl.rpl_skip_error' or
$testname eq 'rpl.rpl_err_ignoredtable' or
$testname eq 'binlog.binlog_killed_simulate' or
$testname eq 'binlog.binlog_killed') and
(/Failed to write to myblockchain\.\w+_log/
)) or
# rpl_bug33931 has deliberate failures
($testname eq 'rpl.rpl_bug33931' and
(/Failed during slave.*thread initialization/
)) or
# rpl_temporary has an error on slave that can be ignored
($testname eq 'rpl.rpl_temporary' and
(/Slave: Can\'t find record in \'user\' Error_code: 1032/
)) or
# Test case for Bug#31590 produces the following error:
/Out of sort memory; increase server sort buffer size/ or
# Bug#35161, test of auto repair --myisam-recover
/able.*_will_crash/ or
# lowercase_table3 using case sensitive option on
# case insensitive filesystem (InnoDB error).
/InnoDB: Cannot open table test\/BUG29839 from/ or
# When trying to set lower_case_table_names = 2
# on a case sensitive file system. Bug#37402.
/lower_case_table_names was set to 2, even though your the file system '.*' is case sensitive. Now setting lower_case_table_names to 0 to avoid future problems./
)
{
next; # Skip these lines
}
if ( /CURRENT_TEST: (.*)/ )
{
$testname= $1;
}
if ( /$pattern/ )
{
$found_problems= 1;
print WARN basename($errlog) . ": $testname: $_";
}
}
}
}
if ( $::opt_check_testcases )
{
# Look for warnings produced by myblockchaintest in testname.warnings
foreach my $test_warning_file
( glob("$::glob_myblockchain_test_dir/r/*.warnings") )
{
$found_problems= 1;
print WARN "Check myqltest warnings in $test_warning_file\n";
}
}
if ( $found_problems )
{
mtr_warning("Got errors/warnings while running tests, please examine",
"\"$warnlog\" for details.");
}
}
}
print "\n";
# Print a list of testcases that failed
if ( $tot_failed != 0 )
{
my $test_mode= join(" ", @::glob_test_mode) || "default";
print "myblockchain-test-run in $test_mode mode: *** Failing the test(s):";
foreach my $tinfo (@$tests)
{
if ( $tinfo->{'result'} eq 'MTR_RES_FAILED' )
{
print " $tinfo->{'name'}";
}
}
print "\n";
}
# Print a list of check_testcases that failed(if any)
if ( $::opt_check_testcases )
{
my @check_testcases= ();
foreach my $tinfo (@$tests)
{
if ( defined $tinfo->{'check_testcase_failed'} )
{
push(@check_testcases, $tinfo->{'name'});
}
}
if ( @check_testcases )
{
print "Check of testcase failed for: ";
print join(" ", @check_testcases);
print "\n\n";
}
}
if ( $tot_failed != 0 || $found_problems)
{
mtr_error("there were failing test cases");
}
}
##############################################################################
#
# Text formatting
#
##############################################################################
sub mtr_print_line () {
print '-' x 55, "\n";
}
sub mtr_print_thick_line () {
print '=' x 55, "\n";
}
sub mtr_print_header () {
print "\n";
if ( $::opt_timer )
{
print "TEST RESULT TIME (ms)\n";
}
else
{
print "TEST RESULT\n";
}
mtr_print_line();
print "\n";
}
##############################################################################
#
# Log and reporting functions
#
##############################################################################
use IO::File;
my $log_file_ref= undef;
sub mtr_log_init ($) {
my ($filename)= @_;
mtr_error("Log is already open") if defined $log_file_ref;
$log_file_ref= IO::File->new($filename, "a") or
mtr_warning("Could not create logfile $filename: $!");
}
sub _mtr_log (@) {
print $log_file_ref join(" ", @_),"\n"
if defined $log_file_ref;
}
sub mtr_report (@) {
# Print message to screen and log
_mtr_log(@_);
print join(" ", @_),"\n";
}
sub mtr_warning (@) {
# Print message to screen and log
_mtr_log("WARNING: ", @_);
print STDERR "myblockchain-test-run: WARNING: ",join(" ", @_),"\n";
}
sub mtr_error (@) {
# Print message to screen and log
_mtr_log("ERROR: ", @_);
print STDERR "myblockchain-test-run: *** ERROR: ",join(" ", @_),"\n";
mtr_exit(1);
}
sub mtr_child_error (@) {
# Print message to screen and log
_mtr_log("ERROR(child): ", @_);
print STDERR "myblockchain-test-run: *** ERROR(child): ",join(" ", @_),"\n";
exit(1);
}
sub mtr_debug (@) {
# Only print if --script-debug is used
if ( $::opt_script_debug )
{
_mtr_log("###: ", @_);
print STDERR "####: ",join(" ", @_),"\n";
}
}
sub mtr_verbose (@) {
# Always print to log, print to screen only when --verbose is used
_mtr_log("> ",@_);
if ( $::opt_verbose )
{
print STDERR "> ",join(" ", @_),"\n";
}
}
1;
|
MrDunne/myblockchain
|
myblockchain-test/lib/v1/mtr_report.pl
|
Perl
|
gpl-2.0
| 17,679
|
/*
| Copyright (C) 2002-2011 Jorg Schuler <jcsjcs at users sourceforge net>
| Paul Richardson <phantom_sf at users.sourceforge.net>
| Part of the gtkpod project.
|
| URL: http://www.gtkpod.org/
| URL: http://gtkpod.sourceforge.net/
|
| This program is free software; you can redistribute it and/or modify
| it under the terms of the GNU General Public License as published by
| the Free Software Foundation; either version 2 of the License, or
| (at your option) any later version.
|
| This program is distributed in the hope that it will be useful,
| but WITHOUT ANY WARRANTY; without even the implied warranty of
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
| GNU General Public License for more details.
|
| You should have received a copy of the GNU General Public License
| along with this program; if not, write to the Free Software
| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
| iTunes and iPod are trademarks of Apple
|
| This product is not supported/written/published by Apple!
|
*/
/* enum to access cat_strings */
#include <gtk/gtk.h>
#include <string.h>
#include "libgtkpod/misc.h"
#include "libgtkpod/misc_conversion.h"
#include "libgtkpod/prefs.h"
#include "date_parser.h"
#include "sorttab_widget.h"
#include "special_sorttab_page.h"
#define CAL_XML "cal_xml"
#define SPECIAL_PAGE "special_sort_tab_page"
enum {
CAT_STRING_PLAYED = 0,
CAT_STRING_MODIFIED = 1,
CAT_STRING_ADDED = 2
};
/* typedef to specify lower or upper margin */
typedef enum {
LOWER_MARGIN, UPPER_MARGIN
} MarginType;
GtkBuilder *_get_calendar_xml(GtkWidget *cal) {
g_return_val_if_fail(GTK_IS_WIDGET(cal), NULL);
GtkBuilder *xml;
xml = g_object_get_data(G_OBJECT(cal), CAL_XML);
g_return_val_if_fail(GTK_IS_BUILDER(xml), NULL);
return xml;
}
SpecialSortTabPage *_get_parent_page(GtkWidget *cal) {
g_return_val_if_fail(GTK_IS_WIDGET(cal), NULL);
SpecialSortTabPage *page;
page = g_object_get_data(G_OBJECT(cal), SPECIAL_PAGE);
g_return_val_if_fail(SPECIAL_SORT_TAB_IS_PAGE(page), NULL);
return page;
}
/* Set the calendar @calendar, as well as spin buttons @hour and @min
* according to @mactime. If @mactime is 0, check @no_margin
* togglebutton, otherwise uncheck it. */
static void cal_set_time_widgets(GtkCalendar *cal, GtkSpinButton *hour, GtkSpinButton *min, GtkToggleButton *no_margin, time_t timet) {
struct tm *tm;
time_t tt = time(NULL);
/* 0, -1 are treated in a special way (no lower/upper margin
* -> set calendar to current time */
if ((timet != 0) && (timet != -1)) {
tt = timet;
if (no_margin)
gtk_toggle_button_set_active(no_margin, FALSE);
}
else if (no_margin)
gtk_toggle_button_set_active(no_margin, TRUE);
tm = localtime(&tt);
if (cal) {
gtk_calendar_select_month(cal, tm->tm_mon, 1900 + tm->tm_year);
gtk_calendar_select_day(cal, tm->tm_mday);
}
if (hour)
gtk_spin_button_set_value(hour, tm->tm_hour);
if (min)
gtk_spin_button_set_value(min, tm->tm_min);
}
static void cal_set_time(GtkWidget *cal, MarginType type, time_t timet) {
GtkBuilder *cal_xml;
GtkCalendar *calendar = NULL;
GtkSpinButton *hour = NULL;
GtkSpinButton *min = NULL;
GtkToggleButton *no_margin = NULL;
cal_xml = _get_calendar_xml(cal);
switch (type) {
case LOWER_MARGIN:
calendar = GTK_CALENDAR (gtkpod_builder_xml_get_widget (cal_xml, "lower_cal"));
hour = GTK_SPIN_BUTTON (gtkpod_builder_xml_get_widget (cal_xml, "lower_hours"));
min = GTK_SPIN_BUTTON (gtkpod_builder_xml_get_widget (cal_xml, "lower_minutes"));
no_margin = GTK_TOGGLE_BUTTON (gtkpod_builder_xml_get_widget (cal_xml, "no_lower_margin"));
break;
case UPPER_MARGIN:
calendar = GTK_CALENDAR (gtkpod_builder_xml_get_widget (cal_xml, "upper_cal"));
hour = GTK_SPIN_BUTTON (gtkpod_builder_xml_get_widget (cal_xml, "upper_hours"));
min = GTK_SPIN_BUTTON (gtkpod_builder_xml_get_widget (cal_xml, "upper_minutes"));
no_margin = GTK_TOGGLE_BUTTON (gtkpod_builder_xml_get_widget (cal_xml, "no_upper_margin"));
break;
}
cal_set_time_widgets(calendar, hour, min, no_margin, timet);
}
/* Extract data from calendar/time.
*
* Return value:
*
* pointer to 'struct tm' filled with the relevant data or NULL, if
* the button no_margin was selected.
*
* If @tm is != NULL, modify that instead.
*
* You must g_free() the retuned value.
*/
static struct tm *cal_get_time(GtkWidget *cal, MarginType type, struct tm *tm) {
GtkCalendar *calendar = NULL;
GtkSpinButton *hour = NULL;
GtkSpinButton *min = NULL;
GtkSpinButton *sec = NULL;
GtkToggleButton *no_margin = NULL;
GtkToggleButton *no_time = NULL;
GtkBuilder *cal_xml;
cal_xml = _get_calendar_xml(cal);
switch (type) {
case LOWER_MARGIN:
calendar = GTK_CALENDAR (gtkpod_builder_xml_get_widget (cal_xml, "lower_cal"));
hour = GTK_SPIN_BUTTON (gtkpod_builder_xml_get_widget (cal_xml, "lower_hours"));
min = GTK_SPIN_BUTTON (gtkpod_builder_xml_get_widget (cal_xml, "lower_minutes"));
no_margin = GTK_TOGGLE_BUTTON (gtkpod_builder_xml_get_widget (cal_xml, "no_lower_margin"));
no_time = GTK_TOGGLE_BUTTON (gtkpod_builder_xml_get_widget (cal_xml, "lower_time"));
break;
case UPPER_MARGIN:
calendar = GTK_CALENDAR (gtkpod_builder_xml_get_widget (cal_xml, "upper_cal"));
hour = GTK_SPIN_BUTTON (gtkpod_builder_xml_get_widget (cal_xml, "upper_hours"));
min = GTK_SPIN_BUTTON (gtkpod_builder_xml_get_widget (cal_xml, "upper_minutes"));
no_margin = GTK_TOGGLE_BUTTON (gtkpod_builder_xml_get_widget (cal_xml, "no_upper_margin"));
no_time = GTK_TOGGLE_BUTTON (gtkpod_builder_xml_get_widget (cal_xml, "upper_time"));
break;
}
if (!gtk_toggle_button_get_active(no_margin)) {
/* Initialize tm with current time and copy the result of
* localtime() to persistent memory that can be g_free()'d */
time_t tt = time(NULL);
if (!tm) {
tm = g_malloc(sizeof(struct tm));
memcpy(tm, localtime(&tt), sizeof(struct tm));
}
if (calendar) {
guint year, month, day;
gtk_calendar_get_date(calendar, &year, &month, &day);
tm->tm_year = year - 1900;
tm->tm_mon = month;
tm->tm_mday = day;
}
if (gtk_toggle_button_get_active(no_time)) {
if (hour)
tm->tm_hour = gtk_spin_button_get_value_as_int(hour);
if (min)
tm->tm_min = gtk_spin_button_get_value_as_int(min);
if (sec)
tm->tm_min = gtk_spin_button_get_value_as_int(sec);
}
else { /* use 0:00 for lower and 23:59 for upper margin */
switch (type) {
case LOWER_MARGIN:
if (hour)
tm->tm_hour = 0;
if (min)
tm->tm_min = 0;
if (sec)
tm->tm_sec = 0;
break;
case UPPER_MARGIN:
if (hour)
tm->tm_hour = 23;
if (min)
tm->tm_min = 59;
if (sec)
tm->tm_sec = 59;
break;
}
}
}
return tm;
}
/* get the category (T_TIME_PLAYED or T_TIME_MODIFIED) selected in the
* combo */
static T_item cal_get_category(GtkWidget *cal) {
GtkWidget *w;
T_item item;
gint i = -1;
GtkBuilder *cal_xml;
cal_xml = _get_calendar_xml(cal);
w = gtkpod_builder_xml_get_widget(cal_xml, "cat_combo");
i = gtk_combo_box_get_active(GTK_COMBO_BOX (w));
switch (i) {
case CAT_STRING_PLAYED:
item = T_TIME_PLAYED;
break;
case CAT_STRING_MODIFIED:
item = T_TIME_MODIFIED;
break;
case CAT_STRING_ADDED:
item = T_TIME_ADDED;
break;
default:
fprintf(stderr, "Programming error: cal_get_category () -- item not found.\n");
/* set to something reasonable at least */
item = T_TIME_PLAYED;
}
return item;
}
/* Returns a string "DD/MM/YYYY HH:MM". Data is taken from
* @tm. Returns NULL if tm==NULL. You must g_free() the returned
* string */
static gchar *cal_get_time_string(struct tm *tm) {
gchar *str = NULL;
if (tm)
str
= g_strdup_printf("%02d/%02d/%04d %d:%02d", tm->tm_mday, tm->tm_mon + 1, 1900 + tm->tm_year, tm->tm_hour, tm->tm_min);
return str;
}
/* Extract data from calendar/time and write it to the corresponding
entry in the specified sort tab */
static void cal_apply_data(GtkWidget *cal) {
struct tm *lower, *upper;
TimeInfo *ti;
T_item item;
SpecialSortTabPage *page;
page = _get_parent_page(cal);
lower = cal_get_time(cal, LOWER_MARGIN, NULL);
upper = cal_get_time(cal, UPPER_MARGIN, NULL);
/* Get selected category (played, modified or added) */
item = cal_get_category(cal);
/* Get pointer to corresponding TimeInfo struct */
ti = special_sort_tab_page_get_timeinfo(page, item);
if (ti) {
GtkToggleButton *act = GTK_TOGGLE_BUTTON (ti->active);
/* is criteria currently checked (active)? */
gboolean active = gtk_toggle_button_get_active(act);
gchar *str = NULL;
gchar *str1 = cal_get_time_string(lower);
gchar *str2 = cal_get_time_string(upper);
if (!lower && !upper)
if (!active) /* deactivate this criteria */
gtk_toggle_button_set_active(act, FALSE);
if (lower && !upper)
str = g_strdup_printf("> %s", str1);
if (!lower && upper)
str = g_strdup_printf("< %s", str2);
if (lower && upper)
str = g_strdup_printf("%s < < %s", str1, str2);
C_FREE (str1);
C_FREE (str2);
if (str) { /* set the new string if it's different */
if (strcmp(str, gtk_entry_get_text(GTK_ENTRY (ti->entry))) != 0) {
gtk_entry_set_text(GTK_ENTRY (ti->entry), str);
/* notification that contents have changed */
g_signal_emit_by_name(ti->entry, "activate");
}
g_free(str);
}
if (!active) { /* activate the criteria */
gtk_toggle_button_set_active(act, TRUE);
}
}
g_free(lower);
g_free(upper);
}
/* Callback for 'Lower/Upper time ' buttons */
static void cal_time_toggled(GtkToggleButton *togglebutton, gpointer user_data) {
GtkWidget *cal = GTK_WIDGET(user_data);
GtkBuilder *cal_xml = _get_calendar_xml(cal);
gboolean sens = gtk_toggle_button_get_active(togglebutton);
if ((GtkWidget *) togglebutton == gtkpod_builder_xml_get_widget(cal_xml, "lower_time")) {
gtk_widget_set_sensitive(gtkpod_builder_xml_get_widget(cal_xml, "lower_time_box"), sens);
}
if ((GtkWidget *) togglebutton == gtkpod_builder_xml_get_widget(cal_xml, "upper_time")) {
gtk_widget_set_sensitive(gtkpod_builder_xml_get_widget(cal_xml, "upper_time_box"), sens);
}
}
/* Callback for 'No Lower/Upper Margin' buttons */
static void cal_no_margin_toggled(GtkToggleButton *togglebutton, gpointer user_data) {
GtkWidget *cal = GTK_WIDGET(user_data);
GtkBuilder *cal_xml = _get_calendar_xml(cal);
gboolean sens = !gtk_toggle_button_get_active(togglebutton);
if ((GtkWidget *) togglebutton == gtkpod_builder_xml_get_widget(cal_xml, "no_lower_margin")) {
gtk_widget_set_sensitive(gtkpod_builder_xml_get_widget(cal_xml, "lower_cal_box"), sens);
}
if ((GtkWidget *) togglebutton == gtkpod_builder_xml_get_widget(cal_xml, "no_upper_margin")) {
gtk_widget_set_sensitive(gtkpod_builder_xml_get_widget(cal_xml, "upper_cal_box"), sens);
}
}
/* Save the default geometry of the window */
static void cal_save_default_geometry(GtkWindow *cal) {
gint x, y;
gtk_window_get_size(cal, &x, &y);
prefs_set_int("size_cal.x", x);
prefs_set_int("size_cal.y", y);
}
/* Callback for 'delete' event */
static gboolean cal_delete_event(GtkWidget *widget, GdkEvent *event, gpointer user_data) {
cal_save_default_geometry(GTK_WINDOW (user_data));
return FALSE;
}
/* Callback for 'Cancel' button */
static void cal_cancel(GtkButton *button, gpointer user_data) {
cal_save_default_geometry(GTK_WINDOW (user_data));
gtk_widget_destroy(user_data);
}
/* Callback for 'Apply' button */
static void cal_apply(GtkButton *button, gpointer user_data) {
cal_save_default_geometry(GTK_WINDOW (user_data));
cal_apply_data(GTK_WIDGET (user_data));
}
/* Callback for 'OK' button */
static void cal_ok(GtkButton *button, gpointer user_data) {
cal_apply(button, user_data);
gtk_widget_destroy(user_data);
}
/**
* Open a calendar window. Preset the values for instance @inst,
* category @item (time played, time modified or time added)
*/
void cal_open_calendar(SpecialSortTabPage *page, T_item item) {
GtkWidget *w;
GtkWidget *cal;
int index = -1;
gint defx, defy;
TimeInfo *ti;
GtkBuilder *cal_xml;
SortTabWidget *parent;
/* Sanity */
if (!SPECIAL_SORT_TAB_IS_PAGE(page))
return;
parent = special_sort_tab_page_get_parent(page);
cal_xml = gtkpod_builder_xml_new(special_sort_tab_page_get_glade_file(page));
gtk_builder_connect_signals (cal_xml, NULL);
cal = gtkpod_builder_xml_get_widget(cal_xml, "calendar_window");
g_object_set_data(G_OBJECT(cal), CAL_XML, cal_xml);
g_object_set_data(G_OBJECT(cal), SPECIAL_PAGE, page);
/* Set to saved size */
defx = prefs_get_int("size_cal.x");
defy = prefs_get_int("size_cal.y");
gtk_window_set_default_size(GTK_WINDOW (cal), defx, defy);
/* Set sorttab number */
w = gtkpod_builder_xml_get_widget(cal_xml, "sorttab_num_spin");
gtk_spin_button_set_range(GTK_SPIN_BUTTON (w), 1, sort_tab_widget_get_max_index());
gtk_spin_button_set_value(GTK_SPIN_BUTTON (w), sort_tab_widget_get_instance(parent));
/* Set Category-Combo */
w = gtkpod_builder_xml_get_widget(cal_xml, "cat_combo");
switch (item) {
case T_TIME_PLAYED:
index = CAT_STRING_PLAYED;
break;
case T_TIME_MODIFIED:
index = CAT_STRING_MODIFIED;
break;
case T_TIME_ADDED:
index = CAT_STRING_ADDED;
break;
default:
fprintf(stderr, "Programming error: cal_open_calendar() -- item not found\n");
break;
}
gtk_combo_box_set_active(GTK_COMBO_BOX (w), index);
/* Make sure we use the current contents of the entry */
special_sort_tab_page_store_state(page);
/* set calendar */
ti = special_sort_tab_page_update_date_interval(page, item, TRUE);
/* set the calendar if we have a valid TimeInfo */
if (ti) {
if (!ti->valid) { /* set to reasonable default */
ti->lower = 0;
ti->upper = 0;
}
/* Lower Margin */
w = gtkpod_builder_xml_get_widget(cal_xml, "no_lower_margin");
g_signal_connect (w,
"toggled",
G_CALLBACK (cal_no_margin_toggled),
cal);
w = gtkpod_builder_xml_get_widget(cal_xml, "lower_time");
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON (w), TRUE);
g_signal_connect (w,
"toggled",
G_CALLBACK (cal_time_toggled),
cal);
cal_set_time(cal, LOWER_MARGIN, ti->lower);
/* Upper Margin */
w = gtkpod_builder_xml_get_widget(cal_xml, "no_upper_margin");
g_signal_connect (w,
"toggled",
G_CALLBACK (cal_no_margin_toggled),
cal);
w = gtkpod_builder_xml_get_widget(cal_xml, "upper_time");
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON (w), TRUE);
g_signal_connect (w,
"toggled",
G_CALLBACK (cal_time_toggled),
cal);
cal_set_time(cal, UPPER_MARGIN, ti->upper);
}
/* Connect delete-event */
g_signal_connect (cal, "delete_event",
G_CALLBACK (cal_delete_event), cal);
/* Connect cancel-button */
g_signal_connect (gtkpod_builder_xml_get_widget (cal_xml, "cal_cancel"), "clicked",
G_CALLBACK (cal_cancel), cal);
/* Connect apply-button */
g_signal_connect (gtkpod_builder_xml_get_widget (cal_xml, "cal_apply"), "clicked",
G_CALLBACK (cal_apply), cal);
/* Connect ok-button */
g_signal_connect (gtkpod_builder_xml_get_widget (cal_xml, "cal_ok"), "clicked",
G_CALLBACK (cal_ok), cal);
gtk_window_set_transient_for(GTK_WINDOW (cal), GTK_WINDOW (gtkpod_app));
gtk_widget_show(cal);
}
|
zeejuncode/gtkpod
|
plugins/sorttab_display/special_sorttab_page_calendar.c
|
C
|
gpl-2.0
| 16,955
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function last_finder</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../string_algo/reference.html#header.boost.algorithm.string.finder_hpp" title="Header <boost/algorithm/string/finder.hpp>">
<link rel="prev" href="first_finder.html" title="Function first_finder">
<link rel="next" href="nth_finder.html" title="Function nth_finder">
</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="first_finder.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../string_algo/reference.html#header.boost.algorithm.string.finder_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="nth_finder.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.algorithm.last_finder"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Function last_finder</span></h2>
<p>boost::algorithm::last_finder — "Last" finder </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="comment">// In header: <<a class="link" href="../../string_algo/reference.html#header.boost.algorithm.string.finder_hpp" title="Header <boost/algorithm/string/finder.hpp>">boost/algorithm/string/finder.hpp</a>>
</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> RangeT<span class="special">></span> <span class="emphasis"><em><span class="identifier">unspecified</span></em></span> <span class="identifier">last_finder</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">RangeT</span> <span class="special">&</span> Search<span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> RangeT<span class="special">,</span> <span class="keyword">typename</span> PredicateT<span class="special">></span>
<span class="emphasis"><em><span class="identifier">unspecified</span></em></span> <span class="identifier">last_finder</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">RangeT</span> <span class="special">&</span> Search<span class="special">,</span> <span class="identifier">PredicateT</span> Comp<span class="special">)</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="id3219774"></a><h2>Description</h2>
<p>Construct the <code class="computeroutput">last_finder</code>. The finder searches for the last occurrence of the string in a given input. The result is given as an <code class="computeroutput">iterator_range</code> delimiting the match.</p>
<p>
</p>
<div class="variablelist"><table border="0">
<col align="left" valign="top">
<tbody>
<tr>
<td><p><span class="term">Parameters:</span></p></td>
<td><div class="variablelist"><table border="0">
<col align="left" valign="top">
<tbody><tr>
<td><p><span class="term"><code class="computeroutput">Search</code></span></p></td>
<td><p>A substring to be searched for. </p></td>
</tr></tbody>
</table></div></td>
</tr>
<tr>
<td><p><span class="term">Returns:</span></p></td>
<td><p>An instance of the <code class="computeroutput">last_finder</code> object </p></td>
</tr>
</tbody>
</table></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 © 2002-2004 Pavol Droba<p>Use, modification and distribution is subject to the Boost
Software License, Version 1.0. (See accompanying file
<code class="filename">LICENSE_1_0.txt</code> 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="first_finder.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../string_algo/reference.html#header.boost.algorithm.string.finder_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="nth_finder.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
|
phra/802_21
|
boost_1_49_0/doc/html/boost/algorithm/last_finder.html
|
HTML
|
gpl-2.0
| 5,657
|
#
# Makefile for misc devices that really don't fit anywhere else.
#
#include $(srctree)/drivers/misc/mediatek/Makefile.custom
obj-y +=B55027X2NA.o
|
pro4tlzz/P9000-Kernel
|
drivers/misc/mediatek/lcm/B55027X2NA/Makefile
|
Makefile
|
gpl-2.0
| 153
|
<!doctype html>
<!--[if lt IE 7 ]> <html lang="en" class="no-js ie ie6"> <![endif]-->
<!--[if IE 7 ]> <html lang="en" class="no-js ie ie7"> <![endif]-->
<!--[if IE 8 ]> <html lang="en" class="no-js ie ie8"> <![endif]-->
<!--[if IE 9 ]> <html lang="en" class="no-js ie ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html lang="en" class="no-js"> <!--<![endif]-->
<head>
<title>View.js — Examples</title>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<script src="jquery.min.js"></script>
<script src="../view.min.js?auto"></script>
<style>
code{
font-family: Lucida Console, Monaco, Andale Mono,"MS Gothic", monospace;
white-space: pre;
font-size:0.9em;
}
body{
font-family: Helvetica Neue, Helvetica, Arial, sans;
padding: 20px;
}
</style>
<link rel="stylesheet" href="alt2.css">
</head>
<body>
<h1>View.js Examples</h1>
<h2>One photo</h2>
<a href="office_m.jpg" class="view">
View it!
</a>
<p>The Code</p>
<pre><code><a href="office_m.jpg" class="view">...</a></code></pre>
<h2>Photosets</h2>
<a href="http://view-js.s3.amazonaws.com/img/dave_hill/office.jpg" class="view" rel="adventure" title="Caption 1">
Image 1
</a>
<br/>
<a href="http://view-js.s3.amazonaws.com/img/dave_hill/cliff.jpg" class="view" rel="adventure" title="Caption for Image 2">
Image 2
</a>
<br/>
<a href="http://view-js.s3.amazonaws.com/img/dave_hill/threat.jpg" class="view" rel="adventure" title="Caption 3">
Image 3
</a>
<p>The Code</p>
<pre><code><a href="office_m.jpg" class="view" rel="adventure">
Image 1
</a>
<br/>
<a href="battle_m.jpg" class="view" rel="adventure">
Image 2
</a>
<br/>
<a href="threat_m.jpg" class="view" rel="adventure">
Image 3
</a></code></pre>
<p>For more examples, visit the <a href="http://finegoodsmarket.com/view">View website</a>.</p>
</body>
</html>
|
PartidoDeLaRed/pdr-blog
|
wp-content/themes/solar/js/view-js/examples/alt2.html
|
HTML
|
gpl-2.0
| 2,009
|
<?php
/**
* Plugin Options.
*
* @package SCE
*/
namespace SCE\Includes\Admin;
/**
* Class Options
*/
class Options {
/**
* A list of options cached for saving.
*
* @var array $options
*/
private static $options = array();
/**
* Get the options for Simple Comment Editing.
*
* @since 3.0.0
*
* @param bool $force true to retrieve options directly, false to use cached version.
* @param string $key The option key to retrieve.
*
* @return string|array|bool Return a string if key is set, array of options (default), or false if key is set and option is not found.
*/
public static function get_options( $force = false, $key = '' ) {
$options = self::$options;
if ( ! is_array( $options ) || empty( $options ) || true === $force ) {
$options = get_site_option( 'sce_options', array() );
self::$options = $options;
}
if ( false === $options || empty( $options ) || ! is_array( $options ) ) {
$options = self::get_defaults();
} else {
$options = wp_parse_args( $options, self::get_defaults() );
}
self::$options = $options;
// Return a key if set.
if ( ! empty( $key ) ) {
if ( isset( $options[ $key ] ) ) {
return $options[ $key ];
} else {
return false;
}
}
return self::$options;
}
/**
* Save options for the plugin.
*
* @param array $options array of options.
*/
public static function update_options( $options = array() ) {
foreach ( $options as $key => &$option ) {
switch ( $key ) {
case 'timer':
$timer = absint( $options[ $key ] );
if ( 0 === $timer ) {
$timer = 5;
}
$option = $timer;
break;
case 'show_icons':
$show_icons = filter_var( $options[ $key ], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE );
if ( null === $show_icons || false === $show_icons ) {
$option = false;
} else {
$option = true;
}
break;
default:
$option = sanitize_text_field( $options[ $key ] );
break;
}
}
if ( \Simple_Comment_Editing::is_multisite() ) {
update_site_option( 'sce_options', $options );
} else {
update_option( 'sce_options', $options );
}
}
/**
* Get the default options for Simple Comment Editing.
*
* @since 3.0.0
*/
private static function get_defaults() {
$defaults = array(
'timer' => 5,
'timer_appearance' => 'words',
'button_theme' => 'default',
'show_icons' => false,
);
/**
* Allow other plugins to add to the defaults.
*
* @since 3.0.0
*
* @param array $defaults An array of option defaults.
*/
$defaults = apply_filters( 'sce_options_defaults', $defaults );
return $defaults;
}
}
|
MinnPost/minnpost-wordpress
|
wp-content/plugins/simple-comment-editing/includes/admin/class-options.php
|
PHP
|
gpl-2.0
| 2,691
|
/*
* SR.java
*
* Created on 19.03.2006, 15:06
*
* Copyright (c) 2005-2008, Eugene Stahov (evgs), http://bombus-im.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.
*
* You can also redistribute and/or modify this program under the
* terms of the Psi License, specified in the accompanied COPYING
* file, as published by the Psi Project; either dated January 1st,
* 2005, 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package locale;
import Client.Config;
import java.util.Hashtable;
import util.StringLoader;
public class SR {
private static Hashtable lang;
public static String MS_JID = loadString("Jid");
public static String MS_PRIVACY_LISTS = loadString("Privacy Lists");
public static String MS_MESSAGE_FONT = loadString("Message font");
public static String MS_ROSTER_FONT = loadString("Roster font");
public static String MS_PASTE_BODY = loadString("Paste Body");
public static String MS_CONFIG_ROOM = loadString("Configure Room");
public static String MS_PASTE_SUBJECT = loadString("Paste Subject");
public static String MS_DISCO = loadString("Service Discovery");
public static String MS_USER_JID = loadString("User JID");
public static String MS_NEW_LIST = loadString("New list");
public static String MS_DEFAULT = loadString("Default");
public static String MS_PRIVACY_RULE = loadString("Privacy rule");
public static String MS_SSL = loadString("Use SSL");
public static String MS_MODIFY = loadString("Modify");
public static String MS_UPDATE = loadString("Update");
public static String MS_ACCOUNT_NAME = loadString("Account name");
public static String MS_GMT_OFFSET = loadString("GMT offset");
public static String MS_TIME_SETTINGS = loadString("Time settings (hours)");
public static String MS_CONNECTED = loadString("Connected");
public static String MS_CONNECT_TO_ = loadString("Connect to ");
public static String MS_ALERT_PROFILE = loadString("Alert Profile");
public static String MS_MOVE_UP = loadString("Move Up");
public static String MS_OWNERS = loadString("Owners");
public static String MS_OK = loadString("Ok");
public static String MS_APP_MINIMIZE = loadString("Minimize");
public static String MS_ROOM = loadString("Room");
public static String MS_MESSAGES = loadString("Messages");
public static String MS_REFRESH = loadString("Refresh");
public static String MS_RESOLVE_NICKNAMES = loadString("Resolve Nicknames");
public static String MS_PRIVACY_ACTION = loadString("Action");
public static String MS_BAN = loadString("Ban");
public static String MS_LEAVE_ROOM = loadString("Leave Room");
public static String MS_PASSWORD = loadString("Password");
public static String MS_ITEM_ACTIONS = loadString("Actions >");
public static String MS_ACTIVATE = loadString("Activate");
public static String MS_AFFILIATION = loadString("Affiliation");
public static String MS_ACCOUNTS = loadString("Accounts");
public static String MS_DELETE_LIST = loadString("Delete list");
public static String MS_ACCOUNT_ = loadString("Account >");
public static String MS_SELECT = loadString("Select");
public static String MS_SUBJECT = loadString("Subject");
//public static String MS_GROUP_MENU = loadString( "Group menu" );
public static String MS_APP_QUIT = loadString("Quit");
public static String MS_EDIT_LIST = loadString("Edit list");
public static String MS_REGISTERING = loadString("Registering");
public static String MS_DONE = loadString("Done");
public static String MS_ERROR_ = loadString("Error: ");
public static String MS_BROWSE = loadString("Browse");
public static String MS_SAVE_LIST = loadString("Save list");
public static String MS_KEEPALIVE_PERIOD = loadString("Keep-Alive period");
public static String MS_NEWGROUP = loadString("<New Group>");
public static String MS_SEND = loadString("Send");
public static String MS_PRIORITY = loadString("Priority");
public static String MS_FAILED = loadString("Failed");
public static String MS_SET_PRIORITY = loadString("Set Priority");
public static String MS_DELETE_RULE = loadString("Delete rule");
public static String MS_IGNORE_LIST = loadString("Ignore-List");
public static String MS_ROSTER_REQUEST = loadString("Roster request");
public static String MS_PRIVACY_TYPE = loadString("Type");
public static String MS_NAME = loadString("Name");
public static String MS_USERNAME = loadString("Username");
public static String MS_FULLSCREEN = loadString("Fullscreen");
public static String MS_ADD_BOOKMARK = loadString("Add bookmark");
public static String MS_CONFERENCES_ONLY = loadString("Conferences only");
public static String MS_CLIENT_INFO = loadString("Client Version");
public static String MS_DISCARD = loadString("Discard Search");
public static String MS_SEARCH_RESULTS = loadString("Search Results");
public static String MS_GENERAL = loadString("General");
public static String MS_MEMBERS = loadString("Members");
public static String MS_ADD_CONTACT = loadString("Add Contact");
public static String MS_SUBSCRIPTION = loadString("Subscription");
public static String MS_STATUS_MENU = loadString("Status >");
public static String MS_JOIN = loadString("Join");
public static String MS_STARTUP_ACTIONS = loadString("Startup actions");
public static String MS_SERVER = loadString("Server");
public static String MS_ADMINS = loadString("Admins");
public static String MS_MK_ILIST = loadString("Make Ignore-List");
public static String MS_OPTIONS = loadString("Options");
public static String MS_DELETE = loadString("Delete");
public static String MS_DELETE_ASK = loadString("Delete contact?");
public static String MS_SUBSCRIBE = loadString("Authorize");
public static String MS_NICKNAMES = loadString("Nicknames");
public static String MS_ADD_ARCHIVE = loadString("To archive");
public static String MS_BACK = loadString("Back");
public static String MS_HEAP_MONITOR = loadString("Heap monitor");
public static String MS_MESSAGE = loadString("Message");
public static String MS_OTHER = loadString("<Other>");
public static String MS_HISTORY = loadString("History");
public static String MS_APPEND = loadString("Append");
public static String MS_ACTIVE_CONTACTS = loadString("Active Contacts");
public static String MS_SELECT_NICKNAME = loadString("Select nickname");
public static String MS_GROUP = loadString("Group");
public static String MS_JOIN_CONFERENCE = loadString("Join conference");
public static String MS_NO = loadString("No");
public static String MS_REENTER = loadString("Re-Enter Room");
public static String MS_NEW_MESSAGE = loadString("New Message");
public static String MS_ADD = loadString("Add");
public static String MS_LOGON = loadString("Logon");
public static String MS_STANZAS = loadString("Stanzas");
public static String MS_AT_HOST = loadString("at Host");
public static String MS_AUTO_CONFERENCES = loadString("Join conferences");
public static String MS_STATUS = loadString("Status");
public static String MS_SMILES_TOGGLE = loadString("Smiles");
public static String MS_CONTACT = loadString("Contact >");
public final static String MS_SLASHME = "/me";
public static String MS_OFFLINE_CONTACTS = loadString("Offline contacts");
public static String MS_TRANSPORT = loadString("Transport");
public static String MS_COMPOSING_EVENTS = loadString("Composing events");
public static String MS_ADD_SMILE = loadString("Add Smile");
public static String MS_NICKNAME = loadString("Nickname");
public static String MS_REVOKE_VOICE = loadString("Revoke Voice");
public static String MS_NOT_IN_LIST = loadString("Not-in-list");
public static String MS_COMMANDS = loadString("Commands");
public static String MS_CHSIGN = loadString("- (Sign)");
public static String MS_BANNED = loadString("Outcasts (Ban)");
public static String MS_SET_AFFILIATION = loadString("Set affiliation to");
public static String MS_REGISTER_ACCOUNT = loadString("Register Account");
public static String MS_AUTOLOGIN = loadString("Autologin");
public static String MS_LOGOFF = loadString("Logoff");
public static String MS_PUBLISH = loadString("Publish");
public static String MS_SUBSCR_REMOVE = loadString("Remove subscription");
public static String MS_SET = loadString("Set");
public static String MS_APPLICATION = loadString("Application");
public static String MS_BOOKMARKS = loadString("Bookmarks");
public static String MS_TEST_SOUND = loadString("Test sound");
public static String MS_STARTUP = loadString("Startup");
public static String MS_EDIT_RULE = loadString("Edit rule");
public static String MS_CANCEL = loadString("Cancel");
public static String MS_CLOSE = loadString("Close");
public static String MS_ARCHIVE = loadString("Archive");
public static String MS_CONFERENCE = loadString("Conference");
public static String MS_SOUND = loadString("Sound");
public static String MS_LOGIN_FAILED = loadString("Login failed");
public static String MS_DISCOVER = loadString("Browse"); //"Discover"
public static String MS_NEW_JID = loadString("New Jid");
public static String MS_PLAIN_PWD = loadString("Plain-text password");
public static String MS_PASTE_NICKNAME = loadString("Paste Nickname");
public static String MS_KICK = loadString("Kick");
public static String MS_CLEAR_LIST = loadString("Remove readed");
public static String MS_GRANT_VOICE = loadString("Grant Voice");
public static String MS_MOVE_DOWN = loadString("Move Down");
public static String MS_QUOTE = loadString("Quote");
public static String MS_ROSTER_ELEMENTS = loadString("Roster elements");
public static String MS_ENABLE_POPUP = loadString("Popup from background");
public static String MS_SMILES = loadString("Smiles");
public static String MS_ABOUT = loadString("About");
public static String MS_RESOURCE = loadString("Resource");
public static String MS_DISCONNECTED = loadString("Disconnected");
public static String MS_EDIT = loadString("Edit");
public static String MS_HOST_IP = loadString("Host name/IP (optional)");
public static String MS_ADD_RULE = loadString("Add rule");
public static String MS_PASTE_JID = loadString("Paste Jid");
public static String MS_GOTO_URL = loadString("Goto URL");
public static String MS_CLOCK_OFFSET = loadString("Clock offset");
public static String MS_YES = loadString("Yes");
public static String MS_SUSPEND = loadString("Suspend");
public static String MS_ALERT_PROFILE_CMD = loadString("Alert Profile >");
public static String MS_MY_VCARD = loadString("My vCard");
public static String MS_TRANSPORTS = loadString("Transports");
public static String MS_NEW_ACCOUNT = loadString("New Account");
public static String MS_SELF_CONTACT = loadString("Self-contact");
public static String MS_VCARD = loadString("vCard");
public static String MS_SET_SUBJECT = loadString("Set Subject");
public static String MS_TOOLS = loadString("Tools");
public static String MS_PORT = loadString("Port");
public static String MS_RESUME = loadString("Resume");
public static String MS_ARE_YOU_SURE_WANT_TO_DISCARD = loadString("Are You sure want to discard ");
public static String MS_FROM_OWNER_TO = loadString(" from OWNER to ");
public static String MS_MODIFY_AFFILIATION = loadString("Modify affiliation");
public static String MS_CLEAR = loadString("Clear");
public static String MS_SELLOGIN = loadString("Connect");
public static String MS_UNAFFILIATE = loadString("Unaffiliate");
public static String MS_GRANT_MODERATOR = loadString("Grant Moderator");
public static String MS_REVOKE_MODERATOR = loadString("Revoke Moderator");
public static String MS_GRANT_ADMIN = loadString("Grant Admin");
public static String MS_GRANT_OWNERSHIP = loadString("Grant Ownership");
public static String MS_VIZITORS_FORBIDDEN = loadString("Visitors are not allowed to send messages to all occupants");
public static String MS_IS_INVITING_YOU = loadString(" is inviting You to ");
public static String MS_ASK_SUBSCRIPTION = loadString("Ask subscription");
public static String MS_GRANT_SUBSCRIPTION = loadString("Grant subscription");
public static String MS_INVITE = loadString("Invite to conference");
public static String MS_REASON = loadString("Reason");
public static String MS_YOU_HAVE_BEEN_INVITED = loadString("You have been invited to ");
public static String MS_DISCO_ROOM = loadString("Participants");
public static String MS_CAPS_STATE = loadString("Abc");
public static String MS_STORE_PRESENCE = loadString("Room presences");
public static String MS_IS_NOW_KNOWN_AS = loadString(" is now known as ");
public static String MS_WAS_BANNED = loadString(" was banned ");
public static String MS_WAS_KICKED = loadString(" was kicked ");
public static String MS_HAS_BEEN_KICKED_BECAUSE_ROOM_BECAME_MEMBERS_ONLY = loadString(" has been kicked because room became members-only");
public static String MS_HAS_LEFT_CHANNEL = loadString(" has left the channel");
public static String MS_HAS_JOINED_THE_CHANNEL_AS = loadString(" has joined the channel as ");
public static String MS_AND = loadString(" and ");
public static String MS_IS_NOW = loadString(" is now ");
public static String MS_ERROR = loadString("Error");
public static String MS_SELECT_HISTORY_FOLDER = loadString("Choose folder");
//public static String MS_NEW_MENU=loadString("show new menu");
public static String MS_SOUND_VOLUME = loadString("Sound volume");
public static String MS_LANGUAGE = loadString("Language");
public static String MS_SAVE_HISTORY = loadString("Save history");
public static String MS_SAVE_PRESENCES = loadString("Save presences");
public static String MS_SAVE_HISTORY_CONF = loadString("Save conference history");
public static String MS_SAVE_PRESENCES_CONF = loadString("Save conference presences");
public static String MS_1251_CORRECTION = loadString("Convert to cp1251");
public static String MS_HISTORY_FOLDER = loadString("History folder");
public static String MS_COPY = loadString("Copy");
public static String MS_PASTE = loadString("Paste");
public static String MS_SAVE_TEMPLATE = loadString("Save template");
public static String MS_TEMPLATE = loadString("Template");
public static String MS_HAS_SET_TOPIC_TO = loadString("has set topic to");
public static String MS_SEEN = loadString("Seen");
public static String MS_IDLE = loadString("Idle");
public static String MS_MAIN_MENU = loadString("Main menu");
public static String MS_CHOOSE_STATUS = loadString("Choose status");
public static String MS_ADD_STATUS = loadString("Add status");
public static String MS_REMOVE_STATUS = loadString("Remove status");
public static String MS_ADRESS = loadString("Address");
public static String MS_EXPORT_TO_FILE = loadString("Make BackUp");
public static String MS_IMPORT_TO_FILE = loadString("Import from BackUp");
public static String MS_VIEW = loadString("View");
public static String MS_STOP = loadString("Stop");
public static String MS_FILE_TRANSFERS = loadString("File transfers");
//#ifdef FILE_TRANSFER
//# public static String MS_PATH = loadString("Path");
//# public static String MS_ACCEPT_FILE = loadString("Accept file");
//# public static String MS_FILE = loadString("File");
//# public static String MS_SAVE_TO = loadString("Save To");
//# public static String MS_SENDER = loadString("Sender");
//# public static String MS_REJECTED = loadString("Rejected");
//# public static String MS_SEND_FILE = loadString("Send file");
//# public static String MS_CANT_OPEN_FILE = loadString("Can't open file");
//#endif
public static String MS_NEW = loadString("New");
public static String MS_NEW_TEMPLATE = loadString("New Template");
public static String MS_SAVE_PHOTO = loadString("Save photo");
//#ifdef COLOR_TUNE
//# public static String MS_BALLOON_INK = loadString("balloon ink");
//# public static String MS_BALLOON_BGND = loadString("balloon background");
//# public static String MS_LIST_BGND = loadString("messagelist & roster background");
//# public static String MS_LIST_BGND_EVEN = loadString("messagelist & roster even lines");
//# public static String MS_LIST_INK = loadString("messagelist & roster & common font");
//# public static String MS_MSG_SUBJ = loadString("Nick color");
//# public static String MS_MSG_HIGHLIGHT = loadString("message highlight");
//# public static String MS_DISCO_CMD = loadString("service discovery commands");
//# public static String MS_BAR_BGND = loadString("panels background");
//# public static String MS_BAR_INK = loadString("header font");
//# public static String MS_CONTACT_DEFAULT = loadString("contact default");
//# public static String MS_CONTACT_CHAT = loadString("contact chat");
//# public static String MS_CONTACT_AWAY = loadString("contact away");
//# public static String MS_CONTACT_XA = loadString("contact extended away");
//# public static String MS_CONTACT_DND = loadString("contact do not disturb");
//# public static String MS_GROUP_INK = loadString("group color");
//# public static String MS_BLK_INK = loadString("keylock font");
//# public static String MS_BLK_BGND = loadString("keylock background");
//# public static String MS_MESSAGE_IN = loadString("message incoming");
//# public static String MS_MESSAGE_OUT = loadString("message outgoing");
//# public static String MS_MESSAGE_PRESENCE = loadString("message presence");
//# public static String MS_MESSAGE_AUTH = loadString("message auth");
//# public static String MS_MESSAGE_HISTORY = loadString("message history");
//# public static String MS_PGS_REMAINED = loadString("progress bar remained");
//# public static String MS_PGS_COMPLETE = loadString("progress bar complete");
//# public static String MS_PGS_INK = loadString("progress bar font");
//# public static String MS_HEAP_TOTAL = loadString("Heap mon total");
//# public static String MS_HEAP_FREE = loadString("Heap mon free");
//# public static String MS_CURSOR_BGND = loadString("Cursor background");
//# public static String MS_CURSOR_OUTLINE = loadString("Cursor ink & outline");
//# public static String MS_SCROLL_BRD = loadString("Scroll border");
//# public static String MS_SCROLL_BAR = loadString("Scroll bar");
//# public static String MS_SCROLL_BGND = loadString("Scroll back");
//# public static String MS_MESSAGE_IN_S = loadString("other message incoming");
//# public static String MS_MESSAGE_OUT_S = loadString("other message outgoing");
//# public static String MS_MESSAGE_PRESENCE_S = loadString("other message presence");
//# public static String MS_POPUP_MESSAGE = loadString("Popup font");
//# public static String MS_POPUP_MESSAGE_BGND = loadString("Popup background");
//# public static String MS_POPUP_SYSTEM = loadString("Popup system font");
//# public static String MS_POPUP_SYSTEM_BGND = loadString("Popup system background");
//# public static String MS_CONTACT_STATUS = loadString("Contact status font");
//# public static String MS_CONTROL_ITEM = loadString("Control color");
//#endif
public static String MS_COLOR_TUNE = loadString("Color tune");
public static String MS_LOAD_SKIN = loadString("Load Scheme");
public static String MS_SOUNDS_OPTIONS = loadString("Sounds options");
public static String MS_TIME = loadString("Time");
public static String MS_ROLE_PARTICIPANT = loadString("participant");
public static String MS_ROLE_MODERATOR = loadString("moderator");
public static String MS_ROLE_VISITOR = loadString("visitor");
public static String MS_AFFILIATION_NONE = loadString("none");
public static String MS_AFFILIATION_MEMBER = loadString("member");
public static String MS_AFFILIATION_ADMIN = loadString("admin");
public static String MS_AFFILIATION_OWNER = loadString("owner");
public static String MS_SEC3 = loadString("second's");
public static String MS_SEC2 = loadString("seconds");
public static String MS_SEC1 = loadString("second");
public static String MS_MIN3 = loadString("minute's");
public static String MS_MIN2 = loadString("minutes");
public static String MS_MIN1 = loadString("minute");
public static String MS_HOUR3 = loadString("hour's");
public static String MS_HOUR2 = loadString("hours");
public static String MS_HOUR1 = loadString("hour");
public static String MS_DAY3 = loadString("day's");
public static String MS_DAY2 = loadString("days");
public static String MS_DAY1 = loadString("day");
public static String MS_AWAY_PERIOD = loadString("Minutes before away");
public static String MS_AWAY_TYPE = loadString("Automatic Away");
public static String MS_AWAY_OFF = loadString("disabled");
public static String MS_AWAY_LOCK = loadString("keyblock");
public static String MS_MESSAGE_LOCK = loadString("by message");
public static String MS_AUTOSTATUS = loadString("AutoStatus");
public static String MS_AUTOSTATUS_TIME = loadString("AutoStatus time (min)");
public static String MS_AUTO_XA = loadString("Auto xa since %t");
public static String MS_AUTO_AWAY = loadString("Auto away since %t");
public static String MS_AUTOFOCUS = loadString("Autofocus");
public static String MS_GRANT_MEMBERSHIP = loadString("Grant Membership");
public static String MS_SURE_CLEAR = loadString("Are You sure want to clear messagelist?");
public static String MS_TOKEN = loadString("Google token request");
public static String MS_FEATURES = loadString("Features");
public static String MS_SHOWPWD = loadString("Show password");
public static String MS_NO_VERSION_AVAILABLE = loadString("No client version available");
public static String MS_MSG_LIMIT = loadString("Message limit");
public static String MS_OPENING_STREAM = loadString("Opening stream");
//public final static String MS_SASL_STREAM="SASL handshake";
public static String MS_ZLIB = loadString("Using compression");
public static String MS_AUTH = loadString("Authenticating");
public static String MS_RESOURCE_BINDING = loadString("Resource binding");
public static String MS_SESSION = loadString("Initiating session");
public static String MS_TEXTWRAP = loadString("Text wrapping");
public static String MS_TEXTWRAP_CHARACTER = loadString("by chars");
public static String MS_TEXTWRAP_WORD = loadString("by words");
public static String MS_INFO = loadString("Info");
public static String MS_REPLY = loadString("Reply");
public static String MS_DIRECT_PRESENCE = loadString("Send status");
public static String MS_CONFIRM_BAN = loadString("Are you sure want to BAN this person?");
public static String MS_NO_REASON = loadString("No reason");
public static String MS_RECENT = loadString("Recent");
public static String MS_CAMERASHOT = loadString("Shot");
public static String MS_SELECT_FILE = loadString("Select file");
public static String MS_LOAD_PHOTO = loadString("Load Photo");
public static String MS_CLEAR_PHOTO = loadString("Clear Photo");
public static String MS_CAMERA = loadString("Camera");
public static String MS_HIDE_FINISHED = loadString("Hide finished");
public static String MS_TRANSFERS = loadString("Transfer tasks");
public static String MS_SURE_DELETE = loadString("Are you sure want to delete this message?");
public static String MS_NEW_BOOKMARK = loadString("New conference");
public static String MS_ROOT = loadString("Root");
public static String MS_DECLINE = loadString("Decline");
public static String MS_AUTH_NEW = loadString("Authorize new contacts");
public static String MS_AUTH_AUTO = loadString("[auto-subscribe]");
public static String MS_KEEPALIVE = loadString("Keep-Alive");
public static String MS_HAS_BEEN_UNAFFILIATED_AND_KICKED_FROM_MEMBERS_ONLY_ROOM = loadString(" has been unaffiliated and kicked from members-only room");
public static String MS_RENAME = loadString("Rename");
public static String MS_MOVE = loadString("Move");
public static String MS_SAVE = loadString("Save");
//#ifdef DETRANSLIT
//# public static String MS_TRANSLIT = loadString("Translit");
//# public static String MS_DETRANSLIT = loadString("ReTranslit");
//# public static String MS_AUTODETRANSLIT = loadString("Auto translit2Cyr");
//#endif
public static String MS_CHECK_UPDATE = loadString("Check Updates");
public static String MS_SHOW_RESOURCES = loadString("Show Resources");
public static String MS_COLLAPSED_GROUPS = loadString("Collapsed groups");
public static String MS_SEND_BUFFER = loadString("Send Buffer");
public static String MS_CHANGE_NICKNAME = loadString("Change nickname");
public static String MS_MESSAGE_COLLAPSE_LIMIT = loadString("Message collapse limit");
public static String MS_MESSAGE_WIDTH_SCROLL_2 = loadString("Scroll width");
public static String MS_WITH_SYSTEM_GC = loadString("Memory cleaning");
public static String MS_AUTOCLEAN_GROUPS = loadString("Auto clean groups");
public static String MS_NO_CLIENT_INFO = loadString("No client info");
public static String MS_CLEAN_ALL_MESSAGES = loadString("Delete all messages");
public static String MS_DO_AUTOJOIN = loadString("Join marked (auto)");
public static String MS_STATS = loadString("Statistics");
public static String MS_STARTED = loadString("Started: ");
public static String MS_TRAFFIC_STATS = loadString("Traffic stats: ");
public static String MS_ALL = loadString("All: ");
public static String MS_CURRENT = loadString("Current: ");
public static String MS_LAST_MESSAGES = loadString("Last Messages");
public static String MS_EDIT_JOIN = loadString("Edit/join");
public static String MS_USE_COLOR_SCHEME = loadString("Use this Color scheme");
public static String MS_DELETE_ALL = loadString("Delete All");
//#ifdef FILE_IO
//# public static String MS_HISTORY_OPTIONS = loadString("History options");
//#ifdef DETRANSLIT
//# public static String MS_1251_TRANSLITERATE_FILENAMES = loadString("Filenames transliterate");
//#endif
//# public static String MS_SAVE_CHAT = loadString("Save chat");
//#endif
public static String MS_SHOW_STATUSES = loadString("Show statuses");
public static String MS_SHOW_HARDWARE = loadString("Shared platform info");
public static String MS_DELIVERY = loadString("Delivery events");
public static String MS_NIL_DROP_MP = loadString("Drop all");
public static String MS_NIL_DROP_P = loadString("Receive messages");
public static String MS_NIL_ALLOW_ALL = loadString("Messages & presences");
public static String MS_FONTSIZE_NORMAL = loadString("Normal");
public static String MS_FONTSIZE_SMALL = loadString("Small");
public static String MS_FONTSIZE_LARGE = loadString("Large");
//public static String MS_ALERT_PROFILE_AUTO = loadString( "Auto" );
public static String MS_ALERT_PROFILE_ALLSIGNALS = loadString("All signals");
public static String MS_ALERT_PROFILE_VIBRA = loadString("Vibra");
public static String MS_ALERT_PROFILE_NOSIGNALS = loadString("No signals");
public static String MS_IS_DEFAULT = loadString(" (default)");
public static String MS_QUIT_ASK = loadString("Quit?");
public static String MS_SURE_QUIT = loadString("Are you sure want to Quit?");
public static String MS_CONFIRM_EXIT = loadString("Exit confirmation");
public static String MS_SHOW_LAST_APPEARED_CONTACTS = loadString("Show last appeared contacts");
public static String MS_CUSTOM_KEYS = loadString("Custom keys");
//#ifdef USER_KEYS
//# public static String MS_KEYS_ACTION = loadString("Keys action");
//# public static String MS_ENABLED = loadString("Enabled");
//# public static String MS_KEY = loadString("Key");
//#endif
public static String MS_APPLY = loadString("Apply");
public static String MS_RECONNECT = loadString("Reconnect");
public static String MS_SORT = loadString("Sort list");
public static String MS_FLASHLIGHT = loadString("Turn on light");
public static String MS_CLEAR_POPUPS = loadString("Clear popups");
public static String MS_MESSAGE_COUNT_LIMIT = loadString("Chat history length");
//2007-10-24 voffk
public static String MS_SUBSCRIPTION_REQUEST_FROM_USER = loadString("This user wants to subscribe to your presence");
public static String MS_SUBSCRIPTION_RECEIVED = loadString("You are now authorized");
public static String MS_SUBSCRIPTION_DELETED = loadString("Your authorization has been removed!");
public static String MS_SEND_FILE_TO = loadString("To: ");
public static String MS_FILE_SIZE = loadString("Size:");
public static String MS_SUN = loadString("Sun");
public static String MS_MON = loadString("Mon");
public static String MS_TUE = loadString("Tue");
public static String MS_WED = loadString("Wed");
public static String MS_THU = loadString("Thu");
public static String MS_FRI = loadString("Fri");
public static String MS_SAT = loadString("Sat");
//2007-11-04
public static String MS_SUBSCR_AUTO = loadString("Automatic subscription");
public static String MS_SUBSCR_ASK = loadString("Ask me");
public static String MS_SUBSCR_DROP = loadString("Drop subscription");
public static String MS_SUBSCR_REJECT = loadString("Deny subscription"); //TODO: correct according to RFC
public static String MS_VISIBLE_GROUP = "Visible";
//2007-11-07
public static String MS_SEARCH = loadString("Search");
public static String MS_REGISTER = loadString("Register");
public static String MS_CHECK_GOOGLE_MAIL = loadString("Check Google mail");
//2008-01-18
public static String MS_BLINKING = loadString("Blink");
public static String MS_NOTICES_OPTIONS = loadString("Notices options");
public static String MS_MESSAGE_SOUND = loadString("Message sound");
public static String MS_ONLINE_SOUND = loadString("Online sound");
public static String MS_OFFLINE_SOUND = loadString("Offline sound");
public static String MS_MESSAGE_FOR_ME_SOUND = loadString("\"Message for me\" sound");
public static String MS_COMPOSING_SOUND = loadString("Composing sound");
public static String MS_CONFERENCE_SOUND = loadString("Conference sound");
public static String MS_STARTUP_SOUND = loadString("StartUP sound");
public static String MS_OUTGOING_SOUND = loadString("Outgoing sound");
public static String MS_VIP_SOUND = loadString("Vip sound");
//2008-01-19
public static String MS_COPY_JID = loadString("Copy JID");
public static String MS_PING = loadString("Ping request");
public static String MS_ONLINE_TIME = loadString("Online time");
//2008-01-20
public static String MS_BREAK_CONECTION = loadString("Break connection");
public static String MS_AUTOSCROLL = loadString("AutoScroll");
public static String MS_EMULATE_TABS = loadString("Emulate tabs");
public static String MS_HIDE_TIMESTAMPS = loadString("Hide timestamps in messages");
public static String MS_POPUPS = loadString("PopUps");
public static String MS_USE_MY_STATUS_MESSAGES = loadString("Use my status messages");
public static String MS_MEMORY = loadString("Memory:");
public static String MS_FREE = loadString("Free: ");
public static String MS_TOTAL = loadString("Total: ");
public static String MS_CONN = loadString("Session(s): ");
public static String MS_DESCRIPTION = loadString("Description");
//2008-01-24
public static String MS_USER = loadString("User");
//#if IMPORT_EXPORT
//# public static String MS_IMPORT_EXPORT = loadString("Import/Export");
//#endif
//2008-02-03
public static String MS_BOLD_FONT = loadString("Bold font for contacts");
public static String MS_RUNNING_MESSAGE = loadString("Running message");
public static String MS_COMPOSING_NOTIFY = loadString("Composing message to you");
public static String MS_COMPRESSION = loadString("Compression");
public static String MS_NEW_ROOM_CREATED = loadString("New room created");
public static String MS_IRCLIKESTATUS = loadString("IRC-like conference nick-status");
public static String MS_SIMULATED_BREAK = loadString("Simulated break");
public static String MS_BUILD_NEW = loadString("Build new version on constructor");
public static String MS_DISABLED = loadString("disabled");
public static String MS_LOAD_ROOMLIST = loadString("Browse rooms");
public static String MS_AUTORESPOND = loadString("Autorespond");
public static String MS_INVERT = loadString("Invert colors");
// public static String MS_ENTER_ACCOUNT_SETTINGS = loadString( "Please create account or enter account(s) settings.\n\nMenu, New Account" );
// public static String MS_ENTER_SETTINGS = loadString( "Please enter settings.\n\nMenu, Tools, Options" );
public static String MS_XML_CONSOLE = loadString("XML console");
//#ifdef CLIPBOARD
//# public static String MS_CLIPBOARD = loadString("Clipboard");
//#endif
public static String MS_BAR_FONT = loadString("Bar font");
public static String MS_POPUP_FONT = loadString("Popup & balloon font");
public static String MS_FONTS_OPTIONS = loadString("Fonts options");
public static String MS_LOAD_HISTORY = loadString("Load history");
public static String MS_CONNECT_TO = loadString("Connect to");
public static String MS_SEND_COLOR_SCHEME = loadString("Send my color scheme");
public static String MS_UNREAD_MESSAGES = loadString("Unread messages");
public static String MS_VIBRATE_ONLY_HIGHLITED = loadString("Vibrate only highlited");
public static String MS_EXTENDED_SETTINGS = loadString("Extended settings");
public static String MS_SAVE_TO_FILE = loadString("Save to file");
public static String MS_LOAD_FROM_FILE = loadString("Load from file");
public static String MS_SHOW_IQ_REQUESTS = loadString("Show iq requests");
public static String MS_SHOW_CLIENTS_ICONS = loadString("Show clients icons");
public static String MS_ACTION = loadString("Action");
public static String MS_VALUE = loadString("Value");
public static String MS_RECONNECT_COUNT_RETRY = loadString("Quantity of attempts");
public static String MS_RECONNECT_WAIT = loadString("Delay before reconnect (sec.)");
public static String MS_MENU = loadString("Menu");
//public static String MS_CHANGE=loadString("Change");
public static String MS_NEXT = loadString("Next");
public static String MS_PREVIOUS = loadString("Previous");
public static String MS_PREVIOUS_ = loadString("Previous: ");
public static String MS_END_OF_VCARD = loadString("[End of vCard]");
public static String MS_NO_VCARD = loadString("[No vCard available]");
public static String MS_NO_PHOTO = loadString("[No photo available]");
public static String MS_UNSUPPORTED_FORMAT = loadString("[Unsupported format]");
public static String MS_PHOTO_TOO_LARGE = loadString("[Large photo was dropped]");
public static String MS_DELETE_GROUP_ASK = loadString("Delete group?");
public static String MS_PANELS = loadString("Panels");
public static String MS_NO_BAR = loadString("[ ]");
public static String MS_MAIN_BAR = loadString("[Main bar]");
public static String MS_INFO_BAR = loadString("[Info bar]");
public static String MS_FLASH_BACKLIGHT = loadString("Flash backlight");
public static String MS_EXECUTE_MENU_BY_NUMKEY = loadString("Execute menu by numkey");
public static String MS_SHOW_NACKNAMES = loadString("Show nicknames");
public static String MS_SEND_PHOTO = loadString("Send photo");
public static String MS_ENABLE_AUTORESPOND = loadString("Enable autorespond");
public static String MS_FILE_MANAGER = loadString("File manager");
public static String MS_ADHOC = loadString("Remote control");
public static String MS_USE_DNS_SRV_RESOLVER = loadString("Resolve hostname");
public static String MS_SHOW_TIME_TRAFFIC = loadString("Show time and traffic");
public static String MS_USERS_SEARCH = loadString("Users search");
//#ifdef PEP
//# public static String MS_PEP = loadString("Personal events");
//# public static String MS_RECEIVE_PEP = loadString("Receive events");
//# public static String MS_PUBLISH_PEP = loadString("Publish events");
//# public static String MS_USERMOOD = loadString("User moods");
//# public static String MS_USERTUNE = loadString("User tune");
//# public static String MS_USERACTIVITY = loadString("User activity");
//# public static String MS_USERLOCATION = loadString("User location");
//# public static String MS_LATITUDE = loadString("Latitude");
//# public static String MS_LONGITUDE = loadString("Longitude");
//# public static String MS_LOCATION_NAME = loadString("Location name");
//# public static String MS_LOCATION_DESCRIPTION = loadString("Location description");
//# public static String MS_RETRIEVE_LOCATION = loadString("Retrieve location");
//# public static String MS_SEND_RECEIVE_USERMOODS = loadString("user moods send/receive");
//# public static String MS_PEP_NOT_SUPPORTED = loadString("Personal events not supported");
//#endif
public static String MS_VIP_GROUP = loadString("VIP");
public static String MS_ENABLE_DISABLE = loadString("Enable/Disable");
public static String MS_ONLINE = loadString("Online");
public static String MS_CHAT = loadString("Chat");
public static String MS_AWAY = loadString("Away");
public static String MS_XA = loadString("xa");
public static String MS_INVISIBLE = loadString("Invisible");
public static String MS_DND = loadString("DND");
public static String MS_OFFLINE = loadString("Offline");
public static String MS_USE = loadString("Use");
public static String MS_VERSION = loadString("Version");
//#ifdef JUICK
//# public static String MS_JUICK_FOCUS = loadString("Focus to Juick contact");
//# public static String MS_JUICK_MESSAGE_REPLY = loadString("[J] Reply to message");
//# public static String MS_JUICK_SEND_PRIVATE_REPLY = loadString("[J] Reply to");
//# public static String MS_JUICK_THINGS = loadString("[J] Things");
//# public static String MS_JUICK_MESSAGE_DELETE = loadString("[J] Delete message");
//# public static String MS_JUICK_POST_SUBSCRIBE = loadString("[J] Subscribe to comments");
//# public static String MS_JUICK_POST_UNSUBSCRIBE = loadString("[J] Unsubscribe from comments");
//# public static String MS_JUICK_POST_RECOMMEND = loadString("[J] Recommend post");
//# public static String MS_JUICK_POST_SHOW = loadString("[J] Show post and comments");
//# public static String MS_JUICK_CONTACT_NOT_FOUND = loadString("For work this command you need contact juick@juick.com in you roster. For more information see http://juick.com/help/");
//#endif
public static String MS_STEP_BACK = loadString("Step back");
public static String MS_ITEM_HEIGHT = loadString("Minimal item height");
public static String MS_SINGLE_CLICK = loadString("Single-click interface");
public static String L_CONFIG = loadString("Light config");
public static String L_ENABLED = loadString("Light enabled");
public static String L_IDLE_VALUE = loadString("Light idle value");
public static String L_KEYPRESS_VALUE = loadString("Light keypress value");
public static String L_KEYPRESS_TIMEOUT = loadString("Keypress timeout");
public static String L_MESSAGE_VALUE = loadString("Message value");
public static String L_MESSAGE_TIMEOUT = loadString("Message timeout");
public static String MS_COPY_TOPIC = loadString("Copy topic");
public static String MS_COLLAPSE_ALL = loadString("Collapse all");
private SR() {
}
public static String MS_XMLLANG;
public static String MS_IFACELANG;
private static void loadLang() {
if (lang == null) {
String langFile = Config.getInstance().langFileName();
if (langFile != null) {
lang = new StringLoader().hashtableLoader(langFile);
}
if (lang == null) {
lang = new Hashtable();
}
MS_XMLLANG = (String) lang.get("xmlLang");
MS_IFACELANG = MS_XMLLANG;
if (MS_IFACELANG == null) {
MS_IFACELANG = "en";
MS_XMLLANG = "en";
}
}
}
private static String loadString(String key) {
if (lang == null) {
loadLang();
}
String value = (String) lang.get(key);
//#ifdef LANG_DEBUG
//# if (value==null) {
//# if (!lang.isEmpty()) {
//# System.out.print("-----> Can't find local string for <");
//# System.out.print(key);
//# System.out.println("> <-----");
//# }
//# } else {
//# System.out.print(key);
//# System.out.print('\t');
//# System.out.println(value);
//# }
//#endif
return (value == null) ? key : value;
}
public static String getPresence(String presenceName) {
if (presenceName.equals("online")) {
return MS_ONLINE;
} else if (presenceName.equals("chat")) {
return MS_CHAT;
} else if (presenceName.equals("away")) {
return MS_AWAY;
} else if (presenceName.equals("xa")) {
return MS_XA;
} else if (presenceName.equals("invisible")) {
return MS_INVISIBLE;
} else if (presenceName.equals("dnd")) {
return MS_DND;
} else if (presenceName.equals("unavailable")) {
return MS_OFFLINE;
}
return null;
}
public static void loaded() {
if (lang != null) {
lang.clear();
lang = null;
}
}
}
|
murat8505/BombusMod-xmpp_client
|
src/locale/SR.java
|
Java
|
gpl-2.0
| 43,121
|
#!/bin/bash
#oscap xccdf eval --profile xccdf_com.example_profile_my_profile --remediate --results=testing_results2.xml testing_ds.xml
oscap xccdf eval --datastream-id=scap_org.open-scap_datastream_tst --xccdf-id=scap_org.open-scap_cref_first-xccdf.xml --profile xccdf_com.example_profile_my_profile --remediate --results=testing_results.xml testing_ds.xml
|
OpenSCAP/oscap-anaconda-addon
|
testing_files/run_oscap_test.sh
|
Shell
|
gpl-2.0
| 359
|
//=============================================================================
// MuseScore
// Music Composition & Notation
// $Id:$
//
// Copyright (C) 2011 Werner Schweer
//
// 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 and appearing in
// the file LICENCE.GPL
//=============================================================================
#include "property.h"
#include "mscore.h"
#include "layoutbreak.h"
//---------------------------------------------------------
// PropertyData
//---------------------------------------------------------
struct PropertyData {
P_ID id;
const char* name; // xml name of property
P_TYPE type;
};
//
// always: property[subtype].id == subtype
//
//
static const PropertyData propertyList[] = {
{ P_SUBTYPE, "subtype", T_INT },
{ P_SELECTED, "selected", T_BOOL },
{ P_COLOR, "color", T_COLOR },
{ P_VISIBLE, "visible", T_BOOL },
{ P_SMALL, "small", T_BOOL },
{ P_SHOW_COURTESY, "", T_INT },
{ P_LINE_TYPE, "", T_INT },
{ P_PITCH, "pitch", T_INT },
{ P_TPC, "tpc", T_INT },
{ P_HEAD_TYPE, "headType", T_INT },
{ P_HEAD_GROUP, "head", T_INT },
{ P_VELO_TYPE, "veloType", T_VALUE_TYPE },
{ P_VELO_OFFSET, "velocity", T_INT },
{ P_ARTICULATION_ANCHOR, "", T_INT },
{ P_DIRECTION, "direction", T_DIRECTION },
{ P_STEM_DIRECTION, "StemDirection", T_DIRECTION },
{ P_NO_STEM, "", T_INT },
{ P_SLUR_DIRECTION, "", T_INT },
{ P_LEADING_SPACE, "", T_INT },
{ P_TRAILING_SPACE, "", T_INT },
{ P_DISTRIBUTE, "distribute", T_BOOL },
{ P_MIRROR_HEAD, "mirror", T_DIRECTION_H },
{ P_DOT_POSITION, "dotPosition", T_DIRECTION },
{ P_ONTIME_OFFSET, "onTimeOffset", T_INT },
{ P_OFFTIME_OFFSET, "offTimeOffset", T_INT },
{ P_TUNING, "tuning", T_REAL },
{ P_PAUSE, "pause", T_REAL },
{ P_BARLINE_SPAN, "", T_INT },
{ P_USER_OFF, 0, T_POINT },
{ P_FRET, "fret", T_INT },
{ P_STRING, "string", T_INT },
{ P_GHOST, "ghost", T_BOOL },
{ P_TIMESIG_NOMINAL, 0, T_FRACTION },
{ P_TIMESIG_ACTUAL, 0, T_FRACTION },
{ P_NUMBER_TYPE, "numberType", T_INT },
{ P_BRACKET_TYPE, "bracketType", T_INT },
{ P_NORMAL_NOTES, "normalNotes", T_INT },
{ P_ACTUAL_NOTES, "actualNotes", T_INT },
{ P_P1, "p1", T_POINT },
{ P_P2, "p2", T_POINT },
{ P_GROW_LEFT, "growLeft", T_REAL },
{ P_GROW_RIGHT, "growRight", T_REAL },
{ P_BOX_HEIGHT, "height", T_REAL },
{ P_BOX_WIDTH, "width", T_REAL },
{ P_TOP_GAP, "topGap", T_SREAL },
{ P_BOTTOM_GAP, "bottomGap", T_SREAL },
{ P_LEFT_MARGIN, "leftMargin", T_REAL },
{ P_RIGHT_MARGIN, "rightMargin", T_REAL },
{ P_TOP_MARGIN, "topMargin", T_REAL },
{ P_BOTTOM_MARGIN, "bottomMargin", T_REAL },
{ P_LAYOUT_BREAK, "subtype", T_LAYOUT_BREAK },
{ P_AUTOSCALE, "autoScale", T_BOOL },
{ P_SIZE, "size", T_SIZE },
{ P_SCALE, 0, T_SCALE },
{ P_LOCK_ASPECT_RATIO, "lockAspectRatio", T_BOOL },
{ P_SIZE_IS_SPATIUM, "sizeIsSpatium", T_BOOL },
{ P_TEXT_STYLE, "textStyle", T_INT },
{ P_USER_MODIFIED, 0, T_BOOL },
{ P_BEAM_POS, 0, T_POINT },
{ P_BEAM_MODE, "BeamMode", T_BEAM_MODE },
{ P_USER_LEN, "", T_REAL },
{ P_SPACE, "space", T_REAL },
{ P_TEMPO, "tempo", T_REAL },
{ P_TEMPO_FOLLOW_TEXT, "followText", T_BOOL },
{ P_ACCIDENTAL_BRACKET, "bracket", T_BOOL },
{ P_NUMERATOR_STRING, "textN", T_STRING },
{ P_DENOMINATOR_STRING, "textD", T_STRING },
{ P_SHOW_NATURALS, "showNaturals", T_BOOL },
{ P_BREAK_HINT, "", T_BOOL },
{ P_FBPREFIX, "prefix", T_INT },
{ P_FBDIGIT, "digit", T_INT },
{ P_FBSUFFIX, "suffix", T_INT },
{ P_FBCONTINUATIONLINE, "continuationLine", T_BOOL},
{ P_FBPARENTHESIS1, "", T_INT },
{ P_FBPARENTHESIS2, "", T_INT },
{ P_FBPARENTHESIS3, "", T_INT },
{ P_FBPARENTHESIS4, "", T_INT },
{ P_FBPARENTHESIS5, "", T_INT },
{ P_VOLTA_TYPE, "", T_INT },
{ P_OTTAVA_TYPE, "", T_INT },
{ P_TRILL_TYPE, "", T_INT },
{ P_HAIRPIN_TYPE, "", T_INT },
{ P_VELO_CHANGE, "", T_INT },
{ P_DYNAMIC_RANGE, "dynType", T_INT },
{ P_PLACEMENT, "placement", T_PLACEMENT },
{ P_VELOCITY, "velocity", T_INT },
{ P_END, "", T_INT }
};
//---------------------------------------------------------
// propertyType
//---------------------------------------------------------
P_TYPE propertyType(P_ID id)
{
return propertyList[id].type;
}
//---------------------------------------------------------
// propertyName
//---------------------------------------------------------
const char* propertyName(P_ID id)
{
return propertyList[id].name;
}
//---------------------------------------------------------
// getProperty
//---------------------------------------------------------
QVariant getProperty(P_ID id, XmlReader& e)
{
switch(propertyType(id)) {
case T_BOOL:
return QVariant(bool(e.readInt()));
case T_SUBTYPE:
case T_INT:
return QVariant(e.readInt());
case T_REAL:
case T_SREAL:
return QVariant(e.readDouble());
case T_FRACTION:
return QVariant::fromValue(e.readFraction());
case T_COLOR:
return QVariant(e.readColor());
case T_POINT:
return QVariant(e.readPoint());
case T_SCALE:
case T_SIZE:
return QVariant(e.readSize());
case T_STRING:
return QVariant(e.readElementText());
case T_DIRECTION:
{
QString value(e.readElementText());
if (value == "up")
return QVariant(MScore::UP);
else if (value == "down")
return QVariant(MScore::DOWN);
else if (value == "auto")
return QVariant(MScore::AUTO);
}
break;
case T_DIRECTION_H:
{
QString value(e.readElementText());
if (value == "left")
return QVariant(MScore::DH_LEFT);
else if (value == "right")
return QVariant(MScore::DH_RIGHT);
else if (value == "auto")
return QVariant(MScore::DH_AUTO);
}
break;
case T_LAYOUT_BREAK: {
QString value(e.readElementText());
if (value == "line")
return QVariant(int(LAYOUT_BREAK_LINE));
if (value == "page")
return QVariant(int(LAYOUT_BREAK_PAGE));
if (value == "section")
return QVariant(int(LAYOUT_BREAK_SECTION));
qDebug("getProperty: invalid T_LAYOUT_BREAK: <%s>", qPrintable(value));
}
break;
case T_VALUE_TYPE: {
QString value(e.readElementText());
if (value == "offset")
return QVariant(int(MScore::OFFSET_VAL));
else if (value == "user")
return QVariant(int(MScore::USER_VAL));
}
break;
case T_PLACEMENT: {
QString value(e.readElementText());
if (value == "above")
return QVariant(int(Element::ABOVE));
else if (value == "below")
return QVariant(int(Element::BELOW));
}
break;
case T_BEAM_MODE: // TODO
return QVariant(int(0));
}
return QVariant();
}
|
wschweer/mscoreserver
|
libmscore/property.cpp
|
C++
|
gpl-2.0
| 9,761
|
/* Copyright (C) YOOtheme GmbH, http://www.gnu.org/licenses/gpl.html GNU/GPL */
function selectZooItem(d,c,a){jQuery("#"+a+"_id").val(d);jQuery("#"+a+"_name").val(c);SqueezeBox.close?SqueezeBox.close():$("sbox-window").close()}
(function(d){var c=function(){};d.extend(c.prototype,{name:"ZooApplication",options:{url:null,msgSelectItem:"Select Item"},initialize:function(a,b){this.options=d.extend({},this.options,b);var e=this;this.input=a;this.content_panel=a.closest("div.content");this.app=a.find("select.application");this.categories=a.find("div.categories");this.types=a.find("div.types");this.item=a.find("div.item");var c=a.find("select.mode");if(c.length)this.mode=c.val(),c.bind("change",function(){e.mode=c.val();e.setValues()});
else if(this.categories.length)this.mode="categories";else if(this.types.length)this.mode="types";else if(this.item.length)this.mode="item";this.setValues();this.app.bind("change",function(){e.setValues();e.item.length&&(e.item.find("input:hidden").val(""),e.item.find("input:text").val(e.options.msgSelectItem))});a.delegate("select","change",function(){d(this).closest("div.content").css("height","")});d(a.closest("form")).find("input[id$=mode]:hidden, input[id$=params_type]:hidden, input[id$=params_category]:hidden, input[id$=params_item_id]:hidden").remove()},
setValues:function(){var a=this.app.val();this.categories.length&&(a&&this.mode=="categories"?this.categories.removeClass("hidden"):this.categories.addClass("hidden"),this.input.find("select.category").each(function(){var b=d(this);b.hasClass("app-"+a)?(b.removeClass("hidden"),b.attr("name",b.data("category"))):(b.addClass("hidden"),b.attr("name",""))}));this.types.length&&(a&&this.mode=="types"?this.types.removeClass("hidden"):this.types.addClass("hidden"),this.input.find("select.type").each(function(){var b=
d(this);b.hasClass("app-"+a)?(b.removeClass("hidden"),b.attr("name",b.data("type"))):(b.addClass("hidden"),b.attr("name",""))}));this.item.length&&(a&&this.mode=="item"?this.item.removeClass("hidden"):this.item.addClass("hidden"),this.item.find("a").attr("href",this.options.url+"&app_id="+a))}});d.fn[c.prototype.name]=function(){var a=arguments,b=a[0]?a[0]:null;return this.each(function(){var e=d(this);if(c.prototype[b]&&e.data(c.prototype.name)&&b!="initialize")e.data(c.prototype.name)[b].apply(e.data(c.prototype.name),
Array.prototype.slice.call(a,1));else if(!b||d.isPlainObject(b)){var f=new c;c.prototype.initialize&&f.initialize.apply(f,d.merge([e],a));e.data(c.prototype.name,f)}else d.error("Method "+b+" does not exist on jQuery."+c.name)})}})(jQuery);
|
winder84/JacAuto_old
|
administrator/components/com_zoo/helpers/fields/zooapplication.js
|
JavaScript
|
gpl-2.0
| 2,594
|
<?php
require '../config/config.php';
$year_num = $_POST['year_num'];
$week_num = $_POST['week_num'];
$currency_shortname = '';
$currency_sql = "SELECT shortname FROM currency WHERE set_default=1";
$currency_qry = mysql_query($currency_sql);
$currency_res = mysql_fetch_assoc($currency_qry);
//check if there is an existing lunch menu for the week
$menu_week_sql = "SELECT * FROM menu_lunch WHERE year_for=".$year_num." AND week_no=".$week_num;
$menu_week_qry = mysql_query($menu_week_sql);
$menu_week_num = mysql_num_rows($menu_week_qry);
?>
<style>
.menu_main_description, .course_desc, .course_desc_existing, .additional_course_desc{ width: 795px; height: 150px; }
.warning{ box-shadow: 0 0 10px #F00 !important; outline: none !important; background-color:#FFC !important; }
.additional_course_price, .unit_price_existing{ text-align: right !important; }
</style>
<?php
$save_button_id = 'lunch_meny_save_all';
$menu_week_res = mysql_fetch_assoc($menu_week_qry);
?>
<div style="background-color:#FFC; padding:4px; overflow:hidden;">
<h2 style="float:left;">OBS! Gäller hela vecka <?php echo $week_num; ?> (mån-fre)</h2>
<div style="float:right;"><input type="checkbox" id="allweek" <?php if($menu_week_res['all_in']){ echo 'checked'; } ?> /> Gäller ala veckor.</div>
</div>
<div style="text-align:right; padding:8px 0px;">
<input type="hidden" id="menu_parameter" value="<?php echo 'W '. $year_num.' '.$week_num; ?>" />
<?php
if($menu_week_num>0){
$save_button_id = 'lunch_meny_update_all';
?>
<em>Created on:</em> <?php echo $menu_week_res['time_created']; ?> <em>Last Saved:</em> <?php echo $menu_week_res['last_saved']; ?>
<input type="hidden" id="saved_menu" value="<?php echo $menu_week_res['id']; ?>" />
<?php
}else{
//check if all in weekly menu of the last record is in effect
$sql = "SELECT week_no, year_for, all_in FROM menu_lunch WHERE specific_days='' ORDER BY id DESC LIMIT 1";
$qry = mysql_query($sql);
$num = mysql_num_rows($qry);
?>
<div style="padding:4px; background-color:#FC9; text-align:center;"><font color="red"><strong>* no saved menu for the week
<?php
$res = mysql_fetch_assoc($qry);
if($res['all_in']==1){
echo '<font color="green"> but week <b>'.$res['week_no'].'</b> for year <b>'.$res['year_for'].'</b> is still in effect</font>';
}
?>
*</strong></font></div>
<input type="hidden" id="saved_menu" value="0" />
<?php
}
?>
</div>
Text ovanför menyn: <input name="text" id="text_over_menu" class="" value="<?php echo stripslashes($menu_week_res['note_header']); ?>" style="width:600px;" />
<br /><br />
<div class="menu_description">
Menu Description:
<textarea class="menu_main_description"><?php echo stripslashes($menu_week_res['description']); ?></textarea>
</div>
<div style="float:right; width: 200px; text-align:right;">
<div style="color:#fff; background-color:#090; padding:8px; float:right; width:200px; text-align:center; font-weight:bold; display:none;" id="message">Successfully Saved.</div>
<input type="button" value="Spara allt" class="btn" id="<?php echo $save_button_id; ?>" style="padding:12px; float:right; margin-top:45px;" />
</div>
<div class="menu_items">
<br /><br />
Courses:
<?php
$courses_sql = "SELECT * FROM menu_lunch_items WHERE menu_id=".$menu_week_res['id'];
$courses_qry = mysql_query($courses_sql);
$courses_num = mysql_num_rows($courses_qry);
if($courses_num>0){
while($courses_res = mysql_fetch_assoc($courses_qry)){
?>
<div class="menu_item">
<div class="menu_item_actions">
<img src="images/delete.png" alt="Radera"><br />
Sort/Order<br />
<select>
<option value="">---</option>
<?php
//if($courses_num==0){ $courses_num=10; }
for($c=1; $c<=$courses_num; $c++){
$sel = 0;
if($c==$courses_res['order']){ $sel='selected'; }
?>
<option value="<?php echo $c; ?>"><?php echo $c; ?></option>
<?php
}
?>
</select>
</div>
<div class="menu_item_desc">
<textarea class="course_desc_existing" id="e_<?php echo $courses_res['id']; ?>"><?php echo stripslashes($courses_res['description']); ?></textarea>
</div>
Pris:
<input type="text" class="unit_price_existing" value="<?php echo $courses_res['price']; ?>" id="course_price_existing_<?php echo $courses_res['id']; ?>" data-rel="<?php echo $courses_res['id']; ?>" /> <?php echo $currency_res['shortname']; ?>
</div>
<?php
}//looping thru courses for this menu
}else{
?>
<div class="menu_item" id="additional_course_'+add_count+'"><div class="menu_item_actions"><br /></div><div class="menu_item_desc"><textarea class="additional_course_desc" id="additionalTextarea_0"></textarea></div>Pris:<input type="text" class="additional_course_price" id="additional_course_price_0" /> <?php echo $currency_res['shortname']; ?></div>
<?php
}
?>
<div id="menu_items_additional"></div>
<input type="button" id="add_course" value="+ Add Course" />
<br /><br /><br />
Text nedanför menyn: <input name="text" id="text_after_menu" value="<?php echo stripslashes($menu_week_res['note_footer']); ?>" style="width:600px;" />
</div>
<script>
var add_count = 0;
$('#add_course').on('click', function (e) {
add_count+=1;
$( "#menu_items_additional" ).append('<div class="menu_item" id="additional_course_'+add_count+'"><div class="menu_item_actions"><img src="images/delete.png" alt="Radera" onClick="remove_additional_course('+add_count+')"><br /></div><div class="menu_item_desc"><textarea class="additional_course_desc" id="additionalTextarea_'+add_count+'" style="width: 795px; height: 150px;"></textarea></div>Pris:<input type="text" class="additional_course_price" id="additional_course_price_'+add_count+'" /> <?php echo $currency_res['shortname']; ?></div>');
});
function remove_additional_course(id){
$( "#additional_course_"+id ).remove();
}
$('#lunch_meny_update_all').on('click', function (e) {
var menu_id = $('#saved_menu').val();
var menu_parameter = $('#menu_parameter').val();
var errors = 0;
//***variable
var allweek=0;
if($('#allweek').prop('checked')){ allweek=1; }
var text_over_menu = $('#text_over_menu').val().trim();
if(text_over_menu==''){
errors++;
$('#text_over_menu').addClass('warning');
}else{
$('#text_over_menu').removeClass('warning');
}
//***variable
var menu_main_description = $('.menu_main_description').val().trim();
if(menu_main_description==''){
errors++;
$('.menu_main_description').addClass('warning');
}else{
$('.menu_main_description').removeClass('warning');
}
var items = '';
var existing_courses = '';
var existing_prices = '';
var existing_separator = '';
var cnt=0;
$(".course_desc_existing").each(function(){
var val_desc = $(this).val().trim();
var id = $(this).attr('id');
var id_data = id.split('_');
var price = $('#course_price_existing_'+id_data[1]).val();
if($('.course_desc_existing').length>1 && cnt>0){
existing_separator = '<^>';
}
items = items+existing_separator+id_data[1];
if(price>0){
$('#course_price_existing_'+id_data[1]).removeClass('warning');
existing_prices = existing_prices+existing_separator+price;
}else{
errors++;
$('#course_price_existing_'+id_data[1]).addClass('warning');
$(this).addClass('warning');
}
if(val_desc==''){
errors++;
$(this).addClass('warning');
}else{
$(this).removeClass('warning');
existing_courses = existing_courses+existing_separator+val_desc;
}
cnt++;
});
var courses = '';
var prices = '';
var separator = '';
var cnt=0;
$(".additional_course_desc").each(function(){
var val_desc = $(this).val().trim();
var id = $(this).attr('id');
var id_data = id.split('_');
var price = $('#additional_course_price_'+id_data[1]).val();
if($(".additional_course_desc").length && cnt>0){
separator = '<^>';
}
if(price>0){
$('#additional_course_price_'+id_data[1]).removeClass('warning');
prices = prices+separator+price;
}else{
errors++;
$('#additional_course_price_'+id_data[1]).addClass('warning');
$(this).addClass('warning');
}
if(val_desc==''){
errors++;
$(this).addClass('warning');
}else{
$(this).removeClass('warning');
courses = courses+separator+val_desc;
}
cnt++;
});
var text_after_menu = $('#text_after_menu').val().trim();
if(text_after_menu==''){
errors++;
$('#text_after_menu').addClass('warning');
}else{
$('#text_after_menu').removeClass('warning');
}
//alert('id:'+menu_id+',all_week:'+allweek+',menu_parameter:'+menu_parameter+',header_text:'+text_over_menu+',menu_description:'+menu_main_description+',courses:'+courses+',prices:'+prices+',e_courses:'+existing_courses+',e_prices:'+existing_prices+',e_items:'+items+',text_after_menu:'+text_after_menu);
//return false;
if(errors>0){
alert('Some required fields are empty, they are highlighted with red color.');
}else{
var menu_parameter = $('#menu_parameter').val();
$.post( "actions/menu_lunch_update.php", {
id:menu_id,
all_week:allweek,
menu_parameter: menu_parameter,
header_text: text_over_menu,
menu_description: menu_main_description,
courses: courses,
prices: prices,
e_courses: existing_courses,
e_prices: existing_prices,
e_items:items,
text_after_menu: text_after_menu
})
.done(function( data ){
var resulta = data.split('|');
//alert('Result: '+resulta[1]);
if(resulta[0]==1){
var menu_params = menu_parameter.split(' ');
$.post( "pages/menu_lunch.php", { year_num: menu_params[1], week_num: menu_params[2] })
.done(function( data_load ) {
$( ".menu_main_box").html(data_load);
$("#message").fadeIn('slow');
setTimeout(
function()
{
$("#message").fadeOut('slow');
}, 10000
);
});
}
});
}
});
$('#lunch_meny_save_all').on('click', function (e) {
var errors = 0;
//***variable
var allweek=0;
if($('#allweek').prop('checked')){ allweek=1; }
var text_over_menu = $('#text_over_menu').val().trim();
if(text_over_menu==''){
errors++;
$('#text_over_menu').addClass('warning');
}else{
$('#text_over_menu').removeClass('warning');
}
//***variable
var menu_main_description = $('.menu_main_description').val().trim();
if(menu_main_description==''){
errors++;
$('.menu_main_description').addClass('warning');
}else{
$('.menu_main_description').removeClass('warning');
}
var courses = '';
var prices = '';
var separator = '';
$(".additional_course_desc").each(function(){
var val_desc = $(this).val().trim();
var id = $(this).attr('id');
var id_data = id.split('_');
var price = $('#additional_course_price_'+id_data[1]).val();
if(id_data[1]>0){
separator = '<^>';
}
if(price>0){
$('#additional_course_price_'+id_data[1]).removeClass('warning');
prices = prices+separator+price;
}else{
errors++;
$('#additional_course_price_'+id_data[1]).addClass('warning');
$(this).addClass('warning');
}
if(val_desc==''){
$(this).addClass('warning');
}else{
errors++;
$(this).removeClass('warning');
courses = courses+separator+val_desc;
}
});
var text_after_menu = $('#text_after_menu').val().trim();
if(text_after_menu==''){
errors++;
$('#text_after_menu').addClass('warning');
}else{
$('#text_after_menu').removeClass('warning');
}
if(errors>0){
alert('Some required fields are empty, they are highlighted with red color.');
}else{
//alert(courses+'\n\n'+prices);
var menu_parameter = $('#menu_parameter').val();
$.post( "actions/menu_lunch_save.php", {
all_week:allweek,
menu_parameter: menu_parameter,
header_text: text_over_menu,
menu_description: menu_main_description,
courses: courses,
prices: prices,
text_after_menu: text_after_menu
})
.done(function( data ){
var resulta = data.split('|');
alert(resulta[1]);
if(resulta[0]==1){
var menu_params = menu_parameter.split(' ');
$.post( "pages/menu_lunch.php", { year_num: menu_params[1], week_num: menu_params[2] })
.done(function( data_load ) {
$( ".menu_main_box").html(data_load);
});
}
});
}
});
</script>
|
sanjay-jagdish/barkerby
|
webmin/tablechart/menu_lunch.php
|
PHP
|
gpl-2.0
| 12,526
|
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Sales
* @copyright Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
$installer = $this;
/* @var $installer Mage_Sales_Model_Entity_Setup */
$installer->addAttribute('invoice', 'email_sent', array('type'=>'int'));
$installer->addAttribute('shipment', 'email_sent', array('type'=>'int'));
|
tonio-44/tikflak
|
shop/app/code/core/Mage/Sales/sql/sales_setup/mysql4-upgrade-0.9.23-0.9.24.php
|
PHP
|
gpl-2.0
| 1,189
|
/*
* Copyright (c) 2014 Qualcomm Atheros, Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
/*
* This file contains the configuration parameters for the dbau1x00 board.
*/
#ifndef __AR7240_H
#define __AR7240_H
#define CONFIG_MIPS32 1 /* MIPS32 CPU core */
#define CONFIG_BOOTDELAY 4 /* autoboot after 4 seconds */
#define CONFIG_BAUDRATE 115200
#define CFG_BAUDRATE_TABLE { 115200}
#define CONFIG_TIMESTAMP /* Print image info with timestamp */
#define CONFIG_ROOTFS_RD
#define CONFIG_BOOTARGS_RD "console=ttyS0,115200 root=01:00 rd_start=0x80600000 rd_size=5242880 init=/sbin/init mtdparts=ar7240-nor0:256k(u-boot),64k(u-boot-env),4096k(rootfs),2048k(uImage)"
/* XXX - putting rootfs in last partition results in jffs errors */
#define CONFIG_BOOTARGS_FL "console=ttyS0,115200 root=31:02 rootfstype=jffs2 init=/sbin/init mtdparts=ar7240-nor0:256k(u-boot),64k(u-boot-env),5120k(rootfs),2048k(uImage)"
#ifdef CONFIG_ROOTFS_FLASH
#define CONFIG_BOOTARGS CONFIG_BOOTARGS_FL
#else
#define CONFIG_BOOTARGS ""
#endif
/*
* Miscellaneous configurable options
*/
#define CFG_LONGHELP /* undef to save memory */
#define CFG_PROMPT "ar7240> " /* Monitor Command Prompt */
#define CFG_CBSIZE 512 /* Console I/O Buffer Size */
#define CFG_PBSIZE (CFG_CBSIZE+sizeof(CFG_PROMPT)+16) /* Print Buffer Size */
#define CFG_MAXARGS 16 /* max number of command args*/
#define CFG_MALLOC_LEN 128*1024
#define CFG_BOOTPARAMS_LEN 128*1024
#define CFG_SDRAM_BASE 0x80000000 /* Cached addr */
//#define CFG_SDRAM_BASE 0xa0000000 /* Cached addr */
#define CFG_LOAD_ADDR 0x81000000 /* default load address */
//#define CFG_LOAD_ADDR 0xa1000000 /* default load address */
#define CFG_MEMTEST_START 0x80100000
#undef CFG_MEMTEST_START
#define CFG_MEMTEST_START 0x80200000
#define CFG_MEMTEST_END 0x83800000
/*------------------------------------------------------------------------
* * * JFFS2
*/
#define CFG_JFFS_CUSTOM_PART /* board defined part */
#define CONFIG_JFFS2_CMDLINE
#define MTDIDS_DEFAULT "nor0=ar7240-nor0"
#define CONFIG_MEMSIZE_IN_BYTES
#ifdef CONFIG_HORNET_EMU_HARDI_WLAN
#define CFG_HZ 24000000
#else
#define CFG_HZ 40000000
#endif
#define CFG_RX_ETH_BUFFER 16
/*
** PLL Config for different CPU/DDR/AHB frequencies
*/
#define CFG_PLL_200_200_100 0x00
#define CFG_PLL_300_300_150 0x01
#define CFG_PLL_320_320_160 0x02
#define CFG_PLL_340_340_170 0x03
#define CFG_PLL_350_350_175 0x04
#define CFG_PLL_360_360_180 0x05
#define CFG_PLL_400_400_200 0x06
#define CFG_PLL_300_300_75 0x07
#define CFG_PLL_400_400_100 0x08
#define CFG_PLL_320_320_80 0x09
#define CFG_PLL_410_400_200 0x0a
#define CFG_PLL_420_400_200 0x0b
#define CFG_PLL_80_80_40 0x0c
#define CFG_PLL_64_64_32 0x0d
#define CFG_PLL_48_48_24 0x0e
#define CFG_PLL_32_32_16 0x0f
#define CFG_PLL_333_333_166 0x10
#define CFG_PLL_266_266_133 0x11
#define CFG_PLL_266_266_66 0x12
#define CFG_PLL_240_240_120 0x13
#define CFG_PLL_160_160_80 0x14
#define CFG_PLL_400_200_200 0x15
#define CFG_PLL_500_400_200 0x16
#define CFG_PLL_600_400_200 0x17
#define CFG_PLL_600_500_250 0x18
#define CFG_PLL_600_400_300 0x19
#define CFG_PLL_500_500_250 0x1a
#define CFG_PLL_600_350_175 0x1b
#define CFG_PLL_600_300_150 0x1c
#define CFG_PLL_600_550_1_1G_275 0x1d
#define CFG_PLL_600_500_1G_250 0x1e
#define CFG_PLL_533_400_200 0x1f
#define CFG_PLL_600_450_200 0x20
#define CFG_PLL_533_500_250 0x21
#define CFG_PLL_700_400_200 0x22
#define CFG_PLL_650_600_300 0x23
#define CFG_PLL_600_600_300 0x24
#define CFG_PLL_600_550_275 0x25
#define CFG_PLL_566_475_237 0x26
#define CFG_PLL_566_450_225 0x27
#define CFG_PLL_600_332_166 0x28
#define CFG_PLL_600_575_287 0x29
#define CFG_PLL_600_525_262 0x2a
#define CFG_PLL_566_550_275 0x2b
#define CFG_PLL_566_525_262 0x2c
#define CFG_PLL_600_332_200 0x2d
#define CFG_PLL_600_266_133 0x2e
#define CFG_PLL_600_266_200 0x2f
#define CFG_PLL_600_650_325 0x30
#define CFG_PLL_566_400_200 0x31
#define CFG_PLL_566_500_250 0x32
#define CFG_PLL_600_1_2G_400_200 0x33
#define CFG_PLL_560_480_240 0x34
#define CFG_PLL_333_166_166 0x35
#define CFG_PLL_350_175_175 0x36
#define CFG_PLL_360_180_180 0x37
#define CFG_PLL_380_190_190 0x38
#define CFG_PLL_262_262_131 0x39
#define CFG_PLL_275_275_137 0x3a
#define CFG_PLL_200_200_200 0x3b
#define CFG_PLL_250_250_125 0x3c
#define CFG_PLL_225_225_112 0x3d
#define CFG_PLL_212_212_106 0x3e
#define CFG_PLL_187_187_93 0x3f
#define CFG_PLL_535_400_200 0x40
#define CFG_PLL_560_400_200 0x41
#define CFG_PLL_560_450_225 0x42
#define CFG_PLL_400_480_240 0x43
/*-----------------------------------------------------------------------
* Cache Configuration
*/
#define CFG_DCACHE_SIZE 32768
#define CFG_ICACHE_SIZE 65536
#define CFG_CACHELINE_SIZE 32
#endif /* __CONFIG_H */
|
wjrsonic/openwrt
|
qca/src/qca-legacy-uboot/include/configs/ar7240.h
|
C
|
gpl-2.0
| 5,563
|
#!/bin/bash
CYPHT_DIR="/home/jason/cypht"
VERSION="v1.1.0-rc4"
SINCE="2017-05-11"
cd "$CYPHT_DIR"
git log --pretty=format:'%h% - %s [%aD]' \
--abbrev-commit \
--since "$SINCE" \
"$VERSION"..HEAD \
| sed -r "s/[|\*\/\\]//g" \
| tr -s ' ' \
| grep -v '^ $' \
| sed -r "s/^ //"
|
jasonmunro/hm3
|
scripts/release_changes.sh
|
Shell
|
gpl-2.0
| 306
|
# -*- perl -*-
#
# Author: Slaven Rezic
#
# Copyright (C) 2004,2009,2015 Slaven Rezic. All rights reserved.
# This package is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.
#
# Mail: slaven@rezic.de
# WWW: http://www.rezic.de/eserte/
#
package PDF::Create::MyPage;
use strict;
use vars qw($VERSION);
$VERSION = '1.06';
######################################################################
# Additional PDF::Create methods
package PDF::Create::Page;
if (!defined &PI) {
eval 'use constant PI => 4 * atan2(1, 1);';
die $@ if $@;
}
if (!defined &set_stroke_color) {
# In newer PDF::Create versions, setrgbcolorstroke exists.
# However, setrgbcolorstroke does not remember the current stroke
# color, and would generate too many RG instructions if called
# repeatedly with the same values.
*set_stroke_color = sub {
my($page, $r, $g, $b) = @_;
return if (defined $page->{'current_stroke_color'} &&
$page->{'current_stroke_color'} eq join(",", $r, $g, $b));
$page->{'pdf'}->page_stream($page);
$page->{'pdf'}->add("$r $g $b RG");
$page->{'current_stroke_color'} = join(",", $r, $g, $b);
};
}
if (!defined &set_fill_color) {
# Counterpart in PDF::Create is setrgbcolor. Same comment as for
# setrgbcolorstroke is true here, too.
*set_fill_color = sub {
my($page, $r, $g, $b) = @_;
return if (defined $page->{'current_fill_color'} &&
$page->{'current_fill_color'} eq join(",", $r, $g, $b));
$page->{'pdf'}->page_stream($page);
$page->{'pdf'}->add("$r $g $b rg");
$page->{'current_fill_color'} = join(",", $r, $g, $b);
};
}
if (!defined &set_line_width) {
# Counterpart in PDF::Create is set_width. Same comment as for
# setrgbcolorstroke is true here, too.
*set_line_width = sub {
my($page, $w) = @_;
return if (defined $page->{'current_line_width'} &&
$page->{'current_line_width'} == $w);
$page->{'pdf'}->page_stream($page);
$page->{'pdf'}->add("$w w");
$page->{'current_line_width'} = $w;
};
}
if (!defined &set_dash_pattern) {
# Missing in PDF::Create 1.24
*set_dash_pattern = sub {
my($page, $array, $phase) = @_;
$phase = 0 if !defined $phase;
my $pdf = $page->{'pdf'};
$pdf->page_stream($page);
$pdf->add("[@$array] $phase d");
};
}
if (!defined &circle) {
# Missing in PDF::Create 1.24
*circle = sub {
my($page, $x, $y, $r) = @_;
my @coords;
for(my $i = 0; $i < PI()*2; $i+=PI()*2/$r/2) {
my($xi,$yi) = map { $_*$r } (sin $i, cos $i);
push @coords, $x+$xi, $y+$yi;
}
push @coords, @coords[0,1];
@coords = map { sprintf "%.2f", $_ } @coords;
$page->moveto(shift @coords, shift @coords);
for(my $i = 0; $i <= $#coords; $i+=2) {
$page->lineto($coords[$i], $coords[$i+1]);
}
$page->stroke;
}
}
# Override the original string_width method, because it uses wrong
# width tables (maybe based on a non-iso-8859-1 font?). See also
# https://rt.cpan.org/Ticket/Display.html?id=110723
my $font_widths = {};
sub my_string_width {
my $self = shift;
my $font = shift;
my $string = shift;
my $fname = $self->{'pdf'}{'fonts'}{$font}{'BaseFont'}[1];
if (!exists $font_widths->{$fname}) {
(my $modname = $fname) =~ s/[^a-zA-Z]//;
$modname = "Font::Metrics::$modname";
my @wx = eval qq{ require $modname; \@${modname}::wx };
if (@wx) {
$font_widths->{$fname} = [ map { int($_*1000) } @wx ];
# Font::AFM uses ISOLatin1Encoding, whereas PDF::Create
# typically sets WinAnsiEncoding. These two are almost the
# same, except for hyphen vs. minus and some other diffs,
# try:
#
# perl -MPostScript::WinANSIEncoding -MFont::AFM -e '@w=PostScript::WinANSIEncoding->array; @l= @Font::AFM::ISOLatin1Encoding; for my $ch (0..255) { if ($w[$ch] ne $l[$ch]) { print "$ch $w[$ch] $l[$ch]\n"}}'
#
# Fix only the most problematic one, hyphen vs. minus:
$font_widths->{$fname}[ord("-")] = $font_widths->{$fname}[173];
} else {
# fallback to original
return $self->string_width($font, $string);
}
}
my $w = 0;
for my $c (split '', $string) {
$w += $$font_widths{$fname}[ord $c];
}
$w / 1000;
}
1;
__END__
|
eserte/bbbike
|
lib/PDF/Create/MyPage.pm
|
Perl
|
gpl-2.0
| 4,200
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>C-Layman: Data Fields</title>
<link href="tabs.css" rel="stylesheet" type="text/css">
<link href="doxygen.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.5.8 -->
<div class="navigation" id="top">
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li class="current"><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li class="current"><a href="functions.html"><span>Data Fields</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li class="current"><a href="functions.html"><span>All</span></a></li>
<li><a href="functions_vars.html"><span>Variables</span></a></li>
</ul>
</div>
</div>
<div class="contents">
Here is a list of all struct and union fields with links to the structures/unions they belong to:
<p>
<ul>
<li>count
: <a class="el" href="struct_dict.html#d43c3812e6d13e0518d9f8b8f463ffcf">Dict</a>
, <a class="el" href="struct_string_list.html#16ff2d8e15ade4948398b0aeb80124a8">StringList</a>
, <a class="el" href="struct_py_object_list.html#d43c3812e6d13e0518d9f8b8f463ffcf">PyObjectList</a>
<li>description
: <a class="el" href="struct_overlay_info.html#8444d6e0dfe2bbab0b5e7b24308f1559">OverlayInfo</a>
<li>homepage
: <a class="el" href="struct_overlay_info.html#5bc3413dec9282bb700a1cf1a24235c2">OverlayInfo</a>
<li>key
: <a class="el" href="struct_dict_elem.html#cd3d88da3c0e0313c3645ff34f62f542">DictElem</a>
<li>list
: <a class="el" href="struct_string_list.html#c7532f926b69022dd1878cc2d3b2e113">StringList</a>
<li>modules
: <a class="el" href="struct_interpreter.html#54484552877f952edaa9238edc7174ec">Interpreter</a>
<li>name
: <a class="el" href="struct_overlay_info.html#5ac083a645d964373f022d03df4849c8">OverlayInfo</a>
<li>next
: <a class="el" href="struct_py_object_list_elem.html#8c80f1351a112162a90491278c0e89ac">PyObjectListElem</a>
, <a class="el" href="struct_dict_elem.html#e283b528dd0b0463c2444296b4252e53">DictElem</a>
<li>object
: <a class="el" href="struct_bare_config.html#db7ba59fec8a5847f73c56fccee0f1a0">BareConfig</a>
, <a class="el" href="struct_py_object_list_elem.html#db7ba59fec8a5847f73c56fccee0f1a0">PyObjectListElem</a>
, <a class="el" href="struct_message.html#db7ba59fec8a5847f73c56fccee0f1a0">Message</a>
, <a class="el" href="struct_layman_a_p_i.html#db7ba59fec8a5847f73c56fccee0f1a0">LaymanAPI</a>
<li>official
: <a class="el" href="struct_overlay_info.html#39ff61d5fdbc3c939eaaae94a1db6e3d">OverlayInfo</a>
<li>ownerEmail
: <a class="el" href="struct_overlay_info.html#b976d386d27f39e2fbfb07ab5a9a74f4">OverlayInfo</a>
<li>ownerName
: <a class="el" href="struct_overlay_info.html#4470dc7453f754e87738462bfede9feb">OverlayInfo</a>
<li>priority
: <a class="el" href="struct_overlay_info.html#cec9ce2df15222151ad66fcb1d74eb9f">OverlayInfo</a>
<li>quality
: <a class="el" href="struct_overlay_info.html#fdabd0073bd86d184b408f1ef57e5c4e">OverlayInfo</a>
<li>root
: <a class="el" href="struct_dict.html#952d143d222751c7308e0180b20ce6e1">Dict</a>
, <a class="el" href="struct_py_object_list.html#a024c10304ef3a9c85e1927577a23a5c">PyObjectList</a>
<li>srcType
: <a class="el" href="struct_overlay_info.html#33d8b4b60c5f2e27c44e1fca9515d237">OverlayInfo</a>
<li>srcUris
: <a class="el" href="struct_overlay_info.html#31254fad8941223b74864ff72eeb5b30">OverlayInfo</a>
<li>supported
: <a class="el" href="struct_overlay_info.html#f7d846dfb6ed3e5f62cfddc7b1007228">OverlayInfo</a>
<li>text
: <a class="el" href="struct_overlay_info.html#5633b1433389cec21ade3811bbe9ca5b">OverlayInfo</a>
<li>val
: <a class="el" href="struct_dict_elem.html#0fc584151635e6718cb3052b5a5dce4d">DictElem</a>
</ul>
</div>
<hr size="1"><address style="text-align: right;"><small>Generated on Fri Aug 6 20:00:53 2010 for C-Layman by
<a href="http://www.doxygen.org/index.html">
<img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.8 </small></address>
</body>
</html>
|
jmesmon/layman
|
c-layman/doc/html/functions.html
|
HTML
|
gpl-2.0
| 4,357
|
<?php
/**
* Site/blog functions that work with the blogs table and related data.
*
* @package WordPress
* @subpackage Multisite
* @since MU
*/
/**
* Update the last_updated field for the current blog.
*
* @since MU
*
* @global wpdb $wpdb
*/
function wpmu_update_blogs_date() {
global $wpdb;
update_blog_details( $wpdb->blogid, array('last_updated' => current_time('mysql', true)) );
/**
* Fires after the blog details are updated.
*
* @since MU
*
* @param int $blog_id Blog ID.
*/
do_action( 'wpmu_blog_updated', $wpdb->blogid );
}
/**
* Get a full blog URL, given a blog id.
*
* @since MU
*
* @param int $blog_id Blog ID
* @return string Full URL of the blog if found. Empty string if not.
*/
function get_blogaddress_by_id( $blog_id ) {
$bloginfo = get_blog_details( (int) $blog_id, false ); // only get bare details!
return ( $bloginfo ) ? esc_url( 'http://' . $bloginfo->domain . $bloginfo->path ) : '';
}
/**
* Get a full blog URL, given a blog name.
*
* @since MU
*
* @param string $blogname The (subdomain or directory) name
* @return string
*/
function get_blogaddress_by_name( $blogname ) {
if ( is_subdomain_install() ) {
if ( $blogname == 'main' )
$blogname = 'www';
$url = rtrim( network_home_url(), '/' );
if ( !empty( $blogname ) )
$url = preg_replace( '|^([^\.]+://)|', "\${1}" . $blogname . '.', $url );
} else {
$url = network_home_url( $blogname );
}
return esc_url( $url . '/' );
}
/**
* Given a blog's (subdomain or directory) slug, retrieve its id.
*
* @since MU
*
* @global wpdb $wpdb
*
* @param string $slug
* @return int A blog id
*/
function get_id_from_blogname( $slug ) {
global $wpdb;
$current_site = get_current_site();
$slug = trim( $slug, '/' );
$blog_id = wp_cache_get( 'get_id_from_blogname_' . $slug, 'blog-details' );
if ( $blog_id )
return $blog_id;
if ( is_subdomain_install() ) {
$domain = $slug . '.' . $current_site->domain;
$path = $current_site->path;
} else {
$domain = $current_site->domain;
$path = $current_site->path . $slug . '/';
}
$blog_id = $wpdb->get_var( $wpdb->prepare("SELECT blog_id FROM {$wpdb->blogs} WHERE domain = %s AND path = %s", $domain, $path) );
wp_cache_set( 'get_id_from_blogname_' . $slug, $blog_id, 'blog-details' );
return $blog_id;
}
/**
* Retrieve the details for a blog from the blogs table and blog options.
*
* @since MU
*
* @global wpdb $wpdb
*
* @param int|string|array $fields Optional. A blog ID, a blog slug, or an array of fields to query against.
* If not specified the current blog ID is used.
* @param bool $get_all Whether to retrieve all details or only the details in the blogs table.
* Default is true.
* @return object|false Blog details on success. False on failure.
*/
function get_blog_details( $fields = null, $get_all = true ) {
global $wpdb;
if ( is_array($fields ) ) {
if ( isset($fields['blog_id']) ) {
$blog_id = $fields['blog_id'];
} elseif ( isset($fields['domain']) && isset($fields['path']) ) {
$key = md5( $fields['domain'] . $fields['path'] );
$blog = wp_cache_get($key, 'blog-lookup');
if ( false !== $blog )
return $blog;
if ( substr( $fields['domain'], 0, 4 ) == 'www.' ) {
$nowww = substr( $fields['domain'], 4 );
$blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain IN (%s,%s) AND path = %s ORDER BY CHAR_LENGTH(domain) DESC", $nowww, $fields['domain'], $fields['path'] ) );
} else {
$blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain = %s AND path = %s", $fields['domain'], $fields['path'] ) );
}
if ( $blog ) {
wp_cache_set($blog->blog_id . 'short', $blog, 'blog-details');
$blog_id = $blog->blog_id;
} else {
return false;
}
} elseif ( isset($fields['domain']) && is_subdomain_install() ) {
$key = md5( $fields['domain'] );
$blog = wp_cache_get($key, 'blog-lookup');
if ( false !== $blog )
return $blog;
if ( substr( $fields['domain'], 0, 4 ) == 'www.' ) {
$nowww = substr( $fields['domain'], 4 );
$blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain IN (%s,%s) ORDER BY CHAR_LENGTH(domain) DESC", $nowww, $fields['domain'] ) );
} else {
$blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain = %s", $fields['domain'] ) );
}
if ( $blog ) {
wp_cache_set($blog->blog_id . 'short', $blog, 'blog-details');
$blog_id = $blog->blog_id;
} else {
return false;
}
} else {
return false;
}
} else {
if ( ! $fields )
$blog_id = get_current_blog_id();
elseif ( ! is_numeric( $fields ) )
$blog_id = get_id_from_blogname( $fields );
else
$blog_id = $fields;
}
$blog_id = (int) $blog_id;
$all = $get_all == true ? '' : 'short';
$details = wp_cache_get( $blog_id . $all, 'blog-details' );
if ( $details ) {
if ( ! is_object( $details ) ) {
if ( $details == -1 ) {
return false;
} else {
// Clear old pre-serialized objects. Cache clients do better with that.
wp_cache_delete( $blog_id . $all, 'blog-details' );
unset($details);
}
} else {
return $details;
}
}
// Try the other cache.
if ( $get_all ) {
$details = wp_cache_get( $blog_id . 'short', 'blog-details' );
} else {
$details = wp_cache_get( $blog_id, 'blog-details' );
// If short was requested and full cache is set, we can return.
if ( $details ) {
if ( ! is_object( $details ) ) {
if ( $details == -1 ) {
return false;
} else {
// Clear old pre-serialized objects. Cache clients do better with that.
wp_cache_delete( $blog_id, 'blog-details' );
unset($details);
}
} else {
return $details;
}
}
}
if ( empty($details) ) {
$details = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE blog_id = %d /* get_blog_details */", $blog_id ) );
if ( ! $details ) {
// Set the full cache.
wp_cache_set( $blog_id, -1, 'blog-details' );
return false;
}
}
if ( ! $get_all ) {
wp_cache_set( $blog_id . $all, $details, 'blog-details' );
return $details;
}
switch_to_blog( $blog_id );
$details->blogname = get_option( 'blogname' );
$details->siteurl = get_option( 'siteurl' );
$details->post_count = get_option( 'post_count' );
restore_current_blog();
/**
* Filter a blog's details.
*
* @since MU
*
* @param object $details The blog details.
*/
$details = apply_filters( 'blog_details', $details );
wp_cache_set( $blog_id . $all, $details, 'blog-details' );
$key = md5( $details->domain . $details->path );
wp_cache_set( $key, $details, 'blog-lookup' );
return $details;
}
/**
* Clear the blog details cache.
*
* @since MU
*
* @param int $blog_id Optional. Blog ID. Defaults to current blog.
*/
function refresh_blog_details( $blog_id = 0 ) {
$blog_id = (int) $blog_id;
if ( ! $blog_id ) {
$blog_id = get_current_blog_id();
}
$details = get_blog_details( $blog_id, false );
if ( ! $details ) {
// Make sure clean_blog_cache() gets the blog ID
// when the blog has been previously cached as
// non-existent.
$details = (object) array(
'blog_id' => $blog_id,
'domain' => null,
'path' => null
);
}
clean_blog_cache( $details );
/**
* Fires after the blog details cache is cleared.
*
* @since 3.4.0
*
* @param int $blog_id Blog ID.
*/
do_action( 'refresh_blog_details', $blog_id );
}
/**
* Update the details for a blog. Updates the blogs table for a given blog id.
*
* @since MU
*
* @global wpdb $wpdb
*
* @param int $blog_id Blog ID
* @param array $details Array of details keyed by blogs table field names.
* @return bool True if update succeeds, false otherwise.
*/
function update_blog_details( $blog_id, $details = array() ) {
global $wpdb;
if ( empty($details) )
return false;
if ( is_object($details) )
$details = get_object_vars($details);
$current_details = get_blog_details($blog_id, false);
if ( empty($current_details) )
return false;
$current_details = get_object_vars($current_details);
$details = array_merge($current_details, $details);
$details['last_updated'] = current_time('mysql', true);
$update_details = array();
$fields = array( 'site_id', 'domain', 'path', 'registered', 'last_updated', 'public', 'archived', 'mature', 'spam', 'deleted', 'lang_id');
foreach ( array_intersect( array_keys( $details ), $fields ) as $field ) {
if ( 'path' === $field ) {
$details[ $field ] = trailingslashit( '/' . trim( $details[ $field ], '/' ) );
}
$update_details[ $field ] = $details[ $field ];
}
$result = $wpdb->update( $wpdb->blogs, $update_details, array('blog_id' => $blog_id) );
if ( false === $result )
return false;
// If spam status changed, issue actions.
if ( $details['spam'] != $current_details['spam'] ) {
if ( $details['spam'] == 1 ) {
/**
* Fires when the blog status is changed to 'spam'.
*
* @since MU
*
* @param int $blog_id Blog ID.
*/
do_action( 'make_spam_blog', $blog_id );
} else {
/**
* Fires when the blog status is changed to 'ham'.
*
* @since MU
*
* @param int $blog_id Blog ID.
*/
do_action( 'make_ham_blog', $blog_id );
}
}
// If mature status changed, issue actions.
if ( $details['mature'] != $current_details['mature'] ) {
if ( $details['mature'] == 1 ) {
/**
* Fires when the blog status is changed to 'mature'.
*
* @since 3.1.0
*
* @param int $blog_id Blog ID.
*/
do_action( 'mature_blog', $blog_id );
} else {
/**
* Fires when the blog status is changed to 'unmature'.
*
* @since 3.1.0
*
* @param int $blog_id Blog ID.
*/
do_action( 'unmature_blog', $blog_id );
}
}
// If archived status changed, issue actions.
if ( $details['archived'] != $current_details['archived'] ) {
if ( $details['archived'] == 1 ) {
/**
* Fires when the blog status is changed to 'archived'.
*
* @since MU
*
* @param int $blog_id Blog ID.
*/
do_action( 'archive_blog', $blog_id );
} else {
/**
* Fires when the blog status is changed to 'unarchived'.
*
* @since MU
*
* @param int $blog_id Blog ID.
*/
do_action( 'unarchive_blog', $blog_id );
}
}
// If deleted status changed, issue actions.
if ( $details['deleted'] != $current_details['deleted'] ) {
if ( $details['deleted'] == 1 ) {
/**
* Fires when the blog status is changed to 'deleted'.
*
* @since 3.5.0
*
* @param int $blog_id Blog ID.
*/
do_action( 'make_delete_blog', $blog_id );
} else {
/**
* Fires when the blog status is changed to 'undeleted'.
*
* @since 3.5.0
*
* @param int $blog_id Blog ID.
*/
do_action( 'make_undelete_blog', $blog_id );
}
}
if ( isset( $details['public'] ) ) {
switch_to_blog( $blog_id );
update_option( 'blog_public', $details['public'] );
restore_current_blog();
}
refresh_blog_details($blog_id);
return true;
}
/**
* Clean the blog cache
*
* @since 3.5.0
*
* @param stdClass $blog The blog details as returned from get_blog_details()
*/
function clean_blog_cache( $blog ) {
$blog_id = $blog->blog_id;
$domain_path_key = md5( $blog->domain . $blog->path );
wp_cache_delete( $blog_id , 'blog-details' );
wp_cache_delete( $blog_id . 'short' , 'blog-details' );
wp_cache_delete( $domain_path_key, 'blog-lookup' );
wp_cache_delete( 'current_blog_' . $blog->domain, 'site-options' );
wp_cache_delete( 'current_blog_' . $blog->domain . $blog->path, 'site-options' );
wp_cache_delete( 'get_id_from_blogname_' . trim( $blog->path, '/' ), 'blog-details' );
wp_cache_delete( $domain_path_key, 'blog-id-cache' );
}
/**
* Retrieve option value for a given blog id based on name of option.
*
* If the option does not exist or does not have a value, then the return value
* will be false. This is useful to check whether you need to install an option
* and is commonly used during installation of plugin options and to test
* whether upgrading is required.
*
* If the option was serialized then it will be unserialized when it is returned.
*
* @since MU
*
* @param int $id A blog ID. Can be null to refer to the current blog.
* @param string $option Name of option to retrieve. Expected to not be SQL-escaped.
* @param mixed $default Optional. Default value to return if the option does not exist.
* @return mixed Value set for the option.
*/
function get_blog_option( $id, $option, $default = false ) {
$id = (int) $id;
if ( empty( $id ) )
$id = get_current_blog_id();
if ( get_current_blog_id() == $id )
return get_option( $option, $default );
switch_to_blog( $id );
$value = get_option( $option, $default );
restore_current_blog();
/**
* Filter a blog option value.
*
* The dynamic portion of the hook name, `$option`, refers to the blog option name.
*
* @since 3.5.0
*
* @param string $value The option value.
* @param int $id Blog ID.
*/
return apply_filters( "blog_option_{$option}", $value, $id );
}
/**
* Add a new option for a given blog id.
*
* You do not need to serialize values. If the value needs to be serialized, then
* it will be serialized before it is inserted into the database. Remember,
* resources can not be serialized or added as an option.
*
* You can create options without values and then update the values later.
* Existing options will not be updated and checks are performed to ensure that you
* aren't adding a protected WordPress option. Care should be taken to not name
* options the same as the ones which are protected.
*
* @since MU
*
* @param int $id A blog ID. Can be null to refer to the current blog.
* @param string $option Name of option to add. Expected to not be SQL-escaped.
* @param mixed $value Optional. Option value, can be anything. Expected to not be SQL-escaped.
* @return bool False if option was not added and true if option was added.
*/
function add_blog_option( $id, $option, $value ) {
$id = (int) $id;
if ( empty( $id ) )
$id = get_current_blog_id();
if ( get_current_blog_id() == $id )
return add_option( $option, $value );
switch_to_blog( $id );
$return = add_option( $option, $value );
restore_current_blog();
return $return;
}
/**
* Removes option by name for a given blog id. Prevents removal of protected WordPress options.
*
* @since MU
*
* @param int $id A blog ID. Can be null to refer to the current blog.
* @param string $option Name of option to remove. Expected to not be SQL-escaped.
* @return bool True, if option is successfully deleted. False on failure.
*/
function delete_blog_option( $id, $option ) {
$id = (int) $id;
if ( empty( $id ) )
$id = get_current_blog_id();
if ( get_current_blog_id() == $id )
return delete_option( $option );
switch_to_blog( $id );
$return = delete_option( $option );
restore_current_blog();
return $return;
}
/**
* Update an option for a particular blog.
*
* @since MU
*
* @param int $id The blog id
* @param string $option The option key
* @param mixed $value The option value
* @return bool True on success, false on failure.
*/
function update_blog_option( $id, $option, $value, $deprecated = null ) {
$id = (int) $id;
if ( null !== $deprecated )
_deprecated_argument( __FUNCTION__, '3.1' );
if ( get_current_blog_id() == $id )
return update_option( $option, $value );
switch_to_blog( $id );
$return = update_option( $option, $value );
restore_current_blog();
refresh_blog_details( $id );
return $return;
}
/**
* Switch the current blog.
*
* This function is useful if you need to pull posts, or other information,
* from other blogs. You can switch back afterwards using restore_current_blog().
*
* Things that aren't switched:
* - autoloaded options. See #14992
* - plugins. See #14941
*
* @see restore_current_blog()
* @since MU
*
* @global wpdb $wpdb
* @global int $blog_id
* @global array $_wp_switched_stack
* @global bool $switched
* @global string $table_prefix
* @global WP_Object_Cache $wp_object_cache
*
* @param int $new_blog The id of the blog you want to switch to. Default: current blog
* @param bool $deprecated Deprecated argument
* @return true Always returns True.
*/
function switch_to_blog( $new_blog, $deprecated = null ) {
global $wpdb;
if ( empty( $new_blog ) )
$new_blog = $GLOBALS['blog_id'];
$GLOBALS['_wp_switched_stack'][] = $GLOBALS['blog_id'];
/*
* If we're switching to the same blog id that we're on,
* set the right vars, do the associated actions, but skip
* the extra unnecessary work
*/
if ( $new_blog == $GLOBALS['blog_id'] ) {
/**
* Fires when the blog is switched.
*
* @since MU
*
* @param int $new_blog New blog ID.
* @param int $new_blog Blog ID.
*/
do_action( 'switch_blog', $new_blog, $new_blog );
$GLOBALS['switched'] = true;
return true;
}
$wpdb->set_blog_id( $new_blog );
$GLOBALS['table_prefix'] = $wpdb->get_blog_prefix();
$prev_blog_id = $GLOBALS['blog_id'];
$GLOBALS['blog_id'] = $new_blog;
if ( function_exists( 'wp_cache_switch_to_blog' ) ) {
wp_cache_switch_to_blog( $new_blog );
} else {
global $wp_object_cache;
if ( is_object( $wp_object_cache ) && isset( $wp_object_cache->global_groups ) )
$global_groups = $wp_object_cache->global_groups;
else
$global_groups = false;
wp_cache_init();
if ( function_exists( 'wp_cache_add_global_groups' ) ) {
if ( is_array( $global_groups ) ) {
wp_cache_add_global_groups( $global_groups );
} else {
wp_cache_add_global_groups( array( 'users', 'userlogins', 'usermeta', 'user_meta', 'useremail', 'userslugs', 'site-transient', 'site-options', 'site-lookup', 'blog-lookup', 'blog-details', 'rss', 'global-posts', 'blog-id-cache' ) );
}
wp_cache_add_non_persistent_groups( array( 'comment', 'counts', 'plugins' ) );
}
}
if ( did_action( 'init' ) ) {
wp_roles()->reinit();
$current_user = wp_get_current_user();
$current_user->for_blog( $new_blog );
}
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'switch_blog', $new_blog, $prev_blog_id );
$GLOBALS['switched'] = true;
return true;
}
/**
* Restore the current blog, after calling switch_to_blog()
*
* @see switch_to_blog()
* @since MU
*
* @global wpdb $wpdb
* @global array $_wp_switched_stack
* @global int $blog_id
* @global bool $switched
* @global string $table_prefix
* @global WP_Object_Cache $wp_object_cache
*
* @return bool True on success, false if we're already on the current blog
*/
function restore_current_blog() {
global $wpdb;
if ( empty( $GLOBALS['_wp_switched_stack'] ) )
return false;
$blog = array_pop( $GLOBALS['_wp_switched_stack'] );
if ( $GLOBALS['blog_id'] == $blog ) {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'switch_blog', $blog, $blog );
// If we still have items in the switched stack, consider ourselves still 'switched'
$GLOBALS['switched'] = ! empty( $GLOBALS['_wp_switched_stack'] );
return true;
}
$wpdb->set_blog_id( $blog );
$prev_blog_id = $GLOBALS['blog_id'];
$GLOBALS['blog_id'] = $blog;
$GLOBALS['table_prefix'] = $wpdb->get_blog_prefix();
if ( function_exists( 'wp_cache_switch_to_blog' ) ) {
wp_cache_switch_to_blog( $blog );
} else {
global $wp_object_cache;
if ( is_object( $wp_object_cache ) && isset( $wp_object_cache->global_groups ) )
$global_groups = $wp_object_cache->global_groups;
else
$global_groups = false;
wp_cache_init();
if ( function_exists( 'wp_cache_add_global_groups' ) ) {
if ( is_array( $global_groups ) ) {
wp_cache_add_global_groups( $global_groups );
} else {
wp_cache_add_global_groups( array( 'users', 'userlogins', 'usermeta', 'user_meta', 'useremail', 'userslugs', 'site-transient', 'site-options', 'site-lookup', 'blog-lookup', 'blog-details', 'rss', 'global-posts', 'blog-id-cache' ) );
}
wp_cache_add_non_persistent_groups( array( 'comment', 'counts', 'plugins' ) );
}
}
if ( did_action( 'init' ) ) {
wp_roles()->reinit();
$current_user = wp_get_current_user();
$current_user->for_blog( $blog );
}
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'switch_blog', $blog, $prev_blog_id );
// If we still have items in the switched stack, consider ourselves still 'switched'
$GLOBALS['switched'] = ! empty( $GLOBALS['_wp_switched_stack'] );
return true;
}
/**
* Determines if switch_to_blog() is in effect
*
* @since 3.5.0
*
* @global array $_wp_switched_stack
*
* @return bool True if switched, false otherwise.
*/
function ms_is_switched() {
return ! empty( $GLOBALS['_wp_switched_stack'] );
}
/**
* Check if a particular blog is archived.
*
* @since MU
*
* @param int $id The blog id
* @return string Whether the blog is archived or not
*/
function is_archived( $id ) {
return get_blog_status($id, 'archived');
}
/**
* Update the 'archived' status of a particular blog.
*
* @since MU
*
* @param int $id The blog id
* @param string $archived The new status
* @return string $archived
*/
function update_archived( $id, $archived ) {
update_blog_status($id, 'archived', $archived);
return $archived;
}
/**
* Update a blog details field.
*
* @since MU
*
* @global wpdb $wpdb
*
* @param int $blog_id BLog ID
* @param string $pref A field name
* @param string $value Value for $pref
* @param null $deprecated
* @return string|false $value
*/
function update_blog_status( $blog_id, $pref, $value, $deprecated = null ) {
global $wpdb;
if ( null !== $deprecated )
_deprecated_argument( __FUNCTION__, '3.1' );
if ( ! in_array( $pref, array( 'site_id', 'domain', 'path', 'registered', 'last_updated', 'public', 'archived', 'mature', 'spam', 'deleted', 'lang_id') ) )
return $value;
$result = $wpdb->update( $wpdb->blogs, array($pref => $value, 'last_updated' => current_time('mysql', true)), array('blog_id' => $blog_id) );
if ( false === $result )
return false;
refresh_blog_details( $blog_id );
if ( 'spam' == $pref ) {
if ( $value == 1 ) {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'make_spam_blog', $blog_id );
} else {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'make_ham_blog', $blog_id );
}
} elseif ( 'mature' == $pref ) {
if ( $value == 1 ) {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'mature_blog', $blog_id );
} else {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'unmature_blog', $blog_id );
}
} elseif ( 'archived' == $pref ) {
if ( $value == 1 ) {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'archive_blog', $blog_id );
} else {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'unarchive_blog', $blog_id );
}
} elseif ( 'deleted' == $pref ) {
if ( $value == 1 ) {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'make_delete_blog', $blog_id );
} else {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'make_undelete_blog', $blog_id );
}
} elseif ( 'public' == $pref ) {
/**
* Fires after the current blog's 'public' setting is updated.
*
* @since MU
*
* @param int $blog_id Blog ID.
* @param string $value The value of blog status.
*/
do_action( 'update_blog_public', $blog_id, $value ); // Moved here from update_blog_public().
}
return $value;
}
/**
* Get a blog details field.
*
* @since MU
*
* @global wpdb $wpdb
*
* @param int $id The blog id
* @param string $pref A field name
* @return bool|string|null $value
*/
function get_blog_status( $id, $pref ) {
global $wpdb;
$details = get_blog_details( $id, false );
if ( $details )
return $details->$pref;
return $wpdb->get_var( $wpdb->prepare("SELECT %s FROM {$wpdb->blogs} WHERE blog_id = %d", $pref, $id) );
}
/**
* Get a list of most recently updated blogs.
*
* @since MU
*
* @global wpdb $wpdb
*
* @param mixed $deprecated Not used
* @param int $start The offset
* @param int $quantity The maximum number of blogs to retrieve. Default is 40.
* @return array The list of blogs
*/
function get_last_updated( $deprecated = '', $start = 0, $quantity = 40 ) {
global $wpdb;
if ( ! empty( $deprecated ) )
_deprecated_argument( __FUNCTION__, 'MU' ); // never used
return $wpdb->get_results( $wpdb->prepare("SELECT blog_id, domain, path FROM $wpdb->blogs WHERE site_id = %d AND public = '1' AND archived = '0' AND mature = '0' AND spam = '0' AND deleted = '0' AND last_updated != '0000-00-00 00:00:00' ORDER BY last_updated DESC limit %d, %d", $wpdb->siteid, $start, $quantity ) , ARRAY_A );
}
/**
* Handler for updating the blog date when a post is published or an already published post is changed.
*
* @since 3.3.0
*
* @param string $new_status The new post status
* @param string $old_status The old post status
* @param object $post Post object
*/
function _update_blog_date_on_post_publish( $new_status, $old_status, $post ) {
$post_type_obj = get_post_type_object( $post->post_type );
if ( ! $post_type_obj || ! $post_type_obj->public ) {
return;
}
if ( 'publish' != $new_status && 'publish' != $old_status ) {
return;
}
// Post was freshly published, published post was saved, or published post was unpublished.
wpmu_update_blogs_date();
}
/**
* Handler for updating the blog date when a published post is deleted.
*
* @since 3.4.0
*
* @param int $post_id Post ID
*/
function _update_blog_date_on_post_delete( $post_id ) {
$post = get_post( $post_id );
$post_type_obj = get_post_type_object( $post->post_type );
if ( ! $post_type_obj || ! $post_type_obj->public ) {
return;
}
if ( 'publish' != $post->post_status ) {
return;
}
wpmu_update_blogs_date();
}
/**
* Handler for updating the blog posts count date when a post is deleted.
*
* @since 4.0.0
*
* @param int $post_id Post ID.
*/
function _update_posts_count_on_delete( $post_id ) {
$post = get_post( $post_id );
if ( ! $post || 'publish' !== $post->post_status ) {
return;
}
update_posts_count();
}
/**
* Handler for updating the blog posts count date when a post status changes.
*
* @since 4.0.0
*
* @param string $new_status The status the post is changing to.
* @param string $old_status The status the post is changing from.
*/
function _update_posts_count_on_transition_post_status( $new_status, $old_status ) {
if ( $new_status === $old_status ) {
return;
}
if ( 'publish' !== $new_status && 'publish' !== $old_status ) {
return;
}
update_posts_count();
}
|
casedot/AllYourBaseTemplate
|
wp-includes/ms-blogs.php
|
PHP
|
gpl-2.0
| 27,920
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math;
import junit.framework.TestCase;
import java.util.Locale;
import org.apache.commons.math.exception.util.LocalizedFormats;
/**
* @version $Revision$ $Date$
*/
public class MathConfigurationExceptionTest extends TestCase {
public void testConstructor(){
MathConfigurationException ex = new MathConfigurationException();
assertNull(ex.getCause());
assertEquals("", ex.getMessage());
assertEquals("", ex.getMessage(Locale.FRENCH));
}
public void testConstructorPatternArguments(){
LocalizedFormats pattern = LocalizedFormats.ROTATION_MATRIX_DIMENSIONS;
Object[] arguments = { Integer.valueOf(6), Integer.valueOf(4) };
MathConfigurationException ex = new MathConfigurationException(pattern, arguments);
assertNull(ex.getCause());
assertEquals(pattern, ex.getLocalizablePattern());
assertEquals(arguments.length, ex.getArguments().length);
for (int i = 0; i < arguments.length; ++i) {
assertEquals(arguments[i], ex.getArguments()[i]);
}
assertFalse(pattern.equals(ex.getMessage()));
assertFalse(ex.getMessage().equals(ex.getMessage(Locale.FRENCH)));
}
public void testConstructorCause(){
String inMsg = "inner message";
Exception cause = new Exception(inMsg);
MathConfigurationException ex = new MathConfigurationException(cause);
assertEquals(cause, ex.getCause());
}
public void testConstructorPatternArgumentsCause(){
LocalizedFormats pattern = LocalizedFormats.ROTATION_MATRIX_DIMENSIONS;
Object[] arguments = { Integer.valueOf(6), Integer.valueOf(4) };
String inMsg = "inner message";
Exception cause = new Exception(inMsg);
MathConfigurationException ex = new MathConfigurationException(cause, pattern, arguments);
assertEquals(cause, ex.getCause());
assertEquals(pattern, ex.getLocalizablePattern());
assertEquals(arguments.length, ex.getArguments().length);
for (int i = 0; i < arguments.length; ++i) {
assertEquals(arguments[i], ex.getArguments()[i]);
}
assertFalse(pattern.equals(ex.getMessage()));
assertFalse(ex.getMessage().equals(ex.getMessage(Locale.FRENCH)));
}
}
|
SpoonLabs/astor
|
examples/math_63/src/test/java/org/apache/commons/math/MathConfigurationExceptionTest.java
|
Java
|
gpl-2.0
| 3,118
|
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | Fez - Digital Repository System |
// +----------------------------------------------------------------------+
// | Copyright (c) 2005, 2006, 2007 The University of Queensland, |
// | Australian Partnership for Sustainable Repositories, |
// | eScholarship Project |
// | |
// | Some of the Fez code was derived from Eventum (Copyright 2003, 2004 |
// | MySQL AB - http://dev.mysql.com/downloads/other/eventum/ - GPL) |
// | |
// | This program is free software; you can redistribute it and/or modify |
// | it under the terms of the GNU General Public License as published by |
// | the Free Software Foundation; either version 2 of the License, or |
// | (at your option) any later version. |
// | |
// | This program is distributed in the hope that it will be useful, |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
// | GNU General Public License for more details. |
// | |
// | You should have received a copy of the GNU General Public License |
// | along with this program; if not, write to: |
// | |
// | Free Software Foundation, Inc. |
// | 59 Temple Place - Suite 330 |
// | Boston, MA 02111-1307, USA. |
// +----------------------------------------------------------------------+
// | Authors: Christiaan Kortekaas <c.kortekaas@library.uq.edu.au>, |
// | Matthew Smith <m.smith@library.uq.edu.au>, |
// | Lachlan Kuhn <l.kuhn@library.uq.edu.au> |
// +----------------------------------------------------------------------+
//
//
include_once(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR."config.inc.php");
include_once(APP_INC_PATH . "class.template.php");
include_once(APP_INC_PATH . "class.auth.php");
include_once(APP_INC_PATH . "class.search_key.php");
include_once(APP_INC_PATH . "class.controlled_vocab.php");
include_once(APP_INC_PATH . "class.collection.php");
include_once(APP_INC_PATH . "class.db_api.php");
$tpl = new Template_API();
$tpl->setTemplate("manage/index.tpl.html");
Auth::checkAuthentication(APP_SESSION);
$tpl->assign("type", "solr_dih");
$tpl->assign("active_nav", "admin");
$isUser = Auth::getUsername();
$isAdministrator = User::isUserAdministrator($isUser);
$isSuperAdministrator = User::isUserSuperAdministrator($isUser);
$tpl->assign("isUser", $isUser);
$tpl->assign("isAdministrator", $isAdministrator);
$tpl->assign("isSuperAdministrator", $isSuperAdministrator);
if (!$isSuperAdministrator) {
$tpl->assign("show_not_allowed_msg", true);
}
$list = Search_Key::getSolrTitles(false);
$coreList = array();
$manyList = array();
foreach ($list as $li) {
if ($li['sek_relationship'] == 0) {
array_push($coreList, $li);
} else {
array_push($manyList, $li);
}
}
//print_r($list);
$tpl->assign("list", $list);
$tpl->assign("coreList", $coreList);
$tpl->assign("manyList", $manyList);
$tpl->assign("list", $list);
$tpl->assign("list_count", count($list));
$tpl->displayTemplate();
?>
|
uqlibrary/fez
|
public/manage/solr_dih.php
|
PHP
|
gpl-2.0
| 3,904
|
/*
* (C) Copyright 2010
* Texas Instruments Incorporated, <www.ti.com>
* Steve Sakoman <steve@sakoman.com>
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <asm/arch/sys_proto.h>
#include <asm/arch/mmc_host_def.h>
#include <asm/arch/clock.h>
#include <asm/arch/gpio.h>
#include <asm/gpio.h>
#include "panda_mux_data.h"
#ifdef CONFIG_USB_EHCI
#include <usb.h>
#include <asm/arch/ehci.h>
#include <asm/ehci-omap.h>
#endif
#define PANDA_ULPI_PHY_TYPE_GPIO 182
DECLARE_GLOBAL_DATA_PTR;
const struct omap_sysinfo sysinfo = {
"Board: OMAP4 Panda\n"
};
struct omap4_scrm_regs *const scrm = (struct omap4_scrm_regs *)0x4a30a000;
/**
* @brief board_init
*
* @return 0
*/
int board_init(void)
{
gpmc_init();
gd->bd->bi_arch_number = MACH_TYPE_OMAP4_PANDA;
gd->bd->bi_boot_params = (0x80000000 + 0x100); /* boot param addr */
return 0;
}
int board_eth_init(bd_t *bis)
{
return 0;
}
/**
* @brief misc_init_r - Configure Panda board specific configurations
* such as power configurations, ethernet initialization as phase2 of
* boot sequence
*
* @return 0
*/
int misc_init_r(void)
{
int phy_type;
u32 auxclk, altclksrc;
/* EHCI is not supported on ES1.0 */
if (omap_revision() == OMAP4430_ES1_0)
return 0;
#ifdef CONFIG_ENV_VARS_UBOOT_RUNTIME_CONFIG
if (omap_revision() >= OMAP4460_ES1_0 ||
omap_revision() <= OMAP4460_ES1_1)
setenv("board_name", strcat(CONFIG_SYS_BOARD, "-es"));
#endif
gpio_direction_input(PANDA_ULPI_PHY_TYPE_GPIO);
phy_type = gpio_get_value(PANDA_ULPI_PHY_TYPE_GPIO);
if (phy_type == 1) {
/* ULPI PHY supplied by auxclk3 derived from sys_clk */
debug("ULPI PHY supplied by auxclk3\n");
auxclk = readl(&scrm->auxclk3);
/* Select sys_clk */
auxclk &= ~AUXCLK_SRCSELECT_MASK;
auxclk |= AUXCLK_SRCSELECT_SYS_CLK << AUXCLK_SRCSELECT_SHIFT;
/* Set the divisor to 2 */
auxclk &= ~AUXCLK_CLKDIV_MASK;
auxclk |= AUXCLK_CLKDIV_2 << AUXCLK_CLKDIV_SHIFT;
/* Request auxilary clock #3 */
auxclk |= AUXCLK_ENABLE_MASK;
writel(auxclk, &scrm->auxclk3);
} else {
/* ULPI PHY supplied by auxclk1 derived from PER dpll */
debug("ULPI PHY supplied by auxclk1\n");
auxclk = readl(&scrm->auxclk1);
/* Select per DPLL */
auxclk &= ~AUXCLK_SRCSELECT_MASK;
auxclk |= AUXCLK_SRCSELECT_PER_DPLL << AUXCLK_SRCSELECT_SHIFT;
/* Set the divisor to 16 */
auxclk &= ~AUXCLK_CLKDIV_MASK;
auxclk |= AUXCLK_CLKDIV_16 << AUXCLK_CLKDIV_SHIFT;
/* Request auxilary clock #3 */
auxclk |= AUXCLK_ENABLE_MASK;
writel(auxclk, &scrm->auxclk1);
}
altclksrc = readl(&scrm->altclksrc);
/* Activate alternate system clock supplier */
altclksrc &= ~ALTCLKSRC_MODE_MASK;
altclksrc |= ALTCLKSRC_MODE_ACTIVE;
/* enable clocks */
altclksrc |= ALTCLKSRC_ENABLE_INT_MASK | ALTCLKSRC_ENABLE_EXT_MASK;
writel(altclksrc, &scrm->altclksrc);
return 0;
}
void set_muxconf_regs_essential(void)
{
do_set_mux((*ctrl)->control_padconf_core_base,
core_padconf_array_essential,
sizeof(core_padconf_array_essential) /
sizeof(struct pad_conf_entry));
do_set_mux((*ctrl)->control_padconf_wkup_base,
wkup_padconf_array_essential,
sizeof(wkup_padconf_array_essential) /
sizeof(struct pad_conf_entry));
if (omap_revision() >= OMAP4460_ES1_0)
do_set_mux((*ctrl)->control_padconf_wkup_base,
wkup_padconf_array_essential_4460,
sizeof(wkup_padconf_array_essential_4460) /
sizeof(struct pad_conf_entry));
}
void set_muxconf_regs_non_essential(void)
{
do_set_mux((*ctrl)->control_padconf_core_base,
core_padconf_array_non_essential,
sizeof(core_padconf_array_non_essential) /
sizeof(struct pad_conf_entry));
if (omap_revision() < OMAP4460_ES1_0)
do_set_mux((*ctrl)->control_padconf_core_base,
core_padconf_array_non_essential_4430,
sizeof(core_padconf_array_non_essential_4430) /
sizeof(struct pad_conf_entry));
else
do_set_mux((*ctrl)->control_padconf_core_base,
core_padconf_array_non_essential_4460,
sizeof(core_padconf_array_non_essential_4460) /
sizeof(struct pad_conf_entry));
do_set_mux((*ctrl)->control_padconf_wkup_base,
wkup_padconf_array_non_essential,
sizeof(wkup_padconf_array_non_essential) /
sizeof(struct pad_conf_entry));
if (omap_revision() < OMAP4460_ES1_0)
do_set_mux((*ctrl)->control_padconf_wkup_base,
wkup_padconf_array_non_essential_4430,
sizeof(wkup_padconf_array_non_essential_4430) /
sizeof(struct pad_conf_entry));
}
#if !defined(CONFIG_SPL_BUILD) && defined(CONFIG_GENERIC_MMC)
int board_mmc_init(bd_t *bis)
{
return omap_mmc_init(0, 0, 0, -1, -1);
}
#endif
#ifdef CONFIG_USB_EHCI
static struct omap_usbhs_board_data usbhs_bdata = {
.port_mode[0] = OMAP_EHCI_PORT_MODE_PHY,
.port_mode[1] = OMAP_USBHS_PORT_MODE_UNUSED,
.port_mode[2] = OMAP_USBHS_PORT_MODE_UNUSED,
};
int ehci_hcd_init(int index, struct ehci_hccr **hccr, struct ehci_hcor **hcor)
{
int ret;
unsigned int utmi_clk;
/* Now we can enable our port clocks */
utmi_clk = readl((void *)CM_L3INIT_HSUSBHOST_CLKCTRL);
utmi_clk |= HSUSBHOST_CLKCTRL_CLKSEL_UTMI_P1_MASK;
sr32((void *)CM_L3INIT_HSUSBHOST_CLKCTRL, 0, 32, utmi_clk);
ret = omap_ehci_hcd_init(&usbhs_bdata, hccr, hcor);
if (ret < 0)
return ret;
return 0;
}
int ehci_hcd_stop(int index)
{
return omap_ehci_hcd_stop();
}
#endif
/*
* get_board_rev() - get board revision
*/
u32 get_board_rev(void)
{
return 0x20;
}
|
shizhai/wprobe
|
build_dir/target-mips_r2_uClibc-0.9.33.2/u-boot-2013.07-rc1/board/ti/panda/panda.c
|
C
|
gpl-2.0
| 6,157
|
# include "cudaCHECK.h"
# include "SpMt.hpp"
# include <cuda.h>
template<>
SpMt<HOST, int> & SpMt<HOST, int>::operator=(const SpMt<HOST, int> &rhs)
{
Nrows = rhs.Nrows;
Nnz = rhs.Nnz;
rowIdx = rhs.rowIdx;
colIdx = rhs.colIdx;
data = rhs.data;
return *this;
}
template<>
SpMt<HOST, int> & SpMt<HOST, int>::operator=(const SpMt<DEVICE, int> &rhs)
{
Nrows = rhs.Nrows;
Nnz = rhs.Nnz;
rowIdx = rhs.rowIdx;
colIdx = rhs.colIdx;
data = rhs.data;
return *this;
}
template<>
SpMt<HOST, long> & SpMt<HOST, long>::operator=(const SpMt<HOST, long> &rhs)
{
Nrows = rhs.Nrows;
Nnz = rhs.Nnz;
rowIdx = rhs.rowIdx;
colIdx = rhs.colIdx;
data = rhs.data;
return *this;
}
template<>
SpMt<HOST, long> & SpMt<HOST, long>::operator=(const SpMt<DEVICE, long> &rhs)
{
Nrows = rhs.Nrows;
Nnz = rhs.Nnz;
rowIdx = rhs.rowIdx;
colIdx = rhs.colIdx;
data = rhs.data;
return *this;
}
template<>
SpMt<DEVICE, int> & SpMt<DEVICE, int>::operator=(const SpMt<HOST, int> &rhs)
{
Nrows = rhs.Nrows;
Nnz = rhs.Nnz;
rowIdx = rhs.rowIdx;
colIdx = rhs.colIdx;
data = rhs.data;
return *this;
}
template<>
SpMt<DEVICE, int> & SpMt<DEVICE, int>::operator=(const SpMt<DEVICE, int> &rhs)
{
Nrows = rhs.Nrows;
Nnz = rhs.Nnz;
rowIdx = rhs.rowIdx;
colIdx = rhs.colIdx;
data = rhs.data;
return *this;
}
template<>
SpMt<DEVICE, long> & SpMt<DEVICE, long>::operator=(const SpMt<HOST, long> &rhs)
{
Nrows = rhs.Nrows;
Nnz = rhs.Nnz;
rowIdx = rhs.rowIdx;
colIdx = rhs.colIdx;
data = rhs.data;
return *this;
}
template<>
SpMt<DEVICE, long> & SpMt<DEVICE, long>::operator=(const SpMt<DEVICE, long> &rhs)
{
Nrows = rhs.Nrows;
Nnz = rhs.Nnz;
rowIdx = rhs.rowIdx;
colIdx = rhs.colIdx;
data = rhs.data;
return *this;
}
|
piyueh/TriPoisson
|
AmgXTest/src/SpMt.cpp
|
C++
|
gpl-2.0
| 1,996
|
<?php
/* 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.
*/
/**
* Links to the messages page
*/
class yui_menu_plugin_messages extends yui_menu_plugin {
function add_items(&$list, $block) {
global $CFG;
$list[$this->id] = new yui_menu_item_link($this,
get_string('messages', 'message'),
"{$CFG->wwwroot}/message/",
"{$CFG->pixpath}/i/email.gif");
}
}
|
gpreunin/HCRHS-Moodle
|
blocks/yui_menu/plugin/messages.php
|
PHP
|
gpl-2.0
| 875
|
require 'v8'
require 'nokogiri'
require_dependency 'excerpt_parser'
require_dependency 'post'
module PrettyText
class Helpers
def t(key, opts)
str = I18n.t("js." + key)
if opts
# TODO: server localisation has no parity with client
# should be fixed
opts.each do |k,v|
str.gsub!("{{#{k}}}", v)
end
end
str
end
# function here are available to v8
def avatar_template(username)
return "" unless username
user = User.where(username_lower: username.downcase).first
user.avatar_template if user.present?
end
def is_username_valid(username)
return false unless username
username = username.downcase
return User.exec_sql('select 1 from users where username_lower = ?', username).values.length == 1
end
end
@mutex = Mutex.new
@ctx_init = Mutex.new
def self.mention_matcher
Regexp.new("(\@[a-zA-Z0-9_]{#{User.username_length.begin},#{User.username_length.end}})")
end
def self.app_root
Rails.root
end
def self.create_new_context
# timeout any eval that takes longer that 5 seconds
ctx = V8::Context.new(timeout: 5000)
ctx["helpers"] = Helpers.new
ctx_load(ctx,
"vendor/assets/javascripts/md5.js",
"vendor/assets/javascripts/lodash.js",
"vendor/assets/javascripts/Markdown.Converter.js",
"lib/headless-ember.js",
"vendor/assets/javascripts/rsvp.js",
Rails.configuration.ember.handlebars_location)
ctx.eval("var Discourse = {}; Discourse.SiteSettings = #{SiteSetting.client_settings_json};")
ctx.eval("var window = {}; window.devicePixelRatio = 2;") # hack to make code think stuff is retina
ctx.eval("var I18n = {}; I18n.t = function(a,b){ return helpers.t(a,b); }");
decorate_context(ctx)
ctx_load(ctx,
"vendor/assets/javascripts/better_markdown.js",
"app/assets/javascripts/defer/html-sanitizer-bundle.js",
"app/assets/javascripts/discourse/dialects/dialect.js",
"app/assets/javascripts/discourse/lib/utilities.js",
"app/assets/javascripts/discourse/lib/markdown.js")
Dir["#{Rails.root}/app/assets/javascripts/discourse/dialects/**.js"].each do |dialect|
unless dialect =~ /\/dialect\.js$/
ctx.load(dialect)
end
end
# Load server side javascripts
if DiscoursePluginRegistry.server_side_javascripts.present?
DiscoursePluginRegistry.server_side_javascripts.each do |ssjs|
if(ssjs =~ /\.erb/)
erb = ERB.new(File.read(ssjs))
erb.filename = ssjs
ctx.eval(erb.result)
else
ctx.load(ssjs)
end
end
end
ctx['quoteTemplate'] = File.open(app_root + 'app/assets/javascripts/discourse/templates/quote.js.shbrs') {|f| f.read}
ctx['quoteEmailTemplate'] = File.open(app_root + 'lib/assets/quote_email.js.shbrs') {|f| f.read}
ctx.eval("HANDLEBARS_TEMPLATES = {
'quote': Handlebars.compile(quoteTemplate),
'quote_email': Handlebars.compile(quoteEmailTemplate),
};")
ctx
end
def self.v8
return @ctx if @ctx
# ensure we only init one of these
@ctx_init.synchronize do
return @ctx if @ctx
@ctx = create_new_context
end
@ctx
end
def self.decorate_context(context)
context.eval("Discourse.SiteSettings = #{SiteSetting.client_settings_json};")
context.eval("Discourse.CDN = '#{Rails.configuration.action_controller.asset_host}';")
context.eval("Discourse.BaseUrl = 'http://#{RailsMultisite::ConnectionManagement.current_hostname}';")
context.eval("Discourse.getURL = function(url) {return '#{Discourse::base_uri}' + url};")
end
def self.markdown(text, opts=nil)
# we use the exact same markdown converter as the client
# TODO: use the same extensions on both client and server (in particular the template for mentions)
baked = nil
@mutex.synchronize do
context = v8
# we need to do this to work in a multi site environment, many sites, many settings
decorate_context(context)
context_opts = opts || {}
context_opts[:sanitize] ||= true
context['opts'] = context_opts
context['raw'] = text
if Post.white_listed_image_classes.present?
Post.white_listed_image_classes.each do |klass|
context.eval("Discourse.Markdown.whiteListClass('#{klass}')")
end
end
context.eval('opts["mentionLookup"] = function(u){return helpers.is_username_valid(u);}')
context.eval('opts["lookupAvatar"] = function(p){return Discourse.Utilities.avatarImg({size: "tiny", avatarTemplate: helpers.avatar_template(p)});}')
baked = context.eval('Discourse.Markdown.markdownConverter(opts).makeHtml(raw)')
end
baked
end
# leaving this here, cause it invokes v8, don't want to implement twice
def self.avatar_img(avatar_template, size)
r = nil
@mutex.synchronize do
v8['avatarTemplate'] = avatar_template
v8['size'] = size
decorate_context(v8)
r = v8.eval("Discourse.Utilities.avatarImg({ avatarTemplate: avatarTemplate, size: size });")
end
r
end
def self.cook(text, opts={})
cloned = opts.dup
# we have a minor inconsistency
cloned[:topicId] = opts[:topic_id]
sanitized = markdown(text.dup, cloned)
sanitized = add_rel_nofollow_to_user_content(sanitized) if SiteSetting.add_rel_nofollow_to_user_content
sanitized
end
def self.add_rel_nofollow_to_user_content(html)
whitelist = []
domains = SiteSetting.exclude_rel_nofollow_domains
whitelist = domains.split(",") if domains.present?
site_uri = nil
doc = Nokogiri::HTML.fragment(html)
doc.css("a").each do |l|
href = l["href"].to_s
begin
uri = URI(href)
site_uri ||= URI(Discourse.base_url)
if !uri.host.present? ||
uri.host.ends_with?(site_uri.host) ||
whitelist.any?{|u| uri.host.ends_with?(u)}
# we are good no need for nofollow
else
l["rel"] = "nofollow"
end
rescue URI::InvalidURIError
# add a nofollow anyway
l["rel"] = "nofollow"
end
end
doc.to_html
end
def self.extract_links(html)
links = []
doc = Nokogiri::HTML.fragment(html)
# remove href inside quotes
doc.css("aside.quote a").each { |l| l["href"] = "" }
# extract all links from the post
doc.css("a").each { |l| links << l["href"] unless l["href"].blank? }
# extract links to quotes
doc.css("aside.quote").each do |a|
topic_id = a['data-topic']
url = "/t/topic/#{topic_id}"
if post_number = a['data-post']
url << "/#{post_number}"
end
links << url
end
links
end
def self.excerpt(html, max_length, options={})
ExcerptParser.get_excerpt(html, max_length, options)
end
def self.strip_links(string)
return string if string.blank?
# If the user is not basic, strip links from their bio
fragment = Nokogiri::HTML.fragment(string)
fragment.css('a').each {|a| a.replace(a.text) }
fragment.to_html
end
def self.make_all_links_absolute(html)
site_uri = nil
doc = Nokogiri::HTML.fragment(html)
doc.css("a").each do |l|
href = l["href"].to_s
begin
uri = URI(href)
site_uri ||= URI(Discourse.base_url)
l["href"] = "#{site_uri}#{l['href']}" unless uri.host.present?
rescue URI::InvalidURIError
# leave it
end
end
doc.to_html
end
protected
def self.ctx_load(ctx, *files)
files.each do |file|
ctx.load(app_root + file)
end
end
end
|
crowdint/reading-reviews
|
lib/pretty_text.rb
|
Ruby
|
gpl-2.0
| 7,731
|
<?php
/**
* Blog single post audio format media
*
* @package Total WordPress theme
* @subpackage Partials
* @version 3.0.0
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// Get audio html
$audio = wpex_get_post_audio_html();
// Display audio if audio exists and the post isn't protected
if ( $audio && ! post_password_required() ) : ?>
<div id="post-media" class="clr">
<div class="blog-post-audio clr">
<?php echo $audio; ?>
</div><!-- .blog-post-audio -->
</div><!-- #post-media -->
<?php
// Otherwise get post thumbnail
else : ?>
<?php get_template_part( 'partials/blog/media/blog-single-thumbnail' ); ?>
<?php endif; ?>
|
iq007/MadScape
|
wp-content/themes/Total/partials/blog/media/blog-single-audio.php
|
PHP
|
gpl-2.0
| 677
|
/* Copyright (C) 2007-2013 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Victor Julien <victor@inliniac.net>
* \author Anoop Saldanha <anoopsaldanha@gmail.com>
*/
#ifndef __TM_THREADS_COMMON_H__
#define __TM_THREADS_COMMON_H__
/** \brief Thread Model Module id's.
*
* \note anything added here should also be added to TmModuleTmmIdToString
* in tm-modules.c
*/
typedef enum {
TMM_DECODENFQ,
TMM_VERDICTNFQ,
TMM_RECEIVENFQ,
TMM_RECEIVEPCAP,
TMM_RECEIVEPCAPFILE,
TMM_DECODEPCAP,
TMM_DECODEPCAPFILE,
TMM_RECEIVEPFRING,
TMM_DECODEPFRING,
TMM_DETECT,
TMM_ALERTFASTLOG,
TMM_ALERTFASTLOG4,
TMM_ALERTFASTLOG6,
TMM_ALERTUNIFIED2ALERT,
TMM_ALERTPRELUDE,
TMM_ALERTDEBUGLOG,
TMM_ALERTSYSLOG,
TMM_LOGDROPLOG,
TMM_ALERTSYSLOG4,
TMM_ALERTSYSLOG6,
TMM_RESPONDREJECT,
TMM_LOGDNSLOG,
TMM_LOGHTTPLOG,
TMM_LOGHTTPLOG4,
TMM_LOGHTTPLOG6,
TMM_LOGTLSLOG,
TMM_LOGTLSLOG4,
TMM_LOGTLSLOG6,
TMM_LOGTCPDATALOG,
TMM_OUTPUTJSON,
TMM_PCAPLOG,
TMM_FILELOG,
TMM_FILESTORE,
TMM_STREAMTCP,
TMM_DECODEIPFW,
TMM_VERDICTIPFW,
TMM_RECEIVEIPFW,
TMM_RECEIVEERFFILE,
TMM_DECODEERFFILE,
TMM_RECEIVEERFDAG,
TMM_DECODEERFDAG,
TMM_RECEIVEAFP,
TMM_DECODEAFP,
TMM_RECEIVENETMAP,
TMM_DECODENETMAP,
TMM_ALERTPCAPINFO,
TMM_RECEIVEMPIPE,
TMM_DECODEMPIPE,
TMM_RECEIVENAPATECH,
TMM_DECODENAPATECH,
TMM_PACKETLOGGER,
TMM_TXLOGGER,
TMM_STATSLOGGER,
TMM_FILELOGGER,
TMM_FILEDATALOGGER,
TMM_STREAMINGLOGGER,
TMM_JSONALERTLOG,
TMM_JSONDROPLOG,
TMM_JSONHTTPLOG,
TMM_JSONDNSLOG,
TMM_JSONSMTPLOG,
TMM_JSONSSHLOG,
TMM_JSONSTATSLOG,
TMM_JSONTLSLOG,
TMM_JSONFILELOG,
TMM_RECEIVENFLOG,
TMM_DECODENFLOG,
TMM_JSONFLOWLOG,
TMM_JSONNETFLOWLOG,
TMM_LOGSTATSLOG,
TMM_FLOWMANAGER,
TMM_FLOWRECYCLER,
TMM_DETECTLOADER,
TMM_UNIXMANAGER,
TMM_LUALOG,
TMM_TLSSTORE,
TMM_SIZE,
} TmmId;
/*Error codes for the thread modules*/
typedef enum {
TM_ECODE_OK = 0, /**< Thread module exits OK*/
TM_ECODE_FAILED, /**< Thread module exits due to failure*/
TM_ECODE_DONE, /**< Thread module task is finished*/
} TmEcode;
/* ThreadVars type */
enum {
TVT_PPT,
TVT_MGMT,
TVT_CMD,
TVT_MAX,
};
#endif /* __TM_THREADS_COMMON_H__ */
|
alessandro-guido/suricata
|
src/tm-threads-common.h
|
C
|
gpl-2.0
| 3,073
|
<?php
/**
* WooCommerce Jetpack EU VAT Number
*
* The WooCommerce Jetpack EU VAT Number class.
*
* @version 2.3.10
* @since 2.3.9
* @author Algoritmika Ltd.
*/
if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! class_exists( 'WCJ_EU_VAT_Number' ) ) :
class WCJ_EU_VAT_Number extends WCJ_Module {
/**
* Constructor.
*
* @version 2.3.10
*/
function __construct() {
$this->id = 'eu_vat_number';
$this->short_desc = __( 'EU VAT Number', 'woocommerce-jetpack' );
$this->desc = __( 'Collect and validate EU VAT numbers on WooCommerce checkout. Automatically disable VAT for valid numbers.', 'woocommerce-jetpack' );
parent::__construct();
$this->add_tools( array(
'eu_countries_vat_rates' => array(
'title' => __( 'EU Countries VAT Rates', 'woocommerce-jetpack' ),
'desc' => __( 'Add all EU countries VAT standard rates to WooCommerce.', 'woocommerce-jetpack' ),
),
) );
if ( $this->is_enabled() ) {
/* if ( ! session_id() ) {
session_start();
} */
// add_action( 'init', 'session_start' );
add_action( 'init', array( $this, 'start_session' ) );
add_filter( 'woocommerce_checkout_fields', array( $this, 'add_eu_vat_number_checkout_field_to_frontend' ), PHP_INT_MAX );
add_filter( 'woocommerce_admin_billing_fields', array( $this, 'add_billing_eu_vat_number_field_to_admin_order_display' ), PHP_INT_MAX );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
// add_filter( 'woocommerce_form_field_text', array( $this, 'add_eu_vat_verify_button' ), PHP_INT_MAX, 4 );
add_action( 'init', array( $this, 'wcj_validate_eu_vat_number' ) );
add_filter( 'woocommerce_matched_rates', array( $this, 'maybe_exclude_vat' ), PHP_INT_MAX, 2 );
add_action( 'woocommerce_after_checkout_validation', array( $this, 'checkout_validate_vat' ), PHP_INT_MAX );
add_action( 'woocommerce_checkout_update_order_meta', array( $this, 'update_eu_vat_number_checkout_field_order_meta' ) );
add_filter( 'woocommerce_customer_meta_fields', array( $this, 'add_eu_vat_number_customer_meta_field' ) );
add_filter( 'default_checkout_billing_eu_vat_number', array( $this, 'add_default_checkout_billing_eu_vat_number' ), PHP_INT_MAX, 2 );
$this->eu_countries_vat_rates_tool = include_once( 'tools/class-wcj-eu-countries-vat-rates-tool.php' );
}
}
/**
* create_eu_countries_vat_rates_tool.
*
* @version 2.3.10
* @since 2.3.10
*/
function create_eu_countries_vat_rates_tool() {
return $this->eu_countries_vat_rates_tool->create_eu_countries_vat_rates_tool( $this->get_tool_header_html( 'eu_countries_vat_rates' ) );
}
/**
* add_default_checkout_billing_eu_vat_number.
*/
function add_default_checkout_billing_eu_vat_number( $default_value, $field_key ) {
if ( isset( $_SESSION['wcj_eu_vat_number_to_check'] ) ) {
return $_SESSION['wcj_eu_vat_number_to_check'];
} elseif ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
if ( $meta = get_user_meta( $current_user->ID, 'billing_eu_vat_number', true ) ) {
return $meta;
}
}
return $default_value;
}
/**
* add_eu_vat_number_customer_meta_field.
*/
function add_eu_vat_number_customer_meta_field( $fields ) {
$fields['billing']['fields']['billing_eu_vat_number'] = array(
'label' => get_option( 'wcj_eu_vat_number_field_label' ),
'description' => ''
);
return $fields;
}
/**
* start_session.
*/
function start_session() {
if ( ! session_id() ) {
session_start();
}
$args = array();
if ( isset( $_POST['post_data'] ) ) {
parse_str( $_POST['post_data'], $args );
if ( isset( $args['billing_eu_vat_number'] ) && isset( $_SESSION['wcj_eu_vat_number_to_check'] ) && $_SESSION['wcj_eu_vat_number_to_check'] != $args['billing_eu_vat_number'] ) {
unset( $_SESSION['wcj_is_eu_vat_number_valid'] );
unset( $_SESSION['wcj_eu_vat_number_to_check'] );
}
}
}
/**
* enqueue_scripts.
*/
function enqueue_scripts() {
if ( 'yes' === get_option( 'wcj_eu_vat_number_validate', 'yes' ) ) {
wp_enqueue_script( 'wcj-eu-vat-number', wcj_plugin_url() . '/includes/js/eu-vat-number.js', array(), false, true );
}
}
/**
* wcj_validate_eu_vat_number.
*/
function wcj_validate_eu_vat_number() {
if ( ! isset( $_GET['wcj_validate_eu_vat_number'] ) ) return;
if ( isset( $_GET['wcj_eu_vat_number_to_check'] ) && '' != $_GET['wcj_eu_vat_number_to_check'] ) {
$eu_vat_number_to_check = substr( $_GET['wcj_eu_vat_number_to_check'], 2 );
$eu_vat_number_country_to_check = substr( $_GET['wcj_eu_vat_number_to_check'], 0, 2 );
if ( 'yes' === apply_filters( 'wcj_get_option_filter', 'no', get_option( 'wcj_eu_vat_number_check_ip_location_country', 'no' ) ) ) {
$location = WC_Geolocation::geolocate_ip();
if ( empty( $location['country'] ) ) {
$location = wc_format_country_state_string( apply_filters( 'woocommerce_customer_default_location', get_option( 'woocommerce_default_country' ) ) );
}
$is_valid = ( $location['country'] === $eu_vat_number_country_to_check ) ?
validate_VAT( $eu_vat_number_country_to_check, $eu_vat_number_to_check ) :
false;
} else {
$is_valid = validate_VAT( $eu_vat_number_country_to_check, $eu_vat_number_to_check );
}
} else {
$is_valid = null;
}
$_SESSION['wcj_is_eu_vat_number_valid'] = $is_valid;
$_SESSION['wcj_eu_vat_number_to_check'] = $_GET['wcj_eu_vat_number_to_check'];
echo $is_valid;
die();
}
/**
* maybe_exclude_vat.
*/
function maybe_exclude_vat( $matched_tax_rates, $tax_class ) {
/* wcj_log( explode( '&', $_POST['post_data'] ) ); */
/* if ( ! isset( $_POST['billing_eu_vat_number'] ) ) return $matched_tax_rates; */
if (
'yes' === get_option( 'wcj_eu_vat_number_validate', 'yes' ) &&
'yes' === get_option( 'wcj_eu_vat_number_disable_for_valid', 'yes' ) &&
isset( $_SESSION['wcj_is_eu_vat_number_valid'] ) && true === $_SESSION['wcj_is_eu_vat_number_valid'] && isset( $_SESSION['wcj_eu_vat_number_to_check'] )
) {
$preserve_base_country_check_passed = true;
if ( 'yes' === apply_filters( 'wcj_get_option_filter', 'no', get_option( 'wcj_eu_vat_number_preserve_in_base_country', 'no' ) ) ) {
$location = wc_get_base_location();
if ( empty( $location['country'] ) ) {
$location = wc_format_country_state_string( apply_filters( 'woocommerce_customer_default_location', get_option( 'woocommerce_default_country' ) ) );
}
$selected_country = substr( $_SESSION['wcj_eu_vat_number_to_check'], 0, 2 );
$preserve_base_country_check_passed = ( $location['country'] !== $selected_country ) ? true : false;
}
if ( $preserve_base_country_check_passed ) {
$modified_matched_tax_rates = array();
foreach ( $matched_tax_rates as $i => $matched_tax_rate ) {
$matched_tax_rate['rate'] = 0;
$modified_matched_tax_rates[ $i ] = $matched_tax_rate;
}
return $modified_matched_tax_rates;
}
}
return $matched_tax_rates;
}
/**
* checkout_validate_vat.
*/
function checkout_validate_vat( $_posted ) {
if ( 'yes' === get_option( 'wcj_eu_vat_number_validate', 'yes' ) ) {
if (
( 'yes' === get_option( 'wcj_eu_vat_number_field_required', 'no' ) && '' == $_posted['billing_eu_vat_number'] ) ||
(
( '' != $_posted['billing_eu_vat_number'] ) &&
(
! isset( $_SESSION['wcj_is_eu_vat_number_valid'] ) || false == $_SESSION['wcj_is_eu_vat_number_valid'] ||
! isset( $_SESSION['wcj_eu_vat_number_to_check'] ) || $_posted['billing_eu_vat_number'] != $_SESSION['wcj_eu_vat_number_to_check']
)
)
) {
wc_add_notice(
get_option( 'wcj_eu_vat_number_not_valid_message', __( '<strong>EU VAT Number</strong> is not valid.', 'woocommerce-jetpack' ) ),
'error'
);
}
}
}
/**
* update_eu_vat_number_checkout_field_order_meta.
*/
function update_eu_vat_number_checkout_field_order_meta( $order_id ) {
$option_name = '_billing_' . $this->id;
if ( isset( $_POST[ $option_name ] ) ) {
update_post_meta( $order_id, $option_name, wc_clean( $_POST[ $option_name ] ) );
}
}
/**
* add_billing_eu_vat_number_field_to_admin_order_display.
*/
function add_billing_eu_vat_number_field_to_admin_order_display( $fields ) {
$fields[ $this->id ] = array(
'type' => 'text',
'label' => get_option( 'wcj_eu_vat_number_field_label' ),
'show' => true,
);
return $fields;
}
/**
* add_eu_vat_verify_button.
*
function add_eu_vat_verify_button( $field, $key, $args, $value ) {
return ( 'billing_eu_vat_number' === $key ) ?
$field . '<span style="font-size:smaller !important;">' . '[<a name="billing_eu_vat_number_verify" href="">' . __( 'Verify', 'woocommerce-jetpack' ) . '</a>]' . '</span>' :
$field;
}
/**
* add_eu_vat_number_checkout_field_to_frontend.
*/
function add_eu_vat_number_checkout_field_to_frontend( $fields ) {
$fields['billing'][ 'billing_' . $this->id ] = array(
'type' => 'text',
// 'default' => isset( $_SESSION['wcj_eu_vat_number_to_check'] ) ? $_SESSION['wcj_eu_vat_number_to_check'] : '',
'label' => get_option( 'wcj_eu_vat_number_field_label' ),
// 'description' => '',
'placeholder' => get_option( 'wcj_eu_vat_number_field_placeholder' ),
'required' => ( 'yes' === get_option( 'wcj_eu_vat_number_field_required', 'no' ) ) ? true : false,
'custom_attributes' => array(),
'clear' => ( 'yes' === get_option( 'wcj_eu_vat_number_field_clear', 'yes' ) ) ? true : false,
'class' => array( get_option( 'wcj_eu_vat_number_field_class', 'form-row-wide' ) ),
'validate' => ( 'yes' === get_option( 'wcj_eu_vat_number_validate', 'yes' ) ) ? array( 'eu-vat-number' ) : array(),
);
return $fields;
}
/**
* get_settings.
*
* @version 2.3.10
*/
function get_settings() {
$settings = array(
array(
'title' => __( 'Options', 'woocommerce-jetpack' ),
'type' => 'title',
'id' => 'wcj_eu_vat_number_options'
),
array(
'title' => __( 'Field Label', 'woocommerce-jetpack' ),
'id' => 'wcj_eu_vat_number_field_label',
'default' => __( 'EU VAT Number', 'woocommerce-jetpack' ),
'type' => 'text',
),
array(
'title' => __( 'Placeholder', 'woocommerce-jetpack' ),
'id' => 'wcj_eu_vat_number_field_placeholder',
'default' => __( 'EU VAT Number', 'woocommerce-jetpack' ),
'type' => 'text',
),
/* array(
'title' => __( 'Require Country Code in VAT Number', 'woocommerce-jetpack' ),
'id' => 'wcj_eu_vat_number_field_require_country_code',
'default' => 'yes',
'type' => 'checkbox',
), */
array(
'title' => __( 'Required', 'woocommerce-jetpack' ),
'desc' => __( 'Yes', 'woocommerce-jetpack' ),
'id' => 'wcj_eu_vat_number_field_required',
'default' => 'no',
'type' => 'checkbox',
),
array(
'title' => __( 'Clear', 'woocommerce-jetpack' ),
'desc' => __( 'Yes', 'woocommerce-jetpack' ),
'id' => 'wcj_eu_vat_number_field_clear',
'default' => 'yes',
'type' => 'checkbox',
),
array(
'title' => __( 'Class', 'woocommerce-jetpack' ),
'id' => 'wcj_eu_vat_number_field_class',
'default' => 'form-row-wide',
'type' => 'select',
'options' => array(
'form-row-wide' => __( 'Wide', 'woocommerce-jetpack' ),
'form-row-first' => __( 'First', 'woocommerce-jetpack' ),
'form-row-last' => __( 'Last', 'woocommerce-jetpack' ),
),
),
array(
'title' => __( 'Validate', 'woocommerce-jetpack' ),
'desc' => __( 'Yes', 'woocommerce-jetpack' ),
'id' => 'wcj_eu_vat_number_validate',
'default' => 'yes',
'type' => 'checkbox',
),
array(
'title' => __( 'Message on Not Valid', 'woocommerce-jetpack' ),
'id' => 'wcj_eu_vat_number_not_valid_message',
'default' => '<strong>EU VAT Number</strong> is not valid.',
'type' => 'textarea',
'css' => 'width:300px;',
),
array(
'title' => __( 'Disable VAT for Valid Numbers', 'woocommerce-jetpack' ),
'desc' => __( 'Yes', 'woocommerce-jetpack' ),
'id' => 'wcj_eu_vat_number_disable_for_valid',
'default' => 'yes',
'type' => 'checkbox',
),
array(
'title' => __( 'Preserve VAT in Base Country', 'woocommerce-jetpack' ),
'desc' => __( 'Yes', 'woocommerce-jetpack' ),
'id' => 'wcj_eu_vat_number_preserve_in_base_country',
'default' => 'no',
'type' => 'checkbox',
'desc_tip' => apply_filters( 'get_wc_jetpack_plus_message', '', 'desc' ),
'custom_attributes'
=> apply_filters( 'get_wc_jetpack_plus_message', '', 'disabled' ),
),
array(
'title' => __( 'Check for IP Location Country', 'woocommerce-jetpack' ),
'desc' => __( 'Yes', 'woocommerce-jetpack' ),
'id' => 'wcj_eu_vat_number_check_ip_location_country',
'default' => 'no',
'type' => 'checkbox',
'desc_tip' => apply_filters( 'get_wc_jetpack_plus_message', '', 'desc' ),
'custom_attributes'
=> apply_filters( 'get_wc_jetpack_plus_message', '', 'disabled' ),
),
array(
'type' => 'sectionend',
'id' => 'wcj_eu_vat_number_options'
),
);
return $this->add_standard_settings( $settings );
}
}
endif;
return new WCJ_EU_VAT_Number();
|
webprese/dev.mgeonline
|
wp-content/plugins/woocommerce-jetpack/includes/class-wcj-eu-vat-number.php
|
PHP
|
gpl-2.0
| 13,898
|
// Módulo respnsável pela criação do gráfico Stacked Area do relatório
// de participação dos alunos nas aulas da disciplina
var LectureParticipationGraph = function () {
var chart;
// Definição do gráfico
var options ={
chart: {
renderTo: '',
type: 'area',
style: { lineHeight: 'normal' }
},
title: {
text: ''
},
xAxis: {
title: {
text: 'Dias'
}
},
yAxis: {
title: {
text: 'Participação'
},
min: 0
},
legend: {
layout: 'vertical',
x: -40
},
tooltip: {
crosshairs: true,
shared: true
},
plotOptions: {
area: {
stacking: 'normal',
lineColor: '#666666',
lineWidth: 1,
marker: {
lineWidth: 1,
lineColor: '#666666'
}
}
},
series: [{
name: 'Quantidade de Pedidos de Ajuda',
}, {
name: 'Quantidade de Postagens',
}, {
name: 'Quantidade de Respostas aos Pedidos de Ajuda',
}, {
name: 'Quantidade de Respostas às Postagens'
}]
}
return {
// Carregamento do gráfico
load: function (graphView) {
// Inicializa o form com o gráfico correspondente
var graph = graphView.form.plotGraphForm(graphView.chart.renderTo);
// Passa a função de carregamento do gráfico via JSON
graph.loadGraph(function (json) {
$.extend(options, graphView);
options.series[0].data = json.helps_by_day;
options.series[1].data = json.activities_by_day;
options.series[2].data = json.answered_helps_by_day;
options.series[3].data = json.answered_activities_by_day;
options.xAxis.categories = json.days;
chart = new Highcharts.Chart(options);
})
}
}
};
|
OpenRedu/OpenRedu
|
app/assets/javascripts/chart/lectures_participation.js
|
JavaScript
|
gpl-2.0
| 1,814
|
<?php
/*
+---------------------------------------------------------------------------+
| OpenX v2.8 |
| ========== |
| |
| Copyright (c) 2003-2009 OpenX Limited |
| For contact details, see: http://www.openx.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
+---------------------------------------------------------------------------+
$Id: banner-htmlpreview.php 62345 2010-09-14 21:16:38Z chris.nutting $
*/
// Require the initialisation file
require_once '../../init.php';
// Required files
require_once MAX_PATH . '/www/admin/config.php';
require_once MAX_PATH . '/www/admin/lib-statistics.inc.php';
require_once MAX_PATH . '/lib/max/Delivery/adRender.php';
require_once MAX_PATH . '/lib/max/Admin_DA.php';
/*-------------------------------------------------------*/
/* Main code */
/*-------------------------------------------------------*/
$aBanner = Admin_DA::getAd((int) $bannerid);
$aBanner['bannerid'] = $aBanner['ad_id'];
if (!empty($aBanner))
{
$conf = $GLOBALS['_MAX']['CONF'];
$bannerName = strip_tags(phpAds_buildBannerName ($bannerid, $aBanner['name'], $aBanner['alt']));
$sizeDescription = ($aBanner['type'] == 'txt') ? ' ' : " width: {$aBanner['width']} height: {$aBanner['height']}";
$bannerCode = MAX_adRender($aBanner, 0, '', '', '', true, '', false, false);
$protocol = $GLOBALS['_MAX']['SSL_REQUEST'] ? "https" : "http";
$deliveryUrl = $protocol .':'. MAX_commonConstructPartialDeliveryUrl($conf['file']['flash']);
echo "
<html>
<head>
<title>$bannerName</title>
<link rel='stylesheet' href='" . OX::assetPath() . "/css/interface-$phpAds_TextDirection.css'>
<script type='text/javascript' src='$deliveryUrl'></script>
</head>
<body marginheight='0' marginwidth='0' leftmargin='0' topmargin='0' bgcolor='#EFEFEF'>
<table cellpadding='0' cellspacing='0' border='0'>
<tr height='32'>
<td width='32'><img src='" . OX::assetPath() . "/images/cropmark-tl.gif' width='32' height='32'></td>
<td background='" . OX::assetPath() . "/images/ruler-top.gif'> </td>
<td width='32'><img src='" . OX::assetPath() . "/images/cropmark-tr.gif' width='32' height='32'></td>
</tr>
<tr height='{$aBanner['height']}'>
<td width='32' background='" . OX::assetPath() . "/images/ruler-left.gif'> </td>
<td bgcolor='#FFFFFF' width='{$aBanner['width']}'>
$bannerCode
</td>
<td width='32'> </td>
</tr>
<tr height='32'>
<td width='32'><img src='" . OX::assetPath() . "/images/cropmark-bl.gif' width='32' height='32'></td>
<td>$sizeDescription</td>
<td width='32'><img src='" . OX::assetPath() . "/images/cropmark-br.gif' width='32' height='32'></td>
</tr>
</table>
</body>
</html>";
}
?>
|
wassemgtk/OpenX-using-S3-and-CloudFront
|
www/admin/banner-htmlpreview.php
|
PHP
|
gpl-2.0
| 4,119
|
define(
//begin v1.x content
{
"dateFormat-full": "EEEE, d MMMM y 'г'. G",
"dateFormat-long": "d MMMM y 'г'. G",
"dateFormat-medium": "dd.MM.yyyy G",
"dateFormat-short": "dd.MM.yy G",
"dateFormatItem-d": "d",
"dateFormatItem-E": "ccc",
"dateFormatItem-Ed": "E, d",
"dateFormatItem-Gy": "y G",
"dateFormatItem-H": "H",
"dateFormatItem-Hm": "H:mm",
"dateFormatItem-Hms": "H:mm:ss",
"dateFormatItem-M": "L",
"dateFormatItem-Md": "dd.MM",
"dateFormatItem-MEd": "E, dd.MM",
"dateFormatItem-MMdd": "dd.MM",
"dateFormatItem-MMM": "LLL",
"dateFormatItem-MMMd": "d MMM",
"dateFormatItem-MMMEd": "ccc, d MMM",
"dateFormatItem-ms": "mm:ss",
"dateFormatItem-y": "y G",
"dateFormatItem-yM": "MM.y G",
"dateFormatItem-yMd": "dd.MM.y G",
"dateFormatItem-yMEd": "E, dd.MM.y G",
"dateFormatItem-yMMM": "LLL y G",
"dateFormatItem-yMMMd": "d MMM y G",
"dateFormatItem-yMMMEd": "E, d MMM y G",
"dateFormatItem-yQQQ": "QQQ y G",
"dateFormatItem-yyMM": "MM.yy G",
"dateFormatItem-yyMMM": "LLL yy G",
"dateFormatItem-yyMMMEd": "E, d MMM yy G",
"dateFormatItem-yyQ": "Q yy G",
"dateFormatItem-yyyy": "y G",
"dateFormatItem-yyyyLLLL": "LLLL y G",
"dateFormatItem-yyyyMM": "MM.yyyy G",
"dateFormatItem-yyyyMMMM": "LLLL y G",
"dateFormatItem-yyyyQQQQ": "QQQQ y 'г'. G",
"days-format-abbr": [
"вс",
"пн",
"вт",
"ср",
"чт",
"пт",
"сб"
],
"days-format-narrow": [
"В",
"Пн",
"Вт",
"С",
"Ч",
"П",
"С"
],
"days-format-wide": [
"воскресенье",
"понедельник",
"вторник",
"среда",
"четверг",
"пятница",
"суббота"
],
"days-standAlone-abbr": [
"Вс",
"Пн",
"Вт",
"Ср",
"Чт",
"Пт",
"Сб"
],
"days-standAlone-narrow": [
"В",
"П",
"В",
"С",
"Ч",
"П",
"С"
],
"days-standAlone-wide": [
"Воскресенье",
"Понедельник",
"Вторник",
"Среда",
"Четверг",
"Пятница",
"Суббота"
],
"quarters-format-abbr": [
"1-й кв.",
"2-й кв.",
"3-й кв.",
"4-й кв."
],
"quarters-format-wide": [
"1-й квартал",
"2-й квартал",
"3-й квартал",
"4-й квартал"
],
"dayPeriods-format-abbr-am": "до полудня",
"dayPeriods-format-abbr-pm": "после полудня",
"dayPeriods-format-narrow-am": "дп",
"dayPeriods-format-narrow-pm": "пп",
"dayPeriods-format-wide-am": "до полудня",
"dayPeriods-format-wide-pm": "после полудня",
"dateFormatItem-yQ": "QQQ y 'г'.",
"timeFormat-full": "H:mm:ss zzzz",
"timeFormat-long": "H:mm:ss z",
"timeFormat-medium": "H:mm:ss",
"timeFormat-short": "H:mm",
"months-format-abbr": [
"янв.",
"февр.",
"марта",
"апр.",
"мая",
"июня",
"июля",
"авг.",
"сент.",
"окт.",
"нояб.",
"дек."
],
"months-format-narrow": [
"Я",
"Ф",
"М",
"А",
"М",
"И",
"И",
"А",
"С",
"О",
"Н",
"Д"
],
"months-format-wide": [
"января",
"февраля",
"марта",
"апреля",
"мая",
"июня",
"июля",
"августа",
"сентября",
"октября",
"ноября",
"декабря"
],
"months-standAlone-abbr": [
"Янв.",
"Февр.",
"Март",
"Апр.",
"Май",
"Июнь",
"Июль",
"Авг.",
"Сент.",
"Окт.",
"Нояб.",
"Дек."
],
"months-standAlone-narrow": [
"Я",
"Ф",
"М",
"А",
"М",
"И",
"И",
"А",
"С",
"О",
"Н",
"Д"
],
"months-standAlone-wide": [
"Январь",
"Февраль",
"Март",
"Апрель",
"Май",
"Июнь",
"Июль",
"Август",
"Сентябрь",
"Октябрь",
"Ноябрь",
"Декабрь"
]
}
//end v1.x content
);
|
Gambiit/pmb-on-docker
|
web_appli/pmb/javascript/dojo/dojo/cldr/nls/ru/buddhist.js
|
JavaScript
|
gpl-2.0
| 3,861
|
<?php
defined('ABSPATH') or die;
global $url;
define('MTS_TYPOGRAPHY_DEFAULT_OPT', MTS_THEME_NAME.'_typography_default');
define('MTS_TYPOGRAPHY_COLLECTIONS_OPT', MTS_THEME_NAME.'_typography_collections');
define('MTS_TYPOGRAPHY_GENERATE_PREVIEWS', true);
require_once($url.'google-typography/google-typography.php');
require_once($url.'php-po/php-po.php'); // for parsing default.po into array
if ( ! class_exists('NHP_Options') ){
if(!defined('NHP_OPTIONS_DIR')){
define('NHP_OPTIONS_DIR', trailingslashit(dirname(__FILE__)));
}
if(!defined('NHP_OPTIONS_URL')){
if( file_exists(STYLESHEETPATH.'/options/options.php') ){
define('NHP_OPTIONS_URL', trailingslashit(get_stylesheet_directory_uri()).'options/');
}elseif( file_exists(TEMPLATEPATH.'/options/options.php') ){
define('NHP_OPTIONS_URL', trailingslashit(get_template_directory_uri()).'options/');
}
}
class NHP_Options{
public $framework_url = 'http://leemason.github.com/NHP-Theme-Options-Framework/';
public $framework_version = '1.0.5';
public $url = NHP_OPTIONS_URL;
public $dir = NHP_OPTIONS_DIR;
public $page = '';
public $args = array();
public $sections = array();
public $extra_tabs = array();
public $errors = array();
public $warnings = array();
public $options = array();
/**
* Class Constructor. Defines the args for the theme options class
*
* @since NHP_Options 1.0
*
* @param $array $args Arguments. Class constructor arguments.
*/
function __construct($sections = array(), $args = array(), $extra_tabs = array()){
$defaults = array();
$defaults['opt_name'] = '';//must be defined by theme/plugin
$defaults['menu_icon'] = NHP_OPTIONS_URL.'/img/menu_icon.png';
$defaults['menu_title'] = __('Options', 'nhp-opts');
$defaults['page_icon'] = 'icon-themes';
$defaults['page_title'] = __('Options', 'nhp-opts');
$defaults['page_slug'] = '_options';
$defaults['page_cap'] = 'manage_options';
$defaults['page_type'] = 'menu';
$defaults['page_parent'] = '';
$defaults['page_position'] = 100;
$defaults['show_import_export'] = true;
$defaults['show_typography'] = true;
$defaults['show_translate'] = true;
$defaults['dev_mode'] = true;
$defaults['stylesheet_override'] = false;
$defaults['footer_credit'] = __('', 'nhp-opts');
$defaults['help_tabs'] = array();
$defaults['help_sidebar'] = __('', 'nhp-opts');
//get args
$this->args = wp_parse_args($args, $defaults);
$this->args = apply_filters('nhp-opts-args', $this->args);
$this->args = apply_filters('nhp-opts-args-'.$this->args['opt_name'], $this->args);
//get sections
$this->sections = apply_filters('nhp-opts-sections', $sections);
$this->sections = apply_filters('nhp-opts-sections-'.$this->args['opt_name'], $this->sections);
//get extra tabs
$this->extra_tabs = apply_filters('nhp-opts-extra-tabs', $extra_tabs);
$this->extra_tabs = apply_filters('nhp-opts-extra-tabs-'.$this->args['opt_name'], $this->extra_tabs);
//set option with defaults
add_action('init', array(&$this, '_set_default_options'));
//options page
add_action('admin_menu', array(&$this, '_options_page'));
//register setting
add_action('admin_init', array(&$this, '_register_setting'));
//add the js for the error handling before the form
add_action('nhp-opts-page-before-form', array(&$this, '_errors_js'), 1);
//add the js for the warning handling before the form
add_action('nhp-opts-page-before-form', array(&$this, '_warnings_js'), 2);
//hook into the wp feeds for downloading the exported settings
add_action('do_feed_nhpopts', array(&$this, '_download_options'), 1, 1);
//ajax for translation panel form
add_action('wp_ajax_mts_translation_panel',array(&$this,'ajax_mts_translation_panel'));
add_action('wp_ajax_mts_save_translation',array(&$this,'ajax_mts_save_translation'));
//get the options for use later on
$this->options = get_option($this->args['opt_name']);
}//function
/**
* ->get(); This is used to return and option value from the options array
*
* @since NHP_Options 1.0.1
*
* @param $array $args Arguments. Class constructor arguments.
*/
function get($opt_name, $default = null){
return (!empty($this->options[$opt_name])) ? $this->options[$opt_name] : $default;
}//function
/**
* ->set(); This is used to set an arbitrary option in the options array
*
* @since NHP_Options 1.0.1
*
* @param string $opt_name the name of the option being added
* @param mixed $value the value of the option being added
*/
function set($opt_name, $value) {
$this->options[$opt_name] = $value;
update_option($this->args['opt_name'], $this->options);
}
/**
* ->show(); This is used to echo and option value from the options array
*
* @since NHP_Options 1.0.1
*
* @param $array $args Arguments. Class constructor arguments.
*/
function show($opt_name){
$option = $this->get($opt_name);
if(!is_array($option)){
echo $option;
}
}//function
/**
* Get default options into an array suitable for the settings API
*
* @since NHP_Options 1.0
*
*/
function _default_values(){
$defaults = array();
foreach($this->sections as $k => $section){
if(isset($section['fields'])){
foreach($section['fields'] as $fieldk => $field){
if(!isset($field['std'])){$field['std'] = '';}
$defaults[$field['id']] = $field['std'];
}//foreach
}//if
}//foreach
//fix for notice on first page load
$defaults['last_tab'] = 0;
return $defaults;
}
/**
* Set default options on admin_init if option doesnt exist (theme activation hook caused problems, so admin_init it is)
*
* @since NHP_Options 1.0
*
*/
function _set_default_options(){
if(!get_option($this->args['opt_name'])){
add_option($this->args['opt_name'], $this->_default_values());
}
$this->options = get_option($this->args['opt_name']);
}//function
/**
* Class Theme Options Page Function, creates main options page.
*
* @since NHP_Options 1.0
*/
function _options_page(){
$this->page = add_theme_page(
$this->args['page_title'],
$this->args['menu_title'],
$this->args['page_cap'],
$this->args['page_slug'],
array(&$this, '_options_page_html'),
$this->args['menu_icon'],
$this->args['page_position']
);
add_action('admin_print_styles-'.$this->page, array(&$this, '_enqueue'));
add_action('load-'.$this->page, array(&$this, '_load_page'));
}//function
/**
* enqueue styles/js for theme page
*
* @since NHP_Options 1.0
*/
function _enqueue(){
wp_register_style(
'nhp-opts-css',
$this->url.'css/options.css',
array('farbtastic'),
time(),
'all'
);
wp_register_style(
'nhp-opts-jquery-ui-css',
apply_filters('nhp-opts-ui-theme', $this->url.'css/jquery-ui-aristo/aristo.css'),
'',
time(),
'all'
);
wp_register_style(
'font-awesome',
get_template_directory_uri().'/css/font-awesome.min.css',
'',
time(),
'all'
);
if(false === $this->args['stylesheet_override']){
wp_enqueue_style('nhp-opts-css');
wp_enqueue_style('font-awesome');
}
wp_register_script(
'nhp-opts-js',
$this->url.'js/options.js',
array('jquery'),
time(),
true
);
// pass $this->args['opt_name'] to js...
wp_localize_script( 'nhp-opts-js', 'nhpopts', array(
'opt_name' => $this->args['opt_name'],
'reset_confirm' => __('Are you sure you want to reset ALL options to default (except theme translation)?', 'mythemeshop'),
'reset_translations_confirm' => __('Are you sure you want to reset translations? You will lose all translations.', 'mythemeshop'),
'import_confirm' => __('Are you sure you want to import options? All current options will be lost.', 'mythemeshop'),
'leave_page_confirm' => __('Settings have changed, you should save them! Are you sure you want to leave this page?')
) );
wp_enqueue_script('nhp-opts-js');
do_action('nhp-opts-enqueue');
do_action('nhp-opts-enqueue-'.$this->args['opt_name']);
foreach($this->sections as $k => $section){
if(isset($section['fields'])){
foreach($section['fields'] as $fieldk => $field){
if(isset($field['type'])){
$field_class = 'NHP_Options_'.$field['type'];
if(!class_exists($field_class)){
require_once($this->dir.'fields/'.$field['type'].'/field_'.$field['type'].'.php');
}//if
if(class_exists($field_class) && method_exists($field_class, 'enqueue')){
$enqueue = new $field_class('','',$this);
$enqueue->enqueue();
}//if
}//if type
}//foreach
}//if fields
}//foreach
}//function
/**
* Download the options file, or display it
*
* @since NHP_Options 1.0.1
*/
function _download_options(){
if(!isset($_GET['secret']) || $_GET['secret'] != md5(AUTH_KEY.SECURE_AUTH_KEY)){wp_die('Invalid Secret for options use');exit;}
if(!isset($_GET['option'])){wp_die('No Option Defined');exit;}
$backup_options = get_option($_GET['option']);
$backup_options['nhp-opts-backup'] = '1';
$content = '###'.serialize($backup_options).'###';
if(isset($_GET['action']) && $_GET['action'] == 'download_options'){
header('Content-Description: File Transfer');
header('Content-type: application/txt');
header('Content-Disposition: attachment; filename="'.$_GET['option'].'_options_'.date('d-m-Y').'.txt"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
echo $content;
exit;
}else{
echo $content;
exit;
}
}
/**
* show page help
*
* @since NHP_Options 1.0
*/
function _load_page(){
//do admin head action for this page
add_action('admin_head', array(&$this, 'admin_head'));
//do admin footer text hook
add_filter('admin_footer_text', array(&$this, 'admin_footer_text'));
$screen = get_current_screen();
if(is_array($this->args['help_tabs'])){
foreach($this->args['help_tabs'] as $tab){
$screen->add_help_tab($tab);
}//foreach
}//if
if($this->args['help_sidebar'] != ''){
$screen->set_help_sidebar($this->args['help_sidebar']);
}//if
do_action('nhp-opts-load-page', $screen);
do_action('nhp-opts-load-page-'.$this->args['opt_name'], $screen);
}//function
/**
* do action nhp-opts-admin-head for theme options page
*
* @since NHP_Options 1.0
*/
function admin_head(){
do_action('nhp-opts-admin-head', $this);
do_action('nhp-opts-admin-head-'.$this->args['opt_name'], $this);
}
function admin_footer_text($footer_text){
return $this->args['footer_credit'];
}//function
/**
* Register Option for use
*
* @since NHP_Options 1.0
*/
function _register_setting(){
register_setting($this->args['opt_name'].'_group', $this->args['opt_name'], array(&$this,'_validate_options'));
foreach($this->sections as $k => $section){
add_settings_section($k.'_section', $section['title'], array(&$this, '_section_desc'), $k.'_section_group');
if(isset($section['fields'])){
foreach($section['fields'] as $fieldk => $field){
if(isset($field['title'])){
$th = (isset($field['sub_desc'])) ? '<span class="field_title">'.$field['title'].'</span><span class="description">'.$field['sub_desc'].'</span>' : '<span class="field_title">'.$field['title'].'</span>';
}else{
$th = '';
}
add_settings_field($fieldk.'_field', $th, array(&$this,'_field_input'), $k.'_section_group', $k.'_section', $field); // checkbox
}//foreach
}//if(isset($section['fields'])){
}//foreach
do_action('nhp-opts-register-settings');
do_action('nhp-opts-register-settings-'.$this->args['opt_name']);
}//function
/**
* Validate the Options options before insertion
*
* @since NHP_Options 1.0
*/
function _validate_options($plugin_options){
// Google Fonts
// stored in a separate option for backwards compatibility
if (!empty($plugin_options['google_typography_collections'])) {
// make sure not to save duplicates
$collections = array();
foreach ($plugin_options['google_typography_collections'] as $coll) {
$selector = (!empty($coll['css_selectors']) ? $coll['css_selectors'] : '0');
if (!isset($collections[$selector])){
$collections[$selector] = $coll;
}
}
$collections = array_values($collections);
update_option(MTS_TYPOGRAPHY_COLLECTIONS_OPT, $collections);
}
unset($plugin_options['google_typography_collections']);
// if translation panel enabled
// save passed translations
// if (!empty($plugin_options['translations']) && $plugin_options['translate'] == '1') {
// update_option('mts_translations_'.MTS_THEME_NAME, $plugin_options['translations']);
// }
// unset($plugin_options['translations']);
set_transient('nhp-opts-saved', '1', 1000 );
if(!empty($plugin_options['import'])){
if($plugin_options['import_code'] != ''){
$import = $plugin_options['import_code'];
}elseif($plugin_options['import_link'] != ''){
$import = wp_remote_retrieve_body( wp_remote_get($plugin_options['import_link']) );
}
$imported_options = unserialize(trim($import,'# '));
if(is_array($imported_options) && isset($imported_options['nhp-opts-backup']) && $imported_options['nhp-opts-backup'] == '1'){
$imported_options['imported'] = 1;
// Fonts
// If no typography array provided, we don't touch the current setting
if (!empty($imported_options['google_typography_collections'])) {
update_option(MTS_TYPOGRAPHY_COLLECTIONS_OPT, $imported_options['google_typography_collections']);
}
unset($imported_options['google_typography_collections']);
// same for Translations
if (!empty($imported_options['translations'])) {
update_option('mts_translations', $imported_options['translations']);
}
return $imported_options;
}
}
// reset translation
if(!empty($plugin_options['reset_translations'])) {
// don't reset settings - pass saved data
$saved_options = get_option($this->args['opt_name']);
delete_option('mts_translations_'.$this->args['opt_name']);
$saved_options['last_tab'] = 'translation_default';
return $saved_options;
}
// reset settings
if(!empty($plugin_options['defaults'])){
$plugin_options = $this->_default_values();
// Fonts
delete_option(MTS_TYPOGRAPHY_DEFAULT_OPT);
delete_option(MTS_TYPOGRAPHY_COLLECTIONS_OPT);
// don't reset mts_translations
return $plugin_options;
}//if set defaults
//validate fields (if needed)
$plugin_options = $this->_validate_values($plugin_options, $this->options);
if($this->errors){
set_transient('nhp-opts-errors', $this->errors, 1000 );
}//if errors
if($this->warnings){
set_transient('nhp-opts-warnings', $this->warnings, 1000 );
}//if errors
do_action('nhp-opts-options-validate', $plugin_options, $this->options);
do_action('nhp-opts-options-validate-'.$this->args['opt_name'], $plugin_options, $this->options);
// no need to store these
unset($plugin_options['defaults']);
unset($plugin_options['import']);
unset($plugin_options['import_code']);
unset($plugin_options['import_link']);
return $plugin_options;
}//function
/**
* Validate values from options form (used in settings api validate function)
* calls the custom validation class for the field so authors can override with custom classes
*
* @since NHP_Options 1.0
*/
function _validate_values($plugin_options, $options){
foreach($this->sections as $k => $section){
if(isset($section['fields'])){
foreach($section['fields'] as $fieldk => $field){
$field['section_id'] = $k;
if(isset($field['type']) && $field['type'] == 'multi_text'){continue;}//we cant validate this yet
if(!isset($plugin_options[$field['id']]) || $plugin_options[$field['id']] == ''){
continue;
}
//force validate of custom filed types
if(isset($field['type']) && !isset($field['validate'])){
if($field['type'] == 'color' || $field['type'] == 'color_gradient'){
$field['validate'] = 'color';
}elseif($field['type'] == 'date'){
$field['validate'] = 'date';
}
}//if
if(isset($field['validate'])){
$validate = 'NHP_Validation_'.$field['validate'];
if(!class_exists($validate)){
require_once($this->dir.'validation/'.$field['validate'].'/validation_'.$field['validate'].'.php');
}//if
if(class_exists($validate)){
$validation = new $validate($field, $plugin_options[$field['id']], $options[$field['id']]);
$plugin_options[$field['id']] = $validation->value;
if(isset($validation->error)){
$this->errors[] = $validation->error;
}
if(isset($validation->warning)){
$this->warnings[] = $validation->warning;
}
continue;
}//if
}//if
if(isset($field['validate_callback']) && function_exists($field['validate_callback'])){
$callbackvalues = call_user_func($field['validate_callback'], $field, $plugin_options[$field['id']], $options[$field['id']]);
$plugin_options[$field['id']] = $callbackvalues['value'];
if(isset($callbackvalues['error'])){
$this->errors[] = $callbackvalues['error'];
}//if
if(isset($callbackvalues['warning'])){
$this->warnings[] = $callbackvalues['warning'];
}//if
}//if
}//foreach
}//if(isset($section['fields'])){
}//foreach
return $plugin_options;
}//function
/**
* HTML OUTPUT.
*
* @since NHP_Options 1.0
*/
function _options_page_html(){
echo '<div class="wrap">';
echo (isset($this->args['intro_text']))?$this->args['intro_text']:'';
do_action('nhp-opts-page-before-form');
do_action('nhp-opts-page-before-form-'.$this->args['opt_name']);
echo '<form method="post" action="options.php" enctype="multipart/form-data" id="nhp-opts-form-wrapper">';
settings_fields($this->args['opt_name'].'_group');
echo '<input type="hidden" id="last_tab" name="'.$this->args['opt_name'].'[last_tab]" value="'.$this->options['last_tab'].'" />';
echo '<div id="nhp-opts-header">';
echo '<a href="http://mythemeshop.com" id="optionpanellogo" class="logo" target="_blank"><img src="'.$this->url.'img/optionpanellogo.png" /></a>';
echo '<span class="headtext">Welcome to your theme\'s mission control center.</span>';
echo '<a href="http://mythemeshop.com/support" class="docsupport" target="_blank"><i class="fa fa-medkit"></i> Support</a>';
echo '<div class="clear"></div><!--clearfix-->';
echo '</div>';
if(isset($_GET['settings-updated']) && $_GET['settings-updated'] == 'true' && get_transient('nhp-opts-saved') == '1'){
if(isset($this->options['imported']) && $this->options['imported'] == 1){
echo '<div id="nhp-opts-imported">'.__('<strong>Settings Imported!</strong>', 'nhp-opts').'</div>';
}else{
echo '<div id="nhp-opts-save">'.__('<strong>Settings Saved!</strong>', 'nhp-opts').'</div>';
}
delete_transient('nhp-opts-saved');
}
echo '<div id="nhp-opts-save-warn">'.__('<strong>Settings have changed, you should save them!</strong>', 'nhp-opts').'</div>';
echo '<div id="nhp-opts-field-errors">'.__('<strong><span></span> error(s) were found!</strong>', 'nhp-opts').'</div>';
echo '<div id="nhp-opts-field-warnings">'.__('<strong><span></span> warning(s) were found!</strong>', 'nhp-opts').'</div>';
echo '<div class="clear"></div><!--clearfix-->';
echo '<div id="nhp-opts-sidebar">';
echo '<ul id="nhp-opts-group-menu">';
foreach($this->sections as $k => $section){
// OnePage: tab 3-14 are homepage items
if ($k == 3) {
echo '<li id="accordion_section_group_li" class="nhp-opts-group-tab-link-li"><a href="javascript:void(0);" id="accordion_section_group_li_a" class="nhp-opts-group-tab-link-a" data-rel="3" title="Homepage"><i class="fa fa-home"></i> <span class="section_title">Homepage</span></a></li>';
echo '<div id="nhp-opts-homepage-accordion">';
}
if ($k == 15) {
echo '<li id="accordion_section_group_li" class="nhp-opts-group-tab-link-li"><a href="javascript:void(0);" id="accordion_section_group_li_a_2" class="nhp-opts-group-tab-link-a" data-rel="3" title="Blog Settings"><i class="fa fa-file-text"></i> <span class="section_title">Blog Settings</span></a></li>';
echo '<div id="nhp-opts-blog-accordion">';
}
$icon = (!isset($section['icon']))?'<i class="fa fa-cogs"></i> ':'<i class="fa '.$section['icon'].'"></i> ';
echo '<li id="'.$k.'_section_group_li" class="nhp-opts-group-tab-link-li">';
echo '<a href="javascript:void(0);" id="'.$k.'_section_group_li_a" class="nhp-opts-group-tab-link-a" data-rel="'.$k.'" title="'.$section['title'].'">'.$icon.'<span class="section_title">'.$section['title'].'</span></a>';
echo '</li>';
if ($k == 14 || $k == 18) {
echo '</div>';
}
}
do_action('nhp-opts-after-section-menu-items', $this);
do_action('nhp-opts-after-section-menu-items-'.$this->args['opt_name'], $this);
// Typography link
if(true === $this->args['show_typography']){
echo '<li id="typography_default_section_group_li" class="nhp-opts-group-tab-link-li">';
echo '<a href="javascript:void(0);" id="typography_default_section_group_li_a" class="nhp-opts-group-tab-link-a" data-rel="typography_default"><i class="fa fa-text-width"></i> '.'<span class="section_title">'.__('Typography', 'nhp-opts').'</span></a>';
echo '</li>';
}//if
// Translation link
if(true === $this->args['show_translate']){
echo '<li id="translation_default_section_group_li" class="nhp-opts-group-tab-link-li">';
echo '<a href="javascript:void(0);" id="translation_default_section_group_li_a" class="nhp-opts-group-tab-link-a" data-rel="translation_default"><i class="fa fa-flag-o"></i> '.'<span class="section_title">'.__('Translate', 'nhp-opts').'</span></a>';
echo '</li>';
}//if
// Import/export link
if(true === $this->args['show_import_export']){
echo '<li id="import_export_default_section_group_li" class="nhp-opts-group-tab-link-li">';
echo '<a href="javascript:void(0);" id="import_export_default_section_group_li_a" class="nhp-opts-group-tab-link-a" data-rel="import_export_default"><i class="fa fa-sign-in"></i> '.'<span class="section_title">'.__('Import / Export', 'nhp-opts').'</span></a>';
echo '</li>';
}//if
foreach($this->extra_tabs as $k => $tab){
$icon = (!isset($tab['icon']))?'<i class="fa fa-cogs" /> ':'<i class="'.$tab['icon'].'" /> ';
echo '<li id="'.$k.'_section_group_li" class="nhp-opts-group-tab-link-li">';
echo '<a href="javascript:void(0);" id="'.$k.'_section_group_li_a" class="nhp-opts-group-tab-link-a custom-tab" data-rel="'.$k.'">'.$icon.$tab['title'].'</a>';
echo '</li>';
}
if(true === $this->args['dev_mode']){
echo '<li id="dev_mode_default_section_group_li" class="nhp-opts-group-tab-link-li">';
echo '<a href="javascript:void(0);" id="dev_mode_default_section_group_li_a" class="nhp-opts-group-tab-link-a custom-tab" data-rel="dev_mode_default"><img src="'.$this->url.'img/glyphicons/glyphicons_195_circle_info.png" /> '.__('Dev Mode Info', 'nhp-opts').'</a>';
echo '</li>';
}//if
echo '</ul>';
echo '</div>';
echo '<div id="nhp-opts-main">';
foreach($this->sections as $k => $section){
echo '<div id="'.$k.'_section_group'.'" class="nhp-opts-group-tab">';
do_settings_sections($k.'_section_group');
echo '</div>';
}
if(true === $this->args['show_import_export']){
echo '<div id="import_export_default_section_group'.'" class="nhp-opts-group-tab">';
echo '<h3>'.__('Import / Export Options', 'nhp-opts').'</h3>';
// presets
if (!empty($this->args['presets'])) {
echo '<h4>'.__('Preset Options', 'nhp-opts').'</h4>';
echo '<div id="presets" class="nhp-opts-field-wrapper">';
foreach ($this->args['presets'] as $preset) {
echo '<div class="preset">';
echo '<h5>'.$preset['title'].'</h5>';
echo '<div class="preset-thumb-wrap">';
echo '<img src="'.$preset['thumbnail'].'" />';
echo '</div>';
if ( ! empty( $preset['demo'] ) )
echo '<a href="'.$preset['demo'].'" target="_blank" class="button button-secondary demo-button">'.__('Demo', 'nhp-opts').'</a>';
echo '<a href="#" class="button button-primary activate-button">'.__('Import', 'nhp-opts').'</a>';
echo '<input type="hidden" class="preset-data" value="'.esc_attr($preset['data']).'" />';
echo '</div>';
}
echo '</div>';
echo '<div id="import_divide"></div>';
}
echo '<h4>'.__('Import Options', 'nhp-opts').'</h4>';
echo '<p><a href="#" id="nhp-opts-import-code-button" class="button-secondary">Import Code</a></p>';
echo '<div id="nhp-opts-import-code-wrapper">';
echo '<div class="nhp-opts-section-desc">';
echo '<p class="description" id="import-code-description">'.apply_filters('nhp-opts-import-file-description',__('Insert your backup code below and hit Import to restore your site options from a backup.', 'nhp-opts')).'</p>';
echo '</div>';
echo '<div class="nhp-opts-field-wrapper">';
echo '<textarea id="import-code-value" name="'.$this->args['opt_name'].'[import_code]" class="large-text" rows="8"></textarea><br />';
echo '<input type="submit" id="nhp-opts-import" name="'.$this->args['opt_name'].'[import]" class="button-primary" value="'.__('Import', 'nhp-opts').'">';
echo '</div>';
echo '</div>';
echo '<div id="import_divide"></div>';
echo '<h4>'.__('Export Options', 'nhp-opts').'</h4>';
echo '<div class="nhp-opts-section-desc">';
//echo '<p class="description">'.apply_filters('nhp-opts-backup-description', __('Here, you can export your current theme options. Keep this safe, as you can use it for backup in case of an emergency. You can also use this to restore settings on this site, or on any other site using this theme. You can also copy the link to your settings, and duplicate it to another site, which is useful if you have a network of blogs that all need the same settings.', 'nhp-opts')).'</p>';
echo '</div>';
echo '<p><a href="#" id="nhp-opts-export-code-copy" class="button-secondary">'.__('Show Export Code', 'mythemeshop').'</a></p>';
$backup_options = $this->options;
// google typography
$typography = get_option(MTS_TYPOGRAPHY_COLLECTIONS_OPT);
if (!empty($typography)) {
$backup_options['google_typography_collections'] = $typography;
}
$mts_translations = get_option('mts_translations_'.MTS_THEME_NAME);
if (!empty($this->options['translate']) && !empty($mts_translations)) {
$backup_options['translations'] = $mts_translations;
}
$backup_options['nhp-opts-backup'] = '1';
$encoded_options = '###'.serialize($backup_options).'###';
echo '<div class="nhp-opts-field-wrapper">';
echo '<textarea class="large-text" id="nhp-opts-export-code" rows="8">';print_r($encoded_options);echo '</textarea>';
echo '</div>';
echo '<input type="text" class="large-text" id="nhp-opts-export-link-value" value="'.add_query_arg(array('feed' => 'nhpopts', 'secret' => md5(AUTH_KEY.SECURE_AUTH_KEY), 'option' => $this->args['opt_name']), site_url()).'" />';
echo '</div>';
}
if(true === $this->args['show_typography']){
echo '<div id="typography_default_section_group'.'" class="nhp-opts-group-tab">';
//echo '<h3>'.__('Theme Typography', 'nhp-opts').'</h3>';
$typography = new GoogleTypography();
$typography->options_ui();
echo '</div>';
}
if(true === $this->args['show_translate']){
echo '<div id="translation_default_section_group'.'" class="nhp-opts-group-tab">';
echo '<h3>'.__('Theme Translation Panel', 'nhp-opts').'</h3>';
echo '<div class="nhp-opts-section-desc">';
echo '<p class="description">'. __('The theme translation panel provides an easy way to translate text appearing on your site, without the hassle of handling .po .mo files. Translations are saved instantly after typing in.', 'nhp-opts').'</p>';
echo '<p id="nhp-opts-reset-translations-action"><input type="submit" id="nhp-opts-reset-translations" name="'.$this->args['opt_name'].'[reset_translations]" class="button-primary" value="'.__('Reset translations', 'nhp-opts').'"></p>';
echo '</div>';
// here comes the translation panel
$translate_enabled = false;
if (!empty($this->options['translate'])) {
$translate_enabled = true;
}
echo '<div class="nhp-opts-field-wrapper">';
echo '<p><label for="nhp-opts-translate"><input type="checkbox" name="'.$this->args['opt_name'].'[translate]" id="nhp-opts-translate" value="1" '.checked($translate_enabled, true, false).' />'.__('Enable translation panel', 'nhp-opts').'</label></p>';
echo '</div>';
echo '<div class="nhp-opts-field-wrapper" id="translate_search_wrapper">';
echo '<p><input type="text" val="" id="translate_search" placeholder="'.__('Search Translations', 'mythemeshop').'" />';
echo '</div>';
echo '<div class="nhp-opts-field-wrapper translate-strings">';
// ajaxed content
echo '</div>';
echo '</div>';
}
foreach($this->extra_tabs as $k => $tab){
echo '<div id="'.$k.'_section_group'.'" class="nhp-opts-group-tab">';
echo '<h3>'.$tab['title'].'</h3>';
echo $tab['content'];
echo '</div>';
}
if(true === $this->args['dev_mode']){
echo '<div id="dev_mode_default_section_group'.'" class="nhp-opts-group-tab">';
echo '<h3>'.__('Dev Mode Info', 'nhp-opts').'</h3>';
echo '<div class="nhp-opts-section-desc">';
echo '<textarea class="large-text" rows="24">'.print_r($this, true).'</textarea>';
echo '</div>';
echo '</div>';
}
do_action('nhp-opts-after-section-items', $this);
do_action('nhp-opts-after-section-items-'.$this->args['opt_name'], $this);
echo '<div class="clear"></div><!--clearfix-->';
echo '</div>';
echo '<div class="clear"></div><!--clearfix-->';
echo '<div id="nhp-opts-footer">';
if(isset($this->args['share_icons'])){
echo '<div id="nhp-opts-share">';
foreach($this->args['share_icons'] as $link){
echo '<a href="'.$link['link'].'" title="'.$link['title'].'" target="_blank"><i class="'.$link['img'].'"></i></a>';
}
echo '</div>';
}
echo '<input type="submit" name="'.$this->args['opt_name'].'[defaults]" value="'.__('Reset to Defaults', 'nhp-opts').'" class="button-secondary" />';
echo '<input type="submit" name="save" id="savechanges" value="'.__('Save Changes', 'nhp-opts').'" class="button-primary" />';
echo '<div class="clear"></div><!--clearfix-->';
echo '</div>';
echo '</form>';
// Floating buttons
echo '<div id="nhp-opts-bottom"></div>';
do_action('nhp-opts-page-after-form');
do_action('nhp-opts-page-after-form-'.$this->args['opt_name']);
echo '<div class="clear"></div><!--clearfix-->';
echo '</div><!--wrap-->';
}//function
/**
* JS to display the errors on the page
*
* @since NHP_Options 1.0
*/
function _errors_js(){
if(isset($_GET['settings-updated']) && $_GET['settings-updated'] == 'true' && get_transient('nhp-opts-errors')){
$errors = get_transient('nhp-opts-errors');
$section_errors = array();
foreach($errors as $error){
$section_errors[$error['section_id']] = (isset($section_errors[$error['section_id']]))?$section_errors[$error['section_id']]:0;
$section_errors[$error['section_id']]++;
}
echo '<script type="text/javascript">';
echo 'jQuery(document).ready(function(){';
echo 'jQuery("#nhp-opts-field-errors span").html("'.count($errors).'");';
echo 'jQuery("#nhp-opts-field-errors").show();';
foreach($section_errors as $sectionkey => $section_error){
echo 'jQuery("#'.$sectionkey.'_section_group_li_a").append("<span class=\"nhp-opts-menu-error\">'.$section_error.'</span>");';
}
foreach($errors as $error){
echo 'jQuery("#'.$error['id'].'").addClass("nhp-opts-field-error");';
echo 'jQuery("#'.$error['id'].'").closest("td").append("<span class=\"nhp-opts-th-error\">'.$error['msg'].'</span>");';
}
echo '});';
echo '</script>';
delete_transient('nhp-opts-errors');
}
}//function
/**
* JS to display the warnings on the page
*
* @since NHP_Options 1.0.3
*/
function _warnings_js(){
if(isset($_GET['settings-updated']) && $_GET['settings-updated'] == 'true' && get_transient('nhp-opts-warnings')){
$warnings = get_transient('nhp-opts-warnings');
$section_warnings = array();
foreach($warnings as $warning){
$section_warnings[$warning['section_id']] = (isset($section_warnings[$warning['section_id']]))?$section_warnings[$warning['section_id']]:0;
$section_warnings[$warning['section_id']]++;
}
echo '<script type="text/javascript">';
echo 'jQuery(document).ready(function(){';
echo 'jQuery("#nhp-opts-field-warnings span").html("'.count($warnings).'");';
echo 'jQuery("#nhp-opts-field-warnings").show();';
foreach($section_warnings as $sectionkey => $section_warning){
echo 'jQuery("#'.$sectionkey.'_section_group_li_a").append("<span class=\"nhp-opts-menu-warning\">'.$section_warning.'</span>");';
}
foreach($warnings as $warning){
echo 'jQuery("#'.$warning['id'].'").addClass("nhp-opts-field-warning");';
echo 'jQuery("#'.$warning['id'].'").closest("td").append("<span class=\"nhp-opts-th-warning\">'.$warning['msg'].'</span>");';
}
echo '});';
echo '</script>';
delete_transient('nhp-opts-warnings');
}
}//function
/**
* Section HTML OUTPUT.
*
* @since NHP_Options 1.0
*/
function _section_desc($section){
$id = rtrim($section['id'], '_section');
if(isset($this->sections[$id]['desc']) && !empty($this->sections[$id]['desc'])) {
echo '<div class="nhp-opts-section-desc">'.$this->sections[$id]['desc'].'</div>';
}
}//function
/**
* Field HTML OUTPUT.
*
* Gets option from options array, then calls the speicfic field type class - allows extending by other devs
*
* @since NHP_Options 1.0
*/
function _field_input($field, $group_id = '', $index = 0){
if(isset($field['callback']) && function_exists($field['callback'])){
$value = (isset($this->options[$field['id']]))?$this->options[$field['id']]:'';
do_action('nhp-opts-before-field', $field, $value);
do_action('nhp-opts-before-field-'.$this->args['opt_name'], $field, $value);
call_user_func($field['callback'], $field, $value);
do_action('nhp-opts-after-field', $field, $value);
do_action('nhp-opts-after-field-'.$this->args['opt_name'], $field, $value);
return;
}
if(isset($field['type'])){
$field_class = 'NHP_Options_'.$field['type'];
if(class_exists($field_class)){
require_once($this->dir.'fields/'.$field['type'].'/field_'.$field['type'].'.php');
}//if
if(class_exists($field_class)){
$value = (isset($this->options[$field['id']]))?$this->options[$field['id']]:'';
if (!empty($group_id)) $value = (@isset($this->options[$group_id][$index][$field['id']]))?$this->options[$group_id][$index][$field['id']]:'';
do_action('nhp-opts-before-field', $field, $value);
do_action('nhp-opts-before-field-'.$this->args['opt_name'], $field, $value);
$render = '';
$render = new $field_class($field, $value, $this);
$render->render();
do_action('nhp-opts-after-field', $field, $value);
do_action('nhp-opts-after-field-'.$this->args['opt_name'], $field, $value);
}//if
}//if $field['type']
//if (!empty($group_id)) return $value;
}//function
function ajax_mts_translation_panel() {
$poparser = new PoParser();
$mts_translations = get_option('mts_translations_'.MTS_THEME_NAME);//$this->options['translations'];
$entries = $poparser->read(get_template_directory().'/lang/default.po');
$i = 0;
$page = (empty($_POST['page']) ? 1 : (int) $_POST['page']);
$search_query = (empty($_POST['search']) ? '' : $_POST['search']);
$strings_per_page = 20;
$strings_tmp = array();
if ($search_query) {
foreach ($entries as $string_id => $object) {
$message = '';
foreach ($object['msgid'] as $line) {
$message .= $line;
}
$value = (empty($mts_translations[$message]) ? '' : $mts_translations[$message]);
if (stristr($value, $search_query) !== false || stristr($message, $search_query) !== false) {
$strings_tmp[$string_id] = $object;
}
}
$entries = $strings_tmp;
}
$number = count($entries);
$number_translated = 0;
$this->mts_translation_pagination($number, $strings_per_page, $page);
$form = '';
foreach ($entries as $string_id => $object) {
$i++;
$message = '';
foreach ($object['msgid'] as $line) {
$message .= $line;
}
if (!empty($mts_translations[$message]))
$number_translated++;
if ($i > ($page-1)*$strings_per_page && $i <= $page*$strings_per_page) {
$reference = implode(' ', $object['reference']);
$reference = implode(', ', explode(' ', $reference));
$value = (empty($mts_translations[$message]) ? '' : $mts_translations[$message]);
$form .= '<div class="translate-string-wrapper">';
// debug
//echo '<!-- '.print_r($object,1).' -->';
$form .= '<label for="translate-string-'.$i.'">'.esc_html($message).' <span>('.$reference.')</span></label>';
//echo '<input type="text" name="'.$this->args['opt_name'].'[translations]['._wp_specialchars( $message, ENT_QUOTES, false, true ).']" id="translate-string-'.$i.'" value="'._wp_specialchars( $value, ENT_QUOTES, false, true ).'">';
$form .= '<textarea id="translate-string-'.$i.'" data-id="'._wp_specialchars( $message, ENT_QUOTES, false, true ).'" class="mts_translate_textarea">';
$form .= esc_textarea($value);
$form .= '</textarea>';
$form .= '</div>';
}
}
echo $form;
if ($number == 0)
$percent = 0;
else
$percent = $number_translated / $number * 100;
echo '<div class="translation_info">'.sprintf(__('Translated <span class="translated">%1$d</span> strings out of <span class="total">%2$d</span> <span class="percent">(%3$.2f%%)</span>', 'mythemeshop'), $number_translated, $number, $percent).'</div>';
$this->mts_translation_pagination($number, $strings_per_page, $page);
exit; // required for AJAX in WP
}
function mts_translation_pagination( $items_number, $items_per_page, $current = 1 ) {
$max_page = ceil($items_number / $items_per_page);
echo '<div class="mts_translation_pagination">';
for ($i = 1; $i <= $max_page; $i++) {
echo '<a href="#"'.($i == $current ? ' class="current"' : '').'>'.$i.'</a> ';
}
echo '</div>';
}
function ajax_mts_save_translation() {
$id = stripslashes($_POST['id']);
$val = stripslashes($_POST['val']);
if ( empty( $id ) || ! is_string( $id ) || ! is_string( $val ) ) {
echo 0;
exit;
}
$translations = get_option('mts_translations_'.MTS_THEME_NAME);
$translations[$id] = $val;
update_option('mts_translations_'.MTS_THEME_NAME, $translations);
echo 1;
exit;
}
}//class
}//if
?>
|
gis3w/gis3w_site
|
wp-content/themes/onepage/options/options.php
|
PHP
|
gpl-2.0
| 44,044
|
<?php
/**
* @author Dr Kaushal Keraminiyage
* @copyright Dr Kaushal Keraminiyage
* @license GNU General Public License version 2 or later
*/
defined("_JEXEC") or die("Restricted access");
/**
* Payments list view class.
*
* @package Confmgr
* @subpackage Views
*/
class ConfmgrViewPayments extends JViewLegacy
{
protected $items;
protected $pagination;
protected $state;
protected $toolbar;
public function display($tpl = null)
{
$app = JFactory::getApplication();
$this->items = $this->get('Items');
$this->state = $this->get('State');
$this->pagination = $this->get('Pagination');
$this->user = JFactory::getUser();
$active = $app->getMenu()->getActive();
if ($active)
{
$this->params = $active->params;
}
else
{
$this->params = new JRegistry();
}
// Prepare the data.
foreach ($this->items as $item)
{
$temp = new JRegistry;
$temp->loadString($item->params);
$active = $app->getMenu()->getActive();
$item->params = clone($this->params);
$item->params->merge($temp);
}
// Check for errors.
if (count($errors = $this->get('Errors')))
{
throw new Exception(implode("\n", $errors));
return false;
}
parent::display($tpl);
}
}
?>
|
kaushal76/methmal
|
components/com_confmgr/views/payments/view.html.php
|
PHP
|
gpl-2.0
| 1,252
|
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@iahu.ca, http://libtomcrypt.org
*/
#include "mycrypt.h"
int find_cipher(const char *name)
{
int x;
_ARGCHK(name != NULL);
for (x = 0; x < TAB_SIZE; x++) {
if (cipher_descriptor[x].name != NULL && !strcmp(cipher_descriptor[x].name, name)) {
return x;
}
}
return -1;
}
|
kidmaple/CoolWall
|
user/dropbear/libtomcrypt/crypt_find_cipher.c
|
C
|
gpl-2.0
| 610
|
.content-view-ezmultiupload #multiupload {
clear: both;
height: 0;
}
.content-view-ezmultiupload #thumbnails {
margin-top: 10px;
}
.content-view-ezmultiupload #thumbnails h2 {
font-size:15px;
line-height:25px;
margin:0;
}
.content-view-ezmultiupload #thumbnails p {
margin:0;
}
.content-view-ezmultiupload #thumbnails .content-image,
.content-view-ezmultiupload #thumbnails .attribute-image,
.content-view-ezmultiupload #thumbnails .thumbnail-move-icon {
height:85px;
text-align:center;
}
.content-view-ezmultiupload .thumbnail-block {
padding: 5px 5px 0 5px;
margin: 5px;
border: 3px solid #eee;
float: left;
width: 130px;
}
.content-view-ezmultiupload .thumbnail-class-name {
padding: 3px;
background-color: #efefef;
text-align: center;
}
.content-view-ezmultiupload .thumbnail-movie-icon {
text-align: center;
}
.content-view-ezmultiupload #multiuploadProgress {
width: 320px;
display: none;
margin: 10px 0;
padding: 3px;
border: 1px solid #ffcc00;
background-color: #fff8eb;
}
.content-view-ezmultiupload #multiuploadProgress p {
word-break:keep-all;
line-height: 1;
font-weight:bold;
}
.content-view-ezmultiupload #multiuploadProgress #multiuploadProgressMessage {
color: #ff3366;
}
.content-view-ezmultiupload #multiuploadProgressBarOutline {
padding: 1px;
border: 1px solid #ccc;
}
.content-view-ezmultiupload #multiuploadProgressBar {
width: 0px;
height: 8px;
background-color: #fc8c00;
}
.content-view-ezmultiupload #uploadButtonOverlay {
max-width: 40%;
}
.content-view-ezmultiupload #cancelUploadButton {
visibility: hidden;
width: 40%;
margin-top: 1em;
border: none rgba(0,0,0,0);
background-color: #e6e6e6;
font-size: 100%;
padding: .4em 1em .45em;
box-shadow: 0 0 0 1px rgba(0,0,0,0.25) inset, 0 2px 0 rgba(255,255,255,0.30) inset, 0 1px 2px rgba(0,0,0,0.15);
background-image: linear-gradient(rgba(255,255,255,0.30),rgba(255,255,255,0.15) 40%,transparent);
transition: .1s linear box-shadow;
border-radius: 4px;
}
|
ezsystems/ezmultiupload
|
design/standard/stylesheets/ezmultiupload.css
|
CSS
|
gpl-2.0
| 2,126
|
/***************************************************************************
collectionscannerdcopiface.h - DCOP Interface
-------------------
begin : 16/08/05
copyright : (C) 2006 by Jeff Mitchell
email : kde-dev@emailgoeshere.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. *
* *
***************************************************************************/
#ifndef COLLECTIONSCANNER_DCOPIFACE_H
#define COLLECTIONSCANNER_DCOPIFACE_H
#include <dcopobject.h>
///////////////////////////////////////////////////////////////////////
// WARNING! Please ask before modifying the DCOP interface!
///////////////////////////////////////////////////////////////////////
class CollectionScannerInterface : virtual public DCOPObject
{
K_DCOP
k_dcop:
virtual void pause() = 0; ///< Pause the scanner
virtual void unpause() = 0; ///< Unpause the scanner
};
#endif
|
lwh/Pana
|
src/collectionscanner/collectionscannerdcopiface.h
|
C
|
gpl-2.0
| 1,600
|
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014 - 2015, British Columbia Institute of Technology
*
* 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.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
* @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
* @license http://opensource.org/licenses/MIT MIT License
* @link http://codeigniter.com
* @since Version 1.0.0
* @filesource
*/
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
/**
* CodeIgniter File Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/helpers/file_helper.html
*/
// ------------------------------------------------------------------------
if (! function_exists ( 'read_file' )) {
/**
* Read File
*
* Opens the file specfied in the path and returns it as a string.
*
* @todo Remove in version 3.1+.
* @deprecated 3.0.0 It is now just an alias for PHP's native file_get_contents().
* @param string $file
* file
* @return string contents
*/
function read_file($file) {
return @file_get_contents ( $file );
}
}
// ------------------------------------------------------------------------
if (! function_exists ( 'write_file' )) {
/**
* Write File
*
* Writes data to the file specified in the path.
* Creates a new file if non-existent.
*
* @param string $path
* @param string $data
* write
* @param string $mode
* (default: 'wb')
* @return bool
*/
function write_file($path, $data, $mode = 'wb') {
if (! $fp = @fopen ( $path, $mode )) {
return FALSE;
}
flock ( $fp, LOCK_EX );
for($result = $written = 0, $length = strlen ( $data ); $written < $length; $written += $result) {
if (($result = fwrite ( $fp, substr ( $data, $written ) )) === FALSE) {
break;
}
}
flock ( $fp, LOCK_UN );
fclose ( $fp );
return is_int ( $result );
}
}
// ------------------------------------------------------------------------
if (! function_exists ( 'delete_files' )) {
/**
* Delete Files
*
* Deletes all files contained in the supplied directory path.
* Files must be writable or owned by the system in order to be deleted.
* If the second parameter is set to TRUE, any directories contained
* within the supplied base directory will be nuked as well.
*
* @param string $path
* @param bool $del_dir
* delete any directories found in the path
* @param bool $htdocs
* skip deleting .htaccess and index page files
* @param int $_level
* depth level (default: 0; internal use only)
* @return bool
*/
function delete_files($path, $del_dir = FALSE, $htdocs = FALSE, $_level = 0) {
// Trim the trailing slash
$path = rtrim ( $path, '/\\' );
if (! $current_dir = @opendir ( $path )) {
return FALSE;
}
while ( FALSE !== ($filename = @readdir ( $current_dir )) ) {
if ($filename !== '.' && $filename !== '..') {
if (is_dir ( $path . DIRECTORY_SEPARATOR . $filename ) && $filename [0] !== '.') {
delete_files ( $path . DIRECTORY_SEPARATOR . $filename, $del_dir, $htdocs, $_level + 1 );
} elseif ($htdocs !== TRUE or ! preg_match ( '/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename )) {
@unlink ( $path . DIRECTORY_SEPARATOR . $filename );
}
}
}
closedir ( $current_dir );
return ($del_dir === TRUE && $_level > 0) ? @rmdir ( $path ) : TRUE;
}
}
// ------------------------------------------------------------------------
if (! function_exists ( 'get_filenames' )) {
/**
* Get Filenames
*
* Reads the specified directory and builds an array containing the filenames.
* Any sub-folders contained within the specified path are read as well.
*
* @param
* string path to source
* @param
* bool whether to include the path as part of the filename
* @param
* bool internal variable to determine recursion status - do not use in calls
* @return array
*/
function get_filenames($source_dir, $include_path = FALSE, $_recursion = FALSE) {
static $_filedata = array ();
if ($fp = @opendir ( $source_dir )) {
// reset the array and make sure $source_dir has a trailing slash on the initial call
if ($_recursion === FALSE) {
$_filedata = array ();
$source_dir = rtrim ( realpath ( $source_dir ), DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR;
}
while ( FALSE !== ($file = readdir ( $fp )) ) {
if (is_dir ( $source_dir . $file ) && $file [0] !== '.') {
get_filenames ( $source_dir . $file . DIRECTORY_SEPARATOR, $include_path, TRUE );
} elseif ($file [0] !== '.') {
$_filedata [] = ($include_path === TRUE) ? $source_dir . $file : $file;
}
}
closedir ( $fp );
return $_filedata;
}
return FALSE;
}
}
// --------------------------------------------------------------------
if (! function_exists ( 'get_dir_file_info' )) {
/**
* Get Directory File Information
*
* Reads the specified directory and builds an array containing the filenames,
* filesize, dates, and permissions
*
* Any sub-folders contained within the specified path are read as well.
*
* @param
* string path to source
* @param
* bool Look only at the top level directory specified?
* @param
* bool internal variable to determine recursion status - do not use in calls
* @return array
*/
function get_dir_file_info($source_dir, $top_level_only = TRUE, $_recursion = FALSE) {
static $_filedata = array ();
$relative_path = $source_dir;
if ($fp = @opendir ( $source_dir )) {
// reset the array and make sure $source_dir has a trailing slash on the initial call
if ($_recursion === FALSE) {
$_filedata = array ();
$source_dir = rtrim ( realpath ( $source_dir ), DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR;
}
// Used to be foreach (scandir($source_dir, 1) as $file), but scandir() is simply not as fast
while ( FALSE !== ($file = readdir ( $fp )) ) {
if (is_dir ( $source_dir . $file ) && $file [0] !== '.' && $top_level_only === FALSE) {
get_dir_file_info ( $source_dir . $file . DIRECTORY_SEPARATOR, $top_level_only, TRUE );
} elseif ($file [0] !== '.') {
$_filedata [$file] = get_file_info ( $source_dir . $file );
$_filedata [$file] ['relative_path'] = $relative_path;
}
}
closedir ( $fp );
return $_filedata;
}
return FALSE;
}
}
// --------------------------------------------------------------------
if (! function_exists ( 'get_file_info' )) {
/**
* Get File Info
*
* Given a file and path, returns the name, path, size, date modified
* Second parameter allows you to explicitly declare what information you want returned
* Options are: name, server_path, size, date, readable, writable, executable, fileperms
* Returns FALSE if the file cannot be found.
*
* @param
* string path to file
* @param
* mixed array or comma separated string of information returned
* @return array
*/
function get_file_info($file, $returned_values = array('name', 'server_path', 'size', 'date')) {
if (! file_exists ( $file )) {
return FALSE;
}
if (is_string ( $returned_values )) {
$returned_values = explode ( ',', $returned_values );
}
foreach ( $returned_values as $key ) {
switch ($key) {
case 'name' :
$fileinfo ['name'] = basename ( $file );
break;
case 'server_path' :
$fileinfo ['server_path'] = $file;
break;
case 'size' :
$fileinfo ['size'] = filesize ( $file );
break;
case 'date' :
$fileinfo ['date'] = filemtime ( $file );
break;
case 'readable' :
$fileinfo ['readable'] = is_readable ( $file );
break;
case 'writable' :
$fileinfo ['writable'] = is_really_writable ( $file );
break;
case 'executable' :
$fileinfo ['executable'] = is_executable ( $file );
break;
case 'fileperms' :
$fileinfo ['fileperms'] = fileperms ( $file );
break;
}
}
return $fileinfo;
}
}
// --------------------------------------------------------------------
if (! function_exists ( 'get_mime_by_extension' )) {
/**
* Get Mime by Extension
*
* Translates a file extension into a mime type based on config/mimes.php.
* Returns FALSE if it can't determine the type, or open the mime config file
*
* Note: this is NOT an accurate way of determining file mime types, and is here strictly as a convenience
* It should NOT be trusted, and should certainly NOT be used for security
*
* @param string $filename
* @return string
*/
function get_mime_by_extension($filename) {
static $mimes;
if (! is_array ( $mimes )) {
$mimes = & get_mimes ();
if (empty ( $mimes )) {
return FALSE;
}
}
$extension = strtolower ( substr ( strrchr ( $filename, '.' ), 1 ) );
if (isset ( $mimes [$extension] )) {
return is_array ( $mimes [$extension] ) ? current ( $mimes [$extension] ) : // Multiple mime types, just give the first one
$mimes [$extension];
}
return FALSE;
}
}
// --------------------------------------------------------------------
if (! function_exists ( 'symbolic_permissions' )) {
/**
* Symbolic Permissions
*
* Takes a numeric value representing a file's permissions and returns
* standard symbolic notation representing that value
*
* @param int $perms
* @return string
*/
function symbolic_permissions($perms) {
if (($perms & 0xC000) === 0xC000) {
$symbolic = 's'; // Socket
} elseif (($perms & 0xA000) === 0xA000) {
$symbolic = 'l'; // Symbolic Link
} elseif (($perms & 0x8000) === 0x8000) {
$symbolic = '-'; // Regular
} elseif (($perms & 0x6000) === 0x6000) {
$symbolic = 'b'; // Block special
} elseif (($perms & 0x4000) === 0x4000) {
$symbolic = 'd'; // Directory
} elseif (($perms & 0x2000) === 0x2000) {
$symbolic = 'c'; // Character special
} elseif (($perms & 0x1000) === 0x1000) {
$symbolic = 'p'; // FIFO pipe
} else {
$symbolic = 'u'; // Unknown
}
// Owner
$symbolic .= (($perms & 0x0100) ? 'r' : '-') . (($perms & 0x0080) ? 'w' : '-') . (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x') : (($perms & 0x0800) ? 'S' : '-'));
// Group
$symbolic .= (($perms & 0x0020) ? 'r' : '-') . (($perms & 0x0010) ? 'w' : '-') . (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x') : (($perms & 0x0400) ? 'S' : '-'));
// World
$symbolic .= (($perms & 0x0004) ? 'r' : '-') . (($perms & 0x0002) ? 'w' : '-') . (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x') : (($perms & 0x0200) ? 'T' : '-'));
return $symbolic;
}
}
// --------------------------------------------------------------------
if (! function_exists ( 'octal_permissions' )) {
/**
* Octal Permissions
*
* Takes a numeric value representing a file's permissions and returns
* a three character string representing the file's octal permissions
*
* @param int $perms
* @return string
*/
function octal_permissions($perms) {
return substr ( sprintf ( '%o', $perms ), - 3 );
}
}
|
janorivera/evaluame_org
|
system/helpers/file_helper.php
|
PHP
|
gpl-2.0
| 12,441
|
/*
Copyright (C) 2011 - 2016 by Mark de Wever <koraq@xs4all.nl>
Part of the Battle for Wesnoth Project http://www.wesnoth.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.
See the COPYING file for more details.
*/
#define GETTEXT_DOMAIN "wesnoth-lib"
#include "gui/dialogs/popup.hpp"
#include "gui/widgets/window.hpp"
#include "video.hpp"
namespace gui2
{
tpopup::tpopup() : window_(NULL)
{
}
tpopup::~tpopup()
{
hide();
}
void tpopup::show(CVideo& video,
const bool allow_interaction,
const unsigned /*auto_close_time*/)
{
if(video.faked()) {
return;
}
hide();
window_ = build_window(video);
post_build(video, *window_);
pre_show(video, *window_);
if(allow_interaction) {
window_->show_non_modal();
} else {
window_->show_tooltip(/*auto_close_time*/);
}
}
void tpopup::hide()
{
if(window_) {
window_->undraw();
delete window_;
window_ = NULL;
}
}
twindow* tpopup::build_window(CVideo& video) const
{
return build(video, window_id());
}
void tpopup::post_build(CVideo& /*video*/, twindow& /*window*/)
{
/* DO NOTHING */
}
void tpopup::pre_show(CVideo& /*video*/, twindow& /*window*/)
{
/* DO NOTHING */
}
} // namespace gui2
|
aginor/wesnoth
|
src/gui/dialogs/popup.cpp
|
C++
|
gpl-2.0
| 1,495
|
<h3>
<a name="o_acpi">خيارات Kernel: acpi</a>
</h3>
<p>تُعد ACPI (واجهة الطاقة والتكوين المتقدم) نظامًا قياسيًا يُعرِّف واجهات إدارة التكوين والطاقة بين أحد أنظمة التشغيل وBIOS (نظام المدخلات/المخرجات الأساسي). افتراضيًا، يتم تشغيل <em>ACPI</em> عندما يتم اكتشاف أن BIOS بتاريخ أحدث من عام 2000. وتوجد معلمات شائعة الاستخدام عديدة للتحكم بسلوك ACPI: <ul><li><em>pci=noacpi</em> -- عدم استخدام ACPI لتوجيه مقاطعات PCI</li><li><em>acpi=oldboot</em> -- استمرار تنشيط أجزاء ACPI ذات الصلة بالتشغيل فقط</li><li><em>acpi=off</em> -- إيقاف تشغيل ACPI تمامًا</li><li><em>acpi=force</em> -- تشغيل ACPI حتى إذا كان BIOS بتاريخ أقدم من 2000</li></ul></p>
<p>يستخدم هذا الخيار في استبدال نظام <a href="#o_apm">apm</a> القديم، خاصةً على أجهزة الكمبيوتر الجديدة.</p>
|
sTeeLM/MINIME
|
toolkit/srpm/SOURCES/gfxboot-themes-1.0.0/themes/openSUSE/help-install/ar/main::opt::o_acpi.html
|
HTML
|
gpl-2.0
| 1,137
|
Sis
===
|
kukucat0322/Sis
|
README.md
|
Markdown
|
gpl-2.0
| 8
|
//=============================================================================
// Brief : Netlink Message Iterator
// Authors : Bruno Santos <bsantos@av.it.pt>
// ----------------------------------------------------------------------------
// OPMIP - Open Proxy Mobile IP
//
// Copyright (C) 2010 Universidade de Aveiro
// Copyrigth (C) 2010 Instituto de Telecomunicações - Pólo de Aveiro
//
// This software is distributed under a license. The full license
// agreement can be found in the file LICENSE in this distribution.
// This software may not be copied, modified, sold or distributed
// other than expressed in the named license agreement.
//
// This software is distributed without any warranty.
//=============================================================================
#ifndef OPMIP_SYS_NETLINK_MESSAGE_ITERATOR__HPP_
#define OPMIP_SYS_NETLINK_MESSAGE_ITERATOR__HPP_
///////////////////////////////////////////////////////////////////////////////
#include <opmip/base.hpp>
#include <opmip/sys/netlink/header.hpp>
#include <algorithm>
///////////////////////////////////////////////////////////////////////////////
namespace opmip { namespace sys { namespace nl {
///////////////////////////////////////////////////////////////////////////////
class message_iterator {
public:
message_iterator()
: _header(0)
{ }
message_iterator(void* buffer, size_t length)
: _header(header::cast(buffer, length)), _length(length)
{ }
header& operator*() { return *_header; }
header* operator->() { return _header; }
message_iterator& operator++()
{
uchar* next = reinterpret_cast<uchar*>(_header) + align_to<4>(_header->length);
size_t len = _length - std::min<size_t>(align_to<4>(_header->length), _length);
BOOST_ASSERT(_header);
_header = header::cast(next, len);
_length = len;
return *this;
}
message_iterator operator++(int)
{
message_iterator tmp(*this);
this->operator++();
return tmp;
}
friend bool operator==(const message_iterator& rhs, const message_iterator& lhs)
{
return rhs._header == lhs._header;
}
friend bool operator!=(const message_iterator& rhs, const message_iterator& lhs)
{
return rhs._header != lhs._header;
}
private:
header* _header;
size_t _length;
};
///////////////////////////////////////////////////////////////////////////////
} /* namespace nl */ } /* namespace sys */ } /* namespace opmip */
// EOF ////////////////////////////////////////////////////////////////////////
#endif /* OPMIP_SYS_NETLINK_MESSAGE_ITERATOR__HPP_ */
|
ATNoG/opmip
|
inc/opmip/sys/netlink/message_iterator.hpp
|
C++
|
gpl-2.0
| 2,535
|
<?php
//TODO Simplify panel for events, use form flags to detect certain actions (e.g. submitted, etc)
global $wpdb, $bp, $EM_Event, $EM_Notices;
/* @var $args array */
/* @var $EM_Events array */
/* @var events_count int */
/* @var future_count int */
/* @var pending_count int */
/* @var url string */
//add new button will only appear if called from em_event_admin template tag, or if the $show_add_new var is set
if(!empty($show_add_new) && current_user_can('edit_events')) echo '<a class="em-button button add-new-h2" href="'.em_add_get_params($_SERVER['REQUEST_URI'],array('action'=>'edit','scope'=>null,'status'=>null,'event_id'=>null)).'">'.__('Add New','dbem').'</a>';
?>
<h2>Custom Event List</h2>
<div class="wrap">
<?php echo $EM_Notices; ?>
<form id="posts-filter" action="" method="get">
<div class="subsubsub">
<a href='<?php echo em_add_get_params($_SERVER['REQUEST_URI'], array('scope'=>null,'status'=>null)); ?>' <?php echo ( !isset($_GET['status']) ) ? 'class="current"':''; ?>><?php _e ( 'Upcoming', 'dbem' ); ?> <span class="count">(<?php echo $future_count; ?>)</span></a> |
<?php if( !current_user_can('publish_events') ): ?>
<a href='<?php echo em_add_get_params($_SERVER['REQUEST_URI'], array('scope'=>null,'status'=>0)); ?>' <?php echo ( isset($_GET['status']) && $_GET['status']=='0' ) ? 'class="current"':''; ?>><?php _e ( 'Pending', 'dbem' ); ?> <span class="count">(<?php echo $pending_count; ?>)</span></a> |
<?php endif; ?>
<a href='<?php echo em_add_get_params($_SERVER['REQUEST_URI'], array('scope'=>'past','status'=>null)); ?>' <?php echo ( !empty($_REQUEST['scope']) && $_REQUEST['scope'] == 'past' ) ? 'class="current"':''; ?>><?php _e ( 'Past Events', 'dbem' ); ?></a>
</div>
<p class="search-box">
<label class="screen-reader-text" for="post-search-input"><?php _e('Search Events','dbem'); ?>:</label>
<input type="text" id="post-search-input" name="em_search" value="<?php echo (!empty($_REQUEST['em_search'])) ? $_REQUEST['em_search']:''; ?>" />
<input type="submit" value="<?php _e('Search Events','dbem'); ?>" class="button" />
</p>
<div class="tablenav">
<?php
if ( $events_count >= $limit ) {
$events_nav = em_admin_paginate( $events_count, $limit, $page);
echo $events_nav;
}
?>
<br class="clear" />
</div>
<?php
if ( empty($EM_Events) ) {
echo get_option ( 'dbem_no_events_message' );
} else {
?>
<table class="widefat events-table">
<thead>
<tr>
<?php /*
<th class='manage-column column-cb check-column' scope='col'>
<input class='select-all' type="checkbox" value='1' />
</th>
*/ ?>
<th><?php _e ( 'Name', 'dbem' ); ?></th>
<th> </th>
<th><?php _e ( 'Location', 'dbem' ); ?></th>
<th colspan="2"><?php _e ( 'Date and time', 'dbem' ); ?></th>
</tr>
</thead>
<tbody>
<?php
foreach ( $EM_Events as $event ) {
/* @var $event EM_Event */
$rowno++;
$class = ($rowno % 2) ? 'alternate' : '';
// FIXME set to american
$localised_start_date = date_i18n(get_option('dbem_date_format'), $event->start);
$localised_end_date = date_i18n(get_option('dbem_date_format'), $event->end);
$style = "";
$today = current_time('timestamp');
$location_summary = "<b>" . $event->get_location()->location_name . "</b><br/>" . $event->get_location()->location_address . " - " . $event->get_location()->location_town;
if ($event->start < $today && $event->end < $today){
$class .= " past";
}
//Check pending approval events
if ( !$event->status ){
$class .= " pending";
}
?>
<tr class="event <?php echo trim($class); ?>" <?php echo $style; ?> id="event_<?php echo $event->event_id ?>">
<?php /*
<td>
<input type='checkbox' class='row-selector' value='<?php echo $event->event_id; ?>' name='events[]' />
</td>
*/ ?>
<td>
<strong>
<a class="row-title" href="<?php echo esc_url($event->get_edit_url()); ?>"><?php echo esc_html($event->name); ?></a>
</strong>
<?php
if( get_option('dbem_rsvp_enabled') == 1 && $event->rsvp == 1 ){
?>
<br/>
<a href="<?php echo esc_url($event->get_bookings_url()); ?>"><?php echo __("Bookings",'dbem'); ?></a> –
<?php _e("Booked",'dbem'); ?>: <?php echo $event->get_bookings()->get_booked_spaces()."/".$event->get_spaces(); ?>
<?php if( get_option('dbem_bookings_approval') == 1 ): ?>
| <?php _e("Pending",'dbem') ?>: <?php echo $event->get_bookings()->get_pending_spaces(); ?>
<?php endif;
}
?>
<div class="row-actions">
<?php if( current_user_can('delete_events')) : ?>
<span class="trash"><a href="<?php echo esc_url(add_query_arg(array('action'=>'event_delete', 'event_id'=>$event->event_id, '_wpnonce'=> wp_create_nonce('event_delete_'.$event->event_id)))); ?>" class="em-event-delete"><?php _e('Delete','dbem'); ?></a></span>
<?php endif; ?>
</div>
</td>
<td>
<a href="<?php echo esc_url(add_query_arg(array('action'=>'event_duplicate', 'event_id'=>$event->event_id, '_wpnonce'=> wp_create_nonce('event_duplicate_'.$event->event_id)))); ?>" title="<?php _e ( 'Duplicate this event', 'dbem' ); ?>">
<strong>+</strong>
</a>
</td>
<td>
<?php echo $location_summary; ?>
</td>
<td>
<?php echo $localised_start_date; ?>
<?php echo ($localised_end_date != $localised_start_date) ? " - $localised_end_date":'' ?>
<br />
<?php
if(!$event->event_all_day){
echo date_i18n(get_option('time_format'), $event->start) . " - " . date_i18n(get_option('time_format'), $event->end);
}else{
echo get_option('dbem_event_all_day_message');
}
?>
</td>
<td>
<?php
if ( $event->is_recurrence() ) {
$recurrence_delete_confirm = __('WARNING! You will delete ALL recurrences of this event, including booking history associated with any event in this recurrence. To keep booking information, go to the relevant single event and save it to detach it from this recurrence series.','dbem');
?>
<strong>
<?php echo $event->get_recurrence_description(); ?> <br />
<a href="<?php echo esc_url($event->get_edit_reschedule_url()); ?>"><?php _e ( 'Edit Recurring Events', 'dbem' ); ?></a>
<?php if( current_user_can('delete_events')) : ?>
<span class="trash"><a href="<?php echo esc_url(add_query_arg(array('action'=>'event_delete', 'event_id'=>$event->recurrence_id, '_wpnonce'=> wp_create_nonce('event_delete_'.$event->recurrence_id)))); ?>" class="em-event-rec-delete" onclick ="if( !confirm('<?php echo $recurrence_delete_confirm; ?>') ){ return false; }"><?php _e('Delete','dbem'); ?></a></span>
<?php endif; ?>
</strong>
<?php
}
?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
} // end of table
?>
<div class='tablenav'>
<div class="alignleft actions">
<br class='clear' />
</div>
<?php if ( $events_count >= $limit ) : ?>
<div class="tablenav-pages">
<?php
echo $events_nav;
?>
</div>
<?php endif; ?>
<br class='clear' />
</div>
</form>
</div>
|
Interoccupy/interoccupy.net
|
wp-content/themes/wp-foundation/plugins/events-manager/tables/events.php
|
PHP
|
gpl-2.0
| 7,749
|
行为型模式
========
>在软件工程中, 行为型模式为设计模式的一种类型,用来识别对象之间的常用交流模式并加以实现。如此,可在进行这些交流活动时增强弹性。
>
>**来源:** [维基百科](https://zh.wikipedia.org/wiki/%E8%A1%8C%E7%82%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F)
|
evnaz/Design-Patterns-In-Swift
|
source-cn/behavioral/header.md
|
Markdown
|
gpl-3.0
| 334
|
/** jbead - http://www.jbead.ch
Copyright (C) 2001-2012 Damian Brunold
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/>.
*/
package ch.jbead;
import java.util.HashMap;
import java.util.Map;
public class BeadCounts {
private Map<Byte, Integer> counts = new HashMap<Byte, Integer>();
public BeadCounts(Model model) {
initCounts(model);
for (Point pt : model.getUsedRect()) {
add(model.get(pt));
}
}
private void initCounts(Model model) {
for (byte color = 0; color < model.getColorCount(); color++) {
counts.put(color, 0);
}
}
private void add(byte color) {
counts.put(color, counts.get(color) + 1);
}
public int getCount(byte color) {
return counts.get(color);
}
public int getColorCount() {
int result = 0;
for (Map.Entry<Byte, Integer> entry : counts.entrySet()) {
if (entry.getValue().intValue() > 0) result++;
}
return result;
}
}
|
craftoid/jbead
|
src/ch/jbead/BeadCounts.java
|
Java
|
gpl-3.0
| 1,619
|
//# -*- mode: c++ -*-
//#
//# StopCmd.h: III
//#
//# Copyright (C) 2002-2004
//# ASTRON (Netherlands Foundation for Research in Astronomy)
//# P.O.Box 2, 7990 AA Dwingeloo, The Netherlands, softwaresupport@astron.nl
//#
//# This program is free software; you can redistribute it and/or modify
//# it under the terms of the GNU General Public License as published by
//# the Free Software Foundation; either version 2 of the License, or
//# (at your option) any later version.
//#
//# This program is distributed in the hope that it will be useful,
//# but WITHOUT ANY WARRANTY; without even the implied warranty of
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//# GNU General Public License for more details.
//#
//# You should have received a copy of the GNU General Public License
//# along with this program; if not, write to the Free Software
//# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//#
//# $Id$
#ifndef STOPCMD_H_
#define STOPCMD_H_
#include <Common/LofarTypes.h>
#include <GCF/TM/GCF_Control.h>
#include <APL/TBB_Protocol/TBB_Protocol.ph>
#include "TP_Protocol.ph"
#include "Command.h"
#include "DriverSettings.h"
namespace LOFAR {
using namespace TBB_Protocol;
namespace TBB {
class StopCmd : public Command
{
public:
// Constructors for a StopCmd object.
StopCmd();
// Destructor for StopCmd.
virtual ~StopCmd();
virtual bool isValid(GCFEvent& event);
virtual void saveTbbEvent(GCFEvent& event);
virtual void sendTpEvent();
virtual void saveTpAckEvent(GCFEvent& event);
virtual void sendTbbAckEvent(GCFPortInterface* clientport);
private:
TbbSettings *TS;
int32 itsChannels;
};
} // end TBB namespace
} // end LOFAR namespace
#endif /* STOPCMD_H_ */
|
kernsuite-debian/lofar
|
MAC/APL/PIC/TBB_Driver/src/StopCmd.h
|
C
|
gpl-3.0
| 1,779
|
/* StarField.h
Copyright (c) 2014 by Michael Zahniser
Endless Sky 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.
Endless Sky 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.
*/
#ifndef STAR_FIELD_H_
#define STAR_FIELD_H_
#include "Body.h"
#include "Shader.h"
#include "gl_header.h"
#include <vector>
class Point;
// Object to hold a set of "stars" to be drawn as a backdrop. The star pattern
// repeats every 4096 pixels. The pattern is generated by a random walk method
// so that some parts will be much denser than others, which is visually more
// interesting than if the stars were evenly spread out in perfectly random
// noise. If the view is moving, the stars are elongated in a motion blur to
// match the motion; otherwise they would seem to jitter around.
class StarField {
public:
void Init(int stars, int width);
void Draw(const Point &pos, const Point &vel) const;
private:
void SetUpGraphics();
void MakeStars(int stars, int width);
private:
int widthMod;
int tileCols;
std::vector<int> tileIndex;
std::vector<Body> haze;
Shader shader;
GLuint vao;
GLuint vbo;
GLuint offsetI;
GLuint sizeI;
GLuint cornerI;
GLuint scaleI;
GLuint rotateI;
GLuint lengthI;
GLuint translateI;
};
#endif
|
capnchainsaw/endless-sky-installer
|
source/StarField.h
|
C
|
gpl-3.0
| 1,599
|
package ru.mitrakov.self.rush.model.emulator;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import ru.mitrakov.self.rush.model.*;
import ru.mitrakov.self.rush.GcResistantIntArray;
import ru.mitrakov.self.rush.utils.collections.IIntArray;
import static ru.mitrakov.self.rush.model.Model.effectValues;
/**
* Analog of Server Actor class (reconstructed from Server v.1.3.6)
* @author Mitrakov
*/
class ActorEx extends Cells.Actor1 {
/** Array to store actor effect steps (index is effect ID, value is count of actor steps when effect is active) */
private final IIntArray effectSteps = new GcResistantIntArray(effectValues.length);
/** List of effect callback functions (index is effect ID, value is to be run when effect is over) */
private final List<Runnable> effectCallbacks = new CopyOnWriteArrayList<Runnable>();
/** List of the actor's abilities */
private final List<Model.Ability> swaggas = new CopyOnWriteArrayList<Model.Ability>();
/** Character (rabbit, squirrel, etc.) */
private Model.Character character;
/** Direction flag (TRUE - the actor looks to the right, FALSE - the actor looks left) */
private boolean directionRight = true;
/**
* Creates a new Extended Actor
* @param cell location
* @param number sequence number of actor on a {@link FieldEx Battlefield}
*/
@SuppressWarnings("ForLoopReplaceableByForEach")
ActorEx(Cell cell, int number) {
super(cell, number);
for (int i = 0; i < effectValues.length; i++) {
effectSteps.add(0);
effectCallbacks.add(null);
}
}
/**
* @return character (rabbit, squirrel, etc.)
*/
public Model.Character getCharacter() {
return character;
}
/**
* Sets a character to the actor
* @param character character (rabbit, squirrel, etc.)
*/
public void setCharacter(Model.Character character) {
this.character = character;
}
/**
* @return TRUE if the actor looks to the right (FALSE otherwise)
*/
boolean isDirectedToRight() {
return directionRight;
}
/**
* Sets the direction of the actor
* @param directedRight TRUE to set the direction to the right, FALSE - to the left
*/
void setDirectionRight(boolean directedRight) {
this.directionRight = directedRight;
}
/**
* Should be called on each step in order to increase internal effect counters
*/
void addStep() {
for (int i = 0; i < effectSteps.length(); i++) {
if (effectSteps.get(i) > 0) {
effectSteps.set(i, effectSteps.get(i)-1);
if (effectSteps.get(i) == 0 && effectCallbacks.get(i) != null)
effectCallbacks.get(i).run();
}
}
}
/**
* Sets an effect to the actor
* @param effect effect
* @param steps count of steps that the effect is active
* @param callback function to be run when the effect is over (may be NULL)
*/
void setEffect(Model.Effect effect, int steps, Runnable callback) {
int effectId = Arrays.binarySearch(effectValues, effect);
effectSteps.set(effectId, steps);
effectCallbacks.set(effectId, callback);
}
/**
* Checks whether the actor has a given effect
* @param effect effect
* @return TRUE, if the actor has a given effect
*/
boolean hasEffect(Model.Effect effect) {
int effectId = Arrays.binarySearch(effectValues, effect);
int steps = effectSteps.get(effectId);
return steps > 0;
}
/**
* Adds an ability to the actor's ability list
* @param ability ability
*/
void addSwagga(Model.Ability ability) {
swaggas.add(ability);
}
/**
* Checks whether the actor has a given ability
* @param s ability
* @return TRUE, if the actor has a given ability
*/
boolean hasSwagga(Model.Ability s) {
for (int i = 0; i < swaggas.size(); i++) {
Model.Ability v = swaggas.get(i); // don't use iterators here (Garbage Collector issues!)
if (v == s) return true;
}
return false;
}
/**
* @return list of all of the actor's abilities
*/
List<Model.Ability> getSwaggas() {
return swaggas;
}
}
|
mitrakov/applerush
|
core/src/ru/mitrakov/self/rush/model/emulator/ActorEx.java
|
Java
|
gpl-3.0
| 4,367
|
(function () {
"use strict";
function config($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/profile");
$stateProvider
.state("/", {
url: "/",
templateUrl: "js/app/views/home.html",
controller: "homeController",
controllerAs: 'vm'
})
.state("/.profile",{
url:"profile",
templateUrl:"js/app/views/profile.html"
})
.state("/.presentation",{
url:"presentation",
templateUrl: "js/app/views/presentation.html"
})
.state("/.summary",{
url:"summary",
templateUrl: "js/app/views/summary.html"
});
}
config.$inject=["$stateProvider", "$urlRouterProvider"];
angular.module("mlevel").config(config);
}());
|
logicalforhad/AngularMultilevelForm
|
springtest/src/main/resources/static/js/app/config/config.js
|
JavaScript
|
gpl-3.0
| 907
|
/************************************************************************
Copyright (C) 2011 - 2014 Project Wolframe.
All rights reserved.
This file is part of Project Wolframe.
Commercial Usage
Licensees holding valid Project Wolframe Commercial licenses may
use this file in accordance with the Project Wolframe
Commercial License Agreement provided with the Software or,
alternatively, in accordance with the terms contained
in a written agreement between the licensee and Project Wolframe.
GNU General Public License Usage
Alternatively, you can redistribute this file 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.
Wolframe 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 Wolframe. If not, see <http://www.gnu.org/licenses/>.
If you have questions regarding the use of this file, please contact
Project Wolframe.
************************************************************************/
///\file pdfPrinterDocumentImpl.hpp
///\brief Defines an implementation of the document interface of a pdfPrinter base on libhpdf
#ifndef _Wolframe_PRNT_HARU_PDF_PRINT_DOCUMENT_LIBHPDF_HPP_INCLUDED
#define _Wolframe_PRNT_HARU_PDF_PRINT_DOCUMENT_LIBHPDF_HPP_INCLUDED
#include "pdfPrinterDocument.hpp"
namespace _Wolframe {
namespace prnt {
Document* createLibHpdfDocument();
}}
#endif
|
ProjectTegano/Tegano
|
src/modules/prnt/harupdfprint/pdfPrinterDocumentImpl.hpp
|
C++
|
gpl-3.0
| 1,674
|
<?php
/*******************************************************************
* Glype is copyright and trademark 2007-2016 UpsideOut, Inc. d/b/a Glype
* and/or its licensors, successors and assigners. All rights reserved.
*
* Use of Glype is subject to the terms of the Software License Agreement.
* http://www.glype.com/license.php
*******************************************************************
* This page allows the user to change settings for their "virtual
* browser" - includes disabling/enabling referrers, choosing a user
* agent string
******************************************************************/
/*****************************************************************
* Initialize glype
******************************************************************/
require 'includes/init.php';
# Stop caching
sendNoCache();
# Start buffering
ob_start();
/*****************************************************************
* Create content
******************************************************************/
# Return without saving button
$return = empty($_GET['return']) ? '' : '<input type="button" value="Cancel" onclick="window.location=\'' . remove_html($_GET['return']) . '\'">';
$returnField = empty($_GET['return']) ? '' : '<input type="hidden" value="' . remove_html($_GET['return']) . '" name="return">';
$agent = empty($_SERVER['HTTP_USER_AGENT']) ? '' : htmlentities($_SERVER['HTTP_USER_AGENT']);
# Quote strings
function escape_single_quotes($value) {
return str_replace("'", "\'", $value);
}
function remove_html($x) {
$x = preg_replace('#"#', '', $x);
$x = preg_replace("#'#", '', $x);
$x = preg_replace('#<#', '', $x);
$x = preg_replace('#>#', '', $x);
$x = preg_replace('#\\\\#', '', $x);
return $x;
}
# Get existing values
$browser = $_SESSION['custom_browser'];
$currentUA = escape_single_quotes($browser['user_agent']);
$realReferrer = $browser['referrer'] == 'real' ? 'true' : 'false';
$customReferrer = $browser['referrer'] == 'real' ? '' : escape_single_quotes($browser['referrer']);
echo <<<OUT
<script type="text/javascript">
// Update custom ua field with value of currently selected preset
function updateCustomUA(select) {
// Get value
var newValue = select.value;
// Custom field
var customField = document.getElementById('user-agent');
// Special cases
switch ( newValue ) {
case 'none':
newValue = '';
break;
case 'custom':
customField.focus();
return;
}
// Set new value
customField.value = newValue;
}
// Set select box to "custom" field when the custom text field is edited
function setCustomUA() {
var setTo = document.getElementById('user-agent').value ? 'custom' : '';
setSelect(document.getElementById('user-agent-presets'), setTo);
}
// Set a select field by value
function setSelect(select, value) {
for ( var i=0; i < select.length; ++i ) {
if ( select[i].value == value ) {
select.selectedIndex = i;
return true;
}
}
return false
}
// Clear custom-referrer text field if real-referrer is checked
function clearCustomReferrer(checkbox) {
if ( checkbox.checked ) {
document.getElementById('custom-referrer').value = '';
}
}
// Clear real-referrer checkbox if custom-referrer text field is edited
function clearRealReferrer() {
document.getElementById('real-referrer').checked = '';
}
// Add domready function to set form to current values
window.addDomReadyFunc(function() {
document.getElementById('user-agent').value = '{$currentUA}';
if ( setSelect(document.getElementById('user-agent-presets'), '{$currentUA}') == false ) {
setCustomUA();
}
document.getElementById('real-referrer').checked = {$realReferrer};
document.getElementById('custom-referrer').value = '{$customReferrer}';
});
</script>
<h2 class="first">Edit Browser</h2>
<p>You can adjust the settings for your "virtual browser" below. These options affect the information the proxy sends to the target server.</p>
<form action="includes/process.php?action=edit-browser" method="post">
<table cellpadding="2" cellspacing="0" align="center" class="large-table">
<tr>
<th colspan="2">User Agent (<a style="cursor:help;" onmouseover="tooltip('Your user agent is sent to the server and identifies the software you are using to access the internet.')" onmouseout="exit()">?</a>)</th>
</tr>
<tr>
<td width="150">Choose from presets:</td>
<td>
<select id="user-agent-presets" onchange="updateCustomUA(this)">
<option value="Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)">XP with IE 8</option>
<option value="Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Zune 4.0; InfoPath.3; MS-RTC LM 8; .NET4.0C; .NET4.0E)">Windows 7 with IE 9</option>
<option value="Opera/9.80 (Windows NT 5.1; U; en) Presto/2.9.168 Version/11.52">XP with Opera Browser</option>
<option value="Opera/9.80 (Windows NT 6.1; U; en) Presto/2.9.168 Version/11.52">Windows 7 with Opera Browser</option>
<option value="Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27">Windows 7 with Safari</option>
<option value="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.36 Safari/535.7">Windows 7 with Chrome</option>
<option value="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:8.0) Gecko/20100101 Firefox/8.0">XP with Firefox 8</option>
<option value="Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:8.0) Gecko/20100101 Firefox/8.0">Windows 7 with Firefox 8</option>
<option value="Mozilla/5.0 (X11; Linux i686; rv:8.0) Gecko/20100101 Firefox/8.0">Linux X11 with Firefox 8</option>
<option value="Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-US) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1">Mac OS X 10.6 with Safari</option>
<option value="Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6.8; en-US; rv:8.0) Gecko/20100101 Firefox/8.0">Mac OS X 10.6 with Firefox 8</option>
<option value="Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.9.168 Version/11.52">Mac OS X 10.6 with Opera Browser</option>
<option value="Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10">iPad</option>
<option value="Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.20 (KHTML, like Gecko) Mobile/7B298g">iPhone</option>
<option value="Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0)">Windows Phone OS 7.5 and IE 9</option>
<option value="Mozilla/5.0 (Linux; U; Android 2.3.5; en-us; HTC Vision Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1">Android 2.3.5</option>
<option value="Mozilla/5.0 (BlackBerry; U; BlackBerry 9850; en-US) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.0.0.115 Mobile Safari/534.11+">Blackberry</option>
<option value="Opera/9.80 (J2ME/MIDP; Opera Mini/9.80 (S60; SymbOS; Opera Mobi/23.348; U; en) Presto/2.5.25 Version/10.54">Symbian with Opera Mini</option>
<option value="{$agent}"> - Current/Real</option>
<option value=""> - None</option>
<option value="custom"> - Custom...</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<input type="text" id="user-agent" name="user-agent" class="full-width" onchange="setCustomUA();">
</td>
</tr>
<tr>
<td colspan="2" class="small-note"><b>Note:</b> some websites may adjust content based on your user agent.</td>
</tr>
</table>
<table cellpadding="2" cellspacing="0" align="center" class="large-table">
<tr>
<th colspan="2">Referrer (<a style="cursor:help;" onmouseover="tooltip('The URL of the referring page is normally sent to the server. You can override this to a custom value or set to send no referrer for extra privacy.')" onmouseout="exit()">?</a>)</th>
</tr>
<tr>
<td width="150">Send real referrer:</td>
<td><input type="checkbox" name="real-referrer" id="real-referrer" onclick="clearCustomReferrer(this)"></td>
</tr>
<tr>
<td>Custom referrer:</td>
<td><input type="text" name="custom-referrer" id="custom-referrer" class="full-width" onchange="clearRealReferrer()"></td>
</tr>
<tr>
<td colspan="2" class="small-note"><b>Note:</b> some websites may validate your referrer and deny access if set to an unexpected value</td>
</tr>
</table>
<br>
<div style="text-align: center;"><input type="submit" value="Save"> {$return}</div>
{$returnField}
</form>
OUT;
/*****************************************************************
* Send content wrapped in our theme
******************************************************************/
# Get buffer
$content = ob_get_contents();
# Clear buffer
ob_end_clean();
# Print content wrapped in theme
echo replaceContent($content);
|
HaydenArmstrong/haydenarmstrong.github.io
|
glype-1.4.15/edit-browser.php
|
PHP
|
gpl-3.0
| 9,542
|
/*
dat-level.c -- dat level module;
Copyright (C) 2015, 2016, 2017 Bruno Félix Rezende Ribeiro
<oitofelix@gnu.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 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mininim.h"
struct level *
next_dat_level (struct level *l, int n)
{
n = validate_legacy_level_number (n);
return load_dat_level (l, n);
}
struct level *
load_dat_level (struct level *l, int n)
{
char *filename;
filename = xasprintf ("%s", levels_dat_filename);
int8_t *dat = (int8_t *)
load_resource (filename, (load_resource_f) load_file, true);
if (! dat) {
error (0, 0, "cannot read dat level file %s", filename);
return NULL;
}
al_free (filename);
int8_t *offset;
int16_t size;
dat_getres (dat, 2000 + n, &offset, &size);
if (! offset) {
error (0, 0, "incorrect format for dat level file %s", filename);
return NULL;
}
memcpy (&lv, offset, sizeof (lv));
interpret_legacy_level (l, n);
l->next_level = next_dat_level;
al_free (dat);
return l;
}
|
oitofelix/mininim
|
src/levels/dat-level.c
|
C
|
gpl-3.0
| 1,569
|
/*
* Vortex OpenSplice
*
* This software and documentation are Copyright 2006 to TO_YEAR ADLINK
* Technology Limited, its affiliated companies and licensors. All rights
* reserved.
*
* Licensed under the ADLINK Software License Agreement Rev 2.7 2nd October
* 2014 (the "License"); you may not use this file except in compliance with
* the License.
* You may obtain a copy of the License at:
* $OSPL_HOME/LICENSE
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#define OS_HAS_STRTOK_R 1
#include <netdb.h>
#include "../common/code/os_gethostname.c"
#include "../common/code/os_stdlib.c"
#include "../common/code/os_stdlib_bsearch.c"
#include "../common/code/os_stdlib_strtod.c"
#include "../common/code/os_stdlib_strtol.c"
#include "../common/code/os_stdlib_strtok_r.c"
|
PrismTech/opensplice
|
src/abstraction/os/AIX5.3/code/os_stdlib.c
|
C
|
gpl-3.0
| 911
|
<?php
/**
* 2007-2016 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2016 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShopBundle\Form\Admin\Type;
use PrestaShopBundle\Form\Admin\Type\CommonAbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\Extension\Core\Type as FormType;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* This form class is responsible to create a category selector using Nested sets
*/
class ChoiceCategoriesTreeType extends CommonAbstractType
{
/**
* {@inheritdoc}
*
* Add the var choices to the view
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['choices'] = $options['list'];
$view->vars['multiple'] = $options['multiple'];
//if form is submitted, inject categories values array to check or not each field
if (!empty($view->vars['value']) && !empty($view->vars['value']['tree'])) {
$view->vars['submitted_values'] = array_flip($view->vars['value']['tree']);
}
}
/**
* {@inheritdoc}
*
* Builds the form.
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('tree', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', array(
'label' => false,
'choices' => $options['valid_list'],
'choices_as_values' => true,
'required' => false,
'multiple' => true,
'expanded' => true,
'error_bubbling' => true
));
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'label' => '',
'list' => [],
'valid_list' => [],
'multiple' => true,
));
}
/**
* Returns the block prefix of this type.
*
* @return string The prefix name
*/
public function getBlockPrefix()
{
return 'choice_tree';
}
}
|
boudel/pje
|
src/PrestaShopBundle/Form/Admin/Type/ChoiceCategoriesTreeType.php
|
PHP
|
gpl-3.0
| 3,040
|
package tahrir.io.net.broadcasts;
import com.google.common.base.Optional;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.eventbus.EventBus;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tahrir.TrConstants;
import tahrir.tools.TrUtils;
import tahrir.ui.IdentityModifiedEvent;
import java.io.*;
import java.lang.reflect.Type;
import java.security.interfaces.RSAPublicKey;
import java.util.*;
/**
* Author : Ravisvi <ravitejasvi@gmail.com>
* Date : 26/6/13
*/
public class IdentityStore {
private static Logger logger = LoggerFactory.getLogger(IdentityStore.class);
private File identityStoreFile = new File(TrConstants.IDENTITY_STORE_TEST_FILE_PATH);
//contains circles in String (label) i.e FOLLOWING, etc. And the id info in UserIdentity.
private HashMap<String, Set<UserIdentity>> usersInLabels;
public HashMap<UserIdentity, Set<String>> labelsOfUser = Maps.newHashMap();
private TreeMap<String, Set<UserIdentity>> usersWithNickname = Maps.newTreeMap();
public EventBus eventBus;
public IdentityStore(File identityStoreFile){
this.identityStoreFile=identityStoreFile;
if(identityStoreFile.exists()){
try {
FileReader identityStoreFileReader = new FileReader(identityStoreFile);
logger.info("Trying to load identity store.");
Type idStoreType = new TypeToken<Map<String, Set<UserIdentity>>>() {}.getType();
usersInLabels = TrUtils.gson.fromJson(identityStoreFileReader, idStoreType);
if (usersInLabels == null) {
logger.info("Failed to load any idStore. Creating new Identity Store.");
usersInLabels = Maps.newHashMap();
}
else {
updateOtherMaps(usersInLabels);
logger.info("Identity Store successfully loaded from file.");
}
}
catch (IOException e) {
logger.info("The identity store file doesn't exist.");
}
}
else{
usersInLabels = Maps.newHashMap();
logger.info("The identity store file doesn't exist.");
}
}
public void setEventBus(EventBus eventBus){
this.eventBus = eventBus;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IdentityStore that = (IdentityStore) o;
if (labelsOfUser != null ? !labelsOfUser.equals(that.labelsOfUser) : that.labelsOfUser != null) return false;
if (usersInLabels != null ? !usersInLabels.equals(that.usersInLabels) : that.usersInLabels != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = usersInLabels != null ? usersInLabels.hashCode() : 0;
result = 31 * result + (labelsOfUser != null ? labelsOfUser.hashCode() : 0);
return result;
}
private void updateOtherMaps(HashMap<String, Set<UserIdentity>> usersInLabel){
for (Map.Entry<String, Set<UserIdentity>> pairs : usersInLabel.entrySet()){
for(UserIdentity userIdentity: pairs.getValue()){
updateLabelsOfUsers(userIdentity, pairs.getKey());
addIdentityToUsersWithNickname(userIdentity);
}
}
}
public void addIdentity(UserIdentity identity){
//As label is not specified, this contact is not added to the file, but added temporarily to the map
if(!(labelsOfUser.containsKey(identity))){
Set<String> labels=Collections.emptySet();
labelsOfUser.put(identity, labels);
logger.debug("New identity created and label added.");
addIdentityToUsersWithNickname(identity);
}
else{
logger.debug("Identity already exists");
}
}
public void removeIdentity(UserIdentity identity){
if(labelsOfUser.containsKey(identity)){
removeIdentityFromNick(identity);
for(String label: labelsOfUser.get(identity)){
removeIdentityFromLabel(identity, label);
}
labelsOfUser.remove(identity);
logger.debug("Identity removed.");
eventBus.post(new IdentityModifiedEvent(identity, IdentityModifiedEvent.IdentityModificationType.DELETE));
updateIdentityInFile();
}
else{
//adds to the already existing identity if the label isn't present.
logger.debug("Identity doesn't exist.");
}
}
public void addIdentityWithLabel(String label, UserIdentity identity){
//checks whether the identity exists, if not, adds the identity first and then adds label.
if(!(labelsOfUser.containsKey(identity))){
Set<String> labels=Sets.newHashSet();
labels.add(label);
labelsOfUser.put(identity, labels);
logger.debug("New identity created and label added.");
addIdentityToUsersWithNickname(identity);
updateUsersInLabel(identity, label);
this.eventBus.post(new IdentityModifiedEvent(identity, IdentityModifiedEvent.IdentityModificationType.ADD));
updateIdentityInFile();
}
else{
//adds to the already existing identity if the label isn't present.
if(((labelsOfUser.get(identity)).contains(label))){
logger.debug("Identity already contains the label.");
}
else{
labelsOfUser.get(identity).add(label);
logger.debug("Added label to the existing identity.");
updateUsersInLabel(identity, label);
}
}
}
private void updateLabelsOfUsers(UserIdentity identity, String label){
if (!(labelsOfUser.containsKey(identity))){
Set<String> labelSet = Sets.newHashSet();
labelSet.add(label);
labelsOfUser.put(identity, labelSet);
}
else if(!(labelsOfUser.get(identity).contains(label))){
labelsOfUser.get(identity).add(label);
logger.debug("Label was not present on the existing identity, added it.");
}
else{
logger.debug("Identity already conains the label.");
}
}
private void updateUsersInLabel(UserIdentity identity, String label){
if (!(usersInLabels.containsKey(label))){
Set<UserIdentity> identitySet = Sets.newHashSet();
identitySet.add(identity);
usersInLabels.put(label, identitySet);
}
else if(usersInLabels.get(label).contains(identity)){
logger.debug("Label already contains identity.");
}
else{
usersInLabels.get(label).add(identity);
logger.debug("Added identity to label.");
}
}
public boolean addIdentityToUsersWithNickname(UserIdentity identity){
if(usersWithNickname.containsKey(identity.getNick())){
//usersWithNickname.get(identity.getNick()).add(identity);
//logger.debug("Nick was already present, added identity to it.");
logger.debug("Nick already present choose another.");
return false;
}
else{
Set<UserIdentity> identitySet=new HashSet();
identitySet.add(identity);
usersWithNickname.put(identity.getNick(), identitySet);
logger.debug("Nick created and identity added.");
return true;
}
}
public void removeLabelFromIdentity(String label, UserIdentity identity){
if(labelsOfUser.containsKey(identity)){
if(labelsOfUser.get(identity).contains(label)){
labelsOfUser.get(identity).remove(label);
logger.debug("Label removed from identity.");
removeIdentityFromLabel(identity, label);
eventBus.post(new IdentityModifiedEvent(identity, IdentityModifiedEvent.IdentityModificationType.DELETE));
updateIdentityInFile();
}
else{
logger.debug("The identity doesn't contain the label.");
}
}
else{
logger.debug("The identity doesn't exist");
}
}
private void removeIdentityFromLabel(UserIdentity identity, String label){
if(usersInLabels.containsKey(label)){
if(usersInLabels.get(label).contains(identity)){
usersInLabels.get(label).remove(identity);
logger.debug("Removed identity from the label.");
removeIdentityFromNick(identity);
}
else{
logger.debug("Identity not present in the label.");
}
}
else{
logger.debug("Label doesn't exist");
}
}
public boolean hasIdentityInLabel(UserIdentity identity){
//currently checks if user is FOLLOWING the identity.
if(labelsOfUser.containsKey(identity)){
if(labelsOfUser.get(identity).contains(TrConstants.FOLLOWING)){
return true;
}
}
return false;
}
public boolean hasIdentityInIdStore(UserIdentity identity){
if(usersWithNickname.containsKey(identity.getNick())){
if (usersWithNickname.get(identity.getNick()).contains(identity)){
return true;
}
else return false;
}
else return false;
}
public Set<UserIdentity> getIdentitiesWithLabel(String label){
if(usersInLabels.containsKey(label)){
logger.debug("Label was present, returning userIdentities.");
return usersInLabels.get(label);
}
else{
return Collections.emptySet();
}
}
public void removeIdentityFromNick(UserIdentity identity) {
if(usersWithNickname.containsKey(identity.getNick())){
logger.debug("Nickname exists, removing identity from it.");
usersWithNickname.get(identity.getNick()).remove(identity);
eventBus.post(new IdentityModifiedEvent(identity, IdentityModifiedEvent.IdentityModificationType.DELETE));
}
else{
logger.debug("Nickname isn't present so identity is also not present.");
}
}
public Set<String> getLabelsForIdentity(UserIdentity identity){
if(labelsOfUser.containsKey(identity)){
logger.debug("Identity was present, returning corresponding labels.");
return labelsOfUser.get(identity);
}
else{
return Collections.emptySet();
}
}
public SortedSet<UserIdentity> getUserIdentitiesStartingWith(String nick){
int indexOfLastChar=nick.length()-1;
String upperBoundNick= nick.substring(0, indexOfLastChar);
upperBoundNick += (char)(nick.charAt(indexOfLastChar)+1);
final SortedMap<String, Set<UserIdentity>> sortedMap = usersWithNickname.subMap(nick, upperBoundNick);
SortedSet<UserIdentity> sortedUserIdentities = Sets.newTreeSet(new NickNameComparator());
for (Set<UserIdentity> userIdentities : sortedMap.values()) {
sortedUserIdentities.addAll(userIdentities);
}
return sortedUserIdentities;
}
private void updateIdentityInFile() {
logger.info("Adding identities to file");
try {
//TODO: Try to append idStore into the file rather than rewriting the whole thing.
FileWriter identityStoreWriter = new FileWriter(identityStoreFile);
identityStoreWriter.write(TrUtils.gson.toJson(usersInLabels));
identityStoreWriter.close();
} catch (final IOException ioException) {
logger.error("Problem writing identities to file: the identities weren't saved.");
ioException.printStackTrace();
}
}
public Set<UserIdentity> getIdentitiesWithNick(String nick){
if(usersWithNickname.containsKey(nick)){
return usersWithNickname.get(nick);
}
else{
return Collections.emptySet();
}
}
public Optional<UserIdentity> getIdentityWithNick(String nick){
/**Current version can't handle more than one identity with same nick.
* This get's the first identity with that nick.
*/
if(usersWithNickname.containsKey(nick)){
return Optional.of(usersWithNickname.get(nick).iterator().next());
}
else{
return Optional.absent();
}
}
public Optional<UserIdentity> getIdentityWithPubKey(RSAPublicKey authorKey) {
for( Map.Entry<String, Set<UserIdentity>> entry: usersWithNickname.entrySet()){
for(UserIdentity identity: entry.getValue()){
if (identity.getPubKey().equals(authorKey)){
return Optional.of(identity);
}
}
}
return Optional.absent();
}
private static class NickNameComparator implements Comparator<UserIdentity> {
@Override
public int compare(final UserIdentity o1, final UserIdentity o2) {
int nickComparison = o1.getNick().compareTo(o2.getNick());
if (nickComparison != 0) {
return nickComparison;
} else {
return o1.getPubKey().toString().compareTo(o2.getPubKey().toString());
}
}
}
}
|
nomel7/tahrir
|
src/main/java/tahrir/io/net/broadcasts/IdentityStore.java
|
Java
|
gpl-3.0
| 13,568
|
<?php
// Yii Imports
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
// CMG Imports
use cmsgears\files\widgets\ImageUploader;
use cmsgears\icons\widgets\IconChooser;
use cmsgears\core\common\utilities\CodeGenUtil;
use cmsgears\core\common\utilities\DateUtil;
// Config
$coreProperties = $this->context->getCoreProperties();
$returnUrl = $this->context->returnUrl;
// Page
$this->title = 'Update Calendar Event | ' . $coreProperties->getSiteName();
// Sidebar
$this->context->sidebar = [ 'parent' => 'sidebar-calendar' ];
// Breadcrumbs
$this->context->breadcrumbs = [
'base' => [
[ 'label' => 'Home', 'url' => Url::toRoute( [ '/home' ], true ) ],
[ 'label' => 'Calendar', 'url' => $this->context->returnUrl ]
],
'update' => [ [ 'label' => 'Update Event' ] ]
];
$countOptions = CodeGenUtil::getRange( 1, 5 );
?>
<div class="data-crud-wrap">
<div class="data-crud-wrap-main">
<div class="data-crud">
<div class="data-crud-title">Add Calendar Event</div>
<?php $form = ActiveForm::begin( [ 'id' => 'frm-calendar', 'options' => [ 'class' => 'form' ] ] ); ?>
<div class="data-crud-form">
<div class="row max-cols-50">
<div class="col col2">
<label>Banner</label>
<?= ImageUploader::widget( [ 'model' => $banner ] ) ?>
</div>
<div class="col col2">
<?= IconChooser::widget( [ 'model' => $model, 'options' => [ 'class' => 'icon-picker-wrap' ] ] ) ?>
</div>
</div>
<div class="row max-cols-50">
<div class="col col2">
<?= $form->field( $model, 'name' ) ?>
</div>
<div class="col col2">
<?= Yii::$app->formDesigner->getIconInput( $form, $model, 'scheduledAt', [ 'options' => [ 'class' => 'datetimepicker' ], 'right' => true, 'icon' => 'cmti cmti-calendar' ] ) ?>
</div>
</div>
<div class="row max-cols-50">
<div class="col col2">
<?= $form->field( $model, 'description' )->textarea() ?>
</div>
<div class="col col2">
<?= $form->field( $model, 'content' )->textarea()->label( 'Details' ) ?>
</div>
</div>
<div class="row max-cols-50">
<div class="col col4">
<?= $form->field( $model, 'status' )->dropDownList( $statusMap, [ 'class' => 'cmt-select' ] ) ?>
</div>
</div>
</div>
<div class="bold text text-large-4 text-primary-l">Reminders before Event</div>
<div class="filler-height filler-height-small"></div>
<div class="data-crud-form">
<div class="row max-cols-100">
<div class="col col3">
<?= $form->field( $model, 'preReminderCount' )->dropDownList( $countOptions, [ 'class' => 'cmt-select' ] )->label( 'Reminder Count' ) ?>
</div>
<div class="col col3">
<?= $form->field( $model, 'preReminderInterval' )->label( 'Reminder Interval' ) ?>
</div>
<div class="col col3">
<?= $form->field( $model, 'preIntervalUnit' )->dropDownList( DateUtil::$lowDurationMap, [ 'class' => 'cmt-select' ] )->label( 'Reminder Units' ) ?>
</div>
</div>
</div>
<div class="filler-height filler-height-small"></div>
<div class="bold text text-large-4 text-primary-l">Reminders after Event</div>
<div class="filler-height filler-height-small"></div>
<div class="data-crud-form">
<div class="row max-cols-100">
<div class="col col3">
<?= $form->field( $model, 'postReminderCount' )->dropDownList( $countOptions, [ 'class' => 'cmt-select' ] )->label( 'Reminder Count' ) ?>
</div>
<div class="col col3">
<?= $form->field( $model, 'postReminderInterval' )->label( 'Reminder Interval' ) ?>
</div>
<div class="col col3">
<?= $form->field( $model, 'postIntervalUnit' )->dropDownList( DateUtil::$lowDurationMap, [ 'class' => 'cmt-select' ] )->label( 'Reminder Units' ) ?>
</div>
</div>
</div>
<div class="filler-height filler-height-small"></div>
<div class="data-crud-actions">
<?= Html::a( 'Cancel', $returnUrl, [ 'class' => 'btn btn-small' ] ); ?>
<input class="frm-element-small" type="submit" value="Update" />
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
|
cmsgears/theme-blog
|
modules/cmsgears/module-notify/frontend/views/calendar/update.php
|
PHP
|
gpl-3.0
| 4,100
|
body {
color: #868686;
background: #32C2CD url(../img/bg-default.jpg) !important;
}
#main-content {
box-shadow: 0 0 10px #757575;
-moz-box-shadow: 0 0 10px #757575;
-webkit-box-shadow:0 0 10px #757575 ;
}
a, a:hover {
text-shadow: none !important;
color: #22878E;
}
ul.faq-list li a:hover, ul.faq-list li a.active{
background: #22C0CB;
}
#header.navbar-inverse .navbar-inner {
background:#4e4e4e url("../img/top-bg.jpg") repeat-x !important;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#4e4e4e',endColorstr='#4e4e4e',GradientType=0)
border-width: 0;
}
#header .navbar-inner .nav .dropdown-toggle:hover, .navbar-inner .nav .dropdown.open .dropdown-toggle {
background-color: #333 !important;
}
#header.navbar-inverse .divider-vertical {
border-left-color: #2c2d2f;
border-right-color: #181a1b;
}
#sidebar > ul > li > a {
color: #fff !important;
}
#sidebar > ul > li a i {
color: #fff !important;
}
#sidebar > ul > li >a:hover, #sidebar > ul > li:hover>a {
color: #fff !important;
background: url("../img/side-bar-list-bg.png");
}
#sidebar > ul > li.active > a{
background: url("../img/side-bar-list-bg.png");
}
#sidebar > ul > li > ul.sub > li > a {
color: #fff;
}
.dropdown-menu li > a:hover, .dropdown-menu .active > a, .dropdown-menu .active > a:hover {
background-color: #EEEEEE;
background-image: none;
color: #333333;
filter: none;
text-decoration: none;
}
#sidebar > ul > li > ul.sub > li {
border-bottom: 1px solid #3393A2;
}
#sidebar > ul > li > ul.sub > li:last-child {
border-bottom:none;
}
.chats li.out .name {
color: #b14c4c;
}
.chats li.in .message {
border-left: 2px solid #2f8e95;
}
.chats li.in .message .arrow {
border-right: 8px solid #2f8e95;
}
.chats li.out .message .arrow {
border-left: 8px solid #b14c4c;
}
.chats li.out .message {
border-right: 2px solid #b14c4c;
}
/* Landscape phone to portrait tablet */
@media (max-width:979px) {
#sidebar {
background-color: #29a3ac !important;
-webkit-border-radius: 4px !important;
-moz-border-radius: 4px !important;
border-radius: 4px !important;
}
#sidebar > ul > li > a {
border-bottom: 1px solid #30c1cb !important;
}
#sidebar > ul > li.active > a, #sidebar > ul > li:hover > a, #sidebar > ul > li > a:hover {
border-bottom: 1px solid #30c1cb !important;
}
}
/*----*/
/*lock*/
.lock-avatar-row, .lock-form-row .tarquoise {
background: #30c1cb;
}
.lock-avatar-row img {
border:10px solid #5aced6;
}
.lock-identity span {
color:#30c1cb;;
}
.lock-form-row .tarquoise {
border:1px solid #30c1cb !important;
}
/*coming soon*/
.coming-soon .input-append .submit-btn {
background: #2fbfca;
color: #195e63;
}
.twt-color , .twt-color:hover, .blog .date .day{
color: #2fbfca !important;
}
ul.social-link li a:hover, .blog .date .month {
background: #2fbfca;
}
/*blog*/
.blog .date {
border: 1px solid #2fc0ca;
}
.blog ul li a:hover, .blog-side-bar ul li a:hover { color: #2fc0ca; text-decoration: none;}
.blog .btn:hover {
background: #2fc0ca;
}
.blog-side-bar ul.tag li a {
background: #2fc0ca;
}
/*invoice-list*/
.invoice-list h5 {
color: #2fc0ca;
}
/*about us*/
.about-us h4, .team-member h3, .team-member ul li a:hover, .contact-us h4 {
color: #2badb6;
}
|
weichaoduo/gomore
|
admin/wwwroot/admin_lap/css/style_default.css
|
CSS
|
gpl-3.0
| 3,430
|
//** Smooth Navigational Menu- By Dynamic Drive DHTML code library: http://www.dynamicdrive.com
//** Script Download/ instructions page: http://www.dynamicdrive.com/dynamicindex1/ddlevelsmenu/
//** Menu created: Nov 12, 2008
//** Dec 12th, 08" (v1.01): Fixed Shadow issue when multiple LIs within the same UL (level) contain sub menus: http://www.dynamicdrive.com/forums/showthread.php?t=39177&highlight=smooth
//** Feb 11th, 09" (v1.02): The currently active main menu item (LI A) now gets a CSS class of ".selected", including sub menu items.
//** May 1st, 09" (v1.3):
//** 1) Now supports vertical (side bar) menu mode- set "orientation" to 'v'
//** 2) In IE6, shadows are now always disabled
//** July 27th, 09" (v1.31): Fixed bug so shadows can be disabled if desired.
//** Feb 2nd, 10" (v1.4): Adds ability to specify delay before sub menus appear and disappear, respectively. See showhidedelay variable below
//** Dec 17th, 10" (v1.5): Updated menu shadow to use CSS3 box shadows when the browser is FF3.5+, IE9+, Opera9.5+, or Safari3+/Chrome. Only .js file changed.
var ddsmoothmenu={
//Specify full URL to down and right arrow images (23 is padding-right added to top level LIs with drop downs):
arrowimages: {down:['downarrowclass', '../Images/down.gif', 23], right:['rightarrowclass', '../Images/right.gif']},
transition: {overtime:300, outtime:300}, //duration of slide in/ out animation, in milliseconds
shadow: {enable:true, offsetx:5, offsety:5}, //enable shadow?
showhidedelay: {showdelay: 100, hidedelay: 200}, //set delay in milliseconds before sub menus appear and disappear, respectively
///////Stop configuring beyond here///////////////////////////
detectwebkit: navigator.userAgent.toLowerCase().indexOf("applewebkit")!=-1, //detect WebKit browsers (Safari, Chrome etc)
detectie6: document.all && !window.XMLHttpRequest,
css3support: window.msPerformance || (!document.all && document.querySelector), //detect browsers that support CSS3 box shadows (ie9+ or FF3.5+, Safari3+, Chrome etc)
getajaxmenu:function($, setting){ //function to fetch external page containing the panel DIVs
var $menucontainer=$('#'+setting.contentsource[0]) //reference empty div on page that will hold menu
$menucontainer.html("Loading Menu...")
$.ajax({
url: setting.contentsource[1], //path to external menu file
async: true,
error:function(ajaxrequest){
$menucontainer.html('Error fetching content. Server Response: '+ajaxrequest.responseText)
},
success:function(content){
$menucontainer.html(content)
ddsmoothmenu.buildmenu($, setting)
}
})
},
buildmenu:function($, setting){
var smoothmenu=ddsmoothmenu
var $mainmenu=$("#"+setting.mainmenuid+">ul") //reference main menu UL
//$mainmenu.parent().get(0).className=setting.classname || "ddsmoothmenu"
var $headers=$mainmenu.find("ul").parent()
$headers.hover(
function(e){
$(this).children('a:eq(0)').addClass('selected')
},
function(e){
$(this).children('a:eq(0)').removeClass('selected')
}
)
$headers.each(function(i){ //loop through each LI header
var $curobj=$(this).css({zIndex: 100-i}) //reference current LI header
var $subul=$(this).find('ul:eq(0)').css({display:'block'})
$subul.data('timers', {})
this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
this.istopheader=$curobj.parents("ul").length==1? true : false //is top level header?
$subul.css({top:this.istopheader && setting.orientation!='v'? this._dimensions.h+"px" : 0})
$curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: smoothmenu.arrowimages.down[2]} : {}).append( //add arrow images
'<img src="'+ (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[1] : smoothmenu.arrowimages.right[1])
+'" class="' + (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[0] : smoothmenu.arrowimages.right[0])
+ '" style="border:0;" />'
)
if (smoothmenu.shadow.enable && !smoothmenu.css3support){ //if shadows enabled and browser doesn't support CSS3 box shadows
this._shadowoffset={x:(this.istopheader?$subul.offset().left+smoothmenu.shadow.offsetx : this._dimensions.w), y:(this.istopheader? $subul.offset().top+smoothmenu.shadow.offsety : $curobj.position().top)} //store this shadow's offsets
if (this.istopheader)
$parentshadow=$(document.body)
else{
var $parentLi=$curobj.parents("li:eq(0)")
$parentshadow=$parentLi.get(0).$shadow
}
this.$shadow=$('<div class="ddshadow'+(this.istopheader? ' toplevelshadow' : '')+'"></div>').prependTo($parentshadow).css({left:this._shadowoffset.x+'px', top:this._shadowoffset.y+'px'}) //insert shadow DIV and set it to parent node for the next shadow div
}
$curobj.hover(
function(e){
var $targetul=$subul //reference UL to reveal
var header=$curobj.get(0) //reference header LI as DOM object
clearTimeout($targetul.data('timers').hidetimer)
$targetul.data('timers').showtimer=setTimeout(function(){
header._offsets={left:$curobj.offset().left, top:$curobj.offset().top}
var menuleft=header.istopheader && setting.orientation!='v'? 0 : header._dimensions.w
menuleft=(header._offsets.left+menuleft+header._dimensions.subulw>$(window).width())? (header.istopheader && setting.orientation!='v'? -header._dimensions.subulw+header._dimensions.w : -header._dimensions.w) : menuleft //calculate this sub menu's offsets from its parent
if ($targetul.queue().length<=1){ //if 1 or less queued animations
$targetul.css({left:menuleft+"px", width:header._dimensions.subulw+'px'}).animate({height:'show',opacity:'show'}, ddsmoothmenu.transition.overtime)
if (smoothmenu.shadow.enable && !smoothmenu.css3support){
var shadowleft=header.istopheader? $targetul.offset().left+ddsmoothmenu.shadow.offsetx : menuleft
var shadowtop=header.istopheader?$targetul.offset().top+smoothmenu.shadow.offsety : header._shadowoffset.y
if (!header.istopheader && ddsmoothmenu.detectwebkit){ //in WebKit browsers, restore shadow's opacity to full
header.$shadow.css({opacity:1})
}
header.$shadow.css({overflow:'', width:header._dimensions.subulw+'px', left:shadowleft+'px', top:shadowtop+'px'}).animate({height:header._dimensions.subulh+'px'}, ddsmoothmenu.transition.overtime)
}
}
}, ddsmoothmenu.showhidedelay.showdelay)
},
function(e){
var $targetul=$subul
var header=$curobj.get(0)
clearTimeout($targetul.data('timers').showtimer)
$targetul.data('timers').hidetimer=setTimeout(function(){
$targetul.animate({height:'hide', opacity:'hide'}, ddsmoothmenu.transition.outtime)
if (smoothmenu.shadow.enable && !smoothmenu.css3support){
if (ddsmoothmenu.detectwebkit){ //in WebKit browsers, set first child shadow's opacity to 0, as "overflow:hidden" doesn't work in them
header.$shadow.children('div:eq(0)').css({opacity:0})
}
header.$shadow.css({overflow:'hidden'}).animate({height:0}, ddsmoothmenu.transition.outtime)
}
}, ddsmoothmenu.showhidedelay.hidedelay)
}
) //end hover
}) //end $headers.each()
if (smoothmenu.shadow.enable && smoothmenu.css3support){ //if shadows enabled and browser supports CSS3 shadows
var $toplevelul=$('#'+setting.mainmenuid+' ul li ul')
var css3shadow=parseInt(smoothmenu.shadow.offsetx)+"px "+parseInt(smoothmenu.shadow.offsety)+"px 5px #aaa" //construct CSS3 box-shadow value
var shadowprop=["boxShadow", "MozBoxShadow", "WebkitBoxShadow", "MsBoxShadow"] //possible vendor specific CSS3 shadow properties
for (var i=0; i<shadowprop.length; i++){
$toplevelul.css(shadowprop[i], css3shadow)
}
}
$mainmenu.find("ul").css({display:'none', visibility:'visible'})
},
init:function(setting){
if (typeof setting.customtheme=="object" && setting.customtheme.length==2){ //override default menu colors (default/hover) with custom set?
var mainmenuid='#'+setting.mainmenuid
var mainselector=(setting.orientation=="v")? mainmenuid : mainmenuid+', '+mainmenuid
document.write('<style type="text/css">\n'
+mainselector+' ul li a {background:'+setting.customtheme[0]+';}\n'
+mainmenuid+' ul li a:hover {background:'+setting.customtheme[1]+';}\n'
+'</style>')
}
this.shadow.enable=(document.all && !window.XMLHttpRequest)? false : this.shadow.enable //in IE6, always disable shadow
jQuery(document).ready(function($){ //ajax menu?
if (typeof setting.contentsource=="object"){ //if external ajax menu
ddsmoothmenu.getajaxmenu($, setting)
}
else{ //else if markup menu
ddsmoothmenu.buildmenu($, setting)
}
})
}
} //end ddsmoothmenu variable
|
vishalmote/online
|
ijs/ddsmoothmenu.js
|
JavaScript
|
gpl-3.0
| 8,796
|
pushd j:\Projects\Steve\BloodCpp.bak\
if not exist St%@instr[0,2,%_date]%@instr[3,2,%_date]%@instr[6,2,%_date] @call mc St%@instr[0,2,%_date]%@instr[3,2,%_date]%@instr[6,2,%_date].%@instr[0,2,%_time]%@instr[3,1,%_time]
cdd c:\Projects\Blood\
copy *.cpp j: /s
copy *.h j: /s
j:
cd..
dir
popd
|
pip/Octology
|
dox/Jobz/7Studios/CygPip/bin/bbs.bat
|
Batchfile
|
gpl-3.0
| 300
|
div {
font-family: Helvetica, sans-serif;
font-weight: bold;
font-size: x-large;
}
#container1 {
margin-bottom: 1em;
width: 440px;
border: 2px solid #808080;
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row wrap-reverse;
flex-flow: row wrap-reverse;
}
#container2 {
width: 240px;
height: 440px;
border: 2px solid #808080;
direction: rtl;
unicode-bidi: bidi-override;
display: -webkit-flex;
display: flex;
-webkit-flex-flow: column wrap;
flex-flow: column wrap;
}
#item1 {
background-color: #ff9999;
width: 100px;
height: 120px;
}
#item2 {
background-color: #ffff66;
width: 200px;
height: 120px;
}
#item3 {
background-color: #99ffcc;
width: 100px;
height: 120px;
}
#item4 {
background-color: #ccccff;
width: 80px;
height: 120px;
}
#item5 {
background-color: #ff9999;
width: 120px;
height: 100px;
}
#item6 {
background-color: #ffff66;
width: 120px;
height: 200px;
}
#item7 {
background-color: #99ffcc;
width: 120px;
height: 100px;
}
#item8 {
background-color: #ccccff;
width: 120px;
height: 80px;
}
|
grtlinux/TAIN_WEB_TEST
|
WEB_TEST01/doc/HTML5_CSS3_DIC_2nd/css3/07_flexbox/bl04.css
|
CSS
|
gpl-3.0
| 1,127
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.