code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2008-2010 Zuza Software Foundation # # This file is part of Virtaal. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.org/licenses/>. """Contains the AutoCompletor class.""" import gobject import re try: from collections import defaultdict except ImportError: class defaultdict(dict): def __init__(self, default_factory=lambda: None): self.__factory = default_factory def __getitem__(self, key): if key in self: return super(defaultdict, self).__getitem__(key) else: return self.__factory() from virtaal.controllers.baseplugin import BasePlugin from virtaal.views.widgets.textbox import TextBox class AutoCompletor(object): """ Does auto-completion of registered words in registered widgets. """ wordsep_re = re.compile(r'\W+', re.UNICODE) MAX_WORDS = 10000 DEFAULT_COMPLETION_LENGTH = 4 # The default minimum length of a word that may # be auto-completed. def __init__(self, main_controller, word_list=[], comp_len=DEFAULT_COMPLETION_LENGTH): """Constructor. @type word_list: iterable @param word_list: A list of words that should be auto-completed.""" self.main_controller = main_controller assert isinstance(word_list, list) self.comp_len = comp_len self._word_list = [] self._word_freq = defaultdict(lambda: 0) self.add_words(word_list) self.widgets = set() def add_widget(self, widget): """Add a widget to the list of widgets to do auto-completion for.""" if widget in self.widgets: return # Widget already added if isinstance(widget, TextBox): self._add_text_box(widget) return raise ValueError("Widget type %s not supported." % (type(widget))) def add_words(self, words, update=True): """Add a word or words to the list of words to auto-complete.""" for word in words: if self.isusable(word): self._word_freq[word] += 1 if update: self._update_word_list() def add_words_from_units(self, units): """Collect all words from the given translation units to use for auto-completion. @type units: list @param units: The translation units to collect words from. """ for unit in units: target = unit.target if not target: continue self.add_words(self.wordsep_re.split(target), update=False) if len(self._word_freq) > self.MAX_WORDS: break self._update_word_list() def autocomplete(self, word): for w in self._word_list: if w.startswith(word): return w, w[len(word):] return None, u'' def clear_widgets(self): """Release all registered widgets from the spell of auto-completion.""" for w in set(self.widgets): self.remove_widget(w) def clear_words(self): """Remove all registered words; effectively turns off auto-completion.""" self._word_freq = [] self._word_list = defaultdict(lambda: 0) def isusable(self, word): """Returns a value indicating if the given word should be kept as a suggestion for autocomplete.""" return len(word) > self.comp_len + 2 def remove_widget(self, widget): """Remove a widget (currently only L{TextBox}s are accepted) from the list of widgets to do auto-correction for. """ if isinstance(widget, TextBox) and widget in self.widgets: self._remove_textbox(widget) def remove_words(self, words): """Remove a word or words from the list of words to auto-complete.""" if isinstance(words, basestring): del self._word_freq[words] self._word_list.remove(words) else: for w in words: try: del self._word_freq[w] self._word_list.remove(w) except KeyError: pass def _add_text_box(self, textbox): """Add the given L{TextBox} to the list of widgets to do auto- correction on.""" if not hasattr(self, '_textbox_insert_ids'): self._textbox_insert_ids = {} handler_id = textbox.connect('text-inserted', self._on_insert_text) self._textbox_insert_ids[textbox] = handler_id self.widgets.add(textbox) def _on_insert_text(self, textbox, text, offset, elem): if not isinstance(text, basestring) or self.wordsep_re.match(text): return # We are only interested in single character insertions, otherwise we # react similarly for paste and similar events if len(text.decode('utf-8')) > 1: return prefix = unicode(textbox.get_text(0, offset) + text) postfix = unicode(textbox.get_text(offset)) buffer = textbox.buffer # Quick fix to check that we don't autocomplete in the middle of a word. right_lim = len(postfix) > 0 and postfix[0] or ' ' if not self.wordsep_re.match(right_lim): return lastword = self.wordsep_re.split(prefix)[-1] if len(lastword) >= self.comp_len: completed_word, word_postfix = self.autocomplete(lastword) if completed_word == lastword: return if completed_word: # Updating of the buffer is deferred until after this signal # and its side effects are taken care of. We abuse # gobject.idle_add for that. insert_offset = offset + len(text) def suggest_completion(): textbox.handler_block(self._textbox_insert_ids[textbox]) #logging.debug("textbox.suggestion = {'text': u'%s', 'offset': %d}" % (word_postfix, insert_offset)) textbox.suggestion = {'text': word_postfix, 'offset': insert_offset} textbox.handler_unblock(self._textbox_insert_ids[textbox]) sel_iter_start = buffer.get_iter_at_offset(insert_offset) sel_iter_end = buffer.get_iter_at_offset(insert_offset + len(word_postfix)) buffer.select_range(sel_iter_start, sel_iter_end) return False gobject.idle_add(suggest_completion, priority=gobject.PRIORITY_HIGH) def _remove_textbox(self, textbox): """Remove the given L{TextBox} from the list of widgets to do auto-correction on. """ if not hasattr(self, '_textbox_insert_ids'): return # Disconnect the "insert-text" event handler textbox.disconnect(self._textbox_insert_ids[textbox]) self.widgets.remove(textbox) def _update_word_list(self): """Update and sort found words according to frequency.""" wordlist = self._word_freq.items() wordlist.sort(key=lambda x:x[1], reverse=True) self._word_list = [items[0] for items in wordlist] class Plugin(BasePlugin): description = _('Automatically complete long words while you type') display_name = _('AutoCompletor') version = 0.1 # INITIALIZERS # def __init__(self, internal_name, main_controller): self.internal_name = internal_name self.main_controller = main_controller self._init_plugin() def _init_plugin(self): from virtaal.common import pan_app self.autocomp = AutoCompletor(self.main_controller) self._store_loaded_id = self.main_controller.store_controller.connect('store-loaded', self._on_store_loaded) if self.main_controller.store_controller.get_store(): # Connect to already loaded store. This happens when the plug-in is enabled after loading a store. self._on_store_loaded(self.main_controller.store_controller) self._unitview_id = None unitview = self.main_controller.unit_controller.view if unitview.targets: self._connect_to_textboxes(unitview, unitview.targets) else: self._unitview_id = unitview.connect('targets-created', self._connect_to_textboxes) def _connect_to_textboxes(self, unitview, textboxes): for target in textboxes: self.autocomp.add_widget(target) # METHDOS # def destroy(self): """Remove all signal-connections.""" self.autocomp.clear_words() self.autocomp.clear_widgets() self.main_controller.store_controller.disconnect(self._store_loaded_id) if getattr(self, '_cursor_changed_id', None): self.store_cursor.disconnect(self._cursor_changed_id) if self._unitview_id: self.main_controller.unit_controller.view.disconnect(self._unitview_id) # EVENT HANDLERS # def _on_cursor_change(self, cursor): def add_widgets(): if hasattr(self, 'lastunit'): if self.lastunit.hasplural(): for target in self.lastunit.target: if target: #logging.debug('Adding words: %s' % (self.autocomp.wordsep_re.split(unicode(target)))) self.autocomp.add_words(self.autocomp.wordsep_re.split(unicode(target))) else: if self.lastunit.target: #logging.debug('Adding words: %s' % (self.autocomp.wordsep_re.split(unicode(self.lastunit.target)))) self.autocomp.add_words(self.autocomp.wordsep_re.split(unicode(self.lastunit.target))) self.lastunit = cursor.deref() gobject.idle_add(add_widgets) def _on_store_loaded(self, storecontroller): self.autocomp.add_words_from_units(storecontroller.get_store().get_units()) if hasattr(self, '_cursor_changed_id'): self.store_cursor.disconnect(self._cursor_changed_id) self.store_cursor = storecontroller.cursor self._cursor_changed_id = self.store_cursor.connect('cursor-changed', self._on_cursor_change) self._on_cursor_change(self.store_cursor)
elric/virtaal-debian-snapshots
virtaal/plugins/autocompletor.py
Python
gpl-2.0
10,937
############################## Handle IRQ ############################# HAVE_UART = y ############################## TOOLS ############################# CROSS_COMPILE ?=mips-linux-gnu- CC = $(CROSS_COMPILE)gcc LD = $(CROSS_COMPILE)ld OBJCOPY = $(CROSS_COMPILE)objcopy drop-sections := .reginfo .mdebug .oomment .note .pdr .options .MIPS.options strip-flags := $(addprefix --remove-section=,$(drop-sections)) HEX_CFLAGS += -Iinclude HEX_CFLAGS += -nostdinc -Wall -Wundef -Werror-implicit-function-declaration \ -fno-common -EL -Os -march=mips32 -mabi=32 -G 0 -mno-abicalls -fno-pic HEX_CFLAGS += -DINTERFACE_NEMC HEX_LDFLAGS := -nostdlib -EL -T target.ld HEX_OBJCOPY_ARGS := -O elf32-tradlittlemips HEX_NAME := firmware_uart.hex OBJS := src/start.o \ src/delay.o \ src/main.o \ src/mcu_ops.o \ src/gpio.o \ ifeq ($(HAVE_UART), y) OBJS += src/uart.o HEX_CFLAGS += -DHANDLE_UART endif all: firmware.bin @hexdump -v -e '"0x" 1/4 "%08x" "," "\n"' $< > $(HEX_NAME) firmware.bin:firmware.o @$(LD) -nostdlib -EL -T target.ld $(OBJS) -Map tmp.map -o tmp.elf @$(OBJCOPY) $(strip-flags) $(HEX_OBJCOPY_ARGS) -O binary tmp.elf $@ firmware.o : $(OBJS) %.o:%.c $(CC) $(HEX_CFLAGS) -o $@ -c $^ %.o:%.S $(CC) $(HEX_CFLAGS) -o $@ -c $^ clean: @find . -name "*.o" | xargs rm -vf @find . -name "*.o.cmd" | xargs rm -vf @find . -name "*.hex" | xargs rm -vf @find . -name "*.bin" | xargs rm -vf @rm -vf tmp.map tmp.elf
IngenicSemiconductor/kernel-inwatch
drivers/dma/jzdma/common_firmware/Makefile
Makefile
gpl-2.0
1,443
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Struct base_unit_info&lt;imperial::hundredweight_base_unit&gt;</title> <link rel="stylesheet" href="../../boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.73.2"> <link rel="start" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../../boost_units/Reference.html#header.boost.units.base_units.imperial.hundredweight_hpp" title="Header &lt;boost/units/base_units/imperial/hundredweight.hpp&gt;"> <link rel="prev" href="base_unit_info_imperial_id3820063.html" title="Struct base_unit_info&lt;imperial::grain_base_unit&gt;"> <link rel="next" href="base_unit_info_imperial_id3820171.html" title="Struct base_unit_info&lt;imperial::inch_base_unit&gt;"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td> <td align="center"><a href="../../../../index.html">Home</a></td> <td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="base_unit_info_imperial_id3820063.html"><img src="../../../../doc/html/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_units/Reference.html#header.boost.units.base_units.imperial.hundredweight_hpp"><img src="../../../../doc/html/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/html/images/home.png" alt="Home"></a><a accesskey="n" href="base_unit_info_imperial_id3820171.html"><img src="../../../../doc/html/images/next.png" alt="Next"></a> </div> <div class="refentry" lang="en"> <a name="boost.units.base_unit_info_imperial_id3820117"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct base_unit_info&lt;imperial::hundredweight_base_unit&gt;</span></h2> <p>boost::units::base_unit_info&lt;imperial::hundredweight_base_unit&gt;</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="emphasis"><em>// In header: &lt;<a class="link" href="../../boost_units/Reference.html#header.boost.units.base_units.imperial.hundredweight_hpp" title="Header &lt;boost/units/base_units/imperial/hundredweight.hpp&gt;">boost/units/base_units/imperial/hundredweight.hpp</a>&gt; </em></span> <span class="bold"><strong>struct</strong></span> <a class="link" href="base_unit_info_imperial_id3820117.html" title="Struct base_unit_info&lt;imperial::hundredweight_base_unit&gt;">base_unit_info</a>&lt;imperial::hundredweight_base_unit&gt; { <span class="emphasis"><em>// <a class="link" href="base_unit_info_imperial_id3820117.html#id3820127-bb">public static functions</a></em></span> <span class="type"><span class="bold"><strong>static</strong></span> <span class="bold"><strong>const</strong></span> <span class="bold"><strong>char</strong></span> *</span> <a class="link" href="base_unit_info_imperial_id3820117.html#id3820130-bb">name</a>() ; <span class="type"><span class="bold"><strong>static</strong></span> <span class="bold"><strong>const</strong></span> <span class="bold"><strong>char</strong></span> *</span> <a class="link" href="base_unit_info_imperial_id3820117.html#id3820138-bb">symbol</a>() ; };</pre></div> <div class="refsect1" lang="en"> <a name="id4258688"></a><h2>Description</h2> <div class="refsect2" lang="en"> <a name="id4258691"></a><h3> <a name="id3820127-bb"></a><code class="computeroutput">base_unit_info</code> public static functions</h3> <div class="orderedlist"><ol type="1"> <li><pre class="literallayout"><span class="type"><span class="bold"><strong>static</strong></span> <span class="bold"><strong>const</strong></span> <span class="bold"><strong>char</strong></span> *</span> <a name="id3820130-bb"></a>name() ;</pre></li> <li><pre class="literallayout"><span class="type"><span class="bold"><strong>static</strong></span> <span class="bold"><strong>const</strong></span> <span class="bold"><strong>char</strong></span> *</span> <a name="id3820138-bb"></a>symbol() ;</pre></li> </ol></div> </div> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright © 2003 -2008 Matthias Christian Schabel, 2007-2008 Steven Watanabe<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="base_unit_info_imperial_id3820063.html"><img src="../../../../doc/html/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_units/Reference.html#header.boost.units.base_units.imperial.hundredweight_hpp"><img src="../../../../doc/html/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/html/images/home.png" alt="Home"></a><a accesskey="n" href="base_unit_info_imperial_id3820171.html"><img src="../../../../doc/html/images/next.png" alt="Next"></a> </div> </body> </html>
scs/uclinux
lib/boost/boost_1_38_0/doc/html/boost/units/base_unit_info_imperial_id3820117.html
HTML
gpl-2.0
5,776
<?php namespace JasPhp; use JasPhp; Class Jasper { public static function makeJasperReport($module, $report, $parameters) { //print "java -jar ../lib/java/jasphp.jar $module $report $parameters";exit; exec("java -jar ../lib/java/dist/jasphp.jar $module $report $parameters", $return); //print_r($return);exit; return $return; } public static function readParameters($filters) { $arrparam = array(); foreach ($filters as $param => $val) { $arrparam[] = $param; $arrparam[] = $val; } $parametros = '"' . implode('" "', $arrparam) . '"'; return $parametros; } } ?>
luelher/JasPhp
lib/JasPhp/Jasper.php
PHP
gpl-2.0
625
<?php /** * Authentication library * * Including this file will automatically try to login * a user by calling auth_login() * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Andreas Gohr <[email protected]> */ if(!defined('DOKU_INC')) die('meh.'); // some ACL level defines define('AUTH_NONE', 0); define('AUTH_READ', 1); define('AUTH_EDIT', 2); define('AUTH_CREATE', 4); define('AUTH_UPLOAD', 8); define('AUTH_DELETE', 16); define('AUTH_ADMIN', 255); /** * Initialize the auth system. * * This function is automatically called at the end of init.php * * This used to be the main() of the auth.php * * @todo backend loading maybe should be handled by the class autoloader * @todo maybe split into multiple functions at the XXX marked positions * @triggers AUTH_LOGIN_CHECK * @return bool */ function auth_setup() { global $conf; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; global $AUTH_ACL; global $lang; /* @var Doku_Plugin_Controller $plugin_controller */ global $plugin_controller; $AUTH_ACL = array(); if(!$conf['useacl']) return false; // try to load auth backend from plugins foreach ($plugin_controller->getList('auth') as $plugin) { if ($conf['authtype'] === $plugin) { $auth = $plugin_controller->load('auth', $plugin); break; } elseif ('auth' . $conf['authtype'] === $plugin) { // matches old auth backends (pre-Weatherwax) $auth = $plugin_controller->load('auth', $plugin); msg('Your authtype setting is deprecated. You must set $conf[\'authtype\'] = "auth' . $conf['authtype'] . '"' . ' in your configuration (see <a href="https://www.dokuwiki.org/auth">Authentication Backends</a>)',-1,'','',MSG_ADMINS_ONLY); } } if(!isset($auth) || !$auth){ msg($lang['authtempfail'], -1); return false; } if ($auth->success == false) { // degrade to unauthenticated user unset($auth); auth_logoff(); msg($lang['authtempfail'], -1); return false; } // do the login either by cookie or provided credentials XXX $INPUT->set('http_credentials', false); if(!$conf['rememberme']) $INPUT->set('r', false); // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like // the one presented at // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used // for enabling HTTP authentication with CGI/SuExec) if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; // streamline HTTP auth credentials (IIS/rewrite -> mod_php) if(isset($_SERVER['HTTP_AUTHORIZATION'])) { list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6))); } // if no credentials were given try to use HTTP auth (for SSO) if(!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) { $INPUT->set('u', $_SERVER['PHP_AUTH_USER']); $INPUT->set('p', $_SERVER['PHP_AUTH_PW']); $INPUT->set('http_credentials', true); } // apply cleaning (auth specific user names, remove control chars) if (true === $auth->success) { $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u')))); $INPUT->set('p', stripctl($INPUT->str('p'))); } if($INPUT->str('authtok')) { // when an authentication token is given, trust the session auth_validateToken($INPUT->str('authtok')); } elseif(!is_null($auth) && $auth->canDo('external')) { // external trust mechanism in place $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r')); } else { $evdata = array( 'user' => $INPUT->str('u'), 'password' => $INPUT->str('p'), 'sticky' => $INPUT->bool('r'), 'silent' => $INPUT->bool('http_credentials') ); trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper'); } //load ACL into a global array XXX $AUTH_ACL = auth_loadACL(); return true; } /** * Loads the ACL setup and handle user wildcards * * @author Andreas Gohr <[email protected]> * * @return array */ function auth_loadACL() { global $config_cascade; global $USERINFO; /* @var Input $INPUT */ global $INPUT; if(!is_readable($config_cascade['acl']['default'])) return array(); $acl = file($config_cascade['acl']['default']); $out = array(); foreach($acl as $line) { $line = trim($line); if(empty($line) || ($line{0} == '#')) continue; // skip blank lines & comments list($id,$rest) = preg_split('/[ \t]+/',$line,2); // substitute user wildcard first (its 1:1) if(strstr($line, '%USER%')){ // if user is not logged in, this ACL line is meaningless - skip it if (!$INPUT->server->has('REMOTE_USER')) continue; $id = str_replace('%USER%',cleanID($INPUT->server->str('REMOTE_USER')),$id); $rest = str_replace('%USER%',auth_nameencode($INPUT->server->str('REMOTE_USER')),$rest); } // substitute group wildcard (its 1:m) if(strstr($line, '%GROUP%')){ // if user is not logged in, grps is empty, no output will be added (i.e. skipped) foreach((array) $USERINFO['grps'] as $grp){ $nid = str_replace('%GROUP%',cleanID($grp),$id); $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest); $out[] = "$nid\t$nrest"; } } else { $out[] = "$id\t$rest"; } } return $out; } /** * Event hook callback for AUTH_LOGIN_CHECK * * @param array $evdata * @return bool */ function auth_login_wrapper($evdata) { return auth_login( $evdata['user'], $evdata['password'], $evdata['sticky'], $evdata['silent'] ); } /** * This tries to login the user based on the sent auth credentials * * The authentication works like this: if a username was given * a new login is assumed and user/password are checked. If they * are correct the password is encrypted with blowfish and stored * together with the username in a cookie - the same info is stored * in the session, too. Additonally a browserID is stored in the * session. * * If no username was given the cookie is checked: if the username, * crypted password and browserID match between session and cookie * no further testing is done and the user is accepted * * If a cookie was found but no session info was availabe the * blowfish encrypted password from the cookie is decrypted and * together with username rechecked by calling this function again. * * On a successful login $_SERVER[REMOTE_USER] and $USERINFO * are set. * * @author Andreas Gohr <[email protected]> * * @param string $user Username * @param string $pass Cleartext Password * @param bool $sticky Cookie should not expire * @param bool $silent Don't show error on bad auth * @return bool true on successful auth */ function auth_login($user, $pass, $sticky = false, $silent = false) { global $USERINFO; global $conf; global $lang; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; $sticky ? $sticky = true : $sticky = false; //sanity check if(!$auth) return false; if(!empty($user)) { //usual login if(!empty($pass) && $auth->checkPass($user, $pass)) { // make logininfo globally available $INPUT->server->set('REMOTE_USER', $user); $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session auth_setCookie($user, auth_encrypt($pass, $secret), $sticky); return true; } else { //invalid credentials - log off if(!$silent) msg($lang['badlogin'], -1); auth_logoff(); return false; } } else { // read cookie information list($user, $sticky, $pass) = auth_getCookie(); if($user && $pass) { // we got a cookie - see if we can trust it // get session info $session = $_SESSION[DOKU_COOKIE]['auth']; if(isset($session) && $auth->useSessionCache($user) && ($session['time'] >= time() - $conf['auth_security_timeout']) && ($session['user'] == $user) && ($session['pass'] == sha1($pass)) && //still crypted ($session['buid'] == auth_browseruid()) ) { // he has session, cookie and browser right - let him in $INPUT->server->set('REMOTE_USER', $user); $USERINFO = $session['info']; //FIXME move all references to session return true; } // no we don't trust it yet - recheck pass but silent $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session $pass = auth_decrypt($pass, $secret); return auth_login($user, $pass, $sticky, true); } } //just to be sure auth_logoff(true); return false; } /** * Checks if a given authentication token was stored in the session * * Will setup authentication data using data from the session if the * token is correct. Will exit with a 401 Status if not. * * @author Andreas Gohr <[email protected]> * * @param string $token The authentication token * @return boolean|null true (or will exit on failure) */ function auth_validateToken($token) { if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']) { // bad token http_status(401); print 'Invalid auth token - maybe the session timed out'; unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance exit; } // still here? trust the session data global $USERINFO; /* @var Input $INPUT */ global $INPUT; $INPUT->server->set('REMOTE_USER',$_SESSION[DOKU_COOKIE]['auth']['user']); $USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info']; return true; } /** * Create an auth token and store it in the session * * NOTE: this is completely unrelated to the getSecurityToken() function * * @author Andreas Gohr <[email protected]> * * @return string The auth token */ function auth_createToken() { $token = md5(auth_randombytes(16)); @session_start(); // reopen the session if needed $_SESSION[DOKU_COOKIE]['auth']['token'] = $token; session_write_close(); return $token; } /** * Builds a pseudo UID from browser and IP data * * This is neither unique nor unfakable - still it adds some * security. Using the first part of the IP makes sure * proxy farms like AOLs are still okay. * * @author Andreas Gohr <[email protected]> * * @return string a MD5 sum of various browser headers */ function auth_browseruid() { /* @var Input $INPUT */ global $INPUT; $ip = clientIP(true); $uid = ''; $uid .= $INPUT->server->str('HTTP_USER_AGENT'); $uid .= $INPUT->server->str('HTTP_ACCEPT_CHARSET'); $uid .= substr($ip, 0, strpos($ip, '.')); $uid = strtolower($uid); return md5($uid); } /** * Creates a random key to encrypt the password in cookies * * This function tries to read the password for encrypting * cookies from $conf['metadir'].'/_htcookiesalt' * if no such file is found a random key is created and * and stored in this file. * * @author Andreas Gohr <[email protected]> * * @param bool $addsession if true, the sessionid is added to the salt * @param bool $secure if security is more important than keeping the old value * @return string */ function auth_cookiesalt($addsession = false, $secure = false) { global $conf; $file = $conf['metadir'].'/_htcookiesalt'; if ($secure || !file_exists($file)) { $file = $conf['metadir'].'/_htcookiesalt2'; } $salt = io_readFile($file); if(empty($salt)) { $salt = bin2hex(auth_randombytes(64)); io_saveFile($file, $salt); } if($addsession) { $salt .= session_id(); } return $salt; } /** * Return truly (pseudo) random bytes if available, otherwise fall back to mt_rand * * @author Mark Seecof * @author Michael Hamann <[email protected]> * @link http://www.php.net/manual/de/function.mt-rand.php#83655 * * @param int $length number of bytes to get * @return string binary random strings */ function auth_randombytes($length) { $strong = false; $rbytes = false; if (function_exists('openssl_random_pseudo_bytes') && (version_compare(PHP_VERSION, '5.3.4') >= 0 || strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') ) { $rbytes = openssl_random_pseudo_bytes($length, $strong); } if (!$strong && function_exists('mcrypt_create_iv') && (version_compare(PHP_VERSION, '5.3.7') >= 0 || strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') ) { $rbytes = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM); if ($rbytes !== false && strlen($rbytes) === $length) { $strong = true; } } // If no strong randoms available, try OS the specific ways if(!$strong) { // Unix/Linux platform $fp = @fopen('/dev/urandom', 'rb'); if($fp !== false) { $rbytes = fread($fp, $length); fclose($fp); } // MS-Windows platform if(class_exists('COM')) { // http://msdn.microsoft.com/en-us/library/aa388176(VS.85).aspx try { $CAPI_Util = new COM('CAPICOM.Utilities.1'); $rbytes = $CAPI_Util->GetRandom($length, 0); // if we ask for binary data PHP munges it, so we // request base64 return value. if($rbytes) $rbytes = base64_decode($rbytes); } catch(Exception $ex) { // fail } } } if(strlen($rbytes) < $length) $rbytes = false; // still no random bytes available - fall back to mt_rand() if($rbytes === false) { $rbytes = ''; for ($i = 0; $i < $length; ++$i) { $rbytes .= chr(mt_rand(0, 255)); } } return $rbytes; } /** * Random number generator using the best available source * * @author Michael Samuel * @author Michael Hamann <[email protected]> * * @param int $min * @param int $max * @return int */ function auth_random($min, $max) { $abs_max = $max - $min; $nbits = 0; for ($n = $abs_max; $n > 0; $n >>= 1) { ++$nbits; } $mask = (1 << $nbits) - 1; do { $bytes = auth_randombytes(PHP_INT_SIZE); $integers = unpack('Inum', $bytes); $integer = $integers["num"] & $mask; } while ($integer > $abs_max); return $min + $integer; } /** * Encrypt data using the given secret using AES * * The mode is CBC with a random initialization vector, the key is derived * using pbkdf2. * * @param string $data The data that shall be encrypted * @param string $secret The secret/password that shall be used * @return string The ciphertext */ function auth_encrypt($data, $secret) { $iv = auth_randombytes(16); $cipher = new Crypt_AES(); $cipher->setPassword($secret); /* this uses the encrypted IV as IV as suggested in http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C for unique but necessarily random IVs. The resulting ciphertext is compatible to ciphertext that was created using a "normal" IV. */ return $cipher->encrypt($iv.$data); } /** * Decrypt the given AES ciphertext * * The mode is CBC, the key is derived using pbkdf2 * * @param string $ciphertext The encrypted data * @param string $secret The secret/password that shall be used * @return string The decrypted data */ function auth_decrypt($ciphertext, $secret) { $iv = substr($ciphertext, 0, 16); $cipher = new Crypt_AES(); $cipher->setPassword($secret); $cipher->setIV($iv); return $cipher->decrypt(substr($ciphertext, 16)); } /** * Log out the current user * * This clears all authentication data and thus log the user * off. It also clears session data. * * @author Andreas Gohr <[email protected]> * * @param bool $keepbc - when true, the breadcrumb data is not cleared */ function auth_logoff($keepbc = false) { global $conf; global $USERINFO; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; // make sure the session is writable (it usually is) @session_start(); if(isset($_SESSION[DOKU_COOKIE]['auth']['user'])) unset($_SESSION[DOKU_COOKIE]['auth']['user']); if(isset($_SESSION[DOKU_COOKIE]['auth']['pass'])) unset($_SESSION[DOKU_COOKIE]['auth']['pass']); if(isset($_SESSION[DOKU_COOKIE]['auth']['info'])) unset($_SESSION[DOKU_COOKIE]['auth']['info']); if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc'])) unset($_SESSION[DOKU_COOKIE]['bc']); $INPUT->server->remove('REMOTE_USER'); $USERINFO = null; //FIXME $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true); if($auth) $auth->logOff(); } /** * Check if a user is a manager * * Should usually be called without any parameters to check the current * user. * * The info is available through $INFO['ismanager'], too * * @author Andreas Gohr <[email protected]> * @see auth_isadmin * * @param string $user Username * @param array $groups List of groups the user is in * @param bool $adminonly when true checks if user is admin * @return bool */ function auth_ismanager($user = null, $groups = null, $adminonly = false) { global $conf; global $USERINFO; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; if(!$auth) return false; if(is_null($user)) { if(!$INPUT->server->has('REMOTE_USER')) { return false; } else { $user = $INPUT->server->str('REMOTE_USER'); } } if(is_null($groups)) { $groups = (array) $USERINFO['grps']; } // check superuser match if(auth_isMember($conf['superuser'], $user, $groups)) return true; if($adminonly) return false; // check managers if(auth_isMember($conf['manager'], $user, $groups)) return true; return false; } /** * Check if a user is admin * * Alias to auth_ismanager with adminonly=true * * The info is available through $INFO['isadmin'], too * * @author Andreas Gohr <[email protected]> * @see auth_ismanager() * * @param string $user Username * @param array $groups List of groups the user is in * @return bool */ function auth_isadmin($user = null, $groups = null) { return auth_ismanager($user, $groups, true); } /** * Match a user and his groups against a comma separated list of * users and groups to determine membership status * * Note: all input should NOT be nameencoded. * * @param string $memberlist commaseparated list of allowed users and groups * @param string $user user to match against * @param array $groups groups the user is member of * @return bool true for membership acknowledged */ function auth_isMember($memberlist, $user, array $groups) { /* @var DokuWiki_Auth_Plugin $auth */ global $auth; if(!$auth) return false; // clean user and groups if(!$auth->isCaseSensitive()) { $user = utf8_strtolower($user); $groups = array_map('utf8_strtolower', $groups); } $user = $auth->cleanUser($user); $groups = array_map(array($auth, 'cleanGroup'), $groups); // extract the memberlist $members = explode(',', $memberlist); $members = array_map('trim', $members); $members = array_unique($members); $members = array_filter($members); // compare cleaned values foreach($members as $member) { if($member == '@ALL' ) return true; if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member); if($member[0] == '@') { $member = $auth->cleanGroup(substr($member, 1)); if(in_array($member, $groups)) return true; } else { $member = $auth->cleanUser($member); if($member == $user) return true; } } // still here? not a member! return false; } /** * Convinience function for auth_aclcheck() * * This checks the permissions for the current user * * @author Andreas Gohr <[email protected]> * * @param string $id page ID (needs to be resolved and cleaned) * @return int permission level */ function auth_quickaclcheck($id) { global $conf; global $USERINFO; /* @var Input $INPUT */ global $INPUT; # if no ACL is used always return upload rights if(!$conf['useacl']) return AUTH_UPLOAD; return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), $USERINFO['grps']); } /** * Returns the maximum rights a user has for the given ID or its namespace * * @author Andreas Gohr <[email protected]> * * @triggers AUTH_ACL_CHECK * @param string $id page ID (needs to be resolved and cleaned) * @param string $user Username * @param array|null $groups Array of groups the user is in * @return int permission level */ function auth_aclcheck($id, $user, $groups) { $data = array( 'id' => $id, 'user' => $user, 'groups' => $groups ); return trigger_event('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb'); } /** * default ACL check method * * DO NOT CALL DIRECTLY, use auth_aclcheck() instead * * @author Andreas Gohr <[email protected]> * * @param array $data event data * @return int permission level */ function auth_aclcheck_cb($data) { $id =& $data['id']; $user =& $data['user']; $groups =& $data['groups']; global $conf; global $AUTH_ACL; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; // if no ACL is used always return upload rights if(!$conf['useacl']) return AUTH_UPLOAD; if(!$auth) return AUTH_NONE; //make sure groups is an array if(!is_array($groups)) $groups = array(); //if user is superuser or in superusergroup return 255 (acl_admin) if(auth_isadmin($user, $groups)) { return AUTH_ADMIN; } if(!$auth->isCaseSensitive()) { $user = utf8_strtolower($user); $groups = array_map('utf8_strtolower', $groups); } $user = $auth->cleanUser($user); $groups = array_map(array($auth, 'cleanGroup'), (array) $groups); $user = auth_nameencode($user); //prepend groups with @ and nameencode $cnt = count($groups); for($i = 0; $i < $cnt; $i++) { $groups[$i] = '@'.auth_nameencode($groups[$i]); } $ns = getNS($id); $perm = -1; if($user || count($groups)) { //add ALL group $groups[] = '@ALL'; //add User if($user) $groups[] = $user; } else { $groups[] = '@ALL'; } //check exact match first $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); if(count($matches)) { foreach($matches as $match) { $match = preg_replace('/#.*$/', '', $match); //ignore comments $acl = preg_split('/[ \t]+/', $match); if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { $acl[1] = utf8_strtolower($acl[1]); } if(!in_array($acl[1], $groups)) { continue; } if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! if($acl[2] > $perm) { $perm = $acl[2]; } } if($perm > -1) { //we had a match - return it return (int) $perm; } } //still here? do the namespace checks if($ns) { $path = $ns.':*'; } else { $path = '*'; //root document } do { $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); if(count($matches)) { foreach($matches as $match) { $match = preg_replace('/#.*$/', '', $match); //ignore comments $acl = preg_split('/[ \t]+/', $match); if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { $acl[1] = utf8_strtolower($acl[1]); } if(!in_array($acl[1], $groups)) { continue; } if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! if($acl[2] > $perm) { $perm = $acl[2]; } } //we had a match - return it if($perm != -1) { return (int) $perm; } } //get next higher namespace $ns = getNS($ns); if($path != '*') { $path = $ns.':*'; if($path == ':*') $path = '*'; } else { //we did this already //looks like there is something wrong with the ACL //break here msg('No ACL setup yet! Denying access to everyone.'); return AUTH_NONE; } } while(1); //this should never loop endless return AUTH_NONE; } /** * Encode ASCII special chars * * Some auth backends allow special chars in their user and groupnames * The special chars are encoded with this function. Only ASCII chars * are encoded UTF-8 multibyte are left as is (different from usual * urlencoding!). * * Decoding can be done with rawurldecode * * @author Andreas Gohr <[email protected]> * @see rawurldecode() * * @param string $name * @param bool $skip_group * @return string */ function auth_nameencode($name, $skip_group = false) { global $cache_authname; $cache =& $cache_authname; $name = (string) $name; // never encode wildcard FS#1955 if($name == '%USER%') return $name; if($name == '%GROUP%') return $name; if(!isset($cache[$name][$skip_group])) { if($skip_group && $name{0} == '@') { $cache[$name][$skip_group] = '@'.preg_replace_callback( '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 'auth_nameencode_callback', substr($name, 1) ); } else { $cache[$name][$skip_group] = preg_replace_callback( '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 'auth_nameencode_callback', $name ); } } return $cache[$name][$skip_group]; } /** * callback encodes the matches * * @param array $matches first complete match, next matching subpatterms * @return string */ function auth_nameencode_callback($matches) { return '%'.dechex(ord(substr($matches[1],-1))); } /** * Create a pronouncable password * * The $foruser variable might be used by plugins to run additional password * policy checks, but is not used by the default implementation * * @author Andreas Gohr <[email protected]> * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451 * @triggers AUTH_PASSWORD_GENERATE * * @param string $foruser username for which the password is generated * @return string pronouncable password */ function auth_pwgen($foruser = '') { $data = array( 'password' => '', 'foruser' => $foruser ); $evt = new Doku_Event('AUTH_PASSWORD_GENERATE', $data); if($evt->advise_before(true)) { $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones $v = 'aeiou'; //vowels $a = $c.$v; //both $s = '!$%&?+*~#-_:.;,'; // specials //use thre syllables... for($i = 0; $i < 3; $i++) { $data['password'] .= $c[auth_random(0, strlen($c) - 1)]; $data['password'] .= $v[auth_random(0, strlen($v) - 1)]; $data['password'] .= $a[auth_random(0, strlen($a) - 1)]; } //... and add a nice number and special $data['password'] .= auth_random(10, 99).$s[auth_random(0, strlen($s) - 1)]; } $evt->advise_after(); return $data['password']; } /** * Sends a password to the given user * * @author Andreas Gohr <[email protected]> * * @param string $user Login name of the user * @param string $password The new password in clear text * @return bool true on success */ function auth_sendPassword($user, $password) { global $lang; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; if(!$auth) return false; $user = $auth->cleanUser($user); $userinfo = $auth->getUserData($user, $requireGroups = false); if(!$userinfo['mail']) return false; $text = rawLocale('password'); $trep = array( 'FULLNAME' => $userinfo['name'], 'LOGIN' => $user, 'PASSWORD' => $password ); $mail = new Mailer(); $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>'); $mail->subject($lang['regpwmail']); $mail->setBody($text, $trep); return $mail->send(); } /** * Register a new user * * This registers a new user - Data is read directly from $_POST * * @author Andreas Gohr <[email protected]> * * @return bool true on success, false on any error */ function register() { global $lang; global $conf; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; global $INPUT; if(!$INPUT->post->bool('save')) return false; if(!actionOK('register')) return false; // gather input $login = trim($auth->cleanUser($INPUT->post->str('login'))); $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname'))); $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email'))); $pass = $INPUT->post->str('pass'); $passchk = $INPUT->post->str('passchk'); if(empty($login) || empty($fullname) || empty($email)) { msg($lang['regmissing'], -1); return false; } if($conf['autopasswd']) { $pass = auth_pwgen($login); // automatically generate password } elseif(empty($pass) || empty($passchk)) { msg($lang['regmissing'], -1); // complain about missing passwords return false; } elseif($pass != $passchk) { msg($lang['regbadpass'], -1); // complain about misspelled passwords return false; } //check mail if(!mail_isvalid($email)) { msg($lang['regbadmail'], -1); return false; } //okay try to create the user if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) { msg($lang['regfail'], -1); return false; } // send notification about the new user $subscription = new Subscription(); $subscription->send_register($login, $fullname, $email); // are we done? if(!$conf['autopasswd']) { msg($lang['regsuccess2'], 1); return true; } // autogenerated password? then send password to user if(auth_sendPassword($login, $pass)) { msg($lang['regsuccess'], 1); return true; } else { msg($lang['regmailfail'], -1); return false; } } /** * Update user profile * * @author Christopher Smith <[email protected]> */ function updateprofile() { global $conf; global $lang; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; if(!$INPUT->post->bool('save')) return false; if(!checkSecurityToken()) return false; if(!actionOK('profile')) { msg($lang['profna'], -1); return false; } $changes = array(); $changes['pass'] = $INPUT->post->str('newpass'); $changes['name'] = $INPUT->post->str('fullname'); $changes['mail'] = $INPUT->post->str('email'); // check misspelled passwords if($changes['pass'] != $INPUT->post->str('passchk')) { msg($lang['regbadpass'], -1); return false; } // clean fullname and email $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name'])); $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail'])); // no empty name and email (except the backend doesn't support them) if((empty($changes['name']) && $auth->canDo('modName')) || (empty($changes['mail']) && $auth->canDo('modMail')) ) { msg($lang['profnoempty'], -1); return false; } if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) { msg($lang['regbadmail'], -1); return false; } $changes = array_filter($changes); // check for unavailable capabilities if(!$auth->canDo('modName')) unset($changes['name']); if(!$auth->canDo('modMail')) unset($changes['mail']); if(!$auth->canDo('modPass')) unset($changes['pass']); // anything to do? if(!count($changes)) { msg($lang['profnochange'], -1); return false; } if($conf['profileconfirm']) { if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { msg($lang['badpassconfirm'], -1); return false; } } if(!$auth->triggerUserMod('modify', array($INPUT->server->str('REMOTE_USER'), &$changes))) { msg($lang['proffail'], -1); return false; } // update cookie and session with the changed data if($changes['pass']) { list( /*user*/, $sticky, /*pass*/) = auth_getCookie(); $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true)); auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky); } return true; } /** * Delete the current logged-in user * * @return bool true on success, false on any error */ function auth_deleteprofile(){ global $conf; global $lang; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; if(!$INPUT->post->bool('delete')) return false; if(!checkSecurityToken()) return false; // action prevented or auth module disallows if(!actionOK('profile_delete') || !$auth->canDo('delUser')) { msg($lang['profnodelete'], -1); return false; } if(!$INPUT->post->bool('confirm_delete')){ msg($lang['profconfdeletemissing'], -1); return false; } if($conf['profileconfirm']) { if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { msg($lang['badpassconfirm'], -1); return false; } } $deleted = array(); $deleted[] = $INPUT->server->str('REMOTE_USER'); if($auth->triggerUserMod('delete', array($deleted))) { // force and immediate logout including removing the sticky cookie auth_logoff(); return true; } return false; } /** * Send a new password * * This function handles both phases of the password reset: * * - handling the first request of password reset * - validating the password reset auth token * * @author Benoit Chesneau <[email protected]> * @author Chris Smith <[email protected]> * @author Andreas Gohr <[email protected]> * * @return bool true on success, false on any error */ function act_resendpwd() { global $lang; global $conf; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; if(!actionOK('resendpwd')) { msg($lang['resendna'], -1); return false; } $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth')); if($token) { // we're in token phase - get user info from token $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; if(!file_exists($tfile)) { msg($lang['resendpwdbadauth'], -1); $INPUT->remove('pwauth'); return false; } // token is only valid for 3 days if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) { msg($lang['resendpwdbadauth'], -1); $INPUT->remove('pwauth'); @unlink($tfile); return false; } $user = io_readfile($tfile); $userinfo = $auth->getUserData($user, $requireGroups = false); if(!$userinfo['mail']) { msg($lang['resendpwdnouser'], -1); return false; } if(!$conf['autopasswd']) { // we let the user choose a password $pass = $INPUT->str('pass'); // password given correctly? if(!$pass) return false; if($pass != $INPUT->str('passchk')) { msg($lang['regbadpass'], -1); return false; } // change it if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) { msg($lang['proffail'], -1); return false; } } else { // autogenerate the password and send by mail $pass = auth_pwgen($user); if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) { msg($lang['proffail'], -1); return false; } if(auth_sendPassword($user, $pass)) { msg($lang['resendpwdsuccess'], 1); } else { msg($lang['regmailfail'], -1); } } @unlink($tfile); return true; } else { // we're in request phase if(!$INPUT->post->bool('save')) return false; if(!$INPUT->post->str('login')) { msg($lang['resendpwdmissing'], -1); return false; } else { $user = trim($auth->cleanUser($INPUT->post->str('login'))); } $userinfo = $auth->getUserData($user, $requireGroups = false); if(!$userinfo['mail']) { msg($lang['resendpwdnouser'], -1); return false; } // generate auth token $token = md5(auth_randombytes(16)); // random secret $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; $url = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&'); io_saveFile($tfile, $user); $text = rawLocale('pwconfirm'); $trep = array( 'FULLNAME' => $userinfo['name'], 'LOGIN' => $user, 'CONFIRM' => $url ); $mail = new Mailer(); $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>'); $mail->subject($lang['regpwmail']); $mail->setBody($text, $trep); if($mail->send()) { msg($lang['resendpwdconfirm'], 1); } else { msg($lang['regmailfail'], -1); } return true; } // never reached } /** * Encrypts a password using the given method and salt * * If the selected method needs a salt and none was given, a random one * is chosen. * * @author Andreas Gohr <[email protected]> * * @param string $clear The clear text password * @param string $method The hashing method * @param string $salt A salt, null for random * @return string The crypted password */ function auth_cryptPassword($clear, $method = '', $salt = null) { global $conf; if(empty($method)) $method = $conf['passcrypt']; $pass = new PassHash(); $call = 'hash_'.$method; if(!method_exists($pass, $call)) { msg("Unsupported crypt method $method", -1); return false; } return $pass->$call($clear, $salt); } /** * Verifies a cleartext password against a crypted hash * * @author Andreas Gohr <[email protected]> * * @param string $clear The clear text password * @param string $crypt The hash to compare with * @return bool true if both match */ function auth_verifyPassword($clear, $crypt) { $pass = new PassHash(); return $pass->verify_hash($clear, $crypt); } /** * Set the authentication cookie and add user identification data to the session * * @param string $user username * @param string $pass encrypted password * @param bool $sticky whether or not the cookie will last beyond the session * @return bool */ function auth_setCookie($user, $pass, $sticky) { global $conf; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; global $USERINFO; if(!$auth) return false; $USERINFO = $auth->getUserData($user); // set cookie $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass); $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true); // set session $_SESSION[DOKU_COOKIE]['auth']['user'] = $user; $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass); $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid(); $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO; $_SESSION[DOKU_COOKIE]['auth']['time'] = time(); return true; } /** * Returns the user, (encrypted) password and sticky bit from cookie * * @returns array */ function auth_getCookie() { if(!isset($_COOKIE[DOKU_COOKIE])) { return array(null, null, null); } list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3); $sticky = (bool) $sticky; $pass = base64_decode($pass); $user = base64_decode($user); return array($user, $sticky, $pass); } //Setup VIM: ex: et ts=2 :
brontosaurusrex/dokuwiki-preconfigured
inc/auth.php
PHP
gpl-2.0
42,215
<?php /** * This file contains all functions for creating a database for teachpress * * @package teachpress\core\installation * @license http://www.gnu.org/licenses/gpl-2.0.html GPLv2 or later * @since 5.0.0 */ /** * This class contains all functions for creating a database for teachpress * @package teachpress\core\installation * @since 5.0.0 */ class TP_Tables { /** * Install teachPress database tables * @since 5.0.0 */ public static function create() { global $wpdb; self::add_capabilities(); $charset_collate = self::get_charset(); // Disable foreign key checks if ( TEACHPRESS_FOREIGN_KEY_CHECKS === false ) { $wpdb->query("SET foreign_key_checks = 0"); } // Settings self::add_table_settings($charset_collate); // Courses self::add_table_courses($charset_collate); self::add_table_course_meta($charset_collate); self::add_table_course_capabilities($charset_collate); self::add_table_course_documents($charset_collate); self::add_table_stud($charset_collate); self::add_table_stud_meta($charset_collate); self::add_table_signup($charset_collate); self::add_table_artefacts($charset_collate); self::add_table_assessments($charset_collate); // Publications self::add_table_pub($charset_collate); self::add_table_pub_meta($charset_collate); self::add_table_pub_capabilities($charset_collate); self::add_table_pub_documents($charset_collate); self::add_table_pub_imports($charset_collate); self::add_table_tags($charset_collate); self::add_table_relation($charset_collate); self::add_table_user($charset_collate); self::add_table_authors($charset_collate); self::add_table_rel_pub_auth($charset_collate); // Enable foreign key checks if ( TEACHPRESS_FOREIGN_KEY_CHECKS === false ) { $wpdb->query("SET foreign_key_checks = 1"); } } /** * Remove teachPress database tables * @since 5.0.0 */ public static function remove() { global $wpdb; $wpdb->query("SET FOREIGN_KEY_CHECKS=0"); $wpdb->query("DROP TABLE `" . TEACHPRESS_ARTEFACTS . "`, `" . TEACHPRESS_ASSESSMENTS . "`, `" . TEACHPRESS_AUTHORS . "`, `" . TEACHPRESS_COURSES . "`, `" . TEACHPRESS_COURSE_CAPABILITIES . "`, `" . TEACHPRESS_COURSE_DOCUMENTS . "`, `" . TEACHPRESS_COURSE_META . "`, `" . TEACHPRESS_PUB . "`, `" . TEACHPRESS_PUB_CAPABILITIES . "`, `" . TEACHPRESS_PUB_DOCUMENTS . "`, `" . TEACHPRESS_PUB_META . "`, `" . TEACHPRESS_PUB_IMPORTS . "`, `" . TEACHPRESS_RELATION ."`, `" . TEACHPRESS_REL_PUB_AUTH . "`, `" . TEACHPRESS_SETTINGS ."`, `" . TEACHPRESS_SIGNUP ."`, `" . TEACHPRESS_STUD . "`, `" . TEACHPRESS_STUD_META . "`, `" . TEACHPRESS_TAGS . "`, `" . TEACHPRESS_USER . "`"); $wpdb->query("SET FOREIGN_KEY_CHECKS=1"); } /** * Returns an associative array with table status informations (Name, Engine, Version, Rows,...) * @param string $table * @return array * @since 5.0.0 */ public static function check_table_status($table){ global $wpdb; return $wpdb->get_row("SHOW TABLE STATUS FROM " . DB_NAME . " WHERE `Name` = '$table'", ARRAY_A); } /** * Tests if the engine for the selected table is InnoDB. If not, the function changes the engine. * @param string $table * @since 5.0.0 * @access private */ private static function change_engine($table){ global $wpdb; $db_info = self::check_table_status($table); if ( $db_info['Engine'] != 'InnoDB' ) { $wpdb->query("ALTER TABLE " . $table . " ENGINE = INNODB"); } } /** * Create table teachpress_courses * @param string $charset_collate * @since 5.0.0 */ public static function add_table_courses($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_COURSES . "'") == TEACHPRESS_COURSES ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_COURSES . " ( `course_id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(100), `type` VARCHAR (100), `room` VARCHAR(100), `lecturer` VARCHAR (100), `date` VARCHAR(60), `places` INT(4), `start` DATETIME, `end` DATETIME, `semester` VARCHAR(100), `comment` VARCHAR(500), `rel_page` INT, `parent` INT, `visible` INT(1), `waitinglist` INT(1), `image_url` VARCHAR(400), `strict_signup` INT(1), `use_capabilities` INT(1), PRIMARY KEY (`course_id`), KEY `semester` (`semester`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_COURSES); } /** * Create table course_capabilities * @param string $charset_collate * @since 5.0.0 */ public static function add_table_course_capabilities($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_COURSE_CAPABILITIES . "'") == TEACHPRESS_COURSE_CAPABILITIES ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_COURSE_CAPABILITIES . " ( `cap_id` INT UNSIGNED AUTO_INCREMENT, `wp_id` INT UNSIGNED, `course_id` INT UNSIGNED, `capability` VARCHAR(100), PRIMARY KEY (`cap_id`), KEY `ind_course_id` (`course_id`), KEY `ind_wp_id` (`wp_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_COURSE_CAPABILITIES); } /** * Create table course_documents * @param string $charset_collate * @since 5.0.0 */ public static function add_table_course_documents($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_COURSE_DOCUMENTS . "'") == TEACHPRESS_COURSE_DOCUMENTS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_COURSE_DOCUMENTS . " ( `doc_id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(500), `path` VARCHAR(500), `added` DATETIME, `size` BIGINT, `sort` INT, `course_id` INT UNSIGNED, PRIMARY KEY (doc_id), KEY `ind_course_id` (`course_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_COURSE_DOCUMENTS); } /** * Create table teachpress_course_meta * @param string $charset_collate * @since 5.0.0 */ public static function add_table_course_meta($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_COURSE_META . "'") == TEACHPRESS_COURSE_META ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_COURSE_META . " ( `meta_id` INT UNSIGNED AUTO_INCREMENT, `course_id` INT UNSIGNED, `meta_key` VARCHAR(255), `meta_value` TEXT, PRIMARY KEY (meta_id), KEY `ind_course_id` (`course_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_COURSE_META); } /** * Create table teachpress_stud * @param string $charset_collate * @since 5.0.0 */ public static function add_table_stud($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_STUD . "'") == TEACHPRESS_STUD ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_STUD . " ( `wp_id` INT UNSIGNED, `firstname` VARCHAR(100) , `lastname` VARCHAR(100), `userlogin` VARCHAR (100), `email` VARCHAR(50), PRIMARY KEY (wp_id), KEY `ind_userlogin` (`userlogin`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_STUD); } /** * Create table teachpress_stud_meta * @param string $charset_collate * @since 5.0.0 */ public static function add_table_stud_meta($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_STUD_META . "'") == TEACHPRESS_STUD_META ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_STUD_META . " ( `meta_id` INT UNSIGNED AUTO_INCREMENT, `wp_id` INT UNSIGNED, `meta_key` VARCHAR(255), `meta_value` TEXT, PRIMARY KEY (meta_id), KEY `ind_wp_id` (`wp_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_STUD_META); } /** * Create table teachpress_signup * @param string $charset_collate * @since 5.0.0 */ public static function add_table_signup($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_SIGNUP ."'") == TEACHPRESS_SIGNUP ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_SIGNUP ." ( `con_id` INT UNSIGNED AUTO_INCREMENT, `course_id` INT UNSIGNED, `wp_id` INT UNSIGNED, `waitinglist` INT(1) UNSIGNED, `date` DATETIME, PRIMARY KEY (con_id), KEY `ind_course_id` (`course_id`), KEY `ind_wp_id` (`wp_id`), KEY `ind_date` (`date`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_SIGNUP); } /** * Create table teachpress_artefacts * @param string $charset_collate * @since 5.0.0 */ public static function add_table_artefacts($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_ARTEFACTS . "'") == TEACHPRESS_ARTEFACTS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_ARTEFACTS . " ( `artefact_id` INT UNSIGNED AUTO_INCREMENT, `parent_id` INT UNSIGNED, `course_id` INT UNSIGNED, `title` VARCHAR(500), `scale` TEXT, `passed` INT(1), `max_value` VARCHAR(50), PRIMARY KEY (artefact_id), KEY `ind_course_id` (`course_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_ARTEFACTS); } /** * Create table teachpress_assessments * @param string $charset_collate * @since 5.0.0 */ public static function add_table_assessments($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_ASSESSMENTS . "'") == TEACHPRESS_ASSESSMENTS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_ASSESSMENTS . " ( `assessment_id` INT UNSIGNED AUTO_INCREMENT, `artefact_id` INT UNSIGNED, `course_id` INT UNSIGNED, `wp_id` INT UNSIGNED, `value` VARCHAR(50), `max_value` VARCHAR(50), `type` VARCHAR(50), `examiner_id` INT, `exam_date` DATETIME, `comment` TEXT, `passed` INT(1), PRIMARY KEY (assessment_id), KEY `ind_course_id` (`course_id`), KEY `ind_artefact_id` (`artefact_id`), KEY `ind_wp_id` (`wp_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_ASSESSMENTS); } /** * Create table teachpress_settings * @param string $charset_collate * @since 5.0.0 */ public static function add_table_settings($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_SETTINGS . "'") == TEACHPRESS_SETTINGS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_SETTINGS . " ( `setting_id` INT UNSIGNED AUTO_INCREMENT, `variable` VARCHAR (100), `value` LONGTEXT, `category` VARCHAR (100), PRIMARY KEY (setting_id) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_SETTINGS); // Add default values self::add_default_settings(); } /** * Add default system settings * @since 5.0.0 */ public static function add_default_settings(){ global $wpdb; $value = '[tpsingle [key]]<!--more-->' . "\n\n[tpabstract]\n\n[tplinks]\n\n[tpbibtex]"; $version = get_tp_version(); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('sem', 'Example term', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('db-version', '$version', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('sign_out', '0', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('login', 'std', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('stylesheet', '1', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('rel_page_courses', 'page', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('rel_page_publications', 'page', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('rel_content_auto', '0', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('rel_content_template', '$value', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('rel_content_category', '', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('import_overwrite', '1', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('convert_bibtex', '0', 'system')"); // Example values $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('Example term', 'Example term', 'semester')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('Example', 'Example', 'course_of_studies')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . "(`variable`, `value`, `category`) VALUES ('Lecture', 'Lecture', 'course_type')"); // Register example meta data fields // course_of_studies $value = 'name = {course_of_studies}, title = {' . __('Course of studies','teachpress') . '}, type = {SELECT}, required = {false}, min = {false}, max = {false}, step = {false}, visibility = {admin}'; $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('course_of_studies', '$value', 'teachpress_stud')"); // birthday $value = 'name = {birthday}, title = {' . __('Birthday','teachpress') . '}, type = {DATE}, required = {false}, min = {false}, max = {false}, step = {false}, visibility = {normal}'; $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('birthday', '$value', 'teachpress_stud')"); // semester_number $value = 'name = {semester_number}, title = {' . __('Semester number','teachpress') . '}, type = {INT}, required = {false}, min = {1}, max = {99}, step = {1}, visibility = {normal}'; $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('semester_number', '$value', 'teachpress_stud')"); // matriculation_number $value = 'name = {matriculation_number}, title = {' . __('Matriculation number','teachpress') . '}, type = {INT}, required = {false}, min = {1}, max = {1000000}, step = {1}, visibility = {admin}'; $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('matriculation_number', '$value', 'teachpress_stud')"); } /** * Create table teachpress_pub * @param string $charset_collate * @since 5.0.0 */ public static function add_table_pub($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_PUB . "'") == TEACHPRESS_PUB ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_PUB . " ( `pub_id` INT UNSIGNED AUTO_INCREMENT, `title` VARCHAR(500), `type` VARCHAR (50), `bibtex` VARCHAR (100), `author` VARCHAR (3000), `editor` VARCHAR (3000), `isbn` VARCHAR (50), `url` TEXT, `date` DATE, `urldate` DATE, `booktitle` VARCHAR (1000), `issuetitle` VARCHAR (200), `journal` VARCHAR(200), `issue` VARCHAR(40), `volume` VARCHAR(40), `number` VARCHAR(40), `pages` VARCHAR(40), `publisher` VARCHAR (500), `address` VARCHAR (300), `edition` VARCHAR (100), `chapter` VARCHAR (40), `institution` VARCHAR (500), `organization` VARCHAR (500), `school` VARCHAR (200), `series` VARCHAR (200), `crossref` VARCHAR (100), `abstract` TEXT, `howpublished` VARCHAR (200), `key` VARCHAR (100), `techtype` VARCHAR (200), `comment` TEXT, `note` TEXT, `image_url` VARCHAR (400), `image_target` VARCHAR (100), `image_ext` VARCHAR (400), `doi` VARCHAR (100), `is_isbn` INT(1), `rel_page` INT, `status` VARCHAR (100) DEFAULT 'published', `added` DATETIME, `modified` DATETIME, `use_capabilities` INT(1), `import_id` INT, PRIMARY KEY (pub_id), KEY `ind_type` (`type`), KEY `ind_date` (`date`), KEY `ind_import_id` (`import_id`), KEY `ind_key` (`key`), KEY `ind_bibtex_key` (`bibtex`), KEY `ind_status` (`status`) ) ROW_FORMAT=DYNAMIC $charset_collate;"); // test engine self::change_engine(TEACHPRESS_PUB); } /** * Create table teachpress_pub_meta * @param string $charset_collate * @since 5.0.0 */ public static function add_table_pub_meta($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_PUB_META . "'") == TEACHPRESS_PUB_META ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_PUB_META . " ( `meta_id` INT UNSIGNED AUTO_INCREMENT, `pub_id` INT UNSIGNED, `meta_key` VARCHAR(255), `meta_value` TEXT, PRIMARY KEY (meta_id), KEY `ind_pub_id` (`pub_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_PUB_META); } /** * Create table pub_capabilities * @param string $charset_collate * @since 6.0.0 */ public static function add_table_pub_capabilities($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_PUB_CAPABILITIES . "'") == TEACHPRESS_PUB_CAPABILITIES ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_PUB_CAPABILITIES . " ( `cap_id` INT UNSIGNED AUTO_INCREMENT, `wp_id` INT UNSIGNED, `pub_id` INT UNSIGNED, `capability` VARCHAR(100), PRIMARY KEY (`cap_id`), KEY `ind_pub_id` (`pub_id`), KEY `ind_wp_id` (`wp_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_PUB_CAPABILITIES); } /** * Create table pub_documents * @param string $charset_collate * @since 6.0.0 */ public static function add_table_pub_documents($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_PUB_DOCUMENTS . "'") == TEACHPRESS_PUB_DOCUMENTS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_PUB_DOCUMENTS . " ( `doc_id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(500), `path` VARCHAR(500), `added` DATETIME, `size` BIGINT, `sort` INT, `pub_id` INT UNSIGNED, PRIMARY KEY (doc_id), KEY `ind_pub_id` (`pub_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_PUB_DOCUMENTS); } /** * Create table pub_imports * @param string $charset_collate * @since 6.1.0 */ public static function add_table_pub_imports($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_PUB_IMPORTS . "'") == TEACHPRESS_PUB_IMPORTS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_PUB_IMPORTS . " ( `id` INT UNSIGNED AUTO_INCREMENT, `wp_id` INT UNSIGNED, `date` DATETIME, PRIMARY KEY (id) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_PUB_DOCUMENTS); } /** * Create table teachpress_tags * @param string $charset_collate * @since 5.0.0 */ public static function add_table_tags($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_TAGS . "'") == TEACHPRESS_TAGS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_TAGS . " ( `tag_id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(300), PRIMARY KEY (tag_id), KEY `ind_tag_name` (`name`) ) ROW_FORMAT=DYNAMIC $charset_collate;"); // test engine self::change_engine(TEACHPRESS_TAGS); } /** * Create table teachpress_relation * @param string $charset_collate * @since 5.0.0 */ public static function add_table_relation($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_RELATION . "'") == TEACHPRESS_RELATION ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_RELATION . " ( `con_id` INT UNSIGNED AUTO_INCREMENT, `pub_id` INT UNSIGNED, `tag_id` INT UNSIGNED, PRIMARY KEY (con_id), KEY `ind_pub_id` (`pub_id`), KEY `ind_tag_id` (`tag_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_RELATION); } /** * Create table teachpress_user * @param string $charset_collate * @since 5.0.0 */ public static function add_table_user($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_USER . "'") == TEACHPRESS_USER ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_USER . " ( `bookmark_id` INT UNSIGNED AUTO_INCREMENT, `pub_id` INT UNSIGNED, `user` INT UNSIGNED, PRIMARY KEY (bookmark_id), KEY `ind_pub_id` (`pub_id`), KEY `ind_user` (`user`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_USER); } /** * Create table teachpress_authors * @param string $charset_collate * @since 5.0.0 */ public static function add_table_authors($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_AUTHORS . "'") == TEACHPRESS_AUTHORS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_AUTHORS . " ( `author_id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(500), `sort_name` VARCHAR(500), PRIMARY KEY (author_id), KEY `ind_sort_name` (`sort_name`) ) ROW_FORMAT=DYNAMIC $charset_collate;"); // test engine self::change_engine(TEACHPRESS_AUTHORS); } /** * Create table teachpress_rel_pub_auth * @param string $charset_collate * @since 5.0.0 */ public static function add_table_rel_pub_auth($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_REL_PUB_AUTH . "'") == TEACHPRESS_REL_PUB_AUTH ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_REL_PUB_AUTH . " ( `con_id` INT UNSIGNED AUTO_INCREMENT, `pub_id` INT UNSIGNED, `author_id` INT UNSIGNED, `is_author` INT(1), `is_editor` INT(1), PRIMARY KEY (con_id), KEY `ind_pub_id` (`pub_id`), KEY `ind_author_id` (`author_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_REL_PUB_AUTH); } /** * Add capabilities * @since 5.0.0 */ private static function add_capabilities() { // global $wp_roles; $role = $wp_roles->get_role('administrator'); if ( !$role->has_cap('use_teachpress') ) { $wp_roles->add_cap('administrator', 'use_teachpress'); } if ( !$role->has_cap('use_teachpress_courses') ) { $wp_roles->add_cap('administrator', 'use_teachpress_courses'); } } /** * charset & collate like WordPress * @since 5.0.0 */ public static function get_charset() { global $wpdb; $charset_collate = ''; if ( ! empty($wpdb->charset) ) { $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset"; } if ( ! empty($wpdb->collate) ) { $charset_collate .= " COLLATE $wpdb->collate"; } $charset_collate .= " ENGINE = INNODB"; return $charset_collate; } }
winkm89/teachPress
core/class-tables.php
PHP
gpl-2.0
31,096
(function ($) { function getCsrfTokenForFullShotImage(callback) { $ .get(Drupal.url('rest/session/token')) .done(function (data) { var csrfToken = data; callback(csrfToken); }); } function patchImageFullShot(csrfToken, file, fid) { //document.getElementById('msg-up').innerHTML = 'Image marked as fullshot ....'; $.ajax({ url: Drupal.url('file/' + fid + '?_format=hal_json'), method: 'PATCH', headers: { 'Content-Type': 'application/hal+json', 'X-CSRF-Token': csrfToken }, data: JSON.stringify(file), success: function (file) { //console.log(node); //document.getElementById('msg-up').innerHTML = 'Image Fullshot started!'; swal({ title: "Full Shot", text: "Image has been selected as full shot. Scan next ID", type: "success", showCancelButton: false, confirmButtonColor: "#DD6B55", confirmButtonText: "OK", closeOnConfirm: true }); }, error: function(){ swal({ title: "Full Shot", text: "There was an error, please try again.", type: "error", showCancelButton: false, confirmButtonColor: "#DD6B55", confirmButtonText: "OK", closeOnConfirm: true }); } }); // setTimeout(function(){ // document.getElementById('msg-up').innerHTML = ''; // }, 3300); } /* * tag value 1 means tag * tag value 0 means undo tag * */ function update_image_fullshot(tag,fidinput) { var nid = fidinput; var Node_imgs = { _links: { type: { href: Drupal.url.toAbsolute(drupalSettings.path.baseUrl + 'rest/type/file/image') } }, // type: { // target_id: 'products' // }, field_full_shoot: { value:tag } }; getCsrfTokenForFullShotImage(function (csrfToken) { if (nid) { patchImageFullShot(csrfToken, Node_imgs, nid); }else{ alert('Node product found, pls refresh the page.'); } }); } $(".studio-img-fullshot").click(function () { var id = $(this).parents('span').attr('id'); console.log('fullshot'); update_image_fullshot(1,id); }); $(document).on("click",".studio-img-fullshot",function(){ var id = $(this).parents('span').attr('id'); console.log('fullshot'); update_image_fullshot(1,id); }); })(jQuery);
asharnb/dawn
modules/custom/studiobridge_store_images/js/studio-bridge-fullshot-image.js
JavaScript
gpl-2.0
3,011
#ifndef __DGAPROC_H #define __DGAPROC_H #include <X11/Xproto.h> #include "pixmap.h" #define DGA_CONCURRENT_ACCESS 0x00000001 #define DGA_FILL_RECT 0x00000002 #define DGA_BLIT_RECT 0x00000004 #define DGA_BLIT_RECT_TRANS 0x00000008 #define DGA_PIXMAP_AVAILABLE 0x00000010 #define DGA_INTERLACED 0x00010000 #define DGA_DOUBLESCAN 0x00020000 #define DGA_FLIP_IMMEDIATE 0x00000001 #define DGA_FLIP_RETRACE 0x00000002 #define DGA_COMPLETED 0x00000000 #define DGA_PENDING 0x00000001 #define DGA_NEED_ROOT 0x00000001 typedef struct { int num; /* A unique identifier for the mode (num > 0) */ char *name; /* name of mode given in the XF86Config */ int VSync_num; int VSync_den; int flags; /* DGA_CONCURRENT_ACCESS, etc... */ int imageWidth; /* linear accessible portion (pixels) */ int imageHeight; int pixmapWidth; /* Xlib accessible portion (pixels) */ int pixmapHeight; /* both fields ignored if no concurrent access */ int bytesPerScanline; int byteOrder; /* MSBFirst, LSBFirst */ int depth; int bitsPerPixel; unsigned long red_mask; unsigned long green_mask; unsigned long blue_mask; short visualClass; int viewportWidth; int viewportHeight; int xViewportStep; /* viewport position granularity */ int yViewportStep; int maxViewportX; /* max viewport origin */ int maxViewportY; int viewportFlags; /* types of page flipping possible */ int offset; int reserved1; int reserved2; } XDGAModeRec, *XDGAModePtr; /* DDX interface */ extern _X_EXPORT int DGASetMode(int Index, int num, XDGAModePtr mode, PixmapPtr *pPix); extern _X_EXPORT void DGASetInputMode(int Index, Bool keyboard, Bool mouse); extern _X_EXPORT void DGASelectInput(int Index, ClientPtr client, long mask); extern _X_EXPORT Bool DGAAvailable(int Index); extern _X_EXPORT Bool DGAActive(int Index); extern _X_EXPORT void DGAShutdown(void); extern _X_EXPORT void DGAInstallCmap(ColormapPtr cmap); extern _X_EXPORT int DGAGetViewportStatus(int Index); extern _X_EXPORT int DGASync(int Index); extern _X_EXPORT int DGAFillRect(int Index, int x, int y, int w, int h, unsigned long color); extern _X_EXPORT int DGABlitRect(int Index, int srcx, int srcy, int w, int h, int dstx, int dsty); extern _X_EXPORT int DGABlitTransRect(int Index, int srcx, int srcy, int w, int h, int dstx, int dsty, unsigned long color); extern _X_EXPORT int DGASetViewport(int Index, int x, int y, int mode); extern _X_EXPORT int DGAGetModes(int Index); extern _X_EXPORT int DGAGetOldDGAMode(int Index); extern _X_EXPORT int DGAGetModeInfo(int Index, XDGAModePtr mode, int num); extern _X_EXPORT Bool DGAVTSwitch(void); extern _X_EXPORT Bool DGAStealButtonEvent(DeviceIntPtr dev, int Index, int button, int is_down); extern _X_EXPORT Bool DGAStealMotionEvent(DeviceIntPtr dev, int Index, int dx, int dy); extern _X_EXPORT Bool DGAStealKeyEvent(DeviceIntPtr dev, int Index, int key_code, int is_down); extern _X_EXPORT Bool DGAOpenFramebuffer(int Index, char **name, unsigned char **mem, int *size, int *offset, int *flags); extern _X_EXPORT void DGACloseFramebuffer(int Index); extern _X_EXPORT Bool DGAChangePixmapMode(int Index, int *x, int *y, int mode); extern _X_EXPORT int DGACreateColormap(int Index, ClientPtr client, int id, int mode, int alloc); extern _X_EXPORT unsigned char DGAReqCode; extern _X_EXPORT int DGAErrorBase; extern _X_EXPORT int DGAEventBase; extern _X_EXPORT int *XDGAEventBase; #endif /* __DGAPROC_H */
atmark-techno/atmark-dist
user/xorg-xserver/xorg-server-1.12.4/hw/xfree86/dixmods/extmod/dgaproc.h
C
gpl-2.0
3,934
<?php /** * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. */ namespace eZ\Publish\Core\MVC\Symfony\Matcher\Tests\ContentBased; use eZ\Publish\API\Repository\LocationService; use eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\Depth as DepthMatcher; use eZ\Publish\API\Repository\Values\Content\Location; use eZ\Publish\API\Repository\Repository; class DepthTest extends BaseTest { /** @var \eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\Depth */ private $matcher; protected function setUp(): void { parent::setUp(); $this->matcher = new DepthMatcher(); } /** * @dataProvider matchLocationProvider * @covers \eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\Depth::matchLocation * @covers \eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\MultipleValued::setMatchingConfig * * @param int|int[] $matchingConfig * @param \eZ\Publish\API\Repository\Values\Content\Location $location * @param bool $expectedResult */ public function testMatchLocation($matchingConfig, Location $location, $expectedResult) { $this->matcher->setMatchingConfig($matchingConfig); $this->assertSame($expectedResult, $this->matcher->matchLocation($location)); } public function matchLocationProvider() { return [ [ 1, $this->getLocationMock(['depth' => 1]), true, ], [ 1, $this->getLocationMock(['depth' => 2]), false, ], [ [1, 3], $this->getLocationMock(['depth' => 2]), false, ], [ [1, 3], $this->getLocationMock(['depth' => 3]), true, ], [ [1, 3], $this->getLocationMock(['depth' => 0]), false, ], [ [0, 1], $this->getLocationMock(['depth' => 0]), true, ], ]; } /** * @dataProvider matchContentInfoProvider * @covers \eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\Depth::matchContentInfo * @covers \eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\MultipleValued::setMatchingConfig * @covers \eZ\Publish\Core\MVC\RepositoryAware::setRepository * * @param int|int[] $matchingConfig * @param \eZ\Publish\API\Repository\Repository $repository * @param bool $expectedResult */ public function testMatchContentInfo($matchingConfig, Repository $repository, $expectedResult) { $this->matcher->setRepository($repository); $this->matcher->setMatchingConfig($matchingConfig); $this->assertSame( $expectedResult, $this->matcher->matchContentInfo($this->getContentInfoMock(['mainLocationId' => 42])) ); } public function matchContentInfoProvider() { return [ [ 1, $this->generateRepositoryMockForDepth(1), true, ], [ 1, $this->generateRepositoryMockForDepth(2), false, ], [ [1, 3], $this->generateRepositoryMockForDepth(2), false, ], [ [1, 3], $this->generateRepositoryMockForDepth(3), true, ], ]; } /** * Returns a Repository mock configured to return the appropriate Location object with given parent location Id. * * @param int $depth * * @return \PHPUnit\Framework\MockObject\MockObject */ private function generateRepositoryMockForDepth($depth) { $locationServiceMock = $this->createMock(LocationService::class); $locationServiceMock->expects($this->once()) ->method('loadLocation') ->with(42) ->will( $this->returnValue( $this->getLocationMock(['depth' => $depth]) ) ); $repository = $this->getRepositoryMock(); $repository ->expects($this->once()) ->method('getLocationService') ->will($this->returnValue($locationServiceMock)); $repository ->expects($this->once()) ->method('getPermissionResolver') ->will($this->returnValue($this->getPermissionResolverMock())); return $repository; } }
gggeek/ezpublish-kernel
eZ/Publish/Core/MVC/Symfony/Matcher/Tests/ContentBased/DepthTest.php
PHP
gpl-2.0
4,768
# # Copyright (C) 2006-2012 OpenWrt.org # # This is free software, licensed under the GNU General Public License v2. # See /LICENSE for more information. # include $(TOPDIR)/rules.mk include $(INCLUDE_DIR)/image.mk define Build/Clean $(MAKE) -C lzma-loader clean endef define Image/Prepare cat $(KDIR)/vmlinux | $(STAGING_DIR_HOST)/bin/lzma e -si -so -eos -lc1 -lp2 -pb2 > $(KDIR)/vmlinux.lzma rm -f $(KDIR)/loader.gz $(MAKE) -C lzma-loader \ BUILD_DIR="$(KDIR)" \ TARGET="$(KDIR)" \ clean install echo -ne "\\x00" >> $(KDIR)/loader.gz rm -f $(KDIR)/fs_mark echo -ne '\xde\xad\xc0\xde' > $(KDIR)/fs_mark $(call prepare_generic_squashfs,$(KDIR)/fs_mark) endef define Image/Build/wgt634u dd if=$(KDIR)/loader.elf of=$(BIN_DIR)/openwrt-wgt634u-$(2).bin bs=131072 conv=sync cat $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx >> $(BIN_DIR)/openwrt-wgt634u-$(2).bin endef define Image/Build/dwl3150 cp $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx $(BIN_DIR)/openwrt-dwl3150-$(2).bin echo "BCM-5352-2050-0000000-01" >> $(BIN_DIR)/openwrt-dwl3150-$(2).bin endef define Image/Build/CyberTAN $(STAGING_DIR_HOST)/bin/addpattern -4 -p $(3) -v v$(4) -i $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx -o $(BIN_DIR)/openwrt-$(2)-$(5).bin $(if $(6),-s $(6)) endef define Image/Build/CyberTAN2 $(STAGING_DIR_HOST)/bin/addpattern -4 -p $(3) -v v$(4) -i $(BIN_DIR)/openwrt-$(2)-$(5).noheader.bin -o $(BIN_DIR)/openwrt-$(2)-$(5).bin $(if $(6),-s $(6)) endef define Image/Build/CyberTANHead $(STAGING_DIR_HOST)/bin/addpattern -5 -p $(3) -v v$(4) -i /dev/null -o $(KDIR)/openwrt-$(2)-header.bin $(if $(6),-s $(6)) endef define Image/Build/Motorola $(STAGING_DIR_HOST)/bin/motorola-bin -$(3) $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx $(BIN_DIR)/openwrt-$(2)-$(4).bin endef define Image/Build/USR $(STAGING_DIR_HOST)/bin/trx2usr $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx $(BIN_DIR)/openwrt-$(2)-$(3).bin endef define Image/Build/Edi $(STAGING_DIR_HOST)/bin/trx2edips $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx $(BIN_DIR)/openwrt-$(2)-$(3).bin endef define trxalign/jffs2-128k -a 0x20000 -f $(KDIR)/root.$(1) endef define trxalign/jffs2-64k -a 0x10000 -f $(KDIR)/root.$(1) endef define trxalign/squashfs -a 1024 -f $(KDIR)/root.$(1) $(if $(2),-f $(2)) -a 0x10000 -A $(KDIR)/fs_mark endef define Image/Build/trxV2 $(call Image/Build/CyberTANHead,$(1),$(2),$(3),$(4),$(5),$(if $(6),$(6))) $(STAGING_DIR_HOST)/bin/trx -2 -o $(BIN_DIR)/openwrt-$(2)-$(5).noheader.bin \ -f $(KDIR)/loader.gz -f $(KDIR)/vmlinux.lzma \ $(call trxalign/$(1),$(1),$(KDIR)/openwrt-$(2)-header.bin) $(call Image/Build/CyberTAN2,$(1),$(2),$(3),$(4),$(5),$(if $(6),$(6))) endef define Image/Build/jffs2-128k $(call Image/Build/CyberTAN,$(1),wrt54gs,W54S,4.80.1,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrtsl54gs,W54U,2.08.1,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/trxV2,$(1),wrt54g3gv2-vf,3G2V,3.00.24,$(patsubst jffs2-%,jffs2,$(1)),6) $(call Image/Build/wgt634u,$(1),$(patsubst jffs2-%,jffs2,$(1))) endef define Image/Build/jffs2-64k $(call Image/Build/CyberTAN,$(1),wrt54g3g,W54F,2.20.1,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrt54g3g-em,W3GN,2.20.1,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrt54g,W54G,4.71.1,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrt54gs_v4,W54s,1.09.1,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrt150n,N150,1.51.3,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrt300n_v1,EWCB,1.03.6,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrt300n_v11,EWC2,1.51.2,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrt350n_v1,EWCG,1.04.1,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/CyberTAN,$(1),wrt610n_v1,610N,1.0.1,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/CyberTAN,$(1),wrt610n_v2,610N,2.0.0,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/CyberTAN,$(1),e3000_v1,61XN,1.0.3,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/CyberTAN,$(1),e3200_v1,3200,1.0.1,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/Motorola,$(1),wa840g,2,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/Motorola,$(1),we800g,3,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/Edi,$(1),ps1208mfg,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/dwl3150,$(1),$(patsubst jffs2-%,jffs2,$(1))) endef define Image/Build/squashfs $(call Image/Build/jffs2-64k,$(1)) $(call Image/Build/jffs2-128k,$(1)) endef define Image/Build/Initramfs $(STAGING_DIR_HOST)/bin/trx -o $(BIN_DIR)/$(IMG_PREFIX)-initramfs.trx -f $(KDIR)/loader.gz -f $(KDIR)/vmlinux.lzma endef define Image/Build/Chk $(STAGING_DIR_HOST)/bin/mkchkimg -o $(BIN_DIR)/openwrt-$(2)-$(5).chk -k $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx -b $(3) -r $(4) endef define Image/Build $(STAGING_DIR_HOST)/bin/trx -o $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx \ -f $(KDIR)/loader.gz -f $(KDIR)/vmlinux.lzma \ $(call trxalign/$(1),$(1)) $(call Image/Build/$(1),$(1)) $(call Image/Build/Motorola,$(1),wr850g,1,$(1)) $(call Image/Build/USR,$(1),usr5461,$(1)) # $(call Image/Build/Chk,$(1),wgr614_v8,U12H072T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wgr614_v9,U12H094T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wndr3300,U12H093T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/Chk,$(1),wndr3400_v1,U12H155T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wndr3400_v2,U12H187T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wndr3400_vcna,U12H155T01_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wndr4000,U12H181T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) $(call Image/Build/Chk,$(1),wnr834b_v2,U12H081T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wnr2000v2,U12H114T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wnr3500L,U12H136T99_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wnr3500U,U12H136T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wnr3500v2,U12H127T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) # $(call Image/Build/Chk,$(1),wnr3500v2_VC,U12H127T70_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1))) endef $(eval $(call BuildImage))
geog-opensource/geog-linino
target/linux/brcm47xx/image/Makefile
Makefile
gpl-2.0
6,299
/*============================================================================= Copyright (c) 2002-2003 Joel de Guzman http://spirit.sourceforge.net/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ //////////////////////////////////////////////////////////////////////////// // // Full calculator example demonstrating Phoenix // This is discussed in the "Closures" chapter in the Spirit User's Guide. // // [ JDG 6/29/2002 ] // //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include <boost/spirit/core.hpp> #include <boost/spirit/attribute.hpp> #include <boost/spirit/phoenix/functions.hpp> #include <iostream> #include <string> #include "Main.h" //#include "bigfp.h" //////////////////////////////////////////////////////////////////////////// using namespace std; using namespace boost::spirit; using namespace phoenix; //////////////////////////////////////////////////////////////////////////// // // Our calculator grammar using phoenix to do the semantics // // Note: The top rule propagates the expression result (value) upwards // to the calculator grammar self.val closure member which is // then visible outside the grammar (i.e. since self.val is the // member1 of the closure, it becomes the attribute passed by // the calculator to an attached semantic action. See the // driver code that uses the calculator below). // //////////////////////////////////////////////////////////////////////////// struct calc_closure : boost::spirit::closure<calc_closure, double> { member1 val; }; struct pow_ { template <typename X, typename Y> struct result { typedef X type; }; template <typename X, typename Y> X operator()(X x, Y y) const { using namespace std; return pow(x, y); } }; // Notice how power(x, y) is lazily implemented using Phoenix function. function<pow_> power; struct calculator : public grammar<calculator, calc_closure::context_t> { template <typename ScannerT> struct definition { definition(calculator const& self) { top = expression[self.val = arg1]; expression = term[expression.val = arg1] >> *( ('+' >> term[expression.val += arg1]) | ('-' >> term[expression.val -= arg1]) ) ; term = factor[term.val = arg1] >> *( ('*' >> factor[term.val *= arg1]) | ('/' >> factor[term.val /= arg1]) ) ; factor = ureal_p[factor.val = arg1] | '(' >> expression[factor.val = arg1] >> ')' | ('-' >> factor[factor.val = -arg1]) | ('+' >> factor[factor.val = arg1]) ; } // const uint_parser<bigint, 10, 1, -1> bigint_parser; typedef rule<ScannerT, calc_closure::context_t> rule_t; rule_t expression, term, factor; rule<ScannerT> top; rule<ScannerT> const& start() const { return top; } }; }; bool DoCalculation(const TCHAR* str, double& result) { // Our parser calculator calc; double n = 0; parse_info<const wchar_t *> info = parse(str, calc[var(n) = arg1], space_p); if (info.full) { result = n; return true; } return false; }
Slesa/launchy
old/Launchy_VC7/Plugins/Calcy/Main.cpp
C++
gpl-2.0
3,793
/** @file * PDM - Pluggable Device Manager, Common Instance Macros. */ /* * Copyright (C) 2006-2015 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ #ifndef ___VBox_vmm_pdmins_h #define ___VBox_vmm_pdmins_h /** @defgroup grp_pdm_ins Common PDM Instance Macros * @ingroup grp_pdm * @{ */ /** @def PDMBOTHCBDECL * Macro for declaring a callback which is static in HC and exported in GC. */ #if defined(IN_RC) || defined(IN_RING0) # ifdef __cplusplus # define PDMBOTHCBDECL(type) extern "C" DECLEXPORT(type) # else # define PDMBOTHCBDECL(type) DECLEXPORT(type) # endif #else # define PDMBOTHCBDECL(type) static DECLCALLBACK(type) #endif /** @def PDMINS_2_DATA * Converts a PDM Device, USB Device, or Driver instance pointer to a pointer to the instance data. */ #define PDMINS_2_DATA(pIns, type) ( (type)(void *)&(pIns)->achInstanceData[0] ) /** @def PDMINS_2_DATA_RCPTR * Converts a PDM Device, USB Device, or Driver instance pointer to a RC pointer to the instance data. */ #define PDMINS_2_DATA_RCPTR(pIns) ( (pIns)->pvInstanceDataRC ) /** @def PDMINS_2_DATA_R3PTR * Converts a PDM Device, USB Device, or Driver instance pointer to a HC pointer to the instance data. */ #define PDMINS_2_DATA_R3PTR(pIns) ( (pIns)->pvInstanceDataR3 ) /** @def PDMINS_2_DATA_R0PTR * Converts a PDM Device, USB Device, or Driver instance pointer to a R0 pointer to the instance data. */ #define PDMINS_2_DATA_R0PTR(pIns) ( (pIns)->pvInstanceDataR0 ) /** @} */ #endif
miguelinux/vbox
include/VBox/vmm/pdmins.h
C
gpl-2.0
2,414
/* ---------------------------------------------------------------------------------------------------------- This website template was downloaded from http://www.nuviotemplates.com - visit us for more templates Structure: display; position; float; z-index; overflow; width; height; margin; padding; border; background; align; font; ---------------------------------------------------------------------------------------------------------- */ body {border:0; margin:0; padding:0; font-size:12pt} a {color:#000; text-decoration:none;} h1, h2, h3 {page-break-after:avoid; page-break-inside:avoid;} table {border-collapse: collapse; border-width:1px; border-style:solid;} th, td {display:table-cell; border-width:1px; border-style:solid;} hr {display:block; height:2px; margin:0; padding:0; background:#000; border:0 solid #000; color:#000;} blockquote {page-break-inside:avoid} ul, ol, dl {page-break-before:avoid} .noprint {display:none;}
bigace/bigace2-extensions
SMARTY/CrystalX/public/cid{CID}/CrystalX/print.css
CSS
gpl-2.0
963
/* * linux/fs/read_write.c * * Copyright (C) 1991, 1992 Linus Torvalds */ #include <linux/slab.h> #include <linux/stat.h> #include <linux/fcntl.h> #include <linux/file.h> #include <linux/uio.h> #include <linux/smp_lock.h> #include <linux/fsnotify.h> #include <linux/security.h> #include <linux/module.h> #include <linux/syscalls.h> #include <linux/pagemap.h> #include <linux/splice.h> #include <trace/fs.h> #include "read_write.h" #include <asm/uaccess.h> #include <asm/unistd.h> const struct file_operations generic_ro_fops = { .llseek = generic_file_llseek, .read = do_sync_read, .aio_read = generic_file_aio_read, .mmap = generic_file_readonly_mmap, .splice_read = generic_file_splice_read, }; EXPORT_SYMBOL(generic_ro_fops); /** * generic_file_llseek_unlocked - lockless generic llseek implementation * @file: file structure to seek on * @offset: file offset to seek to * @origin: type of seek * * Updates the file offset to the value specified by @offset and @origin. * Locking must be provided by the caller. */ loff_t generic_file_llseek_unlocked(struct file *file, loff_t offset, int origin) { struct inode *inode = file->f_mapping->host; switch (origin) { case SEEK_END: offset += inode->i_size; break; case SEEK_CUR: offset += file->f_pos; break; } if (offset < 0 || offset > inode->i_sb->s_maxbytes) return -EINVAL; /* Special lock needed here? */ if (offset != file->f_pos) { file->f_pos = offset; file->f_version = 0; } return offset; } EXPORT_SYMBOL(generic_file_llseek_unlocked); /** * generic_file_llseek - generic llseek implementation for regular files * @file: file structure to seek on * @offset: file offset to seek to * @origin: type of seek * * This is a generic implemenation of ->llseek useable for all normal local * filesystems. It just updates the file offset to the value specified by * @offset and @origin under i_mutex. */ loff_t generic_file_llseek(struct file *file, loff_t offset, int origin) { loff_t rval; mutex_lock(&file->f_dentry->d_inode->i_mutex); rval = generic_file_llseek_unlocked(file, offset, origin); mutex_unlock(&file->f_dentry->d_inode->i_mutex); return rval; } EXPORT_SYMBOL(generic_file_llseek); loff_t no_llseek(struct file *file, loff_t offset, int origin) { return -ESPIPE; } EXPORT_SYMBOL(no_llseek); loff_t default_llseek(struct file *file, loff_t offset, int origin) { loff_t retval; lock_kernel(); switch (origin) { case SEEK_END: offset += i_size_read(file->f_path.dentry->d_inode); break; case SEEK_CUR: offset += file->f_pos; } retval = -EINVAL; if (offset >= 0) { if (offset != file->f_pos) { file->f_pos = offset; file->f_version = 0; } retval = offset; } unlock_kernel(); return retval; } EXPORT_SYMBOL(default_llseek); loff_t vfs_llseek(struct file *file, loff_t offset, int origin) { loff_t (*fn)(struct file *, loff_t, int); fn = no_llseek; if (file->f_mode & FMODE_LSEEK) { fn = default_llseek; if (file->f_op && file->f_op->llseek) fn = file->f_op->llseek; } return fn(file, offset, origin); } EXPORT_SYMBOL(vfs_llseek); SYSCALL_DEFINE3(lseek, unsigned int, fd, off_t, offset, unsigned int, origin) { off_t retval; struct file * file; int fput_needed; retval = -EBADF; file = fget_light(fd, &fput_needed); if (!file) goto bad; retval = -EINVAL; if (origin <= SEEK_MAX) { loff_t res = vfs_llseek(file, offset, origin); retval = res; if (res != (loff_t)retval) retval = -EOVERFLOW; /* LFS: should only happen on 32 bit platforms */ } trace_fs_lseek(fd, offset, origin); fput_light(file, fput_needed); bad: return retval; } #ifdef __ARCH_WANT_SYS_LLSEEK SYSCALL_DEFINE5(llseek, unsigned int, fd, unsigned long, offset_high, unsigned long, offset_low, loff_t __user *, result, unsigned int, origin) { int retval; struct file * file; loff_t offset; int fput_needed; retval = -EBADF; file = fget_light(fd, &fput_needed); if (!file) goto bad; retval = -EINVAL; if (origin > SEEK_MAX) goto out_putf; offset = vfs_llseek(file, ((loff_t) offset_high << 32) | offset_low, origin); trace_fs_llseek(fd, offset, origin); retval = (int)offset; if (offset >= 0) { retval = -EFAULT; if (!copy_to_user(result, &offset, sizeof(offset))) retval = 0; } out_putf: fput_light(file, fput_needed); bad: return retval; } #endif /* * rw_verify_area doesn't like huge counts. We limit * them to something that fits in "int" so that others * won't have to do range checks all the time. */ #define MAX_RW_COUNT (INT_MAX & PAGE_CACHE_MASK) int rw_verify_area(int read_write, struct file *file, loff_t *ppos, size_t count) { struct inode *inode; loff_t pos; int retval = -EINVAL; inode = file->f_path.dentry->d_inode; if (unlikely((ssize_t) count < 0)) return retval; pos = *ppos; if (unlikely((pos < 0) || (loff_t) (pos + count) < 0)) return retval; if (unlikely(inode->i_flock && mandatory_lock(inode))) { retval = locks_mandatory_area( read_write == READ ? FLOCK_VERIFY_READ : FLOCK_VERIFY_WRITE, inode, file, pos, count); if (retval < 0) return retval; } retval = security_file_permission(file, read_write == READ ? MAY_READ : MAY_WRITE); if (retval) return retval; return count > MAX_RW_COUNT ? MAX_RW_COUNT : count; } static void wait_on_retry_sync_kiocb(struct kiocb *iocb) { set_current_state(TASK_UNINTERRUPTIBLE); if (!kiocbIsKicked(iocb)) schedule(); else kiocbClearKicked(iocb); __set_current_state(TASK_RUNNING); } ssize_t do_sync_read(struct file *filp, char __user *buf, size_t len, loff_t *ppos) { struct iovec iov = { .iov_base = buf, .iov_len = len }; struct kiocb kiocb; ssize_t ret; init_sync_kiocb(&kiocb, filp); kiocb.ki_pos = *ppos; kiocb.ki_left = len; for (;;) { ret = filp->f_op->aio_read(&kiocb, &iov, 1, kiocb.ki_pos); if (ret != -EIOCBRETRY) break; wait_on_retry_sync_kiocb(&kiocb); } if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&kiocb); *ppos = kiocb.ki_pos; return ret; } EXPORT_SYMBOL(do_sync_read); ssize_t vfs_read(struct file *file, char __user *buf, size_t count, loff_t *pos) { ssize_t ret; if (!(file->f_mode & FMODE_READ)) return -EBADF; if (!file->f_op || (!file->f_op->read && !file->f_op->aio_read)) return -EINVAL; if (unlikely(!access_ok(VERIFY_WRITE, buf, count))) return -EFAULT; ret = rw_verify_area(READ, file, pos, count); if (ret >= 0) { count = ret; if (file->f_op->read) ret = file->f_op->read(file, buf, count, pos); else ret = do_sync_read(file, buf, count, pos); if (ret > 0) { fsnotify_access(file->f_path.dentry); add_rchar(current, ret); } inc_syscr(current); } return ret; } EXPORT_SYMBOL(vfs_read); ssize_t do_sync_write(struct file *filp, const char __user *buf, size_t len, loff_t *ppos) { struct iovec iov = { .iov_base = (void __user *)buf, .iov_len = len }; struct kiocb kiocb; ssize_t ret; init_sync_kiocb(&kiocb, filp); kiocb.ki_pos = *ppos; kiocb.ki_left = len; for (;;) { ret = filp->f_op->aio_write(&kiocb, &iov, 1, kiocb.ki_pos); if (ret != -EIOCBRETRY) break; wait_on_retry_sync_kiocb(&kiocb); } if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&kiocb); *ppos = kiocb.ki_pos; return ret; } EXPORT_SYMBOL(do_sync_write); ssize_t vfs_write(struct file *file, const char __user *buf, size_t count, loff_t *pos) { ssize_t ret; if (!(file->f_mode & FMODE_WRITE)) return -EBADF; if (!file->f_op || (!file->f_op->write && !file->f_op->aio_write)) return -EINVAL; if (unlikely(!access_ok(VERIFY_READ, buf, count))) return -EFAULT; ret = rw_verify_area(WRITE, file, pos, count); if (ret >= 0) { count = ret; if (file->f_op->write) ret = file->f_op->write(file, buf, count, pos); else ret = do_sync_write(file, buf, count, pos); if (ret > 0) { fsnotify_modify(file->f_path.dentry); add_wchar(current, ret); } inc_syscw(current); } return ret; } EXPORT_SYMBOL(vfs_write); static inline loff_t file_pos_read(struct file *file) { return file->f_pos; } static inline void file_pos_write(struct file *file, loff_t pos) { file->f_pos = pos; } SYSCALL_DEFINE3(read, unsigned int, fd, char __user *, buf, size_t, count) { struct file *file; ssize_t ret = -EBADF; int fput_needed; file = fget_light(fd, &fput_needed); if (file) { loff_t pos = file_pos_read(file); ret = vfs_read(file, buf, count, &pos); trace_fs_read(fd, buf, count, ret); file_pos_write(file, pos); fput_light(file, fput_needed); } return ret; } SYSCALL_DEFINE3(write, unsigned int, fd, const char __user *, buf, size_t, count) { struct file *file; ssize_t ret = -EBADF; int fput_needed; file = fget_light(fd, &fput_needed); if (file) { loff_t pos = file_pos_read(file); ret = vfs_write(file, buf, count, &pos); trace_fs_write(fd, buf, count, ret); file_pos_write(file, pos); fput_light(file, fput_needed); } return ret; } SYSCALL_DEFINE(pread64)(unsigned int fd, char __user *buf, size_t count, loff_t pos) { struct file *file; ssize_t ret = -EBADF; int fput_needed; if (pos < 0) return -EINVAL; file = fget_light(fd, &fput_needed); if (file) { ret = -ESPIPE; if (file->f_mode & FMODE_PREAD) { ret = vfs_read(file, buf, count, &pos); trace_fs_pread64(fd, buf, count, pos, ret); } fput_light(file, fput_needed); } return ret; } #ifdef CONFIG_HAVE_SYSCALL_WRAPPERS asmlinkage long SyS_pread64(long fd, long buf, long count, loff_t pos) { return SYSC_pread64((unsigned int) fd, (char __user *) buf, (size_t) count, pos); } SYSCALL_ALIAS(sys_pread64, SyS_pread64); #endif SYSCALL_DEFINE(pwrite64)(unsigned int fd, const char __user *buf, size_t count, loff_t pos) { struct file *file; ssize_t ret = -EBADF; int fput_needed; if (pos < 0) return -EINVAL; file = fget_light(fd, &fput_needed); if (file) { ret = -ESPIPE; if (file->f_mode & FMODE_PWRITE) { ret = vfs_write(file, buf, count, &pos); trace_fs_pwrite64(fd, buf, count, pos, ret); } fput_light(file, fput_needed); } return ret; } #ifdef CONFIG_HAVE_SYSCALL_WRAPPERS asmlinkage long SyS_pwrite64(long fd, long buf, long count, loff_t pos) { return SYSC_pwrite64((unsigned int) fd, (const char __user *) buf, (size_t) count, pos); } SYSCALL_ALIAS(sys_pwrite64, SyS_pwrite64); #endif /* * Reduce an iovec's length in-place. Return the resulting number of segments */ unsigned long iov_shorten(struct iovec *iov, unsigned long nr_segs, size_t to) { unsigned long seg = 0; size_t len = 0; while (seg < nr_segs) { seg++; if (len + iov->iov_len >= to) { iov->iov_len = to - len; break; } len += iov->iov_len; iov++; } return seg; } EXPORT_SYMBOL(iov_shorten); ssize_t do_sync_readv_writev(struct file *filp, const struct iovec *iov, unsigned long nr_segs, size_t len, loff_t *ppos, iov_fn_t fn) { struct kiocb kiocb; ssize_t ret; init_sync_kiocb(&kiocb, filp); kiocb.ki_pos = *ppos; kiocb.ki_left = len; kiocb.ki_nbytes = len; for (;;) { ret = fn(&kiocb, iov, nr_segs, kiocb.ki_pos); if (ret != -EIOCBRETRY) break; wait_on_retry_sync_kiocb(&kiocb); } if (ret == -EIOCBQUEUED) ret = wait_on_sync_kiocb(&kiocb); *ppos = kiocb.ki_pos; return ret; } /* Do it by hand, with file-ops */ ssize_t do_loop_readv_writev(struct file *filp, struct iovec *iov, unsigned long nr_segs, loff_t *ppos, io_fn_t fn) { struct iovec *vector = iov; ssize_t ret = 0; while (nr_segs > 0) { void __user *base; size_t len; ssize_t nr; base = vector->iov_base; len = vector->iov_len; vector++; nr_segs--; nr = fn(filp, base, len, ppos); if (nr < 0) { if (!ret) ret = nr; break; } ret += nr; if (nr != len) break; } return ret; } /* A write operation does a read from user space and vice versa */ #define vrfy_dir(type) ((type) == READ ? VERIFY_WRITE : VERIFY_READ) ssize_t rw_copy_check_uvector(int type, const struct iovec __user * uvector, unsigned long nr_segs, unsigned long fast_segs, struct iovec *fast_pointer, struct iovec **ret_pointer) { unsigned long seg; ssize_t ret; struct iovec *iov = fast_pointer; /* * SuS says "The readv() function *may* fail if the iovcnt argument * was less than or equal to 0, or greater than {IOV_MAX}. Linux has * traditionally returned zero for zero segments, so... */ if (nr_segs == 0) { ret = 0; goto out; } /* * First get the "struct iovec" from user memory and * verify all the pointers */ if (nr_segs > UIO_MAXIOV) { ret = -EINVAL; goto out; } if (nr_segs > fast_segs) { iov = kmalloc(nr_segs*sizeof(struct iovec), GFP_KERNEL); if (iov == NULL) { ret = -ENOMEM; goto out; } } if (copy_from_user(iov, uvector, nr_segs*sizeof(*uvector))) { ret = -EFAULT; goto out; } /* * According to the Single Unix Specification we should return EINVAL * if an element length is < 0 when cast to ssize_t or if the * total length would overflow the ssize_t return value of the * system call. */ ret = 0; for (seg = 0; seg < nr_segs; seg++) { void __user *buf = iov[seg].iov_base; ssize_t len = (ssize_t)iov[seg].iov_len; /* see if we we're about to use an invalid len or if * it's about to overflow ssize_t */ if (len < 0 || (ret + len < ret)) { ret = -EINVAL; goto out; } if (unlikely(!access_ok(vrfy_dir(type), buf, len))) { ret = -EFAULT; goto out; } ret += len; } out: *ret_pointer = iov; return ret; } static ssize_t do_readv_writev(int type, struct file *file, const struct iovec __user * uvector, unsigned long nr_segs, loff_t *pos) { size_t tot_len; struct iovec iovstack[UIO_FASTIOV]; struct iovec *iov = iovstack; ssize_t ret; io_fn_t fn; iov_fn_t fnv; if (!file->f_op) { ret = -EINVAL; goto out; } ret = rw_copy_check_uvector(type, uvector, nr_segs, ARRAY_SIZE(iovstack), iovstack, &iov); if (ret <= 0) goto out; tot_len = ret; ret = rw_verify_area(type, file, pos, tot_len); if (ret < 0) goto out; fnv = NULL; if (type == READ) { fn = file->f_op->read; fnv = file->f_op->aio_read; } else { fn = (io_fn_t)file->f_op->write; fnv = file->f_op->aio_write; } if (fnv) ret = do_sync_readv_writev(file, iov, nr_segs, tot_len, pos, fnv); else ret = do_loop_readv_writev(file, iov, nr_segs, pos, fn); out: if (iov != iovstack) kfree(iov); if ((ret + (type == READ)) > 0) { if (type == READ) fsnotify_access(file->f_path.dentry); else fsnotify_modify(file->f_path.dentry); } return ret; } ssize_t vfs_readv(struct file *file, const struct iovec __user *vec, unsigned long vlen, loff_t *pos) { if (!(file->f_mode & FMODE_READ)) return -EBADF; if (!file->f_op || (!file->f_op->aio_read && !file->f_op->read)) return -EINVAL; return do_readv_writev(READ, file, vec, vlen, pos); } EXPORT_SYMBOL(vfs_readv); ssize_t vfs_writev(struct file *file, const struct iovec __user *vec, unsigned long vlen, loff_t *pos) { if (!(file->f_mode & FMODE_WRITE)) return -EBADF; if (!file->f_op || (!file->f_op->aio_write && !file->f_op->write)) return -EINVAL; return do_readv_writev(WRITE, file, vec, vlen, pos); } EXPORT_SYMBOL(vfs_writev); SYSCALL_DEFINE3(readv, unsigned long, fd, const struct iovec __user *, vec, unsigned long, vlen) { struct file *file; ssize_t ret = -EBADF; int fput_needed; file = fget_light(fd, &fput_needed); if (file) { loff_t pos = file_pos_read(file); ret = vfs_readv(file, vec, vlen, &pos); trace_fs_readv(fd, vec, vlen, ret); file_pos_write(file, pos); fput_light(file, fput_needed); } if (ret > 0) add_rchar(current, ret); inc_syscr(current); return ret; } SYSCALL_DEFINE3(writev, unsigned long, fd, const struct iovec __user *, vec, unsigned long, vlen) { struct file *file; ssize_t ret = -EBADF; int fput_needed; file = fget_light(fd, &fput_needed); if (file) { loff_t pos = file_pos_read(file); ret = vfs_writev(file, vec, vlen, &pos); trace_fs_writev(fd, vec, vlen, ret); file_pos_write(file, pos); fput_light(file, fput_needed); } if (ret > 0) add_wchar(current, ret); inc_syscw(current); return ret; } static ssize_t do_sendfile(int out_fd, int in_fd, loff_t *ppos, size_t count, loff_t max) { struct file * in_file, * out_file; struct inode * in_inode, * out_inode; loff_t pos; ssize_t retval; int fput_needed_in, fput_needed_out, fl; /* * Get input file, and verify that it is ok.. */ retval = -EBADF; in_file = fget_light(in_fd, &fput_needed_in); if (!in_file) goto out; if (!(in_file->f_mode & FMODE_READ)) goto fput_in; retval = -EINVAL; in_inode = in_file->f_path.dentry->d_inode; if (!in_inode) goto fput_in; if (!in_file->f_op || !in_file->f_op->splice_read) goto fput_in; retval = -ESPIPE; if (!ppos) ppos = &in_file->f_pos; else if (!(in_file->f_mode & FMODE_PREAD)) goto fput_in; retval = rw_verify_area(READ, in_file, ppos, count); if (retval < 0) goto fput_in; count = retval; /* * Get output file, and verify that it is ok.. */ retval = -EBADF; out_file = fget_light(out_fd, &fput_needed_out); if (!out_file) goto fput_in; if (!(out_file->f_mode & FMODE_WRITE)) goto fput_out; retval = -EINVAL; if (!out_file->f_op || !out_file->f_op->sendpage) goto fput_out; out_inode = out_file->f_path.dentry->d_inode; retval = rw_verify_area(WRITE, out_file, &out_file->f_pos, count); if (retval < 0) goto fput_out; count = retval; if (!max) max = min(in_inode->i_sb->s_maxbytes, out_inode->i_sb->s_maxbytes); pos = *ppos; retval = -EINVAL; if (unlikely(pos < 0)) goto fput_out; if (unlikely(pos + count > max)) { retval = -EOVERFLOW; if (pos >= max) goto fput_out; count = max - pos; } fl = 0; #if 0 /* * We need to debate whether we can enable this or not. The * man page documents EAGAIN return for the output at least, * and the application is arguably buggy if it doesn't expect * EAGAIN on a non-blocking file descriptor. */ if (in_file->f_flags & O_NONBLOCK) fl = SPLICE_F_NONBLOCK; #endif retval = do_splice_direct(in_file, ppos, out_file, count, fl); if (retval > 0) { add_rchar(current, retval); add_wchar(current, retval); } inc_syscr(current); inc_syscw(current); if (*ppos > max) retval = -EOVERFLOW; fput_out: fput_light(out_file, fput_needed_out); fput_in: fput_light(in_file, fput_needed_in); out: return retval; } SYSCALL_DEFINE4(sendfile, int, out_fd, int, in_fd, off_t __user *, offset, size_t, count) { loff_t pos; off_t off; ssize_t ret; if (offset) { if (unlikely(get_user(off, offset))) return -EFAULT; pos = off; ret = do_sendfile(out_fd, in_fd, &pos, count, MAX_NON_LFS); if (unlikely(put_user(pos, offset))) return -EFAULT; return ret; } return do_sendfile(out_fd, in_fd, NULL, count, 0); } SYSCALL_DEFINE4(sendfile64, int, out_fd, int, in_fd, loff_t __user *, offset, size_t, count) { loff_t pos; ssize_t ret; if (offset) { if (unlikely(copy_from_user(&pos, offset, sizeof(loff_t)))) return -EFAULT; ret = do_sendfile(out_fd, in_fd, &pos, count, 0); if (unlikely(put_user(pos, offset))) return -EFAULT; return ret; } return do_sendfile(out_fd, in_fd, NULL, count, 0); }
kzlin129/tt-gpl
go12/linux-2.6.28.10/fs/read_write.c
C
gpl-2.0
19,284
# # The Qubes OS Project, http://www.qubes-os.org # # Copyright (C) 2014-2016 Wojtek Porczyk <[email protected]> # Copyright (C) 2016 Marek Marczykowski <[email protected]>) # Copyright (C) 2016 Bahtiar `kalkin-` Gadimov <[email protected]> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, see <https://www.gnu.org/licenses/>. # ''' This module contains the TemplateVM implementation ''' import qubes import qubes.config import qubes.vm.qubesvm import qubes.vm.mix.net from qubes.config import defaults from qubes.vm.qubesvm import QubesVM class TemplateVM(QubesVM): '''Template for AppVM''' dir_path_prefix = qubes.config.system_path['qubes_templates_dir'] @property def appvms(self): ''' Returns a generator containing all domains based on the current TemplateVM. ''' for vm in self.app.domains: if hasattr(vm, 'template') and vm.template is self: yield vm netvm = qubes.VMProperty('netvm', load_stage=4, allow_none=True, default=None, # pylint: disable=protected-access setter=qubes.vm.qubesvm.QubesVM.netvm._setter, doc='VM that provides network connection to this domain. When ' '`None`, machine is disconnected.') def __init__(self, *args, **kwargs): assert 'template' not in kwargs, "A TemplateVM can not have a template" self.volume_config = { 'root': { 'name': 'root', 'snap_on_start': False, 'save_on_stop': True, 'rw': True, 'source': None, 'size': defaults['root_img_size'], }, 'private': { 'name': 'private', 'snap_on_start': False, 'save_on_stop': True, 'rw': True, 'source': None, 'size': defaults['private_img_size'], 'revisions_to_keep': 0, }, 'volatile': { 'name': 'volatile', 'size': defaults['root_img_size'], 'snap_on_start': False, 'save_on_stop': False, 'rw': True, }, 'kernel': { 'name': 'kernel', 'snap_on_start': False, 'save_on_stop': False, 'rw': False } } super(TemplateVM, self).__init__(*args, **kwargs) @qubes.events.handler('property-set:default_user', 'property-set:kernel', 'property-set:kernelopts', 'property-set:vcpus', 'property-set:memory', 'property-set:maxmem', 'property-set:qrexec_timeout', 'property-set:shutdown_timeout', 'property-set:management_dispvm') def on_property_set_child(self, _event, name, newvalue, oldvalue=None): """Send event about default value change to child VMs (which use default inherited from the template). This handler is supposed to be set for properties using `_default_with_template()` function for the default value. """ if newvalue == oldvalue: return for vm in self.appvms: if not vm.property_is_default(name): continue vm.fire_event('property-reset:' + name, name=name)
nrgaway/qubes-core-admin
qubes/vm/templatevm.py
Python
gpl-2.0
4,118
#!/bin/sh # # Copyright (c) 2007 Junio C Hamano # test_description='git apply --whitespace=strip and configuration file. ' . ./test-lib.sh test_expect_success setup ' mkdir sub && echo A >sub/file1 && cp sub/file1 saved && git add sub/file1 && echo "B " >sub/file1 && git diff >patch.file ' # Also handcraft GNU diff output; note this has trailing whitespace. tr '_' ' ' >gpatch.file <<\EOF && --- file1 2007-02-21 01:04:24.000000000 -0800 +++ file1+ 2007-02-21 01:07:44.000000000 -0800 @@ -1 +1 @@ -A +B_ EOF sed -e 's|file1|sub/&|' gpatch.file >gpatch-sub.file && sed -e ' /^--- /s|file1|a/sub/&| /^+++ /s|file1|b/sub/&| ' gpatch.file >gpatch-ab-sub.file && check_result () { if grep " " "$1" then echo "Eh?" false elif grep B "$1" then echo Happy else echo "Huh?" false fi } test_expect_success 'apply --whitespace=strip' ' rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && git apply --whitespace=strip patch.file && check_result sub/file1 ' test_expect_success 'apply --whitespace=strip from config' ' rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && git config apply.whitespace strip && git apply patch.file && check_result sub/file1 ' D=$(pwd) test_expect_success 'apply --whitespace=strip in subdir' ' cd "$D" && git config --unset-all apply.whitespace && rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && cd sub && git apply --whitespace=strip ../patch.file && check_result file1 ' test_expect_success 'apply --whitespace=strip from config in subdir' ' cd "$D" && git config apply.whitespace strip && rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && cd sub && git apply ../patch.file && check_result file1 ' test_expect_success 'same in subdir but with traditional patch input' ' cd "$D" && git config apply.whitespace strip && rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && cd sub && git apply ../gpatch.file && check_result file1 ' test_expect_success 'same but with traditional patch input of depth 1' ' cd "$D" && git config apply.whitespace strip && rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && cd sub && git apply ../gpatch-sub.file && check_result file1 ' test_expect_success 'same but with traditional patch input of depth 2' ' cd "$D" && git config apply.whitespace strip && rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && cd sub && git apply ../gpatch-ab-sub.file && check_result file1 ' test_expect_success 'same but with traditional patch input of depth 1' ' cd "$D" && git config apply.whitespace strip && rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && git apply -p0 gpatch-sub.file && check_result sub/file1 ' test_expect_success 'same but with traditional patch input of depth 2' ' cd "$D" && git config apply.whitespace strip && rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && git apply gpatch-ab-sub.file && check_result sub/file1 ' test_expect_success 'in subdir with traditional patch input' ' cd "$D" && git config apply.whitespace strip && cat >.gitattributes <<-EOF && /* whitespace=blank-at-eol sub/* whitespace=-blank-at-eol EOF rm -f sub/file1 && cp saved sub/file1 && git update-index --refresh && cd sub && git apply ../gpatch.file && echo "B " >expect && test_cmp expect file1 ' test_done
haglerchristopher/automation
src/3rd_party/git/t/t4119-apply-config.sh
Shell
gpl-2.0
3,650
/** * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "config.h" #if ENABLE(WML) #include "WMLInputElement.h" #include "EventNames.h" #include "FormDataList.h" #include "Frame.h" #include "HTMLNames.h" #include "KeyboardEvent.h" #include "MappedAttribute.h" #include "RenderTextControlSingleLine.h" #include "TextEvent.h" #include "WMLDocument.h" #include "WMLNames.h" #include "WMLPageState.h" namespace WebCore { WMLInputElement::WMLInputElement(const QualifiedName& tagName, Document* doc) : WMLFormControlElement(tagName, doc) , m_isPasswordField(false) , m_isEmptyOk(false) , m_numOfCharsAllowedByMask(0) { } WMLInputElement::~WMLInputElement() { if (m_isPasswordField) document()->unregisterForDocumentActivationCallbacks(this); } static const AtomicString& formatCodes() { DEFINE_STATIC_LOCAL(AtomicString, codes, ("AaNnXxMm")); return codes; } bool WMLInputElement::isKeyboardFocusable(KeyboardEvent*) const { return WMLFormControlElement::isFocusable(); } bool WMLInputElement::isMouseFocusable() const { return WMLFormControlElement::isFocusable(); } void WMLInputElement::dispatchFocusEvent() { InputElement::dispatchFocusEvent(this, this); WMLElement::dispatchFocusEvent(); } void WMLInputElement::dispatchBlurEvent() { // Firstly check if it is allowed to leave this input field String val = value(); if ( //SAMSUNG_CHANGES_BEGGIN /*(!m_isEmptyOk && val.isEmpty()) || */ //SAMSUNG_CHANGES_END !isConformedToInputMask(val)) { updateFocusAppearance(true); return; } // update the name variable of WML input elmenet String nameVariable = formControlName(); if (!nameVariable.isEmpty()) wmlPageStateForDocument(document())->storeVariable(nameVariable, val); InputElement::dispatchBlurEvent(this, this); WMLElement::dispatchBlurEvent(); } void WMLInputElement::updateFocusAppearance(bool restorePreviousSelection) { InputElement::updateFocusAppearance(m_data, this, this, restorePreviousSelection); } void WMLInputElement::aboutToUnload() { InputElement::aboutToUnload(this, this); } int WMLInputElement::size() const { return m_data.size(); } const AtomicString& WMLInputElement::formControlType() const { // needs to be lowercase according to DOM spec if (m_isPasswordField) { DEFINE_STATIC_LOCAL(const AtomicString, password, ("password")); return password; } DEFINE_STATIC_LOCAL(const AtomicString, text, ("text")); return text; } const AtomicString& WMLInputElement::formControlName() const { return m_data.name(); } const String& WMLInputElement::suggestedValue() const { return m_data.suggestedValue(); } String WMLInputElement::value() const { String value = m_data.value(); if (value.isNull()) value = constrainValue(getAttribute(HTMLNames::valueAttr)); return value; } void WMLInputElement::setValue(const String& value, bool sendChangeEvent) { setFormControlValueMatchesRenderer(false); m_data.setValue(constrainValue(value)); if (inDocument()) document()->updateStyleIfNeeded(); if (renderer()) renderer()->updateFromElement(); setNeedsStyleRecalc(); unsigned max = m_data.value().length(); if (document()->focusedNode() == this) InputElement::updateSelectionRange(this, this, max, max); else cacheSelection(max, max); InputElement::notifyFormStateChanged(this); } // SAMSUNG_WML_FIXES+ // wml/struct/control/input/format/1 void WMLInputElement::setValuePreserveSelectionPos(const String& value) { //InputElement::updatePlaceholderVisibility(m_data, this, this); setFormControlValueMatchesRenderer(false); m_data.setValue(constrainValue(value)); if (inDocument()) document()->updateStyleIfNeeded(); if (renderer()) renderer()->updateFromElement(); setNeedsStyleRecalc(); InputElement::notifyFormStateChanged(this); } // SAMSUNG_WML_FIXES- void WMLInputElement::setValueForUser(const String& value) { /* InputElement class defines pure virtual function 'setValueForUser', which will be useful only in HTMLInputElement. Do nothing in 'WMLInputElement'. */ } void WMLInputElement::setValueFromRenderer(const String& value) { InputElement::setValueFromRenderer(m_data, this, this, value); } bool WMLInputElement::saveFormControlState(String& result) const { if (m_isPasswordField) return false; result = value(); return true; } void WMLInputElement::restoreFormControlState(const String& state) { ASSERT(!m_isPasswordField); // should never save/restore password fields setValue(state, true); } void WMLInputElement::select() { if (RenderTextControl* r = toRenderTextControl(renderer())) r->select(); } void WMLInputElement::accessKeyAction(bool) { // should never restore previous selection here focus(false); } void WMLInputElement::parseMappedAttribute(MappedAttribute* attr) { if (attr->name() == HTMLNames::nameAttr) m_data.setName(parseValueForbiddingVariableReferences(attr->value())); else if (attr->name() == HTMLNames::typeAttr) { String type = parseValueForbiddingVariableReferences(attr->value()); m_isPasswordField = (type == "password"); } else if (attr->name() == HTMLNames::valueAttr) { // We only need to setChanged if the form is looking at the default value right now. if (m_data.value().isNull()) setNeedsStyleRecalc(); setFormControlValueMatchesRenderer(false); } else if (attr->name() == HTMLNames::maxlengthAttr) InputElement::parseMaxLengthAttribute(m_data, this, this, attr); else if (attr->name() == HTMLNames::sizeAttr) InputElement::parseSizeAttribute(m_data, this, attr); else if (attr->name() == WMLNames::formatAttr) m_formatMask = validateInputMask(parseValueForbiddingVariableReferences(attr->value())); else if (attr->name() == WMLNames::emptyokAttr) m_isEmptyOk = (attr->value() == "true"); else WMLElement::parseMappedAttribute(attr); // FIXME: Handle 'accesskey' attribute // FIXME: Handle 'tabindex' attribute // FIXME: Handle 'title' attribute } void WMLInputElement::copyNonAttributeProperties(const Element* source) { const WMLInputElement* sourceElement = static_cast<const WMLInputElement*>(source); m_data.setValue(sourceElement->m_data.value()); WMLElement::copyNonAttributeProperties(source); } RenderObject* WMLInputElement::createRenderer(RenderArena* arena, RenderStyle*) { return new (arena) RenderTextControlSingleLine(this, false); } void WMLInputElement::detach() { WMLElement::detach(); setFormControlValueMatchesRenderer(false); } bool WMLInputElement::appendFormData(FormDataList& encoding, bool) { if (formControlName().isEmpty()) return false; encoding.appendData(formControlName(), value()); return true; } void WMLInputElement::reset() { setValue(String(), true); } void WMLInputElement::defaultEventHandler(Event* evt) { bool clickDefaultFormButton = false; String filteredString; if (evt->type() == eventNames().textInputEvent && evt->isTextEvent()) { TextEvent* textEvent = static_cast<TextEvent*>(evt); if (textEvent->data() == "\n") clickDefaultFormButton = true; // SAMSUNG_WML_FIXES+ // wml/struct/control/input/format/1 // else if (renderer() && !isConformedToInputMask(textEvent->data()[0], toRenderTextControl(renderer())->text().length() + 1)) else if (renderer()) { WMLElement::defaultEventHandler(evt); if (evt->defaultHandled()) { filteredString = filterInvalidChars((toRenderTextControl(renderer()))->text()); setValuePreserveSelectionPos(filteredString); return; } } // SAMSUNG_WML_FIXES- } if (evt->type() == eventNames().keydownEvent && evt->isKeyboardEvent() && focused() && document()->frame() && document()->frame()->doTextFieldCommandFromEvent(this, static_cast<KeyboardEvent*>(evt))) { evt->setDefaultHandled(); return; } // Let the key handling done in EventTargetNode take precedence over the event handling here for editable text fields if (!clickDefaultFormButton) { WMLElement::defaultEventHandler(evt); if (evt->defaultHandled()) return; } // Use key press event here since sending simulated mouse events // on key down blocks the proper sending of the key press event. if (evt->type() == eventNames().keypressEvent && evt->isKeyboardEvent()) { // Simulate mouse click on the default form button for enter for these types of elements. if (static_cast<KeyboardEvent*>(evt)->charCode() == '\r') clickDefaultFormButton = true; } if (clickDefaultFormButton) { // Fire onChange for text fields. RenderObject* r = renderer(); if (r && toRenderTextControl(r)->wasChangedSinceLastChangeEvent()) { dispatchEvent(Event::create(eventNames().changeEvent, true, false)); // Refetch the renderer since arbitrary JS code run during onchange can do anything, including destroying it. r = renderer(); if (r) toRenderTextControl(r)->setChangedSinceLastChangeEvent(false); } evt->setDefaultHandled(); return; } if (evt->isBeforeTextInsertedEvent()) InputElement::handleBeforeTextInsertedEvent(m_data, this, this, evt); if (renderer() && (evt->isMouseEvent() || evt->isDragEvent() || evt->isWheelEvent() || evt->type() == eventNames().blurEvent || evt->type() == eventNames().focusEvent)) toRenderTextControlSingleLine(renderer())->forwardEvent(evt); } void WMLInputElement::cacheSelection(int start, int end) { m_data.setCachedSelectionStart(start); m_data.setCachedSelectionEnd(end); } String WMLInputElement::constrainValue(const String& proposedValue) const { return InputElement::sanitizeUserInputValue(this, proposedValue, m_data.maxLength()); } void WMLInputElement::documentDidBecomeActive() { ASSERT(m_isPasswordField); reset(); } void WMLInputElement::willMoveToNewOwnerDocument() { // Always unregister for cache callbacks when leaving a document, even if we would otherwise like to be registered if (m_isPasswordField) document()->unregisterForDocumentActivationCallbacks(this); WMLElement::willMoveToNewOwnerDocument(); } void WMLInputElement::didMoveToNewOwnerDocument() { if (m_isPasswordField) document()->registerForDocumentActivationCallbacks(this); WMLElement::didMoveToNewOwnerDocument(); } void WMLInputElement::initialize() { String nameVariable = formControlName(); String variableValue; WMLPageState* pageSate = wmlPageStateForDocument(document()); ASSERT(pageSate); if (!nameVariable.isEmpty()) variableValue = pageSate->getVariable(nameVariable); if (variableValue.isEmpty() || !isConformedToInputMask(variableValue)) { String val = value(); if (isConformedToInputMask(val)) variableValue = val; else variableValue = ""; pageSate->storeVariable(nameVariable, variableValue); } setValue(variableValue, true); if (!hasAttribute(WMLNames::emptyokAttr)) { if (m_formatMask.isEmpty() || // check if the format codes is just "*f" (m_formatMask.length() == 2 && m_formatMask[0] == '*' && formatCodes().find(m_formatMask[1]) != -1)) m_isEmptyOk = true; } } String WMLInputElement::validateInputMask(const String& inputMask) { bool isValid = true; bool hasWildcard = false; unsigned escapeCharCount = 0; unsigned maskLength = inputMask.length(); UChar formatCode; for (unsigned i = 0; i < maskLength; ++i) { formatCode = inputMask[i]; if (formatCodes().find(formatCode) == -1) { if (formatCode == '*' || (WTF::isASCIIDigit(formatCode) && formatCode != '0')) { // validate codes which ends with '*f' or 'nf' formatCode = inputMask[++i]; if ((i + 1 != maskLength) || formatCodes().find(formatCode) == -1) { isValid = false; break; } hasWildcard = true; } else if (formatCode == '\\') { //skip over the next mask character ++i; ++escapeCharCount; } else { isValid = false; break; } } } if (!isValid) return String(); // calculate the number of characters allowed to be entered by input mask m_numOfCharsAllowedByMask = maskLength; if (escapeCharCount) m_numOfCharsAllowedByMask -= escapeCharCount; if (hasWildcard) { formatCode = inputMask[maskLength - 2]; if (formatCode == '*') m_numOfCharsAllowedByMask = m_data.maxLength(); else { unsigned leftLen = String(&formatCode).toInt(); m_numOfCharsAllowedByMask = leftLen + m_numOfCharsAllowedByMask - 2; } } return inputMask; } // SAMSUNG_WML_FIXES+ String WMLInputElement::filterInvalidChars(const String& inputChars) { String filteredString; unsigned charCount = 0; for (unsigned i = 0; i < inputChars.length(); ++i) { if (isConformedToInputMask(inputChars[i], charCount+1, false)) { filteredString.append(inputChars[i]); charCount++; } } return filteredString; } // SAMSUNG_WML_FIXES- bool WMLInputElement::isConformedToInputMask(const String& inputChars) { for (unsigned i = 0; i < inputChars.length(); ++i) if (!isConformedToInputMask(inputChars[i], i + 1, false)) return false; return true; } bool WMLInputElement::isConformedToInputMask(UChar inChar, unsigned inputCharCount, bool isUserInput) { if (m_formatMask.isEmpty()) return true; if (inputCharCount > m_numOfCharsAllowedByMask) return false; unsigned maskIndex = 0; if (isUserInput) { unsigned cursorPosition = 0; if (renderer()) cursorPosition = toRenderTextControl(renderer())->selectionStart(); else cursorPosition = m_data.cachedSelectionStart(); maskIndex = cursorPositionToMaskIndex(cursorPosition); } else maskIndex = cursorPositionToMaskIndex(inputCharCount - 1); bool ok = true; UChar mask = m_formatMask[maskIndex]; // match the inputed character with input mask switch (mask) { case 'A': ok = !WTF::isASCIIDigit(inChar) && !WTF::isASCIILower(inChar) && WTF::isASCIIPrintable(inChar); break; case 'a': ok = !WTF::isASCIIDigit(inChar) && !WTF::isASCIIUpper(inChar) && WTF::isASCIIPrintable(inChar); break; case 'N': ok = WTF::isASCIIDigit(inChar); break; case 'n': ok = !WTF::isASCIIAlpha(inChar) && WTF::isASCIIPrintable(inChar); break; case 'X': ok = !WTF::isASCIILower(inChar) && WTF::isASCIIPrintable(inChar); break; case 'x': ok = !WTF::isASCIIUpper(inChar) && WTF::isASCIIPrintable(inChar); break; case 'M': ok = WTF::isASCIIPrintable(inChar); break; case 'm': ok = WTF::isASCIIPrintable(inChar); break; default: ok = (mask == inChar); break; } return ok; } unsigned WMLInputElement::cursorPositionToMaskIndex(unsigned cursorPosition) { UChar mask; int index = -1; do { mask = m_formatMask[++index]; if (mask == '\\') ++index; else if (mask == '*' || (WTF::isASCIIDigit(mask) && mask != '0')) { index = m_formatMask.length() - 1; break; } } while (cursorPosition--); return index; } } #endif
cattleprod/samsung-kernel-gt-i9100
external/webkit/WebCore/wml/WMLInputElement.cpp
C++
gpl-2.0
16,920
// // Created by David Seery on 10/08/2015. // --@@ // Copyright (c) 2017 University of Sussex. All rights reserved. // // This file is part of the Sussex Effective Field Theory for // Large-Scale Structure platform (LSSEFT). // // LSSEFT is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // LSSEFT is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with LSSEFT. If not, see <http://www.gnu.org/licenses/>. // // @license: GPL-2 // @contributor: David Seery <[email protected]> // --@@ // #ifndef LSSEFT_MASTER_CONTROLLER_H #define LSSEFT_MASTER_CONTROLLER_H #include <memory> #include "argument_cache.h" #include "local_environment.h" #include "scheduler.h" #include "database/data_manager.h" #include "database/tokens.h" #include "cosmology/types.h" #include "cosmology/FRW_model.h" #include "cosmology/oneloop_growth_integrator.h" #include "cosmology/Pk_filter.h" #include "cosmology/Matsubara_XY_calculator.h" #include "cosmology/oneloop_growth_integrator.h" #include "cosmology/concepts/range.h" #include "cosmology/concepts/power_spectrum.h" #include "error/error_handler.h" #include "MPI_detail/mpi_traits.h" #include "MPI_detail/mpi_payloads.h" #include "boost/mpi.hpp" class master_controller { // CONSTRUCTOR, DESTRUCTOR public: //! construct a master controller delegate master_controller(boost::mpi::environment& me, boost::mpi::communicator& mw, argument_cache& ac); //! destructor is default ~master_controller() = default; // INTERFACE public: //! process command-line arguments void process_arguments(int argc, char* argv[]); //! execute void execute(); // RANK TO WORKER NUMBER CONVERSIONS (worker number runs from 1 .. n-1, rank runs from 1 .. n, based on master process on rank 0) protected: //! Get worker number unsigned int worker_number() { return(static_cast<unsigned int>(this->mpi_world.rank()-1)); } //! Return MPI rank of this process unsigned int get_rank(void) const { return(static_cast<unsigned int>(this->mpi_world.rank())); } //! Map worker number to communicator rank unsigned int worker_rank(unsigned int worker_number) const { return(worker_number+1); } //! Map communicator rank to worker number unsigned int worker_number(unsigned int worker_rank) const { return(worker_rank-1); } // WORKER HANDLING protected: //! execute a job specified by a work list template <typename WorkItemList> void scatter(const FRW_model& model, const FRW_model_token& token, WorkItemList& work, data_manager& dmgr); //! store a payload returned by a worker template <typename WorkItem> void store_payload(const FRW_model_token& token, unsigned int source, data_manager& dmgr); //! terminate worker processes void terminate_workers(); //! instruct workers to await new tasks std::unique_ptr<scheduler> set_up_workers(unsigned int tag); //! instruct workers that the current batch of tasks is finished void close_down_workers(); // COMPUTE ONE-LOOP KERNELS protected: //! compute kernels at given redshifts void integrate_loop_growth(const FRW_model& model, const FRW_model_token& token, z_database& z_db, data_manager& dmgr, const growth_params_token& params_tok, const growth_params& params); // INTERNAL DATA private: // MPI environment //! MPI environment object, inherited from parent task manager boost::mpi::environment& mpi_env; //! MPI communicator, inherited from parent task manager boost::mpi::communicator& mpi_world; // Caches //! argument cache, inherited from parent task manager argument_cache& arg_cache; //! local environment properties (constructed locally) local_environment local_env; // Functional blocks //! error handler error_handler err_handler; }; template <typename WorkItemList> void master_controller::scatter(const FRW_model& model, const FRW_model_token& token, WorkItemList& work, data_manager& dmgr) { using WorkItem = typename WorkItemList::value_type; boost::timer::cpu_timer timer; // total CPU time boost::timer::cpu_timer write_timer; // time spent writing to the database write_timer.stop(); if(this->mpi_world.size() == 1) throw runtime_exception(exception_type::runtime_error, ERROR_TOO_FEW_WORKERS); // ask data manager to prepare for new writes boost::timer::cpu_timer pre_timer; // time spent doing preparation dmgr.setup_write(work); pre_timer.stop(); // instruct slave processes to await transfer function tasks std::unique_ptr<scheduler> sch = this->set_up_workers(MPI_detail::work_item_traits<WorkItem>::new_task_message()); bool sent_closedown = false; auto next_work_item = work.cbegin(); while(!sch->all_inactive()) { // check whether all work is exhausted if(next_work_item == work.cend() && !sent_closedown) { sent_closedown = true; this->close_down_workers(); } // check whether any workers are waiting for assignments if(next_work_item != work.cend() && sch->is_assignable()) { std::vector<unsigned int> unassigned_list = sch->make_assignment(); std::vector<boost::mpi::request> requests; for(std::vector<unsigned int>::const_iterator t = unassigned_list.begin(); next_work_item != work.cend() && t != unassigned_list.end(); ++t) { // assign next work item to this worker requests.push_back(this->mpi_world.isend(this->worker_rank(*t), MPI_detail::work_item_traits<WorkItem>::new_item_message(), MPI_detail::build_payload(model, next_work_item))); sch->mark_assigned(*t); ++next_work_item; } // wait for all messages to be received boost::mpi::wait_all(requests.begin(), requests.end()); } // check whether any messages are waiting in the queue boost::optional<boost::mpi::status> stat = this->mpi_world.iprobe(); while(stat) // consume messages until no more are available { switch(stat->tag()) { case MPI_detail::MESSAGE_WORK_PRODUCT_READY: { write_timer.resume(); this->store_payload<WorkItem>(token, stat->source(), dmgr); write_timer.stop(); sch->mark_unassigned(this->worker_number(stat->source())); break; } case MPI_detail::MESSAGE_END_OF_WORK_ACK: { this->mpi_world.recv(stat->source(), MPI_detail::MESSAGE_END_OF_WORK_ACK); sch->mark_inactive(this->worker_number(stat->source())); break; } default: { assert(false); } } stat = this->mpi_world.iprobe(); } } boost::timer::cpu_timer post_timer; // time spent tidying up the database after a write dmgr.finalize_write(work); post_timer.stop(); timer.stop(); std::ostringstream msg; msg << "completed work in time " << format_time(timer.elapsed().wall) << " [" << "database performance: prepare " << format_time(pre_timer.elapsed().wall) << ", " << "writes " << format_time(write_timer.elapsed().wall) << ", " << "cleanup " << format_time(post_timer.elapsed().wall) << "]"; this->err_handler.info(msg.str()); } template <typename WorkItem> void master_controller::store_payload(const FRW_model_token& token, unsigned int source, data_manager& dmgr) { typename MPI_detail::work_item_traits<WorkItem>::incoming_payload_type payload; this->mpi_world.recv(source, MPI_detail::MESSAGE_WORK_PRODUCT_READY, payload); dmgr.store(token, payload.get_data()); } #endif //LSSEFT_MASTER_CONTROLLER_H
ds283/LSSEFT
controller/master_controller.h
C
gpl-2.0
8,832
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. NEITHER * DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE SOFTWARE OF * ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR SUPPLIED WITH THE * MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH THIRD PARTY FOR * ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT * IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER * LICENSES CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE * RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO RECEIVER'S * SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM. * RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE * LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. */ /* * Copyright (c) 2008, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <boot/boot.h> #include <msm7k/gpio.h> /* gross */ typedef struct gpioregs gpioregs; struct gpioregs { unsigned out; unsigned in; unsigned int_status; unsigned int_clear; unsigned int_en; unsigned int_edge; unsigned int_pos; unsigned oe; }; static gpioregs GPIO_REGS[] = { { .out = GPIO_OUT_0, .in = GPIO_IN_0, .int_status = GPIO_INT_STATUS_0, .int_clear = GPIO_INT_CLEAR_0, .int_en = GPIO_INT_EN_0, .int_edge = GPIO_INT_EDGE_0, .int_pos = GPIO_INT_POS_0, .oe = GPIO_OE_0, }, { .out = GPIO_OUT_1, .in = GPIO_IN_1, .int_status = GPIO_INT_STATUS_1, .int_clear = GPIO_INT_CLEAR_1, .int_en = GPIO_INT_EN_1, .int_edge = GPIO_INT_EDGE_1, .int_pos = GPIO_INT_POS_1, .oe = GPIO_OE_1, }, { .out = GPIO_OUT_2, .in = GPIO_IN_2, .int_status = GPIO_INT_STATUS_2, .int_clear = GPIO_INT_CLEAR_2, .int_en = GPIO_INT_EN_2, .int_edge = GPIO_INT_EDGE_2, .int_pos = GPIO_INT_POS_2, .oe = GPIO_OE_2, }, { .out = GPIO_OUT_3, .in = GPIO_IN_3, .int_status = GPIO_INT_STATUS_3, .int_clear = GPIO_INT_CLEAR_3, .int_en = GPIO_INT_EN_3, .int_edge = GPIO_INT_EDGE_3, .int_pos = GPIO_INT_POS_3, .oe = GPIO_OE_3, }, { .out = GPIO_OUT_4, .in = GPIO_IN_4, .int_status = GPIO_INT_STATUS_4, .int_clear = GPIO_INT_CLEAR_4, .int_en = GPIO_INT_EN_4, .int_edge = GPIO_INT_EDGE_4, .int_pos = GPIO_INT_POS_4, .oe = GPIO_OE_4, }, }; static gpioregs *find_gpio(unsigned n, unsigned *bit) { if(n > 106) return 0; if(n > 94) { *bit = 1 << (n - 95); return GPIO_REGS + 4; } if(n > 67) { *bit = 1 << (n - 68); return GPIO_REGS + 3; } if(n > 42) { *bit = 1 << (n - 43); return GPIO_REGS + 2; } if(n > 15) { *bit = 1 << (n - 16); return GPIO_REGS + 1; } *bit = 1 << n; return GPIO_REGS + 0; } void gpio_output_enable(unsigned n, unsigned out) { gpioregs *r; unsigned b; unsigned v; if((r = find_gpio(n, &b)) == 0) return; v = readl(r->oe); if(out) { writel(v | b, r->oe); } else { writel(v & (~b), r->oe); } } void gpio_write(unsigned n, unsigned on) { gpioregs *r; unsigned b; unsigned v; if((r = find_gpio(n, &b)) == 0) return; v = readl(r->out); if(on) { writel(v | b, r->out); } else { writel(v & (~b), r->out); } } int gpio_read(unsigned n) { gpioregs *r; unsigned b; if((r = find_gpio(n, &b)) == 0) return 0; return (readl(r->in) & b) ? 1 : 0; } void gpio_dir(int nr, int out) { gpio_output_enable(nr, out); } void gpio_set(int nr, int set) { gpio_write(nr, set); } int gpio_get(int nr) { return gpio_read(nr); }
luckasfb/OT_903D-kernel-2.6.35.7
bootable/bootloader/legacy/arch_msm7k/gpio.c
C
gpl-2.0
6,641
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import sys def hook(mod): if sys.version[0] > '1': for i in range(len(mod.imports)-1, -1, -1): if mod.imports[i][0] == 'strop': del mod.imports[i] return mod
pdubroy/kurt
build/MacOS/PyInstaller/pyinstaller-svn-r812/hooks/hook-carchive.py
Python
gpl-2.0
1,029
/************************************************************************* * * FILE NAME : ifxmips_pci.c * PROJECT : IFX UEIP * MODULES : PCI * * DATE : 29 June 2009 * AUTHOR : Lei Chuanhua * * DESCRIPTION : PCI Host Controller Driver * COPYRIGHT : Copyright (c) 2009 * Infineon Technologies AG * Am Campeon 1-12, 85579 Neubiberg, Germany * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * HISTORY * $Version $Date $Author $Comment * 1.0 29 Jun Lei Chuanhua First UEIP release *************************************************************************/ /*! \file ifxmips_pci.c \ingroup IFX_PCI \brief pci bus driver source file */ #include <linux/module.h> #include <linux/types.h> #include <linux/pci.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/mm.h> #include <asm/paccess.h> #include <asm/addrspace.h> #include <asm/ifx/ifx_types.h> #include <asm/ifx/ifx_regs.h> #include <asm/ifx/common_routines.h> #include <asm/ifx/ifx_gpio.h> #include <asm/ifx/irq.h> #include <asm/ifx/ifx_rcu.h> #include "ifxmips_pci_reg.h" #include "ifxmips_pci.h" #define IFX_PCI_VER_MAJOR 1 #define IFX_PCI_VER_MID 2 #define IFX_PCI_VER_MINOR 0 extern u32 max_pfn, max_low_pfn; extern struct pci_controller ifx_pci_controller; extern int ifx_pci_bus_status; extern void __iomem *ifx_pci_cfg_space; extern u32 pci_config_addr(u8 bus_num, u16 devfn, int where); /* Used by ifxmips_interrupt.c to suppress bus exception */ int pci_bus_error_flag; extern u32 ifx_pci_config_read(u32 addr); extern void ifx_pci_config_write(u32 addr, u32 data); #ifdef CONFIG_IFX_DUAL_MINI_PCI #define IFX_PCI_REQ1 29 #define IFX_PCI_GNT1 30 #endif /* CONFIG_IFX_DUAL_MINI_PCI */ static const int pci_gpio_module_id = IFX_GPIO_MODULE_PCI; #ifdef CONFIG_IFX_PCI_DANUBE_EBU_LED_RST #include <asm/ifx/ifx_ebu_led.h> static inline void ifx_pci_dev_reset_init(void) { ifx_ebu_led_enable(); ifx_ebu_led_set_data(9, 1); } static inline void ifx_pci_dev_reset(void) { ifx_ebu_led_set_data(9, 0); mdelay(5); ifx_ebu_led_set_data(9, 1); mdelay(1); ifx_ebu_led_disable(); } #else /* GPIO in global view */ #define IFX_PCI_RST 21 static inline void ifx_pci_dev_reset_init(void) { /* * PCI_RST: P1.5 used as a general GPIO, instead of PCI_RST gpio. * In Danube/AR9, it reset internal PCI core and external PCI device * However, in VR9, it only resets external PCI device. Internal core * reset by PCI software reset registers. * GPIO21 if used as PCI_RST, software can't control reset time. * Since it uses as a general GPIO, ALT should 0, 0. */ ifx_gpio_pin_reserve(IFX_PCI_RST, pci_gpio_module_id); ifx_gpio_output_set(IFX_PCI_RST, pci_gpio_module_id); ifx_gpio_dir_out_set(IFX_PCI_RST, pci_gpio_module_id); ifx_gpio_altsel0_clear(IFX_PCI_RST, pci_gpio_module_id); ifx_gpio_altsel1_clear(IFX_PCI_RST, pci_gpio_module_id); ifx_gpio_open_drain_set(IFX_PCI_RST, pci_gpio_module_id); } static inline void ifx_pci_dev_reset(void) { /* Reset external PCI device. */ ifx_gpio_output_clear(IFX_PCI_RST, pci_gpio_module_id); smp_wmb(); mdelay(5); ifx_gpio_output_set(IFX_PCI_RST, pci_gpio_module_id); smp_wmb(); mdelay(1); } #endif /* CONFIG_IFX_PCI_DANUBE_EBU_LED_RST */ static u32 round_up_to_next_power_of_two(u32 x) { x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x++; return x; } static void ifx_pci_startup(void) { u32 reg; /* Choose reset from RCU first, then do reset */ reg = IFX_REG_R32(IFX_CGU_PCI_CR); reg |= IFX_PCI_CLK_RESET_FROM_CGU; /* XXX, Should be RCU*/ IFX_REG_W32(reg, IFX_CGU_PCI_CR); /* Secondly, RCU reset PCI domain including PCI CLK and PCI bridge */ ifx_rcu_rst(IFX_RCU_DOMAIN_PCI, IFX_RCU_MODULE_PCI); reg = IFX_REG_R32(IFX_CGU_IF_CLK); reg &= ~ IFX_PCI_CLK_MASK; /* * CGU PCI CLK is specific with platforms. Danube has four bits, * AR9 and VR9 has five bits. Their definitions are in platform header * file */ #ifdef CONFIG_IFX_PCI_EXTERNAL_CLK_SRC reg &= ~IFX_PCI_INTERNAL_CLK_SRC; /* External clk has no need to set clk in register */ #else reg |= IFX_PCI_INTERNAL_CLK_SRC; #ifdef CONFIG_IFX_PCI_INTERNAL_CLK_SRC_60 /* PCI 62.5 MHz clock */ reg |= IFX_PCI_60MHZ; #else /* PCI 33.3 MHz clock */ reg |= IFX_PCI_33MHZ; #endif /* CONFIG_IFX_PCI_INTERNAL_CLK_SRC_60 */ #endif /* CONFIG_IFX_PCI_EXTERNAL_CLK_SRC */ IFX_REG_W32(reg, IFX_CGU_IF_CLK); reg = IFX_REG_R32(IFX_CGU_PCI_CR); #ifdef CONFIG_IFX_PCI_EXTERNAL_CLK_SRC reg &= ~IFX_PCI_CLK_FROM_CGU; #else reg |= IFX_PCI_CLK_FROM_CGU; #endif /* CONFIG_IFX_PCI_EXTERNAL_CLK_SRC */ reg &= ~IFX_PCI_DELAY_MASK; #if !defined(CONFIG_IFX_PCI_CLOCK_DELAY_NANO_SECONDS) || CONFIG_IFX_PCI_CLOCK_DELAY_NANO_SECONDS < 0 || CONFIG_IFX_PCI_CLOCK_DELAY_NANO_SECONDS > 7 #error "please define CONFIG_IFX_PCI_CLOCK_DELAY_NANO_SECONDS properly" #endif reg |= (CONFIG_IFX_PCI_CLOCK_DELAY_NANO_SECONDS << IFX_PCI_DELAY_SHIFT); #if !defined(CONFIG_IFX_PCI_CLOCK_DELAY_TENTH_NANO_SECOND) || CONFIG_IFX_PCI_CLOCK_DELAY_TENTH_NANO_SECOND < 0 || CONFIG_IFX_PCI_CLOCK_DELAY_TENTH_NANO_SECOND > 5 #error "Please CONFIG_CONFIG_IFX_PCI_CLOCK_DELAY_TENTH_NANO_SECOND properly" #endif reg |= (CONFIG_IFX_PCI_CLOCK_DELAY_TENTH_NANO_SECOND << 18); IFX_REG_W32(reg, IFX_CGU_PCI_CR); ifx_pci_dev_reset_init(); #ifdef CONFIG_IFX_DUAL_MINI_PCI /* PCI_REQ1: P1.13 ALT 01 */ ifx_gpio_pin_reserve(IFX_PCI_REQ1, pci_gpio_module_id); ifx_gpio_dir_in_set(IFX_PCI_REQ1, pci_gpio_module_id); ifx_gpio_altsel0_set(IFX_PCI_REQ1, pci_gpio_module_id); ifx_gpio_altsel1_clear(IFX_PCI_REQ1, pci_gpio_module_id); /* PCI_GNT1: P1.14 ALT 01 */ ifx_gpio_pin_reserve(IFX_PCI_GNT1, pci_gpio_module_id); ifx_gpio_dir_out_set(IFX_PCI_GNT1, pci_gpio_module_id); ifx_gpio_altsel0_set(IFX_PCI_GNT1, pci_gpio_module_id); ifx_gpio_altsel1_clear(IFX_PCI_GNT1, pci_gpio_module_id); ifx_gpio_open_drain_set(IFX_PCI_GNT1, pci_gpio_module_id); #endif /* CONFIG_IFX_DUAL_MINI_PCI */ /* Enable auto-switching between PCI and EBU, normal ack */ reg = IFX_PCI_CLK_CTRL_EBU_PCI_SWITCH_EN | IFX_PCI_CLK_CTRL_FPI_NORMAL_ACK; IFX_REG_W32(reg, IFX_PCI_CLK_CTRL); /* Configuration mode, i.e. configuration is not done, PCI access has to be retried */ IFX_REG_CLR_BIT(IFX_PCI_MOD_CFG_OK, IFX_PCI_MOD); smp_wmb(); /* Enable bus master/IO/MEM access */ reg = IFX_REG_R32(IFX_PCI_CMD); reg |= IFX_PCI_CMD_IO_EN | IFX_PCI_CMD_MEM_EN | IFX_PCI_CMD_MASTER_EN; IFX_REG_W32(reg, IFX_PCI_CMD); reg = IFX_REG_R32(IFX_PCI_ARB); #ifdef CONFIG_IFX_DUAL_MINI_PCI /* Enable external 4 PCI masters */ reg &= ~(SM(3, IFX_PCI_ARB_PCI_PORT_ARB)); #else /* Enable external 1 PCI masters */ reg &= ~(SM(1, IFX_PCI_ARB_PCI_PORT_ARB)); #endif /* Enable internal arbiter */ reg |= IFX_PCI_ARB_INTERNAL_EN; /* Enable internal PCI master reqest */ reg &= ~(SM(3, IFX_PCI_ARB_PCI_MASTER_REQ0)); /* Enable EBU reqest */ reg &= ~(SM(3, IFX_PCI_ARB_PCI_MASTER_REQ1)); /* Enable all external masters request */ reg &= ~(SM(3, IFX_PCI_ARB_PCI_MASTER_REQ2)); IFX_REG_W32(reg, IFX_PCI_ARB); smp_wmb(); /* * FPI ==> PCI MEM address mapping * base: 0xb8000000 == > 0x18000000 * size: 8x4M = 32M */ reg = IFX_PCI_MEM_PHY_BASE; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP0); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP1); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP2); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP3); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP4); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP5); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP6); reg += 0x400000; IFX_REG_W32(reg, IFX_PCI_FPI_ADDR_MAP7); /* FPI ==> PCI IO address mapping * base: 0xbAE00000 == > 0xbAE00000 * size: 2M */ IFX_REG_W32(IFX_PCI_IO_PHY_BASE, IFX_PCI_FPI_ADDR_MAP11_HIGH); /* PCI ==> FPI address mapping * base: 0x0 ==> 0x0 * size: 32M */ /* At least 16M. Otherwise there will be discontiguous memory region. */ reg = IFX_PCI_BAR_PREFETCH; reg |= ((-round_up_to_next_power_of_two((max_low_pfn << PAGE_SHIFT))) & 0x0F000000); IFX_REG_W32(reg, IFX_PCI_BAR11MASK); IFX_REG_W32(0x0, IFX_PCI_ADDR_MAP11); IFX_REG_W32(0x0, IFX_PCI_BAR1); #ifdef CONFIG_IFX_PCI_HW_SWAP /* both TX and RX endian swap are enabled */ reg = IFX_PCI_SWAP_RX | IFX_PCI_SWAP_TX; IFX_REG_W32(reg, IFX_PCI_SWAP); smp_wmb(); #endif reg = IFX_REG_R32(IFX_PCI_BAR12MASK); reg |= IFX_PCI_BAR_DECODING_EN; IFX_REG_W32(reg, IFX_PCI_BAR12MASK); reg = IFX_REG_R32(IFX_PCI_BAR13MASK); reg |= IFX_PCI_BAR_DECODING_EN; IFX_REG_W32(reg, IFX_PCI_BAR13MASK); reg = IFX_REG_R32(IFX_PCI_BAR14MASK); reg |= IFX_PCI_BAR_DECODING_EN; IFX_REG_W32(reg, IFX_PCI_BAR14MASK); reg = IFX_REG_R32(IFX_PCI_BAR15MASK); reg |= IFX_PCI_BAR_DECODING_EN; IFX_REG_W32(reg, IFX_PCI_BAR15MASK); reg = IFX_REG_R32(IFX_PCI_BAR16MASK); reg |= IFX_PCI_BAR_DECODING_EN; IFX_REG_W32(reg, IFX_PCI_BAR16MASK); /* Use 4 dw burse length, XXX 8 dw will cause PCI timeout */ reg = SM(IFX_PCI_FPI_BURST_LEN4, IFX_PCI_FPI_RD_BURST_LEN) | SM(IFX_PCI_FPI_BURST_LEN4, IFX_PCI_FPI_WR_BURST_LEN); IFX_REG_W32(reg, IFX_PCI_FPI_BURST_LENGTH); /* Configuration OK. */ IFX_REG_SET_BIT(IFX_PCI_MOD_CFG_OK, IFX_PCI_MOD); smp_wmb(); mdelay(1); ifx_pci_dev_reset(); } /* Brief: disable external pci aribtor request * Details: * blocking call, i.e. only return when there is no external PCI bus activities */ void ifx_disable_external_pci(void) { IFX_REG_RMW32_FILED(IFX_PCI_ARB_PCI_MASTER_REQ2, 3, IFX_PCI_ARB); smp_wmb(); /* make sure EBUSY is low && Frame Ird is high) */ while ((IFX_REG_R32(IFX_PCI_ARB) & (IFX_PCI_ARB_PCI_NOT_READY | IFX_PCI_ARB_PCI_NO_FRM | IFX_PCI_ARB_EBU_IDLE)) != (IFX_PCI_ARB_PCI_NOT_READY | IFX_PCI_ARB_PCI_NO_FRM)); } /* Brief: enable external pci aribtor request * Details: * non-blocking call */ void ifx_enable_external_pci(void) { /* Clear means enabling all external masters request */ IFX_REG_CLR_BIT(IFX_PCI_ARB_PCI_MASTER_REQ2, IFX_PCI_ARB); smp_wmb(); } #ifdef CONFIG_DANUBE_EBU_PCI_SW_ARBITOR void ifx_enable_ebu(void) { u32 reg; /* Delay before enabling ebu ??? */ /* Disable int/ext pci request */ reg = IFX_REG_R32(IFX_PCI_ARB); reg &= ~(IFX_PCI_ARB_PCI_MASTER_REQ1); reg |= (IFX_PCI_ARB_PCI_MASTER_REQ0 | IFX_PCI_ARB_PCI_MASTER_REQ2); IFX_REG_W32(reg, IFX_PCI_ARB); /* Poll for pci bus idle */ reg = IFX_REG_R32(IFX_PCI_ARB); while ((reg & IFX_PCI_ART_PCI_IDLE) != IFX_PCI_ART_PCI_IDLE) { reg = IFX_REG_R32(IFX_PCI_ARB); }; /* EBU only, Arbitor fix*/ IFX_REG_W32(0, IFX_PCI_CLK_CTRL); /* * Unmask CFRAME_MASK changing PCI's Config Space via internal path * might need to change to external path */ /* Start configuration, one burst read is allowed */ reg = IFX_REG_R32(IFX_PCI_MOD); reg &= ~IFX_PCI_MOD_CFG_OK; reg |= IFX_PCI_MOD_TWO_IRQ_INTA_AND_INTB | SM(1, IFX_PCI_MOD_READ_BURST_THRESHOLD); IFX_REG_W32(reg, IFX_PCI_MOD); reg = IFX_REG_R32(IFX_PCI_CARDBUS_FRAME_MASK); reg &= ~IFX_PCI_CARDBUS_FRAME_MASK_EN; IFX_REG_W32(reg, IFX_PCI_CARDBUS_FRAME_MASK); IFX_REG_SET_BIT(IFX_PCI_MOD_CFG_OK, IFX_PCI_MOD); reg = IFX_REG_R32(IFX_PCI_CARDBUS_FRAME_MASK); } EXPORT_SYMBOL(ifx_enable_ebu); void ifx_disable_ebu(void) { u32 reg; /* Delay before enabling ebu ??? */ /* Restore EBU and PCI auto switch */ IFX_REG_W32(IFX_PCI_CLK_CTRL_EBU_PCI_SWITCH_EN, IFX_PCI_CLK_CTRL); /* * unmask CFRAME_MASK changing PCI's Config Space via internal path * might need to change to external path */ reg = IFX_REG_R32(IFX_PCI_MOD); /* Start configuration, one burst read is allowed */ reg &= ~IFX_PCI_MOD_CFG_OK; reg |= IFX_PCI_MOD_TWO_IRQ_INTA_AND_INTB | SM(1, IFX_PCI_MOD_READ_BURST_THRESHOLD); IFX_REG_W32(reg, IFX_PCI_MOD); reg = IFX_REG_R32(IFX_PCI_CARDBUS_FRAME_MASK); reg |= IFX_PCI_CARDBUS_FRAME_MASK_EN; IFX_REG_W32(reg, IFX_PCI_CARDBUS_FRAME_MASK); IFX_REG_SET_BIT(IFX_PCI_MOD_CFG_OK, IFX_PCI_MOD); /* Enable int/ext pci request */ reg = IFX_REG_R32(IFX_PCI_ARB); reg &= ~(IFX_PCI_ARB_PCI_MASTER_REQ0 | IFX_PCI_ARB_PCI_MASTER_REQ2); reg |= IFX_PCI_ARB_PCI_MASTER_REQ1; IFX_REG_W32(reg, IFX_PCI_ARB); } EXPORT_SYMBOL(ifx_disable_ebu); #endif /* CONFIG_DANUBE_EBU_PCI_SW_ARBITOR */ static void __devinit pcibios_fixup_resources(struct pci_dev *dev) { struct pci_controller* hose = (struct pci_controller *)dev->sysdata; int i; unsigned long offset; if (!hose) { printk(KERN_ERR "No hose for PCI dev %s!\n", pci_name(dev)); return; } for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) { struct resource *res = dev->resource + i; if (!res->flags) continue; if (res->end == 0xffffffff) { printk(KERN_INFO "PCI:%s Resource %d [%016llx-%016llx] is unassigned\n", pci_name(dev), i, (u64)res->start, (u64)res->end); res->end -= res->start; res->start = 0; res->flags |= IORESOURCE_UNSET; continue; } offset = 0; if (res->flags & IORESOURCE_MEM) { offset = hose->mem_offset; } else if (res->flags & IORESOURCE_IO) { offset = hose->io_offset; } if (offset != 0) { res->start += offset; res->end += offset; printk(KERN_INFO "Fixup res %d (%lx) of dev %s: %llx -> %llx\n", i, res->flags, pci_name(dev), (u64)res->start - offset, (u64)res->start); } } IFX_PCI_PRINT("[%s %s %d]: %s\n", __FILE__, __func__, __LINE__, pci_name(dev)); /* Enable I/O, MEM, Bus Master, Special Cycles SERR, Fast back-to-back */ pci_write_config_word(dev, PCI_COMMAND, PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER | PCI_COMMAND_SPECIAL | PCI_COMMAND_SERR | PCI_COMMAND_FAST_BACK); } DECLARE_PCI_FIXUP_EARLY(PCI_ANY_ID, PCI_ANY_ID, pcibios_fixup_resources); /** * \fn int ifx_pci_bios_map_irq(struct pci_dev *dev, u8 slot, u8 pin) * \brief Map a PCI device to the appropriate interrupt line * * \param[in] dev The Linux PCI device structure for the device to map * \param[in] slot The slot number for this device on __BUS 0__. Linux * enumerates through all the bridges and figures out the * slot on Bus 0 where this device eventually hooks to. * \param[in] pin The PCI interrupt pin read from the device, then swizzled * as it goes through each bridge. * \return Interrupt number for the device * \ingroup IFX_PCI_OS */ int ifx_pci_bios_map_irq(IFX_PCI_CONST struct pci_dev *dev, u8 slot, u8 pin) { int irq = -1; IFX_PCI_PRINT("%s dev %s slot %d pin %d \n", __func__, pci_name(dev), slot, pin); switch (pin) { case 0: break; case 1: IFX_PCI_PRINT("%s dev %s: interrupt pin 1\n", __func__, pci_name(dev)); /* * PCI_INTA--shared with EBU * falling edge level triggered:0x4, low level:0xc, rising edge:0x2 */ IFX_REG_W32(IFX_EBU_PCC_CON_IREQ_LOW_LEVEL_DETECT, IFX_EBU_PCC_CON); /* enable interrupt only */ IFX_REG_W32(IFX_EBU_PCC_IEN_PCI_EN, IFX_EBU_PCC_IEN); irq = INT_NUM_IM0_IRL22; break; case 2: case 3: break; default: printk(KERN_WARNING "WARNING: %s dev %s: invalid interrupt pin %d\n", __func__, pci_name(dev), pin); break; } return irq; } /** * \fn int ifx_pci_bios_plat_dev_init(struct pci_dev *dev) * \brief Called to perform platform specific PCI setup * * \param[in] dev The Linux PCI device structure for the device to map * \return OK * \ingroup IFX_PCI_OS */ int ifx_pci_bios_plat_dev_init(struct pci_dev *dev) { return 0; } static void inline ifx_pci_core_rst(void) { u32 reg; unsigned long flags; volatile int i; local_irq_save(flags); /* Ack the interrupt */ IFX_REG_W32(IFX_REG_R32(IFX_PCI_IRA), IFX_PCI_IRA); /* Disable external masters */ ifx_disable_external_pci(); /* PCI core reset start */ reg = IFX_REG_R32(IFX_PCI_SFT_RST); reg |= IFX_PCI_SFT_RST_REQ; IFX_REG_W32(reg, IFX_PCI_SFT_RST); for (i = 0; i < 100; i++); /* Wait for PCI core reset to be finished */ while ((IFX_REG_R32(IFX_PCI_SFT_RST) & IFX_PCI_SFT_RST_ACKING)); /* Out of reset to normal operation */ reg = IFX_REG_R32(IFX_PCI_SFT_RST); reg &= ~IFX_PCI_SFT_RST_REQ; IFX_REG_W32(reg, IFX_PCI_SFT_RST); for (i = 0; i < 50; i++); /* Enable external masters */ ifx_enable_external_pci(); local_irq_restore(flags); } static irqreturn_t #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,19) ifx_pci_core_int_isr(int irq, void *dev_id) #else ifx_pci_core_int_isr(int irq, void *dev_id, struct pt_regs *regs) #endif { /* Only care about Timeout interrupt */ if ((IFX_REG_R32(IFX_PCI_IRR) & IFX_PCI_IR_TIMEOUT) == IFX_PCI_IR_TIMEOUT) { printk(KERN_ERR "%s: PCI timeout occurred\n", __func__); ifx_pci_core_rst(); } return IRQ_HANDLED; } static void ifx_pci_ir_irq_init(void) { int ret; /* Clear the interrupt first */ IFX_REG_W32(IFX_PCI_IR_TIMEOUT, IFX_PCI_IRA); ret = request_irq(IFX_PCI_IR, ifx_pci_core_int_isr, IRQF_DISABLED, "ifx_pci_ir", NULL); if (ret) { printk("%s:request irq %d failed with %d \n", __func__, IFX_PCI_IR, ret); return; } /* Unmask Timeout interrupt */ IFX_REG_W32(IFX_PCI_IR_TIMEOUT, IFX_PCI_IRM); } /*! * \fn static int __init ifx_pci_init(void) * \brief Initialize the IFX PCI host controller, register with PCI * bus subsystem. * * \return -ENOMEM configuration/io space mapping failed. * \return -EIO pci bus not initialized * \return 0 OK * \ingroup IFX_PCI_OS */ static int __init ifx_pci_init(void) { u32 cmdreg; void __iomem *io_map_base; char ver_str[128] = {0}; pci_bus_error_flag = 1; ifx_pci_startup(); ifx_pci_cfg_space = ioremap_nocache(IFX_PCI_CFG_PHY_BASE, IFX_PCI_CFG_SIZE); if (ifx_pci_cfg_space == NULL) { printk(KERN_ERR "%s configuration space ioremap failed\n", __func__); return -ENOMEM; } IFX_PCI_PRINT("[%s %s %d]: ifx_pci_cfg_space %p\n", __FILE__, __func__, __LINE__, ifx_pci_cfg_space); /* Otherwise, warning will pop up */ io_map_base = ioremap(IFX_PCI_IO_PHY_BASE, IFX_PCI_IO_SIZE); if (io_map_base == NULL) { iounmap(ifx_pci_cfg_space); IFX_PCI_PRINT("%s io space ioremap failed\n", __func__); return -ENOMEM; } ifx_pci_controller.io_map_base = (unsigned long)io_map_base; cmdreg = ifx_pci_config_read(pci_config_addr(0, PCI_DEVFN(PCI_BRIDGE_DEVICE, 0), PCI_COMMAND)); if (!(cmdreg & PCI_COMMAND_MASTER)) { printk(KERN_INFO "PCI: Skipping PCI probe. Bus is not initialized.\n"); iounmap(ifx_pci_cfg_space); return -EIO; } ifx_pci_bus_status |= PCI_BUS_ENABLED; /* Turn on ExpMemEn */ cmdreg = ifx_pci_config_read(pci_config_addr(0, PCI_DEVFN(PCI_BRIDGE_DEVICE, 0), 0x40)); ifx_pci_config_write(pci_config_addr(0, PCI_DEVFN(PCI_BRIDGE_DEVICE, 0), 0x40), cmdreg | 0x10); cmdreg = ifx_pci_config_read(pci_config_addr(0, PCI_DEVFN(PCI_BRIDGE_DEVICE, 0), 0x40)); /* Enable normal FPI bus exception after we configured everything */ IFX_REG_CLR_BIT(IFX_PCI_CLK_CTRL_FPI_NORMAL_ACK, IFX_PCI_CLK_CTRL); IFX_PCI_PRINT("[%s %s %d]: mem_resource @%p, io_resource @%p\n", __FILE__, __func__, __LINE__, &ifx_pci_controller.mem_resource, &ifx_pci_controller.io_resource); register_pci_controller(&ifx_pci_controller); ifx_pci_ir_irq_init(); ifx_drv_ver(ver_str, "PCI host controller", IFX_PCI_VER_MAJOR, IFX_PCI_VER_MID, IFX_PCI_VER_MINOR); printk(KERN_INFO "%s", ver_str); return 0; } arch_initcall(ifx_pci_init); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Lei Chuanhua, [email protected]"); MODULE_SUPPORTED_DEVICE("Infineon builtin PCI module for Danube AR9 and VR9"); MODULE_DESCRIPTION("Infineon builtin PCI host controller driver");
kbridgers/VOLTE4GFAX
target/linux/ltqcpe/files-2.6.32/arch/mips/pci/ifxmips_pci.c
C
gpl-2.0
21,354
#ifndef AnalysisTool_h #define AnalysisTool_h 1 #include "StackingTool.hh" #include <sstream> // stringstream using namespace std; class AnalysisTool { public: AnalysisTool(); virtual ~AnalysisTool(); virtual void PrintTool(); virtual bool getInterest(); virtual bool getInterest(int particle, int sturface); virtual bool getInterest(int particle, int sturface, int creationProcess, int flagPhotoElectron); virtual bool getInterest(int particle, int sturface, int volume); virtual bool getInterest(int particle, int surface, double energy); virtual string processData(); virtual string processData(int id, float energy); virtual string processData(int creation_process); private: }; #endif
OWoolland/MemoryMappedFileReader
Source/include/AnalysisTool.hh
C++
gpl-2.0
809
body{ font-family: 'open_sansregular'; } .header { background: url(../images/bgo.jpg); min-height: 600px; } .header-right { background: url(../images/handpico.png) no-repeat 100% 101%; height: 600px; } .pricing-grid ul li a:hover,.footer ul li a:hover, .copy-right a:hover { color:#DB7734; } /*----*/ .apple{ background: url(../images/osprits.png) no-repeat -1px 0px; } .and{ background: url(../images/osprits.png) no-repeat -69px 0px; } .win{ background: url(../images/osprits.png) no-repeat -136px 0px; } /*----*/ .monitor{ background: url(../images/osprits.png) no-repeat 3px -54px; } .target{ background: url(../images/osprits.png) no-repeat -49px -54px; } .photo{ background: url(../images/osprits.png) no-repeat -98px -54px; } .colors{ background: url(../images/osprits.png) no-repeat -151px -54px; } .man{ background: url(../images/osprits.png) no-repeat -203px -54px; } .spare{ background: url(../images/osprits.png) no-repeat -255px -54px; } /*----*/ #selector a { background: url(../images/osprits.png) no-repeat -27px -172px; } #selector a.current { background: url(../images/osprits.png) no-repeat -7px -172px; } /*----*/ .twitter{ background: url(../images/osprits.png) no-repeat 5px -131px #D6D6D6; } .twitter:hover{ background: url(../images/osprits.png) no-repeat 5px -131px #DB7734; } .facebook{ background: url(../images/osprits.png) no-repeat -39px -130px #D6D6D6; } .facebook:hover{ background: url(../images/osprits.png) no-repeat -39px -130px #DB7734; } .pin{ background: url(../images/osprits.png) no-repeat -83px -130px #D6D6D6; } .pin:hover{ background: url(../images/osprits.png) no-repeat -83px -130px #DB7734; } .googlepluse{ background: url(../images/social-icons.png) no-repeat -120px 3px #D6D6D6; } .googlepluse:hover{ background: url(../images/social-icons.png) no-repeat -120px 3px #DB7734; } .in{ background: url(../images/osprits.png) no-repeat -171px -130px #D6D6D6; } .in:hover{ background: url(../images/osprits.png) no-repeat -171px -130px #DB7734; } .youtube{ background: url(../images/osprits.png) no-repeat -214px -130px #D6D6D6; } .youtube:hover{ background: url(../images/osprits.png) no-repeat -214px -130px #DB7734; } /*----*/ .shipping{ background: url(../images/osprits.png) no-repeat -121px -198px; } .payment{ background: url(../images/osprits.png) no-repeat -162px -198px; } .payment-date-section{ background: url(../images/calender.png) no-repeat #fff 50%; } /*----*/ input[type=checkbox].css-checkbox1 + label.css-label1 { background: url(../images/osprits.png) no-repeat -204px -203px; } input[type=checkbox].css-checkbox1:checked + label.css-label1 { background: url(../images/osprits.png) no-repeat -224px -203px; } input[type=checkbox].css-checkbox2 + label.css-label2 { background: url(../images/osprits.png) no-repeat -224px -203px; } input[type=checkbox].css-checkbox2:checked + label.css-label2 { background: url(../images/osprits.png) no-repeat -204px -203px; } /*----*/ .mfp-close { background: url(../images/osprits.png) no-repeat -7px -231px; } .mfp-close:hover, .mfp-close:focus { background: url(../images/osprits.png) no-repeat -44px -231px; } /*----*/ .pricing-grid h3,.cart{ background:#DB7734; } .cart a { background: #BA662D; } .payment-online-form-left input[type="text"]:active, .payment-online-form-left input[type="text"]:hover { color:#DB7734; } .payment-sendbtns input[type="reset"],.payment-sendbtns input[type="submit"]:hover{ background: #DB7734; } /*----start-responsive-design----*/ @media only screen and (max-width: 1024px) and (min-width: 768px){ .header-right { background: url(../images/handpico.png) no-repeat 100% 101%; height: 600px; background-size: 100%; } } @media only screen and (max-width: 768px) and (min-width: 640px){ .header { background: url(../images/bgo.jpg); min-height: 523px; } .header-right { display:none; } .header-left label{ width: 149px; min-height: 303px; display: inline-block; padding-top: 0; margin: 0px; background: url(../images/iphoneo.png) no-repeat; } } @media only screen and (max-width: 640px) and (min-width: 480px){ .header { background: url(../images/bgo.jpg); min-height: 523px; } .header-right { display:none; } .header-left label{ width: 149px; min-height: 303px; display: inline-block; padding-top: 0; margin: 0px; background: url(../images/iphoneo.png) no-repeat; } } @media only screen and (max-width: 480px) and (min-width:320px){ .header { background: url(../images/bgo.jpg); min-height: 499px; } .header-right { display:none; } .header-left label{ width: 149px; min-height: 303px; display: inline-block; padding-top: 0; margin: 0px; background: url(../images/iphoneo.png) no-repeat; } } @media only screen and (max-width: 320px) and (min-width:240px){ .header { background: url(../images/bgo.jpg); min-height: 355px; } .header-right { display:none; } .header-left label{ width: 101px; min-height: 191px; display: inline-block; padding-top: 0; margin: 0px; background: url(../images/iphoneos.png) no-repeat; } }
Victormafire/WheresApp
server/src/main/webapp/web/css/orange.css
CSS
gpl-2.0
5,101
<?php /** * The header template file. * @package PaperCuts * @since PaperCuts 1.0.0 */ ?><!DOCTYPE html> <!--[if IE 7]> <html class="ie ie7" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 8]> <html class="ie ie8" <?php language_attributes(); ?>> <![endif]--> <!--[if !(IE 7) | !(IE 8) ]><!--> <html <?php language_attributes(); ?>> <!--<![endif]--> <head> <?php global $papercuts_options_db; ?> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <meta name="viewport" content="width=device-width" /> <title><?php wp_title( '|', true, 'right' ); ?></title> <?php if ($papercuts_options_db['papercuts_favicon_url'] != ''){ ?> <link rel="shortcut icon" href="<?php echo esc_url($papercuts_options_db['papercuts_favicon_url']); ?>" /> <?php } ?> <?php wp_head(); ?> </head> <body <?php body_class(); ?> id="wrapper"> <?php if ( !is_page_template('template-landing-page.php') ) { ?> <?php if ( has_nav_menu( 'top-navigation' ) || $papercuts_options_db['papercuts_header_facebook_link'] != '' || $papercuts_options_db['papercuts_header_twitter_link'] != '' || $papercuts_options_db['papercuts_header_google_link'] != '' || $papercuts_options_db['papercuts_header_rss_link'] != '' ) { ?> <div id="top-navigation-wrapper"> <div class="top-navigation"> <?php if ( has_nav_menu( 'top-navigation' ) ) { wp_nav_menu( array( 'menu_id'=>'top-nav', 'theme_location'=>'top-navigation' ) ); } ?> <div class="header-icons"> <?php if ($papercuts_options_db['papercuts_header_facebook_link'] != ''){ ?> <a class="social-icon facebook-icon" href="<?php echo esc_url($papercuts_options_db['papercuts_header_facebook_link']); ?>"><img src="<?php echo esc_url(get_template_directory_uri()); ?>/images/icon-facebook.png" alt="Facebook" /></a> <?php } ?> <?php if ($papercuts_options_db['papercuts_header_twitter_link'] != ''){ ?> <a class="social-icon twitter-icon" href="<?php echo esc_url($papercuts_options_db['papercuts_header_twitter_link']); ?>"><img src="<?php echo esc_url(get_template_directory_uri()); ?>/images/icon-twitter.png" alt="Twitter" /></a> <?php } ?> <?php if ($papercuts_options_db['papercuts_header_google_link'] != ''){ ?> <a class="social-icon google-icon" href="<?php echo esc_url($papercuts_options_db['papercuts_header_google_link']); ?>"><img src="<?php echo esc_url(get_template_directory_uri()); ?>/images/icon-google.png" alt="Google +" /></a> <?php } ?> <?php if ($papercuts_options_db['papercuts_header_rss_link'] != ''){ ?> <a class="social-icon rss-icon" href="<?php echo esc_url($papercuts_options_db['papercuts_header_rss_link']); ?>"><img src="<?php echo esc_url(get_template_directory_uri()); ?>/images/icon-rss.png" alt="RSS" /></a> <?php } ?> </div> </div> </div> <?php }} ?> <header id="wrapper-header"> <div id="header"> <div class="header-content-wrapper"> <div class="header-content"> <?php if ( $papercuts_options_db['papercuts_logo_url'] == '' ) { ?> <p class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>"><?php bloginfo( 'name' ); ?></a></p> <?php if ( $papercuts_options_db['papercuts_display_site_description'] != 'Hide' ) { ?> <p class="site-description"><?php bloginfo( 'description' ); ?></p> <?php } ?> <?php } else { ?> <a href="<?php echo esc_url( home_url( '/' ) ); ?>"><img class="header-logo" src="<?php echo esc_url($papercuts_options_db['papercuts_logo_url']); ?>" alt="<?php bloginfo( 'name' ); ?>" /></a> <?php } ?> <?php if ( $papercuts_options_db['papercuts_display_search_form'] != 'Hide' && !is_page_template('template-landing-page.php') ) { ?> <?php get_search_form(); ?> <?php } ?> </div> </div> <?php if ( has_nav_menu( 'main-navigation' ) && !is_page_template('template-landing-page.php') ) { ?> <div class="menu-box-wrapper"> <div class="menu-box"> <?php wp_nav_menu( array( 'menu_id'=>'nav', 'theme_location'=>'main-navigation' ) ); ?> </div> </div> <?php } ?> </div> <!-- end of header --> </header> <!-- end of wrapper-header --> <div id="container"> <div id="main-content"> <div id="content"> <?php if ( is_home() || is_front_page() ) { ?> <?php if ( get_header_image() != '' && $papercuts_options_db['papercuts_display_header_image'] != 'Everywhere except Homepage' ) { ?> <div class="header-image-wrapper"><div class="header-image"><img src="<?php header_image(); ?>" alt="<?php bloginfo( 'name' ); ?>" /></div></div> <?php } ?> <?php } else { ?> <?php if ( get_header_image() != '' && $papercuts_options_db['papercuts_display_header_image'] != 'Only on Homepage' ) { ?> <div class="header-image-wrapper"><div class="header-image"><img src="<?php header_image(); ?>" alt="<?php bloginfo( 'name' ); ?>" /></div></div> <?php } ?> <?php } ?>
udhayarajselvan/matrix
wp-content/themes/papercuts/header.php
PHP
gpl-2.0
4,753
<?php session_start(); $exercise = $_SESSION['exercise']; if($_POST){ unset($exercise[$_POST['id']]); $_SESSION['exercise'] = $exercise; header('Location: ./'); } $workout = $exercise[$_REQUEST['id']]; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>Exercise Log: Delete</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" type="text/css" /> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <link rel="stylesheet" type="text/css" href="../style/stylesheet.css" /> </head> <body> <div class="container"> <div class="page-header"> <h1>Exercise <small>Viewing <?=$workout['Name']?> workout</small></h1> </div> <ul> <li>Workout Name: <?=$workout['Name']?></li> <li>Workout Amount: <?=$workout['Amount']?></li> <li>Workout Time: <?=$workout['Time']?></li> <li>Workout Calories Burned: <?=$workout['Calories']?></li> </ul> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script> <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <script type="text/javascript"> (function($){ $(function(){ }); })(jQuery); </script> </body> </html>
kevinflaherty/Web-Programming
fitness/exercise/view.php
PHP
gpl-2.0
2,009
<?php /** * Validate form * * @param array $form definition * @param array $data filtered * @return boolean | array ('fildname'=>'error message') */ function validateForm($form, $datafiltered) { $validatedata = null; foreach ($form as $key => $form_field) { // if ($form[$key]['validation'] != null) { // hay que validar if (array_key_exists( 'validation', $form[$key] )) { // hay que validar $validation = $form_field['validation']; $valor = $datafiltered[$key]; foreach ($validation as $val_type => $val_data) { switch ($val_type) { case 'required': if ($valor == null) { if (array_key_exists('error_message', $validation)) { $validatedata[$key] = $validation['error_message']; } else { $validatedata[$key] = $key." no puede ser nulo"; } } break; case 'minsize': // echo '<pre>'; // print_r(strlen($valor)); // echo '</pre>'; if ($valor != null && (strlen($valor) < $validation['minsize'])) { if (array_key_exists('error_message', $validation)) { $validatedata[$key] = $validation['error_message']; } else { $validatedata[$key] = $key." debe de tener más de ".$validation['minsize']; } } break; case 'maxsize': if ($valor != null && (strlen($valor) > $validation['maxsize'])) { if (array_key_exists('error_message', $validation)) { $validatedata[$key] = $validation['error_message']; } else { $validatedata[$key] = $key." debe de tener más de ".$validation['maxsize']; } } break; } } } } if ($validatedata == null) { $validatedata = true; } return $validatedata; }
bermartinv/php2015
modules/core/src/core/validateForm.php
PHP
gpl-2.0
2,403
# woyuchengying.github.io * [语言无关类](#语言无关类) * [操作系统](#操作系统) * [智能系统](#智能系统) * [分布式系统](#分布式系统) * [编译原理](#编译原理) * [函数式概念](#函数式概念) * [计算机图形学](#计算机图形学) * [WEB服务器](#web服务器) * [版本控制](#版本控制) * [编辑器](#编辑器) * [NoSQL](#nosql) * [PostgreSQL](#postgresql) * [MySQL](#mysql) * [管理和监控](#管理和监控) * [项目相关](#项目相关) * [设计模式](#设计模式) * [Web](#web) * [大数据](#大数据) * [编程艺术](#编程艺术) * [其它](#其它) ## 智能系统 ## 操作系统
woyuchengying/woyuchengying.github.io
README.md
Markdown
gpl-2.0
703
<?php module_head("The KDevelop $k_series_version Team");?> <h4>Main Developers: <a href="mailto:team at kdevelop.org">team at kdevelop.org</a></h4> <a href="mailto:bernd at physik.hu-berlin.de">Bernd Gehrmann</a> Initial idea and architecture, much initial source code <br> <a href="mailto:caleb at aei-tech.com">Caleb Tenis</a> IDEAl mode, KTabBar, bugfixes <br> <a href="mailto:roberto at kdevelop.org">Roberto Raggi</a> QEditor component, code completion, Abbrev component, C++ support, Java support, persistant class store <br> <a href="mailto:jbb at kdevelop.org">John Birch</a> Debugger frontend <br> <a href="mailto:falk at kdevelop.org">Falk Brettschneider</a> MDI <br> <a href="mailto:jens.dagerbo at swipnet.se">Jens Dagerbo</a> Global search and replace, persistent bookmarks, FileList plugin, source history navigation, Optional automatic reload on external file modifications, CTAGS plugin <br> <a href="mailto:mario.scalas at libero.it">Mario Scalas</a> Part explorer, CVS integration, Cervisia integration <br> <a href="mailto:harry at kdevelop.org">Harald Fernengel</a> Valgrind, diff, preforce support <br> <a href="mailto:linux at jrockey.com">Julian Rockey</a> New File wizard <br> <a href="mailto:jsgaarde at tdcspace.dk">Jakob Simon-Gaarde</a> QMake based project manager <br> <a href="mailto:victor_roeder at gmx.de">Victor R&ouml;der</a> Automake project manager <br> <a href="mailto:geiseri at yahoo.com">Ian Reinhart Geiser</a> Application templates <br> <a href="mailto:smeier at kdevelop.org">Sandy Meier</a> PHP support, context menu stuff <br> <a href="mailto:cloudtemple at mksat.net">Alexander Dymo</a> Co-maintainer, Pascal support, C++ support, New File and Documentation parts, QMake manager, KDevAssistant application, toolbar classbrowser, Qt Designer integration <br> <a href="mailto:amilcar at ida ! ing ! tu-bs ! de">Amilcar do Carmo Lucas</a> Co-maintainer, KDevelop API documentation, website update, directory restructuring, bug-keeper, doxygen part <br> <a href="mailto:rgruber () users ! sourceforge ! net">Robert Gruber</a> Code Snippet plugin <br> <a href="mailto:jonas.jacobi at web.de">Jonas B. Jacobi</a> Doxygen preview and autocomment, classview <br> <a href="mailto:scunz at ng-projekt.de">Sascha Cunz</a> KDevLicense interface, application templates <br> <a href="mailto:child at t17.ds.pwr.wroc.pl">Marek Janukowicz</a> Ruby support <br> <a href="mailto:mathieu.chouinard at kdemail.net">Mathieu Chouinard</a> PDF,Djvu and PDB Documentation plugin, palmOS development support <br> <a href="mailto:">Andrew M. Patterson</a> GTK, GNOME and Bonobo application templates <br> <a href="mailto:Richard_Dale () tipitina ! demon ! co ! uk">Richard Dale</a> Ruby support <br> <a href="mailto:marchand () kde ! org">Mickael Marchand</a> SVN support <br> <br> <h4>Program and Documentation Translations:</h4> Please look at the <a href="http://l10n.kde.org/teams-list.php">Internationalization site</a> or visit the <a href="index.html?filename=<?php echo $k_base_version; ?>/kdevelop_po_status.html">GUI translation status page</a> or visit the <a href="http://l10n.kde.org/stats/doc/stable/package/kdevelop/">User Manual translation status page</a>.<br> <br> <br> <h4>Additions, patches and bugfixes:</h4> Oliver Kellogg <a href="mailto:okellogg at users.sourceforge.net">&lt;okellogg at users.sourceforge.net&gt;</a><br> Ajay Guleria <a href="mailto:ajay_guleria at yahoo.com">&lt;ajay_guleria at yahoo.com&gt;</a><br> Luc Willems <a href="mailto:Willems.luc at pandora.be">&lt;Willems.luc at pandora.be&gt;</a><br> Marcel Turino <a href="mailto:M.Turino at gmx.de">&lt;M.Turino at gmx.de&gt;</a><br> Tobias Gl&auml;&szlig;er <a href="mailto:tobi.web at gmx.de">&lt;tobi.web at gmx.de&gt;</a><br> Andreas Koepfle <a href="mailto:koepfle at ti.uni-mannheim.de">&lt;koepfle at ti.uni-mannheim.de&gt;</a><br> Dominik Haumann <a href="mailto:dhdev at gmx.de">&lt;dhdev at gmx.de&gt;</a><br> Alexander Neundorf <a href="mailto:neundorf () kde ! org">&lt;neundorf () kde ! org&gt;</a><br> Giovanni Venturi <a href="mailto:jumpyj () tiscali ! it">&lt;jumpyj () tiscali ! it&gt;</a><br> Stephan Binner <a href="mailto:binner () kde ! org">&lt;binner () kde ! org&gt;</a><br> Andras Mantia &lt;amantia () kde ! org&gt;<br> Stephan Kulow &lt;coolo () kde ! org&gt;<br> Adriaan de Groot &lt;groot () kde ! org&gt;<br> Matt Rogers &lt;mattr () kde ! org&gt;<br> Helge Deller &lt;deller () kde ! org&gt;<br> Helio Chissini de Castro &lt;helio () conectiva ! com ! br&gt;<br> Thomas Downing<br> Oliver Maurhart<br> Stefan Lang<br> Vladimir Reshetnikov<br> Zepplock<br> Tom Albers &lt;tomalbers () kde ! nl&gt;<br> Benjamin Meyer &lt;benjamin () csh ! rit ! edu&gt;<br> Alexander Borghgraef<br> Daniel Franke<br> leo zhu<br> Thomas Fischer<br> Michael Nottebrock<br> Carsten Lohrke<br> Hendrik Kueck<br> Yann Hodique &lt;Yann.Hodique () lifl ! fr&gt;<br> Lukas Tinkl &lt;lukas kde.org&gt;<br> Christian Loose<br> Thomas Capricelli &lt;orzel () kde ! org&gt;<br> Scott Wheeler &lt;wheeler () kde ! org&gt;<br> Zack Rusin &lt;zack () kde ! org&gt;<br> Aaron Seigo &lt;aseigo () kde ! org&gt;<br> Tobias Erbsland &lt;te () profzone ! ch&gt;<br> Laurent Montel &lt;montel () kde ! org&gt;<br> Giovanni Venturi &lt;jumpyj () tiscali ! it&gt;<br> Jonathan Riddell &lt;jri () jriddell ! org&gt;<br> Martijn Klingens &lt;klingens () kde ! org&gt;<br> Volker Krause &lt;volker.krause () rwth-aachen ! de&gt;<br> George Staikos &lt;staikos () kde ! org&gt;<br> <br> <h4>Startlogo</h4> Ram&oacute;n Lamana Villar <a href="mailto:ramon at alumnos.upm.es">&lt;ramon at alumnos.upm.es&gt;</a><br> <br> <br> <h4>Binary packages:</h4> The RPM's are done by the distributors or are contributed by users to the http://download.kde.org site. <?php module_tail(); module_head("KDevelop Homepage"); ?> <h4>Content</h4> Alexander Dymo <a href="mailto:cloudtemple at mksat.net">&lt;cloudtemple at mksat.net&gt;</a><br> Amilcar do Carmo Lucas <a href="mailto:amilcar at ida ! ing ! tu-bs ! de">&lt;amilcar at ida ! ing ! tu-bs ! de&gt;</a><br> <br> <br> <h4>Programming & Design</h4> Sandy Meier <a href="mailto:smeier at kdevelop.de">&lt;smeier at kdevelop.de&gt;</a><br> Thomas Fromm <a href="mailto:tfromm at cs.uni-potsdam.de">&lt;tfromm at cs.uni-potsdam.de&gt;</a><br> Stefan Bartel <a href="mailto:bartel at rz.uni-potsdam.de">&lt;bartel at rz.uni-potsdam.de&gt;</a><br> Amilcar do Carmo Lucas <a href="mailto:amilcar at ida ! ing ! tu-bs ! de">&lt;amilcar at ida ! ing ! tu-bs ! de&gt;</a><br> <br> <br> <h4>Translations</h4> <?php get_website_translation_authors($k_base_version); ?> <br> <br> <h4>Additional Software</h4> PHP Forum <a href="http://phorum.org/">http://phorum.org/</a><br> IRC applet <a href="http://www.pjirc.com/">http://www.pjirc.com/</a><br> Doxygen <a href="http://www.doxygen.org/">http://www.doxygen.org/</a><br> MRTG <a href="http://people.ee.ethz.ch/~oetiker/webtools/mrtg/">http://people.ee.ethz.ch/~oetiker/webtools/mrtg/</a><br> GraphViz Site Map Generator <a href="http://urlgreyhot.com/contact/">http://urlgreyhot.com/contact/</a><br> CvsChangeLogBuilder <a href="http://cvschangelogb.sourceforge.net/">http://cvschangelogb.sourceforge.net/</a><br> jaxml, scanerrlog <a href="http://www.librelogiciel.com/software/">http://www.librelogiciel.com/software/</a><br> phpRemoteView <a href="http://php.spb.ru/remview/">http://php.spb.ru/remview/</a><br> Webalizer <a href="http://www.mrunix.net/webalizer/">http://www.mrunix.net/webalizer/</a><br> <br> <?php module_tail();?> <?php module_head("Sponsors"); ?> Sascha Beyer <a href="mailto:Sascha.Beyer at gecits-eu.com">&lt;Sascha.Beyer at gecits-eu.com&gt;</a> (kdevelop.org domain name)<br> Fachschaftsrat Informatik, Universit&auml; Potsdam (web server) <a href="http://fara.cs.uni-potsdam.de">fara.cs.uni-potsdam.de</a> <?php module_tail();?>
KDE/kdev-www
3.2/authors.html
HTML
gpl-2.0
7,853
#!/usr/bin/env python3 import sys import os sys.path.append(os.path.realpath(".")) import unittest import cleanstream import tagger import pretransfer import transfer import interchunk import postchunk import adaptdocx if __name__ == "__main__": os.chdir(os.path.dirname(__file__)) failures = 0 for module in [tagger, pretransfer, transfer, interchunk, postchunk, adaptdocx, cleanstream]: suite = unittest.TestLoader().loadTestsFromModule(module) res = unittest.TextTestRunner(verbosity=2).run(suite) if(not(res.wasSuccessful())): failures += 1 sys.exit(min(failures, 255))
unhammer/apertium
tests/run_tests.py
Python
gpl-2.0
744
/* * Copyright (c) 2010, Google, Inc. * * This file is part of Libav. * * Libav is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * Libav is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Libav; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * VP8 decoder support via libvpx */ #define VPX_CODEC_DISABLE_COMPAT 1 #include <vpx/vpx_decoder.h> #include <vpx/vp8dx.h> #include "libavutil/common.h" #include "libavutil/imgutils.h" #include "avcodec.h" #include "internal.h" typedef struct VP8DecoderContext { struct vpx_codec_ctx decoder; } VP8Context; static av_cold int vpx_init(AVCodecContext *avctx, const struct vpx_codec_iface *iface) { VP8Context *ctx = avctx->priv_data; struct vpx_codec_dec_cfg deccfg = { /* token partitions+1 would be a decent choice */ .threads = FFMIN(avctx->thread_count, 16) }; av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str()); av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config()); if (vpx_codec_dec_init(&ctx->decoder, iface, &deccfg, 0) != VPX_CODEC_OK) { const char *error = vpx_codec_error(&ctx->decoder); av_log(avctx, AV_LOG_ERROR, "Failed to initialize decoder: %s\n", error); return AVERROR(EINVAL); } avctx->pix_fmt = AV_PIX_FMT_YUV420P; return 0; } static int vp8_decode(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { VP8Context *ctx = avctx->priv_data; AVFrame *picture = data; const void *iter = NULL; struct vpx_image *img; int ret; if (vpx_codec_decode(&ctx->decoder, avpkt->data, avpkt->size, NULL, 0) != VPX_CODEC_OK) { const char *error = vpx_codec_error(&ctx->decoder); const char *detail = vpx_codec_error_detail(&ctx->decoder); av_log(avctx, AV_LOG_ERROR, "Failed to decode frame: %s\n", error); if (detail) av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail); return AVERROR_INVALIDDATA; } if ((img = vpx_codec_get_frame(&ctx->decoder, &iter))) { if (img->fmt != VPX_IMG_FMT_I420) { av_log(avctx, AV_LOG_ERROR, "Unsupported output colorspace (%d)\n", img->fmt); return AVERROR_INVALIDDATA; } if ((int) img->d_w != avctx->width || (int) img->d_h != avctx->height) { av_log(avctx, AV_LOG_INFO, "dimension change! %dx%d -> %dx%d\n", avctx->width, avctx->height, img->d_w, img->d_h); if (av_image_check_size(img->d_w, img->d_h, 0, avctx)) return AVERROR_INVALIDDATA; avcodec_set_dimensions(avctx, img->d_w, img->d_h); } if ((ret = ff_get_buffer(avctx, picture, 0)) < 0) return ret; av_image_copy(picture->data, picture->linesize, img->planes, img->stride, avctx->pix_fmt, img->d_w, img->d_h); *got_frame = 1; } return avpkt->size; } static av_cold int vp8_free(AVCodecContext *avctx) { VP8Context *ctx = avctx->priv_data; vpx_codec_destroy(&ctx->decoder); return 0; } #if CONFIG_LIBVPX_VP8_DECODER static av_cold int vp8_init(AVCodecContext *avctx) { return vpx_init(avctx, &vpx_codec_vp8_dx_algo); } AVCodec ff_libvpx_vp8_decoder = { .name = "libvpx", .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_VP8, .priv_data_size = sizeof(VP8Context), .init = vp8_init, .close = vp8_free, .decode = vp8_decode, .capabilities = CODEC_CAP_AUTO_THREADS | CODEC_CAP_DR1, .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"), }; #endif /* CONFIG_LIBVPX_VP8_DECODER */ #if CONFIG_LIBVPX_VP9_DECODER static av_cold int vp9_init(AVCodecContext *avctx) { return vpx_init(avctx, &vpx_codec_vp9_dx_algo); } AVCodec ff_libvpx_vp9_decoder = { .name = "libvpx-vp9", .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_VP9, .priv_data_size = sizeof(VP8Context), .init = vp9_init, .close = vp8_free, .decode = vp8_decode, .capabilities = CODEC_CAP_AUTO_THREADS | CODEC_CAP_EXPERIMENTAL, .long_name = NULL_IF_CONFIG_SMALL("libvpx VP9"), }; #endif /* CONFIG_LIBVPX_VP9_DECODER */
DDTChen/CookieVLC
vlc/contrib/android/ffmpeg/libavcodec/libvpxdec.c
C
gpl-2.0
4,941
// // ReadEntityBodyMode.cs // // Author: Martin Thwaites ([email protected]) // // Copyright (C) 2014 Martin Thwaites // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. namespace System.Web { public enum ReadEntityBodyMode { None, Classic, Bufferless, Buffered, } }
hardvain/mono-compiler
class/System.Web/System.Web/ReadEntityBodyMode.cs
C#
gpl-2.0
1,312
#!/usr/bin/python3 # @begin:license # # Copyright (c) 2015-2019, Benjamin Niemann <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # @end:license import logging import random from . import ipc_test_pb2 from . import ipc_test logger = logging.getLogger(__name__) class IPCPerfTest(ipc_test.IPCPerfTestBase): async def test_small_messages(self): request = ipc_test_pb2.TestRequest() request.t.add(numerator=random.randint(0, 4), denominator=random.randint(1, 2)) await self.run_test(request, 5000) async def test_large_messages(self): request = ipc_test_pb2.TestRequest() for _ in range(10000): request.t.add(numerator=random.randint(0, 4), denominator=random.randint(1, 2)) await self.run_test(request, 100)
odahoda/noisicaa
noisicaa/core/ipc_perftest.py
Python
gpl-2.0
1,459
VERSION = 1.0.1 all: smistrip -d MIB src-mib/nagios*.mib test: smilint -p ./MIB/NAGIOS-ROOT-MIB ./MIB/NAGIOS-NOTIFY-MIB tarball: tar cvzf nagiosmib-${VERSION}.tar.gz README CHANGES LEGAL LICENSE ./MIB/*MIB md5sum nagiosmib-${VERSION}.tar.gz > nagiosmib-${VERSION}.tar.gz.md5sum
monitoring-plugins/nagios-mib
Makefile
Makefile
gpl-2.0
286
#ifndef INC_FMTLexer_hpp_ #define INC_FMTLexer_hpp_ #include <antlr/config.hpp> /* $ANTLR 2.7.7 (20130428): "format.g" -> "FMTLexer.hpp"$ */ #include <antlr/CommonToken.hpp> #include <antlr/InputBuffer.hpp> #include <antlr/BitSet.hpp> #include "FMTTokenTypes.hpp" #include <antlr/CharScanner.hpp> #include <fstream> #include <sstream> #include "fmtnode.hpp" #include "CFMTLexer.hpp" #include <antlr/TokenStreamSelector.hpp> //using namespace antlr; class CUSTOM_API FMTLexer : public antlr::CharScanner, public FMTTokenTypes { private: antlr::TokenStreamSelector* selector; CFMTLexer* cLexer; public: void SetSelector( antlr::TokenStreamSelector& s) { selector = &s; } void SetCLexer( CFMTLexer& l) { cLexer = &l; } private: void initLiterals(); public: bool getCaseSensitiveLiterals() const { return false; } public: FMTLexer(std::istream& in); FMTLexer(antlr::InputBuffer& ib); FMTLexer(const antlr::LexerSharedInputState& state); antlr::RefToken nextToken(); public: void mSTRING(bool _createToken); public: void mCSTRING(bool _createToken); public: void mLBRACE(bool _createToken); public: void mRBRACE(bool _createToken); public: void mSLASH(bool _createToken); public: void mCOMMA(bool _createToken); public: void mA(bool _createToken); public: void mTERM(bool _createToken); public: void mNONL(bool _createToken); public: void mF(bool _createToken); public: void mD(bool _createToken); public: void mE(bool _createToken); public: void mG(bool _createToken); public: void mI(bool _createToken); public: void mO(bool _createToken); public: void mB(bool _createToken); public: void mZ(bool _createToken); public: void mZZ(bool _createToken); public: void mQ(bool _createToken); public: void mH(bool _createToken); public: void mT(bool _createToken); public: void mL(bool _createToken); public: void mR(bool _createToken); public: void mX(bool _createToken); public: void mC(bool _createToken); public: void mCMOA(bool _createToken); public: void mCMoA(bool _createToken); public: void mCmoA(bool _createToken); public: void mCMOI(bool _createToken); public: void mCDI(bool _createToken); public: void mCMI(bool _createToken); public: void mCYI(bool _createToken); public: void mCSI(bool _createToken); public: void mCSF(bool _createToken); public: void mCHI(bool _createToken); public: void mChI(bool _createToken); public: void mCDWA(bool _createToken); public: void mCDwA(bool _createToken); public: void mCdwA(bool _createToken); public: void mCAPA(bool _createToken); public: void mCApA(bool _createToken); public: void mCapA(bool _createToken); public: void mPERCENT(bool _createToken); public: void mDOT(bool _createToken); public: void mPM(bool _createToken); public: void mMP(bool _createToken); protected: void mW(bool _createToken); public: void mWHITESPACE(bool _createToken); protected: void mDIGITS(bool _createToken); protected: void mCHAR(bool _createToken); public: void mNUMBER(bool _createToken); private: static const unsigned long _tokenSet_0_data_[]; static const antlr::BitSet _tokenSet_0; static const unsigned long _tokenSet_1_data_[]; static const antlr::BitSet _tokenSet_1; static const unsigned long _tokenSet_2_data_[]; static const antlr::BitSet _tokenSet_2; }; #endif /*INC_FMTLexer_hpp_*/
olebole/gnudatalanguage
src/FMTLexer.hpp
C++
gpl-2.0
3,373
#include "db/db.h" Database::Database() { this->records_tree_ = nullptr; } void Database::Read(DatabaseReader &reader) { this->records_tree_ = reader.ReadIndex(); } Record *Database::GetRecordsTree() const { return this->records_tree_; } void Database::SetRecordsTree(Record *records_tree) { this->records_tree_ = records_tree; }
bramberg/cclinf2
src/db/db.cc
C++
gpl-2.0
339
import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main()
tjamet/dynker
dynker/builder.py
Python
gpl-2.0
6,135
<?php global $lang; global $languages; $l_top_lang_visited_pages="Najczęściej {$languages[$lang]} odwiedzane strony"; $l_page="Strona"; $l_last_update="ostatnio aktualizowane"; $l_last_visited="ostatnio odwiedzane"; $l_average_daily_visits="średnio dziennych wizyt"; $l_global_website_statistics="Całkowite statystyki serwisu"; $l_served_pages="Ten serwer serwuje średnio %.02f stron dziennie dystrybuowanych w wielu językach jak ten (wyniki w tabeli wykluczając strony main.html)&nbsp;:"; $l_language="język"; $l_percentage="procentowo"; $l_stat_graphics="Te wykresy pokazują średnią odwiedzających www.kdevelop.org"; $l_day_graphic= "Wykres dzienny"; $l_week_graphic= "Wykres tygodniowy"; $l_month_graphic="Wykres miesięczny"; $l_year_grahic= "Wykres roczny"; return include("inc/stats.php"); ?>
KDE/kdev-www
lang/pl/stats.html
HTML
gpl-2.0
819
<?php /** * * You may not change or alter any portion of this comment or credits * of supporting developers from this source code or any supporting source code * which is considered copyrighted (c) material of the original comment or credit authors. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * @copyright XOOPS Project (https://xoops.org) * @license GNU GPL 2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html) * @package * @since 2.5.9 * @author Michael Beck (aka Mamba) */ require_once __DIR__ . '/../../../mainfile.php'; $op = \Xmf\Request::getCmd('op', ''); switch ($op) { case 'load': loadSampleData(); break; } // XMF TableLoad for SAMPLE data function loadSampleData() { // $moduleDirName = basename(dirname(__DIR__)); xoops_loadLanguage('comment'); $items = \Xmf\Yaml::readWrapped('quotes_data.yml'); \Xmf\Database\TableLoad::truncateTable('randomquote_quotes'); \Xmf\Database\TableLoad::loadTableFromArray('randomquote_quotes', $items); redirect_header('../admin/index.php', 1, _CM_ACTIVE); }
mambax7/257
htdocs/modules/wflinks/testdata/index.php
PHP
gpl-2.0
1,254
#ifndef GAP_HPC_MISC_H #define GAP_HPC_MISC_H #include "system.h" #ifndef HPCGAP #error This header is only meant to be used with HPC-GAP #endif /**************************************************************************** ** *V ThreadUI . . . . . . . . . . . . . . . . . . . . support UI for threads ** */ extern UInt ThreadUI; /**************************************************************************** ** *V DeadlockCheck . . . . . . . . . . . . . . . . . . check for deadlocks ** */ extern UInt DeadlockCheck; /**************************************************************************** ** *V SyNumProcessors . . . . . . . . . . . . . . . . . number of logical CPUs ** */ extern UInt SyNumProcessors; /**************************************************************************** ** *V SyNumGCThreads . . . . . . . . . . . . . . . number of GC worker threads ** */ extern UInt SyNumGCThreads; /**************************************************************************** ** *F MergeSort() . . . . . . . . . . . . . . . sort an array using mergesort. ** ** MergeSort() sorts an array of 'count' elements of individual size 'width' ** with ordering determined by the parameter 'lessThan'. The 'lessThan' ** function is to return a non-zero value if the first argument is less ** than the second argument, zero otherwise. ** */ extern void MergeSort(void *data, UInt count, UInt width, int (*lessThan)(const void *a, const void *)); #endif // GAP_HPC_MISC_H
sebasguts/gap
src/hpc/misc.h
C
gpl-2.0
1,488
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_FRAME_EXTRA_SYSTEM_APIS_H_ #define CHROME_FRAME_EXTRA_SYSTEM_APIS_H_ #include <mshtml.h> #include <shdeprecated.h> class __declspec(uuid("54A8F188-9EBD-4795-AD16-9B4945119636")) IWebBrowserEventsService : public IUnknown { public: STDMETHOD(FireBeforeNavigate2Event)(VARIANT_BOOL* cancel) = 0; STDMETHOD(FireNavigateComplete2Event)(VOID) = 0; STDMETHOD(FireDownloadBeginEvent)(VOID) = 0; STDMETHOD(FireDownloadCompleteEvent)(VOID) = 0; STDMETHOD(FireDocumentCompleteEvent)(VOID) = 0; }; class __declspec(uuid("{87CC5D04-EAFA-4833-9820-8F986530CC00}")) IWebBrowserEventsUrlService : public IUnknown { public: STDMETHOD(GetUrlForEvents)(BSTR* url) = 0; }; class __declspec(uuid("{3050F804-98B5-11CF-BB82-00AA00BDCE0B}")) IWebBrowserPriv : public IUnknown { public: STDMETHOD(NavigateWithBindCtx)(VARIANT* uri, VARIANT* flags, VARIANT* target_frame, VARIANT* post_data, VARIANT* headers, IBindCtx* bind_ctx, LPOLESTR url_fragment); STDMETHOD(OnClose)(); }; class IWebBrowserPriv2Common : public IUnknown { public: STDMETHOD(NavigateWithBindCtx2)(IUri* uri, VARIANT* flags, VARIANT* target_frame, VARIANT* post_data, VARIANT* headers, IBindCtx* bind_ctx, LPOLESTR url_fragment); }; class IWebBrowserPriv2CommonIE9 : public IUnknown { public: STDMETHOD(NavigateWithBindCtx2)(IUri* uri, VARIANT* flags, VARIANT* target_frame, VARIANT* post_data, VARIANT* headers, IBindCtx* bind_ctx, LPOLESTR url_fragment, DWORD unused1); }; interface __declspec(uuid("3050f801-98b5-11cf-bb82-00aa00bdce0b")) IDocObjectService : public IUnknown { STDMETHOD(FireBeforeNavigate2)(IDispatch* dispatch, LPCTSTR url, DWORD flags, LPCTSTR frame_name, BYTE* post_data, DWORD post_data_len, LPCTSTR headers, BOOL play_nav_sound, BOOL* cancel) = 0; STDMETHOD(FireNavigateComplete2)(IHTMLWindow2* html_window2, DWORD flags) = 0; STDMETHOD(FireDownloadBegin)() = 0; STDMETHOD(FireDownloadComplete)() = 0; STDMETHOD(FireDocumentComplete)(IHTMLWindow2* html_window2, DWORD flags) = 0; STDMETHOD(UpdateDesktopComponent)(IHTMLWindow2* html_window2) = 0; STDMETHOD(GetPendingUrl)(BSTR* pending_url) = 0; STDMETHOD(ActiveElementChanged)(IHTMLElement* html_element) = 0; STDMETHOD(GetUrlSearchComponent)(BSTR* search) = 0; STDMETHOD(IsErrorUrl)(LPCTSTR url, BOOL* is_error) = 0; }; interface __declspec(uuid("f62d9369-75ef-4578-8856-232802c76468")) ITridentService2 : public IUnknown { STDMETHOD(FireBeforeNavigate2)(IDispatch* dispatch, LPCTSTR url, DWORD flags, LPCTSTR frame_name, BYTE* post_data, DWORD post_data_len, LPCTSTR headers, BOOL play_nav_sound, BOOL* cancel) = 0; STDMETHOD(FireNavigateComplete2)(IHTMLWindow2*, uint32); STDMETHOD(FireDownloadBegin)(VOID); STDMETHOD(FireDownloadComplete)(VOID); STDMETHOD(FireDocumentComplete)(IHTMLWindow2*, uint32); STDMETHOD(UpdateDesktopComponent)(IHTMLWindow2*); STDMETHOD(GetPendingUrl)(uint16**); STDMETHOD(ActiveElementChanged)(IHTMLElement*); STDMETHOD(GetUrlSearchComponent)(uint16**); STDMETHOD(IsErrorUrl)(uint16 const*, int32*); STDMETHOD(AttachMyPics)(VOID *, VOID**); STDMETHOD(ReleaseMyPics)(VOID*); STDMETHOD(IsGalleryMeta)(int32, VOID*); STDMETHOD(EmailPicture)(uint16*); STDMETHOD(FireNavigateError)(IHTMLWindow2*, uint16*, uint16*, uint32, int*); STDMETHOD(FirePrintTemplateEvent)(IHTMLWindow2*, int32); STDMETHOD(FireUpdatePageStatus)(IHTMLWindow2*, uint32, int32); STDMETHOD(FirePrivacyImpactedStateChange)(int32 privacy_violated); STDMETHOD(InitAutoImageResize)(VOID); STDMETHOD(UnInitAutoImageResize)(VOID); }; #define TLEF_RELATIVE_INCLUDE_CURRENT (0x01) #define TLEF_RELATIVE_BACK (0x10) #define TLEF_RELATIVE_FORE (0x20) #endif
qtekfun/htcDesire820Kernel
external/chromium_org/chrome_frame/extra_system_apis.h
C
gpl-2.0
4,312
<?php /** * @package Expose * @version 3.0.1 * @author ThemeXpert http://www.themexpert.com * @copyright Copyright (C) 2010 - 2011 ThemeXpert * @license http://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3 * @file layout.php **/ //prevent direct access defined ('EXPOSE_VERSION') or die ('resticted aceess'); //import joomla filesystem classes jimport('joomla.filesystem.folder'); jimport('joomla.filesystem.file'); class ExposeLayout { protected $modules = array(); protected $widgets = array(); protected $activeWidgets = array(); public function __construct() { //load all widgets in an array and trigger the initialize event for those widgets. $this->loadWidgets(); } public static function getInstance() { static $instance; if(!isset($instance)) { $instance = New ExposeLayout; } return $instance; } public function countModules($position) { //check if the module schema already exist for this position return it back. //if not exist set if first if(!isset($this->modules[$position]['schema'])) { $this->setModuleSchema($position); } $published = 0; //check orphan module position which have nos subset. if($this->countModulesForPosition($position) OR $this->countWidgetsForPosition($position)) { //set this position in active array record $this->modules[$position]['active'][] = $position; $published ++; $this->modules[$position]['published'] = $published; return TRUE; } //loop through all module-position(eg: roof-1, roof-2) and set the total published module num. foreach($this->modules[$position]['schema'] as $num => $v) { $positionName = ($position . '-' . $num) ; if($this->countModulesForPosition($positionName) OR $this->countWidgetsForPosition($positionName)) { //set this position in active array record $this->modules[$position]['active'][] = $positionName; $published ++; } } $this->modules[$position]['published'] = $published; if($published > 0) return TRUE; return FALSE; } public function renderModules($position) { global $expose; $totalPublished = $this->modules[$position]['published']; $i = 1; if($totalPublished > 0 AND isset($this->modules[$position]['active'])) { $widths = $this->getModuleSchema($position); $containerClass = 'ex-column'; foreach($this->getActiveModuleLists($position) as $positionName) { //$totalModulesInPosition = $this->countModulesForPosition( $positionName ); $width = array_shift($widths); $class = ''; $html = ''; //we'll make all width 100% for mobile device if($expose->platform == 'mobile'){ $width = 100; } if($i == 1) $class .= 'ex-first '; if($i == $totalPublished){ $class .= 'ex-last '; } $class .= ($i%2) ? 'ex-odd' : 'ex-even'; if($i == ($totalPublished -1)) $class .= ' ie6-offset'; $style = "style=\"width: $width%\" "; if(count($this->modules[$position]['schema']) == 1) $style = ''; //Exception for single module position //we'll load all widgets first published in this position if($this->countWidgetsForPosition($positionName)) { foreach($this->activeWidgets[$positionName] as $widget) { $name = 'widget-' . $widget->name; $html .= "<div class=\"ex-block ex-widget no-title column-spacing $name clearfix\">"; $html .= "<div class=\"ex-content\">"; $html .= $widget->render(); $html .= "</div>"; $html .= "</div>"; } } $modWrapperStart = "<div class=\"$containerClass $class $positionName\" $style>"; $modWrapperEnd = "</div>"; //now load modules content $chrome = $this->getModuleChrome($position,$positionName); $html .= '<jdoc:include type="modules" name="'.$positionName.'" style="'.$chrome.'" />'; echo $modWrapperStart . $html . $modWrapperEnd; $i++; } } } protected function setModuleSchema($position) { global $expose; $values = $expose->get($position); $values = explode(',', $values); foreach($values as $value) { list($i, $v) = explode(':', "$value:"); $this->modules[$position]['schema'][$i][] = $v; } } public function getModuleSchema($position) { if(!isset($this->modules[$position])) { return; } $published = $this->modules[$position]['published']; //return module schema based on active modules return $this->modules[$position]['schema'][$published]; } public function getModuleChrome($position, $module) { if(!isset($this->modules[$position]['chrome'])) { $this->setModuleChrome($position); } return $this->modules[$position]['chrome'][$module]; } protected function setModuleChrome($position) { global $expose; $fieldName = $position . '-chrome'; $data = $expose->get($fieldName); $data = explode(',', $data); foreach($data as $json) { list($modName, $chrome) = explode(':',$json); $this->modules[$position]['chrome'][$modName] = $chrome; } } public function getActiveModuleLists($position) { //return active module array associate with position return $this->modules[$position]['active']; } public function getWidget($name) { if(isset($this->widgets[$name])) { return $this->widgets[$name]; } return FALSE; } public function getWidgetsForPosition($position) { if(!isset($this->widgets)) { $this->loadWidgets(); } $widgets = array(); foreach($this->widgets as $name => $instance) { if($instance->isEnabled() AND $instance->isInPosition($position) AND method_exists($instance, 'render')){ $widgets[$name] = $instance; } } return $widgets; } public function countWidgetsForPosition($position) { global $expose; $count = 0; $this->activeWidgets[$position] = array(); if($expose->platform == 'mobile') { foreach($this->getWidgetsForPosition($position) as $widget) { if($widget->isInMobile()) { if(!in_array($widget, $this->activeWidgets[$position])) { $this->activeWidgets[$position][] = $widget; } $count++ ; } } }else{ foreach ($this->getWidgetsForPosition($position) as $widget) { if(!in_array($widget, $this->activeWidgets[$position])) { $this->activeWidgets[$position][] = $widget; } $count++; } } return $count; //return count($this->getWidgetsForPosition($position)); } public function countModulesForPosition($position) { global $expose; $parentField = substr($position,0,strpos($position,'-')); //split the number and get the parent field name if($expose->platform == 'mobile') { if($expose->get($parentField.'-mobile')) { return $expose->document->countModules($position); }else{ return FALSE; } } return $expose->document->countModules($position); } protected function loadWidgets() { global $expose; //define widgets paths $widgetPaths = array( $expose->exposePath . DS . 'widgets', $expose->templatePath . DS .'widgets' ); $widgetLists = array(); //first loop through all the template and framework path and take widget instance foreach($widgetPaths as $widgetPath) { $widgets = JFolder::files($widgetPath, '.php'); if(is_array($widgets)) { foreach($widgets as $widget) { $widgetName = JFile::stripExt($widget); $path = $widgetPath . DS . $widgetName .'.php'; $widgetLists[$widgetName] = $path; } } } ksort($widgetLists); foreach($widgetLists as $name => $path) { $className = 'ExposeWidget'. ucfirst($name); if(!class_exists($className) AND JFile::exists($path)) { require_once($path); if(class_exists($className)) { $this->widgets[$name] = new $className(); } } } //now initialize the widgets which is not position specific foreach($this->widgets as $name => $instance) { //we'll load the widgets based on platform permission if($expose->platform == 'mobile') { if($instance->isEnabled() AND $instance->isInMobile() AND method_exists($instance , 'init')) { $instance->init(); } }else{ if($instance->isEnabled() AND method_exists($instance, 'init')) { $instance->init(); } } } } public function renderBody() { global $expose; $layouts = (isset ($_COOKIE[$expose->templateName.'_layouts'])) ? $_COOKIE[$expose->templateName.'_layouts'] : $expose->get('layouts'); if(isset ($_REQUEST['layouts'])){ setcookie($expose->templateName.'_layouts',$_REQUEST['layouts'],time()+3600,'/'); $layouts = $_REQUEST['layouts']; } $bPath = $expose->exposePath . DS . 'layouts'; $tPath = $expose->templatePath . DS .'layouts'; $ext = '.php'; if( $expose->platform == 'mobile' ) { $device = strtolower($expose->browser->getBrowser()); $bfile = $bPath .DS . $device . $ext; $tfile = $tPath .DS . $device . $ext; if($expose->get('iphone-enabled') AND $device == 'iphone') { $this->loadFile(array($tfile,$bfile)); }elseif($expose->get('android-enabled') AND $device == 'android'){ $this->loadFile(array($tfile,$bfile)); }else{ return FALSE; } }else{ $bfile = $bPath .DS . $layouts . $ext; $tfile = $tPath .DS . $layouts . $ext; $this->loadFile(array($tfile,$bfile)); } } public function loadFile($paths) { if(is_array($paths)) { foreach($paths as $path) { if(JFile::exists($path)){ require_once($path); break; } } }else if(JFile::exists($paths)) { require_once ($paths); }else{ JError::raiseNotice(E_NOTICE,"No file file found on given path $paths"); } } public function getModules() { return $this->modules; } }
jbelborja/deportivo
libraries/expose/core/layout.php
PHP
gpl-2.0
12,235
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>首页-灰绿色主题</title> <link href="../css/style.css" rel="stylesheet" type="text/css"> <script src="../js/jQuery.js" type="text/javascript"></script> <script src="../js/common.js" type="text/javascript"></script> <script src="../js/model/WdatePicker/WdatePicker.js" type="text/javascript"></script> <script src="../js/utils.js" type="text/javascript"></script> <script src="../js/model/highcharts/highcharts.js"></script> </head> <body> <div class="layout_header"> <div class="header"> <div class="h_logo"><a href="#" title="101网校课程管理系统"><img src="../images/qaup_logo.png" width="130" height="40" alt=""/></a></div> <div class="h_nav"> <span class="hi"><img src="../images/head_default.jpg" alt="id"/> 欢迎你,管理员!</span><span class="link"><a href="#"><i class="icon16 icon16-setting"></i> 设置</a><a href="#"><i class="icon16 icon16-power"></i> 注销</a></span> </div> <div class="clear"></div> </div> </div> <div class="layout_leftnav"> <div class="inner"> <div class="nav-vertical"> <ul class="accordion"> <li><a href="#"><i class="icon20 icon20_index"></i>信息管理<span></span></a> <ul class="sub-menu"> <li><a href="/mySchool/web/courseList.html">课程管理</a></li> <li><a href="/mySchool/web/teacherList.html">教师管理</a></li> <li><a href="/mySchool/web/studentList.html">学生管理</a></li> <li><a href="/mySchool/web/financeList.html" class="active">财务管理</a></li> </ul> </li> </ul> </div> </div> </div> <div class="layout_rightmain"> <div class="inner"> <div class="pd10x20"> <div class="page-title mb20"> <i class="i_icon"></i><label id="teacher_name">Male</label> </div> <div class="panel"> <div class="panel-tab pd10"> <ul> <li class="active" id="a1" onclick="setTab('a', 1, 3)">课程表</li> <li id="a2" onclick="setTab('a', 2, 3)">年级分布</li> <li id="a3" onclick="setTab('a', 3, 3)">课时费</li> <div class="clear"></div> </ul> </div> <div class="panel-main pd10"> <div id="con_a_1" style="width: 1000px;" class="hover" > <div class="panel-header"> <div><a href="#" class="btn btn-primary" onclick="downloadCourse()">下载</a></div> </div> <table class="table table-striped"> <thead> <tr> <th >学生</th> <th >年级</th> <th >科目</th> <th >课时长</th> <th >上课时间</th> <th >教室</th> </tr> </thead> <tbody id = "couse_list_tbody"> </tbody> </table> </div> <div id="con_a_2" style="display:none; width: 1000px;" ></div> <div id="con_a_3" style="display:none; width: 1000px;" > <table class="table table-striped"> <thead> <tr> <th >年级</th> <th >课时费/时</th> </tr> </thead> <tbody id = "cost_list_tbody"> </tbody> </table> </div> </div> </div> </div> </div> </div> </body> <script type="text/javascript"> var teacherId = ''; var startTimeStr = ''; var endTimeStr = ''; var gradeSet = new Array(); var gradeNameArray = new Array(); var gradeIdNum = new Array(); window.onload = function() { teacherId = getQuery("teacherId"); startTimeStr = getQuery("startTimeStr"); endTimeStr = getQuery("endTimeStr"); initGradeSet(); var teacherUrl = "/mySchool/office/getTeacherById.action"; var params = "teacherId=" + teacherId; var teacherJson = ajaxQuery(teacherUrl, params); this.document.getElementById("teacher_name").innerHTML = teacherJson.data.teacherList[0].name; fillCourseTable(teacherId, startTimeStr, endTimeStr); drawGradeImg(); initFinanceList(); } function initGradeSet() { var gradeUrl = "/mySchool/office/getGradeList.action"; var gradeListJson = ajaxQuery(gradeUrl, null); var row_length = gradeListJson.data.size; for (var i = 0; i < row_length; i++) { gradeSet[gradeListJson.data.gradeList[i].gradeId] = gradeListJson.data.gradeList[i].gradeName; gradeNameArray[i] = gradeListJson.data.gradeList[i].gradeName; gradeIdNum[i] = 0; } gradeIdNum[row_length] = 0; } function fillCourseTable(teacherId, startTimeStr, endTimeStr){ var courseUrl = "/mySchool/office/getCourseList.action"; var params = "startTimeStr=" + startTimeStr + "&" + "endTimeStr=" + endTimeStr + "&" + "teacherId=" + teacherId + "&courseStatus=1"; var courseListJson = ajaxQuery(courseUrl, params); if(courseListJson.data.size == 0){ return; } var data = courseListJson.data; var row_length = data.size; var task_tbody = document.getElementById("couse_list_tbody"); for(var i = 0; i < row_length; i++){ var tr = document.createElement("tr"); var studentName = document.createElement("td"); studentName.innerHTML = data.course_list[i].studentName; tr.appendChild(studentName); var grade = document.createElement("td"); grade.innerHTML = gradeSet[data.course_list[i].gradeId]; tr.appendChild(grade); var subjectName = document.createElement("td"); subjectName.innerHTML = data.course_list[i].subjectName; tr.appendChild(subjectName); var courseTime = document.createElement("td"); courseTime.innerHTML = data.course_list[i].courseTime; tr.appendChild(courseTime); var time = document.createElement("td"); time.innerHTML = (new Date(data.course_list[i].time)).Format("yyyy-MM-dd hh:mm:ss"); tr.appendChild(time); var classroom = document.createElement("td"); classroom.innerHTML = data.course_list[i].classroom; tr.appendChild(classroom); gradeIdNum[data.course_list[i].gradeId] += 1; task_tbody.appendChild(tr); } } function drawGradeImg() { $(function() { $('#con_a_2').highcharts({ title: { text: '课程年级分布图', x: -20 //center }, xAxis: { categories: gradeNameArray }, yAxis: { title: { text: '课程年级学生数' }, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, tooltip: { valueSuffix: '个' }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle', borderWidth: 0 }, series: [{ name: '学生数', data: gradeIdNum.slice(1) }] }); }); } function initFinanceList() { var teacherGradeCostUrl = "/mySchool/finance/getTeacherGradeCostList.action"; var params = "teacherId=" + teacherId; var teacherJson = ajaxQuery(teacherGradeCostUrl, params); var task_tbody = document.getElementById("cost_list_tbody"); var data = teacherJson.data; var row_length = data.size; for (var i = 0; i < row_length; i++) { var tr = document.createElement("tr"); var grade = document.createElement("td"); grade.innerHTML = gradeSet[data.teacherList[i].gradeId]; tr.appendChild(grade); var cost = document.createElement("td"); cost.innerHTML = data.teacherList[i].cost; tr.appendChild(cost); task_tbody.appendChild(tr); } } function downloadCourse(){ var params = ""; params += "startTimeStr=" + startTimeStr + "&"; params += "endTimeStr=" + endTimeStr + "&"; params += "teacherId=" + teacherId; window.location.href = "/mySchool/office/downloadCourse.action?"+params; } </script> </html>
lxqfirst/mySchool
WebContent/web/financeDetail.html
HTML
gpl-2.0
10,505
<?php /* Plugin Name: Social Likes Description: Wordpress plugin for Social Likes library by Artem Sapegin (http://sapegin.me/projects/social-likes) Version: 5.5.7 Author: TS Soft Author URI: http://ts-soft.ru/en/ License: MIT Copyright 2014 TS Soft LLC (email: [email protected] ) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ class wpsociallikes { const OPTION_NAME_MAIN = 'sociallikes'; const OPTION_NAME_CUSTOM_LOCALE = 'sociallikes_customlocale'; const OPTION_NAME_PLACEMENT = 'sociallikes_placement'; const OPTION_NAME_SHORTCODE = 'sociallikes_shortcode'; const OPTION_NAME_EXCERPTS = 'sociallikes_excerpts'; var $lang; var $options; var $buttons = array( 'vk_btn', 'facebook_btn', 'twitter_btn', 'google_btn', 'pinterest_btn', 'lj_btn', 'linkedin_btn', 'odn_btn', 'mm_btn', 'email_btn' ); function wpsociallikes() { add_option(self::OPTION_NAME_CUSTOM_LOCALE, ''); add_option(self::OPTION_NAME_PLACEMENT, 'after'); add_option(self::OPTION_NAME_SHORTCODE, 'disabled'); add_option(self::OPTION_NAME_EXCERPTS, 'disabled'); add_action('init', array(&$this, 'ap_action_init')); add_action('wp_head', array(&$this, 'header_content')); add_action('wp_enqueue_scripts', array(&$this, 'header_scripts')); add_action('admin_menu', array(&$this, 'wpsociallikes_menu')); add_action('save_post', array(&$this, 'save_post_meta')); add_action('admin_enqueue_scripts', array(&$this, 'wpsociallikes_admin_scripts')); add_filter('the_content', array(&$this, 'add_social_likes')); // https://github.com/tssoft/wp-social-likes/issues/7 add_filter('the_excerpt_rss', array(&$this, 'exclude_div_in_RSS_description')); add_filter('the_content_feed', array(&$this, 'exclude_div_in_RSS_content')); add_filter('plugin_action_links', array(&$this, 'add_action_links'), 10, 2); add_shortcode('wp-social-likes', array(&$this, 'shortcode_content')); } function ap_action_init() { $this->load_options(); $custom_locale = $this->options['customLocale']; if ($custom_locale) { load_textdomain('wp-social-likes', plugin_dir_path( __FILE__ ).'/languages/wp-social-likes-'.$custom_locale.'.mo'); } else { load_plugin_textdomain('wp-social-likes', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/'); } $this->title_vkontakte = __('Share link on VK', 'wp-social-likes'); $this->title_facebook = __('Share link on Facebook', 'wp-social-likes'); $this->title_twitter = __('Share link on Twitter', 'wp-social-likes'); $this->title_plusone = __('Share link on Google+', 'wp-social-likes'); $this->title_pinterest = __('Share image on Pinterest', 'wp-social-likes'); $this->title_livejournal = __('Share link on LiveJournal', 'wp-social-likes'); $this->title_linkedin = __('Share link on LinkedIn', 'wp-social-likes'); $this->title_odnoklassniki = __('Share link on Odnoklassniki', 'wp-social-likes'); $this->title_mailru = __('Share link on Mail.ru', 'wp-social-likes'); $this->title_email = __('Share link by E-mail', 'wp-social-likes'); $this->label_vkontakte = __('VK', 'wp-social-likes'); $this->label_facebook = __('Facebook', 'wp-social-likes'); $this->label_twitter = __('Twitter', 'wp-social-likes'); $this->label_plusone = __('Google+', 'wp-social-likes'); $this->label_pinterest = __('Pinterest', 'wp-social-likes'); $this->label_livejournal = __('LiveJournal', 'wp-social-likes'); $this->label_linkedin = __('LinkedIn', 'wp-social-likes'); $this->label_odnoklassniki = __('Odnoklassniki', 'wp-social-likes'); $this->label_mailru = __('Mail.ru', 'wp-social-likes'); $this->label_email = __('E-mail', 'wp-social-likes'); $this->label_share = __('Share', 'wp-social-likes'); } function header_content() { $skin = str_replace('light', '', $this->options['skin']); if (($skin != 'classic') && ($skin != 'flat') && ($skin != 'birman')) { $skin = 'classic'; } ?> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/social-likes_<?php echo $skin ?>.css"> <?php if ($this->button_is_active('lj_btn')) { ?> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal_<?php echo $skin ?>.css"> <?php } if ($this->button_is_active('linkedin_btn')) { ?> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin_<?php echo $skin ?>.css"> <?php } if ($this->button_is_active('email_btn')) { ?> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/email.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/email_<?php echo $skin ?>.css"> <?php } ?> <script src="<?php echo plugin_dir_url(__FILE__) ?>js/social-likes.min.js"></script> <?php if ($this->custom_buttons_enabled()) { ?> <script src="<?php echo plugin_dir_url(__FILE__) ?>js/custom-buttons.js"></script> <?php } } function header_scripts() { wp_enqueue_script('jquery'); } function wpsociallikes_admin_scripts() { wp_enqueue_script('jquery'); wp_enqueue_script('jquery-ui-sortable'); } function wpsociallikes_menu() { $post_opt = $this->options['post']; $page_opt = $this->options['page']; add_meta_box('wpsociallikes', 'Social Likes', array(&$this, 'wpsociallikes_meta'), 'post', 'normal', 'default', array('default'=>$post_opt)); add_meta_box('wpsociallikes', 'Social Likes', array(&$this, 'wpsociallikes_meta'), 'page', 'normal', 'default', array('default'=>$page_opt)); $args = array( 'public' => true, '_builtin' => false ); $post_types = get_post_types($args, 'names', 'and'); foreach ($post_types as $post_type ) { add_meta_box('wpsociallikes', 'Social Likes', array(&$this, 'wpsociallikes_meta'), $post_type, 'normal', 'default', array('default'=>$post_opt)); } $plugin_page = add_options_page('Social Likes', 'Social Likes', 'administrator', basename(__FILE__), array (&$this, 'display_admin_form')); add_action('admin_head-' . $plugin_page, array(&$this, 'admin_menu_head')); } function wpsociallikes_meta($post, $metabox) { if (!strstr($_SERVER['REQUEST_URI'], '-new.php')) { $checked = get_post_meta($post->ID, 'sociallikes', true); } else { $checked = $metabox['args']['default']; } if ($checked) { $img_url = get_post_meta($post->ID, 'sociallikes_img_url', true); if ($img_url == '' && $this->options['pinterestImg']) { $img_url = $this->get_post_first_img($post); } } else { $img_url = ''; } ?> <div id="social-likes"> <input type="hidden" name="wpsociallikes_update_meta" value="true" /> <div style="padding: 5px 0"> <input type="checkbox" name="wpsociallikes_enabled" id="wpsociallikes_enabled" <?php if ($checked) echo 'checked class="checked"' ?> title="<?php echo get_permalink($post->ID); ?>" /> <label for="wpsociallikes_enabled"><?php _e('Add social buttons', 'wp-social-likes') ?></label> </div> <table> <tr> <td><label for="wpsociallikes_image_url" style="padding-right:5px"><?php _e('Image&nbspURL:', 'wp-social-likes') ?></label></td> <td style="width:100%"> <input name="wpsociallikes_image_url" id="wpsociallikes_image_url" value="<?php echo $img_url ?>" <?php if (!$checked) echo 'disabled' ?> type="text" placeholder="<?php _e('Image URL (required for Pinterest)', 'wp-social-likes') ?>" style="width:100%" /> </td> </tr> </table> </div> <script> (function($) { var savedImageUrlValue = ''; $('input#wpsociallikes_enabled').change(function () { var $this = $(this); $this.toggleClass('checked'); var socialLikesEnabled = $this.hasClass('checked'); var imageUrlField = $('#wpsociallikes_image_url'); if (socialLikesEnabled) { imageUrlField .removeAttr('disabled') .val(savedImageUrlValue); } else { savedImageUrlValue = imageUrlField.val(); imageUrlField .attr('disabled', 'disabled') .val(''); } }); })( jQuery ); </script> <?php } function get_post_first_img($post) { $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); return $matches [1] [0]; } function save_post_meta($post_id) { if (!isset($_POST['wpsociallikes_update_meta']) || (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)) { return; } if ('page' == $_POST['post_type']) { if (!current_user_can('edit_page', $post_id)) { return; } } else { if (!current_user_can('edit_post', $post_id)) { return; } } update_post_meta($post_id, 'sociallikes', isset($_POST['wpsociallikes_enabled'])); $img_url_sent = isset($_POST['wpsociallikes_image_url']); $img_url = $img_url_sent ? $_POST['wpsociallikes_image_url'] : ''; if ($img_url_sent && $img_url == '' && $this->options['pinterestImg']) { $post = get_post($post_id); $img_url = $this->get_post_first_img($post); } update_post_meta($post_id, 'sociallikes_img_url', $img_url); } function add_social_likes($content = '') { global $post; if (in_the_loop() && get_post_meta($post->ID, 'sociallikes', true) && (is_page() || is_single() || $this->options['excerpts'] || !$this->is_post_with_excerpt())) { $this->lang = get_bloginfo('language'); $buttons = $this->build_buttons($post); $placement = $this->options['placement']; if ($placement != 'none') { if ($placement == 'before') { $content = $buttons . $content; } else if ($placement == 'before-after') { $content = $buttons . $content . $buttons; } else { $content .= $buttons; } } } return $content; } function is_post_with_excerpt() { global $page, $pages; $post_content = $pages[$page - 1]; return preg_match('/<!--more(.*?)?-->/', $post_content); } function build_buttons($post) { $twitter_via = $this->options['twitterVia']; //$twitter_rel = $this->options['twitterRel']; $look = $this->options['look']; $skin = $this->options['skin']; $light = false; if (strpos($skin, 'light')) { $light = true; $skin = str_replace('light', '', $skin); } $iconsOnly = $this->options['iconsOnly']; $label_vkontakte = $iconsOnly ? '' : $this->label_vkontakte; $label_facebook = $iconsOnly ? '' : $this->label_facebook; $label_twitter = $iconsOnly ? '' : $this->label_twitter; $label_plusone = $iconsOnly ? '' : $this->label_plusone; $label_pinterest = $iconsOnly ? '' : $this->label_pinterest; $label_livejournal = $iconsOnly ? '' : $this->label_livejournal; $label_linkedin = $iconsOnly ? '' : $this->label_linkedin; $label_odnoklassniki = $iconsOnly ? '' : $this->label_odnoklassniki; $label_mailru = $iconsOnly ? '' : $this->label_mailru; $label_email = $iconsOnly ? '' : $this->label_email; $socialButton['vk_btn'] = '<div class="vkontakte" title="'.$this->title_vkontakte.'">'.$label_vkontakte.'</div>'; $socialButton['facebook_btn'] = '<div class="facebook" title="'.$this->title_facebook.'">'.$label_facebook.'</div>'; $socialButton['twitter_btn'] = '<div class="twitter" '; if ($twitter_via != '') { $socialButton['twitter_btn'] .= 'data-via="' . $twitter_via . '" '; } /*if ($twitter_rel != '') { $socialButton['twitter_btn'] .= 'data-related="' . $twitter_rel . '" '; }*/ $socialButton['twitter_btn'] .= 'title="'.$this->title_twitter.'">'.$label_twitter.'</div>'; $socialButton['google_btn'] = '<div class="plusone" title="'.$this->title_plusone.'">'.$label_plusone.'</div>'; $img_url = get_post_meta($post->ID, 'sociallikes_img_url', true); $socialButton['pinterest_btn'] = '<div class="pinterest" title="' . $this->title_pinterest . '"'; if ($img_url != '') { $socialButton['pinterest_btn'] .= ' data-media="' . $img_url . '"'; } if ($img_url == '' && $this->options['pinterestImg']) { $socialButton['pinterest_btn'] .= ' data-media="' . $this->get_post_first_img($post) . '"'; } $socialButton['pinterest_btn'] .= '>' . $label_pinterest . '</div>'; $socialButton['lj_btn'] = '<div class="livejournal" title="' .$this->title_livejournal .'" data-html="&lt;a href=\'{url}\'&gt;{title}&lt;/a&gt;">' .$label_livejournal.'</div>'; $socialButton['linkedin_btn'] = '<div class="linkedin" title="'.$this->title_linkedin.'">'.$label_linkedin.'</div>'; $socialButton['odn_btn'] = '<div class="odnoklassniki" title="'.$this->title_odnoklassniki.'">'.$label_odnoklassniki.'</div>'; $socialButton['mm_btn'] = '<div class="mailru" title="'.$this->title_mailru.'">'.$label_mailru.'</div>'; $socialButton['email_btn'] = '<div class="email" title="'.$this->title_email.'">'.$label_email.'</div>'; $main_div = '<div class="social-likes'; $classAppend = ''; if ($iconsOnly) { $classAppend .= ' social-likes_notext'; } if (($skin == 'flat') && $light) { $classAppend .= ' social-likes_light'; } if ($look == 'h') { $main_div .= $classAppend.'"'; } elseif ($look == 'v') { $main_div .= ' social-likes_vertical'.$classAppend.'"'; } else { $main_div .= ' social-likes_single'.$classAppend.'" data-single-title="'.$this->label_share.'"'; } $main_div .= ' data-title="' . $post->post_title . '"'; $main_div .= ' data-url="' . get_permalink( $post->ID ) . '"'; $main_div .= $this->options['counters'] ? ' data-counters="yes"' : ' data-counters="no"'; $main_div .= $this->options['zeroes'] ? ' data-zeroes="yes"' : ''; $main_div .= '>'; foreach ($this->options['buttons'] as $btn) { if (in_array($btn, $this->buttons)) { $main_div .= $socialButton[$btn]; } } $main_div .= '</div><form style="display: none;" class="sociallikes-livejournal-form"></form>'; return $main_div; } function admin_menu_head() { ?> <link rel="stylesheet" id="sociallikes-style-classic" href="<?php echo plugin_dir_url(__FILE__) ?>css/social-likes_classic.css"> <link rel="stylesheet" id="sociallikes-style-flat" href="<?php echo plugin_dir_url(__FILE__) ?>css/social-likes_flat.css"> <link rel="stylesheet" id="sociallikes-style-birman" href="<?php echo plugin_dir_url(__FILE__) ?>css/social-likes_birman.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal.css"> <link rel="stylesheet" id="sociallikes-style-classic-livejournal" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal_classic.css"> <link rel="stylesheet" id="sociallikes-style-flat-livejournal" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal_flat.css"> <link rel="stylesheet" id="sociallikes-style-birman-livejournal" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal_birman.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin.css"> <link rel="stylesheet" id="sociallikes-style-classic-linkedin" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin_classic.css"> <link rel="stylesheet" id="sociallikes-style-flat-linkedin" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin_flat.css"> <link rel="stylesheet" id="sociallikes-style-birman-linkedin" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin_birman.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/email.css"> <link rel="stylesheet" id="sociallikes-style-classic-email" href="<?php echo plugin_dir_url(__FILE__) ?>css/email_classic.css"> <link rel="stylesheet" id="sociallikes-style-flat-email" href="<?php echo plugin_dir_url(__FILE__) ?>css/email_flat.css"> <link rel="stylesheet" id="sociallikes-style-birman-email" href="<?php echo plugin_dir_url(__FILE__) ?>css/email_birman.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/admin-page.css"> <script src="<?php echo plugin_dir_url(__FILE__) ?>js/social-likes.min.js"></script> <script src="<?php echo plugin_dir_url(__FILE__) ?>js/preview.js"></script> <?php } function display_admin_form() { if (isset($_POST['submit']) || isset($_POST['apply_to_posts']) || isset($_POST['apply_to_pages'])) { $this->submit_admin_form(); } if (isset($_POST['apply_to_posts'])) { $args = array('numberposts' => -1, 'post_type' => 'post', 'post_status' => 'any'); $result = get_posts($args); foreach ($result as $post) { update_post_meta($post->ID, 'sociallikes', isset($_POST['post_chb'])); } } if (isset($_POST['apply_to_pages'])) { $args = array('post_type' => 'page'); $result = get_pages($args); foreach ($result as $post) { update_post_meta($post->ID, 'sociallikes', isset($_POST['page_chb'])); } } $this->load_options(); $look = $this->options['look']; $counters = $this->options['counters']; $post = $this->options['post']; $page = $this->options['page']; $skin = $this->options['skin']; $light = false; if (strpos($skin, 'light')) { $light = true; } if (($skin != 'classic') && ($skin != 'flat') && ($skin != 'flatlight') && ($skin != 'birman')) { $skin = 'classic'; } $zeroes = $this->options['zeroes']; $iconsOnly = $this->options['iconsOnly']; $label["vk_btn"] = __("VK", 'wp-social-likes'); $label["facebook_btn"] = __("Facebook", 'wp-social-likes'); $label["twitter_btn"] = __("Twitter", 'wp-social-likes'); $label["google_btn"] = __("Google+", 'wp-social-likes'); $label["pinterest_btn"] = __("Pinterest", 'wp-social-likes'); $label["lj_btn"] = __("LiveJournal", 'wp-social-likes'); $label["linkedin_btn"] = __("LinkedIn", 'wp-social-likes'); $label["odn_btn"] = __("Odnoklassniki", 'wp-social-likes'); $label["mm_btn"] = __("Mail.ru", 'wp-social-likes'); $label["email_btn"] = __("E-mail", 'wp-social-likes'); $this->lang = get_bloginfo('language'); ?> <div class="wrap"> <h2><?php _e('Social Likes Settings', 'wp-social-likes') ?></h2> <form name="wpsociallikes" method="post" action="?page=wp-social-likes.php&amp;updated=true"> <?php wp_nonce_field('update-options'); ?> <input id="title_vkontakte" type="hidden" value="<?php echo $this->title_vkontakte ?>"> <input id="title_facebook" type="hidden" value="<?php echo $this->title_facebook ?>"> <input id="title_twitter" type="hidden" value="<?php echo $this->title_twitter ?>"> <input id="title_plusone" type="hidden" value="<?php echo $this->title_plusone ?>"> <input id="title_pinterest" type="hidden" value="<?php echo $this->title_pinterest ?>"> <input id="title_livejournal" type="hidden" value="<?php echo $this->title_livejournal ?>"> <input id="title_linkedin" type="hidden" value="<?php echo $this->title_linkedin ?>"> <input id="title_odnoklassniki" type="hidden" value="<?php echo $this->title_odnoklassniki ?>"> <input id="title_mailru" type="hidden" value="<?php echo $this->title_mailru ?>"> <input id="title_email" type="hidden" value="<?php echo $this->title_email ?>"> <input id="label_vkontakte" type="hidden" value="<?php echo $this->label_vkontakte ?>"> <input id="label_facebook" type="hidden" value="<?php echo $this->label_facebook ?>"> <input id="label_twitter" type="hidden" value="<?php echo $this->label_twitter ?>"> <input id="label_plusone" type="hidden" value="<?php echo $this->label_plusone ?>"> <input id="label_pinterest" type="hidden" value="<?php echo $this->label_pinterest ?>"> <input id="label_livejournal" type="hidden" value="<?php echo $this->label_livejournal ?>"> <input id="label_linkedin" type="hidden" value="<?php echo $this->label_linkedin ?>"> <input id="label_odnoklassniki" type="hidden" value="<?php echo $this->label_odnoklassniki ?>"> <input id="label_mailru" type="hidden" value="<?php echo $this->label_mailru ?>"> <input id="label_email" type="hidden" value="<?php echo $this->label_email ?>"> <input id="label_share" type="hidden" value="<?php echo $this->label_share ?>"> <input id="confirm_leaving_message" type="hidden" value="<?php _e('You have unsaved changes on this page. Do you want to leave this page and discard your changes?', 'wp-social-likes') ?>"> <table class="plugin-setup"> <tr valign="top"> <th scope="row"><?php _e('Skin', 'wp-social-likes') ?></th> <td class="switch-button-row"> <div style="float: left;"> <input type="radio" name="skin" id="skin_classic" class="view-state<?php if ($skin == 'classic') echo ' checked' ?>" value="classic" <?php if ($skin == 'classic') echo 'checked' ?> /> <label class="switch-button" for="skin_classic"><?php _e('Classic', 'wp-social-likes') ?></label> <input type="radio" name="skin" id="skin_flat" class="view-state<?php if ($skin == 'flat') echo ' checked' ?>" value="flat" <?php if ($skin == 'flat') echo ' checked' ?> /> <label class="switch-button" for="skin_flat"><?php _e('Flat', 'wp-social-likes') ?></label> <input type="radio" name="skin" id="skin_flatlight" class="view-state<?php if ($skin == 'flat') echo ' checked' ?>" value="flatlight" <?php if ($skin == 'flatlight') echo ' checked' ?> /> <label class="switch-button" for="skin_flatlight"><?php _e('Flat Light', 'wp-social-likes') ?></label> <input type="radio" name="skin" id="skin_birman" class="view-state<?php if ($skin == 'birman') echo ' checked' ?>" value="birman" <?php if ($skin == 'birman') echo ' checked' ?> /> <label class="switch-button" for="skin_birman"><?php _e('Birman', 'wp-social-likes') ?></label> </div> </td> </tr> <tr valign="top"> <th scope="row"><?php _e('Look', 'wp-social-likes') ?></th> <td class="switch-button-row"> <div style="float: left;"> <input type="radio" name="look" id="h_look" class="view-state<?php if ($look == 'h') echo ' checked' ?>" value="h" <?php if ($look == 'h') echo 'checked' ?> /> <label class="switch-button" for="h_look"<!--class="wpsl-label-->"><?php _e('Horizontal', 'wp-social-likes') ?></label> <input type="radio" name="look" id="v_look" class="view-state<?php if ($look == 'v') echo ' checked' ?>" value="v" <?php if ($look == 'v') echo ' checked' ?> /> <label class="switch-button" for="v_look"><?php _e('Vertical', 'wp-social-likes') ?></label> <input type="radio" name="look" id="s_look" class="view-state<?php if ($look == 's') echo ' checked' ?>" value="s" <?php if ($look == 's') echo ' checked' ?> /> <label class="switch-button" for="s_look"><?php _e('Single button', 'wp-social-likes') ?></label> </div> </td> </tr> <tr valign="top"> <th scope="row"></th> <td scope="row" class="without-bottom"> <div class="option-checkboxes"> <input type="checkbox" name="counters" id="counters" <?php if ($counters) echo 'checked' ?> /> <label for="counters" class="wpsl-label"><?php _e('Show counters', 'wp-social-likes') ?></label> </div> <div class="option-checkboxes" id="zeroes-container"> <input type="checkbox" name="zeroes" id="zeroes" <?php if ($zeroes) echo 'checked' ?> /> <label for="zeroes" class="wpsl-label"><?php _e('With zeroes', 'wp-social-likes') ?></label> </div> <div class="option-checkboxes" id="icons-container"> <input type="checkbox" name="icons" id="icons" <?php if ($iconsOnly) echo 'checked' ?> /> <label for="icons" class="wpsl-label"><?php _e('Icons only', 'wp-social-likes') ?></label> </div> </td> </tr> <tr valign="top"> <th class="valign-top" scope="row"><?php _e('Websites', 'wp-social-likes') ?></th> <td class="without-bottom"> <ul class="sortable-container"> <?php $remainingButtons = $this->buttons; for ($i = 1; $i <= count($label); $i++) { $btn = null; $checked = false; if ($i <= count($this->options['buttons'])) { $btn = $this->options['buttons'][$i - 1]; $index = array_search($btn, $remainingButtons, true); if ($index !== false) { array_splice($remainingButtons, $index, 1); $checked = true; } } if ($btn == null) { $btn = array_shift($remainingButtons); } $hidden = ($this->lang != 'ru-RU') && !$checked && ($btn == 'odn_btn' || $btn == 'mm_btn'); ?> <li class="sortable-item<?php if ($hidden) echo ' hidden' ?>"> <input type="checkbox" name="site[]" id="<?php echo $btn ?>" value="<?php echo $btn ?>" <?php if ($checked) echo 'checked' ?> /> <label for="<?php echo $btn ?>" class="wpsl-label"><?php echo $label[$btn] ?></label> </li> <?php } ?> </ul> <?php if ($this->lang != 'ru-RU' && !($this->button_is_active('odn_btn') && $this->button_is_active('mm_btn'))) { ?><span class="more-websites"><?php _e('More websites', 'wp-social-likes') ?></span><?php } ?> </td> </tr> <tr valign="top"> <th scope="row"><?php _e('Twitter Via', 'wp-social-likes') ?></th> <td> <input type="text" name="twitter_via" placeholder="<?php _e('Username', 'wp-social-likes') ?>" class="wpsl-field" value="<?php echo $this->options['twitterVia']; ?>" /> </td> </tr> <!--tr valign="top"> <th scope="row">Twitter Related</th> <td> <input type="text" name="twitter_rel" placeholder="Username:Description" class="wpsl-field" value="<?php echo $this->options['twitterRel']; ?>"/> </td> </tr--> <tr valign="top"> <th scope="row"></th> <td scope="row" class="without-bottom"> <input type="checkbox" name="pinterest_img" id="pinterest_img" <?php if ($this->options['pinterestImg']) echo 'checked' ?> /> <label for="pinterest_img" class="wpsl-label"><?php _e('Automatically place first image in the post/page to the Image URL field', 'wp-social-likes') ?></label> </td> </tr> <tr valign="top"> <th scope="row"></th> <td class="without-bottom"> <input type="checkbox" name="post_chb" id="post_chb" <?php if ($post) echo 'checked' ?> /> <label for="post_chb" class="wpsl-label"><?php _e('Add by default for new posts', 'wp-social-likes') ?></label> <input type="submit" name="apply_to_posts" id="apply_to_posts" value="<?php _e('Apply to existing posts', 'wp-social-likes') ?>" class="button-secondary"/> </td> </tr> <tr valign="top"> <th scope="row"></th> <td> <input type="checkbox" name="page_chb" id="page_chb" <?php if ($page) echo 'checked' ?> /> <label for="page_chb" class="wpsl-label"><?php _e('Add by default for new pages', 'wp-social-likes') ?></label> <input type="submit" name="apply_to_pages" id="apply_to_pages" value="<?php _e('Apply to existing pages', 'wp-social-likes') ?>" class="button-secondary" /> </td> </tr> </table> <div class="row"> <div id="preview" class="shadow-border" <?php if ($this->lang == 'ru-RU') echo 'language="ru"' ?> ></div> </div> <?php submit_button(); ?> </form> </div> <?php } function submit_admin_form() { $options = array( 'skin' => $_POST['skin'], 'look' => $_POST['look'], 'post' => isset($_POST['post_chb']), 'page' => isset($_POST['page_chb']), 'pinterestImg' => isset($_POST['pinterest_img']), 'twitterVia' => $_POST['twitter_via'], //'twitterRel' => $_POST['twitter_rel'], 'iconsOnly' => isset($_POST['icons']), 'counters' => isset($_POST['counters']), 'zeroes' => isset($_POST['zeroes']), 'buttons' => array() ); if (isset($_POST['site'])) { foreach ($_POST['site'] as $btn) { if (in_array($btn, $this->buttons)) { array_push($options['buttons'], $btn); } } } update_option(self::OPTION_NAME_MAIN, $options); $this->delete_deprecated_options(); } function exclude_div_in_RSS_description($content) { global $post; if (get_post_meta($post->ID, 'sociallikes', true)) { $index = strripos($content, ' '); $content = substr_replace($content, '', $index); } return $content; } function exclude_div_in_RSS_content($content) { if (is_feed()) { $content = preg_replace("/<div.*(class)=(\"|')social-likes(\"|').*>.*<\/div>/smUi", '', $content); } return $content; } function shortcode_content() { global $post; if ($this->options['shortcode']) { return $this->build_buttons($post); } return ''; } function add_action_links($all_links, $current_file) { if (basename(__FILE__) == basename($current_file)) { $plugin_file_name_parts = explode('/', plugin_basename(__FILE__)); $plugin_file_name = $plugin_file_name_parts[count($plugin_file_name_parts) - 1]; $settings_link = '<a href="' . admin_url('options-general.php?page=' . $plugin_file_name) . '">' . __('Settings', 'wp-social-likes') . '</a>'; array_unshift($all_links, $settings_link); } return $all_links; } function custom_buttons_enabled() { return $this->button_is_active('lj_btn') || $this->button_is_active('linkedin_btn') || $this->button_is_active('email_btn'); } function button_is_active($name) { return in_array($name, $this->options['buttons']); } function load_options() { $options = $this->load_deprecated_options(); if (!$options) { $options = get_option(self::OPTION_NAME_MAIN); if (!$options || !is_array($options)) { $options = array( 'counters' => true, 'look' => 'h', 'post' => true, 'skin' => 'classic' ); } if (!$options['buttons'] || !is_array($options['buttons'])) { $options['buttons'] = array(); for ($i = 0; $i < 4; $i++) { array_push($options['buttons'], $this->buttons[$i]); } } } $options['customLocale'] = get_option(self::OPTION_NAME_CUSTOM_LOCALE); $options['placement'] = get_option(self::OPTION_NAME_PLACEMENT); $options['shortcode'] = get_option(self::OPTION_NAME_SHORTCODE) == 'enabled'; $options['excerpts'] = get_option(self::OPTION_NAME_EXCERPTS) == 'enabled'; $defaultValues = array( 'look' => 'h', 'skin' => 'classic', 'twitterVia' => '', 'twitterRel' => '' ); foreach ($defaultValues as $key => $value) { if (!isset($options[$key]) || !$options[$key]) { $options[$key] = $value; } } $this->options = $options; } function load_deprecated_options() { if (!get_option('sociallikes_skin') || !get_option('sociallikes_look')) { return null; } $options = array( 'skin' => get_option('sociallikes_skin'), 'look' => get_option('sociallikes_look'), 'post' => get_option('sociallikes_post'), 'page' => get_option('sociallikes_page'), 'pinterestImg' => get_option('sociallikes_pinterest_img'), 'twitterVia' => get_option('sociallikes_twitter_via'), 'twitterRel' => get_option('sociallikes_twitter_rel'), 'iconsOnly' => get_option('sociallikes_icons'), 'counters' => get_option('sociallikes_counters'), 'zeroes' => get_option('sociallikes_zeroes'), 'buttons' => array() ); for ($i = 1; $i <= 8; $i++) { $option = 'pos' . $i; $btn = get_option($option); if (get_option($btn)) { array_push($options['buttons'], $btn); } } return $options; } function delete_deprecated_options() { delete_option('sociallikes_counters'); delete_option('sociallikes_look'); delete_option('sociallikes_twitter_via'); delete_option('sociallikes_twitter_rel'); delete_option('sociallikes_pinterest_img'); delete_option('sociallikes_post'); delete_option('sociallikes_page'); delete_option('sociallikes_skin'); delete_option('sociallikes_icons'); delete_option('sociallikes_zeroes'); delete_option('vk_btn'); delete_option('facebook_btn'); delete_option('twitter_btn'); delete_option('google_btn'); delete_option('pinterest_btn'); delete_option('lj_btn'); delete_option('odn_btn'); delete_option('mm_btn'); delete_option('pos1'); delete_option('pos2'); delete_option('pos3'); delete_option('pos4'); delete_option('pos5'); delete_option('pos6'); delete_option('pos7'); delete_option('pos8'); } } $wpsociallikes = new wpsociallikes(); function social_likes($postId = null) { echo get_social_likes($postId); } function get_social_likes($postId = null) { $post = get_post($postId); global $wpsociallikes; return $post != null ? $wpsociallikes->build_buttons($post) : ''; } ?>
tienthai0511/talk
wp-content/plugins/wp-social-likes/wp-social-likes.php
PHP
gpl-2.0
33,776
// // LVKDefaultMessageStickerItem.h // VKMessenger // // Created by Eliah Nikans on 6/9/14. // Copyright (c) 2014 Levelab. All rights reserved. // #import "LVKMessageItemProtocol.h" @interface LVKDefaultMessageStickerItem : UICollectionViewCell <LVKMessageItemProtocol> @property (weak, nonatomic) IBOutlet UIImageView *image; @property (weak, nonatomic) IBOutlet NSLayoutConstraint *imageWidthConstraint; @end
CocoaHeadsMsk/vkmessenger
VKMessenger/LVKDefaultMessageStickerItem.h
C
gpl-2.0
420
<?php /** * VuFind Statistics Class for Record Views * * PHP version 5 * * Copyright (C) Villanova University 2009. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @category VuFind2 * @package Statistics * @author Chris Hallberg <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org/wiki/system_classes Wiki */ namespace VuFind\Statistics; /** * VuFind Statistics Class for Record Views * * @category VuFind2 * @package Statistics * @author Chris Hallberg <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org/wiki/system_classes Wiki */ class Record extends AbstractBase { /** * Saves the record view to wherever the config [Statistics] says so * * @param \VuFind\Search\Base\Results $data Results from Search controller * @param Zend_Controller_Request_Http $request Request data * * @return void */ public function log($data, $request) { $this->save( array( 'recordId' => $data->getUniqueId(), 'recordSource' => $data->getResourceSource() ), $request ); } /** * Returns a set of basic statistics including total records * and most commonly viewed records. * * @param integer $listLength How long the top list is * @param bool $bySource Sort record views by source? * * @return array */ public function getStatsSummary($listLength = 5, $bySource = false) { foreach ($this->getDrivers() as $driver) { $summary = $driver->getFullList('recordId'); if (!empty($summary)) { $sources = $driver->getFullList('recordSource'); $hashes = array(); // Generate hashes (faster than grouping by looping) for ($i=0;$i<count($summary);$i++) { $source = $sources[$i]['recordSource']; $id = $summary[$i]['recordId']; $hashes[$source][$id] = isset($hashes[$source][$id]) ? $hashes[$source][$id] + 1 : 1; } $top = array(); // For each source foreach ($hashes as $source=>$records) { // Using a reference to consolidate code dramatically $reference =& $top; if ($bySource) { $top[$source] = array(); $reference =& $top[$source]; } // For each record foreach ($records as $id=>$count) { $newRecord = array( 'value' => $id, 'count' => $count, 'source' => $source ); // Insert sort (limit to listLength) for ($i=0;$i<$listLength-1 && $i<count($reference);$i++) { if ($count > $reference[$i]['count']) { // Insert in order array_splice($reference, $i, 0, array($newRecord)); continue 2; // Skip the append after this loop } } if (count($reference) < $listLength) { $reference[] = $newRecord; } } $reference = array_slice($reference, 0, $listLength); } return array( 'top' => $top, 'total' => count($summary) ); } } return array(); } }
no-reply/cbpl-vufind
module/VuFind/src/VuFind/Statistics/Record.php
PHP
gpl-2.0
4,569
<?php /** * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. */ namespace eZ\Publish\Core\Base\Container\Compiler\Search\Legacy; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Definition; /** * This compiler pass will register Legacy Search Engine criterion handlers. */ class CriteriaConverterPass implements CompilerPassInterface { /** * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container */ public function process(ContainerBuilder $container) { if ( !$container->hasDefinition('ezpublish.search.legacy.gateway.criteria_converter.content') && !$container->hasDefinition('ezpublish.search.legacy.gateway.criteria_converter.location') && !$container->hasDefinition('ezplatform.trash.search.legacy.gateway.criteria_converter') && !$container->hasDefinition('ezpublish.spi.persistence.legacy.url.criterion_converter') ) { return; } if ($container->hasDefinition('ezpublish.search.legacy.gateway.criteria_converter.content')) { $criteriaConverterContent = $container->getDefinition('ezpublish.search.legacy.gateway.criteria_converter.content'); $contentHandlers = $container->findTaggedServiceIds('ezpublish.search.legacy.gateway.criterion_handler.content'); $this->addHandlers($criteriaConverterContent, $contentHandlers); } if ($container->hasDefinition('ezpublish.search.legacy.gateway.criteria_converter.location')) { $criteriaConverterLocation = $container->getDefinition('ezpublish.search.legacy.gateway.criteria_converter.location'); $locationHandlers = $container->findTaggedServiceIds('ezpublish.search.legacy.gateway.criterion_handler.location'); $this->addHandlers($criteriaConverterLocation, $locationHandlers); } if ($container->hasDefinition('ezplatform.trash.search.legacy.gateway.criteria_converter')) { $trashCriteriaConverter = $container->getDefinition('ezplatform.trash.search.legacy.gateway.criteria_converter'); $trashCriteriaHandlers = $container->findTaggedServiceIds('ezplatform.trash.search.legacy.gateway.criterion_handler'); $this->addHandlers($trashCriteriaConverter, $trashCriteriaHandlers); } if ($container->hasDefinition('ezpublish.spi.persistence.legacy.url.criterion_converter')) { $urlCriteriaConverter = $container->getDefinition('ezpublish.spi.persistence.legacy.url.criterion_converter'); $urlCriteriaHandlers = $container->findTaggedServiceIds('ezpublish.persistence.legacy.url.criterion_handler'); $this->addHandlers($urlCriteriaConverter, $urlCriteriaHandlers); } } protected function addHandlers(Definition $definition, $handlers) { foreach ($handlers as $id => $attributes) { $definition->addMethodCall('addHandler', [new Reference($id)]); } } }
gggeek/ezpublish-kernel
eZ/Publish/Core/Base/Container/Compiler/Search/Legacy/CriteriaConverterPass.php
PHP
gpl-2.0
3,289
#ifndef UI_UNDOVIEW_H #define UI_UNDOVIEW_H #include <QtWidgets/QUndoView> namespace ui { class UndoView : public QUndoView { Q_OBJECT public: explicit UndoView(QWidget *parent = 0); signals: public slots: }; } // namespace ui #endif // UI_UNDOVIEW_H
jablonkai/dbFlow
src/gui/undoview.h
C
gpl-2.0
279
<?php global $post; if( tie_get_option( 'archives_socail' ) ):?> <div class="mini-share-post"> <ul> <li><a href="https://twitter.com/share" class="twitter-share-button" data-url="<?php the_permalink(); ?>" data-text="<?php the_title(); ?>" data-via="<?php echo tie_get_option( 'share_twitter_username' ) ?>" data-lang="en">tweet</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script></li> <li> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="fb-like" data-href="<?php the_permalink(); ?>" data-send="false" data-layout="button_count" data-width="90" data-show-faces="false"></div> </li> <li><div class="g-plusone" data-size="medium" data-href="<?php the_permalink(); ?>"></div> <script type='text/javascript'> (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> </li> <li><script type="text/javascript" src="http://assets.pinterest.com/js/pinit.js"></script><a href="http://pinterest.com/pin/create/button/?url=<?php the_permalink(); ?>&amp;media=<?php echo tie_thumb_src('', 660 ,330); ?>" class="pin-it-button" count-layout="horizontal"><img border="0" src="http://assets.pinterest.com/images/PinExt.png" title="Pin It" /></a></li> </ul> </div> <!-- .share-post --> <?php endif; ?>
axsauze/HackaSoton
wp-content/themes/sahifa/includes/post-share.php
PHP
gpl-2.0
1,973
/* * Driver for the SGS-Thomson M48T35 Timekeeper RAM chip * * Real Time Clock interface for Linux * * TODO: Implement periodic interrupts. * * Copyright (C) 2000 Silicon Graphics, Inc. * Written by Ulf Carlsson ([email protected]) * * Based on code written by Paul Gortmaker. * * This driver allows use of the real time clock (built into * nearly all computers) from user space. It exports the /dev/rtc * interface supporting various ioctl() and also the /proc/rtc * pseudo-file for status 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. * */ #define RTC_VERSION "1.09b" #include <linux/bcd.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/smp_lock.h> #include <linux/types.h> #include <linux/miscdevice.h> #include <linux/ioport.h> #include <linux/fcntl.h> #include <linux/rtc.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/proc_fs.h> #include <asm/m48t35.h> #include <asm/sn/ioc3.h> #include <asm/io.h> #include <asm/uaccess.h> #include <asm/system.h> #include <asm/sn/klconfig.h> #include <asm/sn/sn0/ip27.h> #include <asm/sn/sn0/hub.h> #include <asm/sn/sn_private.h> static long rtc_ioctl(struct file *filp, unsigned int cmd, unsigned long arg); static int rtc_read_proc(char *page, char **start, off_t off, int count, int *eof, void *data); static void get_rtc_time(struct rtc_time *rtc_tm); /* * Bits in rtc_status. (6 bits of room for future expansion) */ #define RTC_IS_OPEN 0x01 /* means /dev/rtc is in use */ #define RTC_TIMER_ON 0x02 /* missed irq timer active */ static unsigned char rtc_status; /* bitmapped status byte. */ static unsigned long rtc_freq; /* Current periodic IRQ rate */ static struct m48t35_rtc *rtc; /* * If this driver ever becomes modularised, it will be really nice * to make the epoch retain its value across module reload... */ static unsigned long epoch = 1970; /* year corresponding to 0x00 */ static const unsigned char days_in_mo[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; static long rtc_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct rtc_time wtime; switch (cmd) { case RTC_RD_TIME: /* Read the time/date from RTC */ { get_rtc_time(&wtime); break; } case RTC_SET_TIME: /* Set the RTC */ { struct rtc_time rtc_tm; unsigned char mon, day, hrs, min, sec, leap_yr; unsigned int yrs; if (!capable(CAP_SYS_TIME)) return -EACCES; if (copy_from_user(&rtc_tm, (struct rtc_time*)arg, sizeof(struct rtc_time))) return -EFAULT; yrs = rtc_tm.tm_year + 1900; mon = rtc_tm.tm_mon + 1; /* tm_mon starts at zero */ day = rtc_tm.tm_mday; hrs = rtc_tm.tm_hour; min = rtc_tm.tm_min; sec = rtc_tm.tm_sec; if (yrs < 1970) return -EINVAL; leap_yr = ((!(yrs % 4) && (yrs % 100)) || !(yrs % 400)); if ((mon > 12) || (day == 0)) return -EINVAL; if (day > (days_in_mo[mon] + ((mon == 2) && leap_yr))) return -EINVAL; if ((hrs >= 24) || (min >= 60) || (sec >= 60)) return -EINVAL; if ((yrs -= epoch) > 255) /* They are unsigned */ return -EINVAL; if (yrs > 169) return -EINVAL; if (yrs >= 100) yrs -= 100; sec = bin2bcd(sec); min = bin2bcd(min); hrs = bin2bcd(hrs); day = bin2bcd(day); mon = bin2bcd(mon); yrs = bin2bcd(yrs); spin_lock_irq(&rtc_lock); rtc->control |= M48T35_RTC_SET; rtc->year = yrs; rtc->month = mon; rtc->date = day; rtc->hour = hrs; rtc->min = min; rtc->sec = sec; rtc->control &= ~M48T35_RTC_SET; spin_unlock_irq(&rtc_lock); return 0; } default: return -EINVAL; } return copy_to_user((void *)arg, &wtime, sizeof wtime) ? -EFAULT : 0; } /* * We enforce only one user at a time here with the open/close. * Also clear the previous interrupt data on an open, and clean * up things on a close. */ static int rtc_open(struct inode *inode, struct file *file) { lock_kernel(); spin_lock_irq(&rtc_lock); if (rtc_status & RTC_IS_OPEN) { spin_unlock_irq(&rtc_lock); unlock_kernel(); return -EBUSY; } rtc_status |= RTC_IS_OPEN; spin_unlock_irq(&rtc_lock); unlock_kernel(); return 0; } static int rtc_release(struct inode *inode, struct file *file) { /* * Turn off all interrupts once the device is no longer * in use, and clear the data. */ spin_lock_irq(&rtc_lock); rtc_status &= ~RTC_IS_OPEN; spin_unlock_irq(&rtc_lock); return 0; } /* * The various file operations we support. */ static const struct file_operations rtc_fops = { .owner = THIS_MODULE, .unlocked_ioctl = rtc_ioctl, .open = rtc_open, .release = rtc_release, }; static struct miscdevice rtc_dev= { RTC_MINOR, "rtc", &rtc_fops }; static int __init rtc_init(void) { rtc = (struct m48t35_rtc *) (KL_CONFIG_CH_CONS_INFO(master_nasid)->memory_base + IOC3_BYTEBUS_DEV0); printk(KERN_INFO "Real Time Clock Driver v%s\n", RTC_VERSION); if (misc_register(&rtc_dev)) { printk(KERN_ERR "rtc: cannot register misc device.\n"); return -ENODEV; } if (!create_proc_read_entry("driver/rtc", 0, NULL, rtc_read_proc, NULL)) { printk(KERN_ERR "rtc: cannot create /proc/rtc.\n"); misc_deregister(&rtc_dev); return -ENOENT; } rtc_freq = 1024; return 0; } static void __exit rtc_exit (void) { /* interrupts and timer disabled at this point by rtc_release */ remove_proc_entry ("rtc", NULL); misc_deregister(&rtc_dev); } module_init(rtc_init); module_exit(rtc_exit); /* * Info exported via "/proc/rtc". */ static int rtc_get_status(char *buf) { char *p; struct rtc_time tm; /* * Just emulate the standard /proc/rtc */ p = buf; get_rtc_time(&tm); /* * There is no way to tell if the luser has the RTC set for local * time or for Universal Standard Time (GMT). Probably local though. */ p += sprintf(p, "rtc_time\t: %02d:%02d:%02d\n" "rtc_date\t: %04d-%02d-%02d\n" "rtc_epoch\t: %04lu\n" "24hr\t\t: yes\n", tm.tm_hour, tm.tm_min, tm.tm_sec, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, epoch); return p - buf; } static int rtc_read_proc(char *page, char **start, off_t off, int count, int *eof, void *data) { int len = rtc_get_status(page); if (len <= off+count) *eof = 1; *start = page + off; len -= off; if (len>count) len = count; if (len<0) len = 0; return len; } static void get_rtc_time(struct rtc_time *rtc_tm) { /* * Do we need to wait for the last update to finish? */ /* * Only the values that we read from the RTC are set. We leave * tm_wday, tm_yday and tm_isdst untouched. Even though the * RTC has RTC_DAY_OF_WEEK, we ignore it, as it is only updated * by the RTC when initially set to a non-zero value. */ spin_lock_irq(&rtc_lock); rtc->control |= M48T35_RTC_READ; rtc_tm->tm_sec = rtc->sec; rtc_tm->tm_min = rtc->min; rtc_tm->tm_hour = rtc->hour; rtc_tm->tm_mday = rtc->date; rtc_tm->tm_mon = rtc->month; rtc_tm->tm_year = rtc->year; rtc->control &= ~M48T35_RTC_READ; spin_unlock_irq(&rtc_lock); rtc_tm->tm_sec = bcd2bin(rtc_tm->tm_sec); rtc_tm->tm_min = bcd2bin(rtc_tm->tm_min); rtc_tm->tm_hour = bcd2bin(rtc_tm->tm_hour); rtc_tm->tm_mday = bcd2bin(rtc_tm->tm_mday); rtc_tm->tm_mon = bcd2bin(rtc_tm->tm_mon); rtc_tm->tm_year = bcd2bin(rtc_tm->tm_year); /* * Account for differences between how the RTC uses the values * and how they are defined in a struct rtc_time; */ if ((rtc_tm->tm_year += (epoch - 1900)) <= 69) rtc_tm->tm_year += 100; rtc_tm->tm_mon--; }
mpalmer/linux-2.6
drivers/char/ip27-rtc.c
C
gpl-2.0
7,743
<!DOCTYPE html> <html> <head> <title>Asterisk Project : Asterisk Standard Channel Variables</title> <link rel="stylesheet" href="styles/site.css" type="text/css" /> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body class="theme-default aui-theme-default"> <div id="page"> <div id="main" class="aui-page-panel"> <div id="main-header"> <div id="breadcrumb-section"> <ol id="breadcrumbs"> <li class="first"> <span><a href="index.html">Asterisk Project</a></span> </li> <li> <span><a href="Configuration-and-Operation_4260139.html">Configuration and Operation</a></span> </li> <li> <span><a href="Channel-Variables_4620340.html">Channel Variables</a></span> </li> </ol> </div> <h1 id="title-heading" class="pagetitle"> <span id="title-text"> Asterisk Project : Asterisk Standard Channel Variables </span> </h1> </div> <div id="content" class="view"> <div class="page-metadata"> Added by mdavenport , edited by mjordan on Aug 11, 2012 </div> <div id="main-content" class="wiki-content group"> <p>There are a number of variables that are defined or read by Asterisk. Here is a listing of them. More information is available in each application's help text. All these variables are in UPPER CASE only.</p> <p>Variables marked with a * are builtin functions and can't be set, only read in the dialplan. Writes to such variables are silently ignored.</p> <h3 id="AsteriskStandardChannelVariables-VariablespresentinAsterisk1.8andforward%3A">Variables present in Asterisk 1.8 and forward:</h3> <ul> <li>${CDR(accountcode)} * - Account code (if specified)</li> <li>${BLINDTRANSFER} - The name of the channel on the other side of a blind transfer</li> <li>${BRIDGEPEER} - Bridged peer</li> <li>${BRIDGEPVTCALLID} - Bridged peer PVT call ID (SIP Call ID if a SIP call)</li> <li>${CALLERID(ani)} * - Caller ANI (PRI channels)</li> <li>${CALLERID(ani2)} * - ANI2 (Info digits) also called Originating line information or OLI</li> <li>${CALLERID(all)} * - Caller ID</li> <li>${CALLERID(dnid)} * - Dialed Number Identifier</li> <li>${CALLERID(name)} * - Caller ID Name only</li> <li>${CALLERID(num)} * - Caller ID Number only</li> <li>${CALLERID(rdnis)} * - Redirected Dial Number ID Service</li> <li>${CALLINGANI2} * - Caller ANI2 (PRI channels)</li> <li>${CALLINGPRES} * - Caller ID presentation for incoming calls (PRI channels)</li> <li>${CALLINGTNS} * - Transit Network Selector (PRI channels)</li> <li>${CALLINGTON} * - Caller Type of Number (PRI channels)</li> <li>${CHANNEL} * - Current channel name</li> <li>${CONTEXT} * - Current context</li> <li>${DATETIME} * - Current date time in the format: DDMMYYYY-HH:MM:SS (Deprecated; use ${STRFTIME(${EPOCH},,%d%m%Y-%H:%M:%S)})</li> <li>${DB_RESULT} - Result value of DB_EXISTS() dial plan function</li> <li>${EPOCH} * - Current unix style epoch</li> <li>${EXTEN} * - Current extension</li> <li>${ENV(VAR)} - Environmental variable VAR</li> <li>${GOTO_ON_BLINDXFR} - Transfer to the specified context/extension/priority after a blind transfer (use ^ characters in place of | to separate context/extension/priority when setting this variable from the dialplan)</li> <li>${HANGUPCAUSE} * - Asterisk cause of hangup (inbound/outbound)</li> <li>${HINT} * - Channel hints for this extension</li> <li>${HINTNAME} * - Suggested Caller*ID name for this extension</li> <li>${INVALID_EXTEN} - The invalid called extension (used in the &quot;i&quot; extension)</li> <li>${LANGUAGE} * - Current language (Deprecated; use ${LANGUAGE()})</li> <li>${LEN(VAR)} - String length of VAR (integer)</li> <li>${PRIORITY} * - Current priority in the dialplan</li> <li>${PRIREDIRECTREASON} - Reason for redirect on PRI, if a call was directed</li> <li>${TIMESTAMP} * - Current date time in the format: YYYYMMDD-HHMMSS (Deprecated; use ${STRFTIME(${EPOCH},,%Y%m%d-%H%M%S)})</li> <li>${TRANSFER_CONTEXT} - Context for transferred calls</li> <li>${FORWARD_CONTEXT} - Context for forwarded calls</li> <li>${DYNAMIC_PEERNAME} - The name of the channel on the other side when a dynamic feature is used.</li> <li>${DYNAMIC_FEATURENAME} The name of the last triggered dynamic feature.</li> <li>${UNIQUEID} * - Current call unique identifier</li> <li>${SYSTEMNAME} * - value of the systemname option of asterisk.conf</li> <li>${ENTITYID} * - Global Entity ID set automatically, or from asterisk.conf</li> </ul> <h3 id="AsteriskStandardChannelVariables-VariablespresentinAsterisk11andforward%3A">Variables present in Asterisk 11 and forward:</h3> <ul> <li>${AGIEXITONHANGUP} - set to <code>1</code> to force the behavior of a call to AGI to behave as it did in 1.4, where the AGI script would exit immediately on detecting a channel hangup</li> <li>${CALENDAR_SUCCESS} * - Status of the <a href="https://wiki.asterisk.org/wiki/display/AST/Asterisk+11+Function_CALENDAR_WRITE">CALENDAR_WRITE</a> function. Set to <code>1</code> if the function completed successfully; <code>0</code> otherwise.</li> <li>${SIP_RECVADDR} * - the address a SIP MESSAGE request was received from</li> <li>${VOICEMAIL_PLAYBACKSTATUS} * - Status of the <a href="https://wiki.asterisk.org/wiki/display/AST/Asterisk+11+Application_VoiceMailPlayMsg">VoiceMailPlayMsg</a> application. <code>SUCCESS</code> if the voicemail was played back successfully, {{FAILED} otherwise</li> </ul> </div> </div> </div> <div id="footer"> <section class="footer-body"> <p>Document generated by Confluence on Dec 20, 2013 14:18</p> </section> </div> </div> </body> </html>
truongduy134/asterisk
doc/Asterisk-Admin-Guide/Asterisk-Standard-Channel-Variables_4620398.html
HTML
gpl-2.0
6,529
<?php class Miscinfo_b extends Lxaclass { static $__desc_realname = array("", "", "real_name"); static $__desc_paddress = array("", "", "personal_address"); static $__desc_padd_city = array("", "", "city"); static $__desc_padd_country = array( "", "", "Country", "Country of the Client"); static $__desc_ptelephone = array("", "", "telephone_no"); static $__desc_caddress = array("", "", "company_address"); static $__desc_cadd_country = array("", "", "country" ); static $__desc_cadd_city = array("", "", "city"); static $__desc_ctelephone = array("", "", "telephone"); static $__desc_cfax = array("", "", "fax"); static $__desc_text_comment = array("t", "", "comments"); } class sp_Miscinfo extends LxSpecialClass { static $__desc = array("","", "miscinfo"); static $__desc_nname = array("", "", "name"); static $__desc_miscinfo_b = array("", "", "personal_info_of_client"); static $__acdesc_update_miscinfo = array("","", "details"); function updateform($subaction, $param) { $vlist['nname']= array('M', $this->getSpecialname()); $vlist['miscinfo_b_s_realname']= ""; $vlist['miscinfo_b_s_paddress']= ""; $vlist['miscinfo_b_s_padd_city']= ""; $vlist['miscinfo_b_s_padd_country']= ""; $vlist['miscinfo_b_s_ptelephone']= ""; $vlist['miscinfo_b_s_caddress']= ""; $vlist['miscinfo_b_s_ctelephone']= ""; $vlist['miscinfo_b_s_cadd_city']= ""; $vlist['miscinfo_b_s_cadd_country']= ""; $vlist['miscinfo_b_s_cfax']= ""; return $vlist; } }
zuoziqi/KloxoST
httpdocs/lib/client/miscinfolib.php
PHP
gpl-2.0
1,486
<?php /** * @version SEBLOD 3.x Core * @package SEBLOD (App Builder & CCK) // SEBLOD nano (Form Builder) * @url https://www.seblod.com * @editor Octopoos - www.octopoos.com * @copyright Copyright (C) 2009 - 2018 SEBLOD. All Rights Reserved. * @license GNU General Public License version 2 or later; see _LICENSE.php **/ defined( '_JEXEC' ) or die; $after_html = '<span class="switch notice">'.JText::_( 'COM_CCK_FIELD_WILL_NOT_BE_LINKED' ).JText::_( 'COM_CCK_FIELD_WILL_BE_LINKED' ).'</span>'; $object = 'joomla_user_group'; echo JCckDev::renderForm( 'core_form', '', $config, array( 'label'=>'Content Type2', 'selectlabel'=>'None', 'options'=>'Linked to Content Type=optgroup', 'options2'=>'{"query":"","table":"#__cck_core_types","name":"title","where":"published=1 AND storage_location=\"'.$object.'\"","value":"name","orderby":"title","orderby_direction":"ASC","limit":"","language_detection":"joomla","language_codes":"EN,GB,US,FR","language_default":"EN"}', 'bool4'=>1, 'required'=>'', 'css'=>'storage-cck-more', 'attributes'=>'disabled="disabled"', 'storage_field'=>'storage_cck' ), array( 'after'=>$after_html ), 'w100' ); ?>
Octopoos/SEBLOD
plugins/cck_storage_location/joomla_user_group/tmpl/edit.php
PHP
gpl-2.0
1,167
/* * File: ShardExceptions.cpp * Author: dagothar * * Created on October 22, 2015, 8:00 PM */ #include "ShardExceptions.hpp" using namespace gripperz::shards;
dagothar/gripperz
src/shards/ShardExceptions.cpp
C++
gpl-2.0
170
äòR<?php exit; ?>a:6:{s:10:"last_error";s:0:"";s:10:"last_query";s:104:"SELECT ID FROM jj_posts WHERE post_parent = 6 AND post_type = 'page' AND post_status = 'publish' LIMIT 1";s:11:"last_result";a:0:{}s:8:"col_info";a:1:{i:0;O:8:"stdClass":13:{s:4:"name";s:2:"ID";s:5:"table";s:8:"jj_posts";s:3:"def";s:0:"";s:10:"max_length";i:0;s:8:"not_null";i:1;s:11:"primary_key";i:1;s:12:"multiple_key";i:0;s:10:"unique_key";i:0;s:7:"numeric";i:1;s:4:"blob";i:0;s:4:"type";s:3:"int";s:8:"unsigned";i:1;s:8:"zerofill";i:0;}}s:8:"num_rows";i:0;s:10:"return_val";i:0;}
macksfield/NudeAudio
wp-content/cache/db/000000/all/dcd/9ce/dcd9cecc07acdbcfb772254e9aff8b75.php
PHP
gpl-2.0
557
/* sane - Scanner Access Now Easy. Copyright (C) 2002 Frank Zago (sane at zago dot net) This file is part of the SANE package. 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. As a special exception, the authors of SANE give permission for additional uses of the libraries contained in this release of SANE. The exception is that, if you link a SANE library with other files to produce an executable, this does not by itself cause the resulting executable to be covered by the GNU General Public License. Your use of that executable is in no way restricted on account of linking the SANE library code into it. This exception does not, however, invalidate any other reasons why the executable file might be covered by the GNU General Public License. If you submit changes to SANE to the maintainers to be included in a subsequent release, you agree by submitting the changes that those changes may be distributed with this exception intact. If you write modifications of your own for SANE, it is your choice whether to permit this exception to apply to your modifications. If you do not wish that, delete this exception notice. */ /* $Id: leo.h,v 1.4 2005-07-07 11:55:42 fzago-guest Exp $ */ /* Commands supported by the scanner. */ #define SCSI_TEST_UNIT_READY 0x00 #define SCSI_INQUIRY 0x12 #define SCSI_SCAN 0x1b #define SCSI_SET_WINDOW 0x24 #define SCSI_READ_10 0x28 #define SCSI_SEND_10 0x2a #define SCSI_REQUEST_SENSE 0x03 #define SCSI_GET_DATA_BUFFER_STATUS 0x34 typedef struct { unsigned char data[16]; int len; } CDB; /* Set a specific bit depending on a boolean. * MKSCSI_BIT(TRUE, 3) will generate 0x08. */ #define MKSCSI_BIT(bit, pos) ((bit)? 1<<(pos): 0) /* Set a value in a range of bits. * MKSCSI_I2B(5, 3, 5) will generate 0x28 */ #define MKSCSI_I2B(bits, pos_b, pos_e) ((bits) << (pos_b) & ((1<<((pos_e)-(pos_b)+1))-1)) /* Store an integer in 2, 3 or 4 byte in an array. */ #define Ito16(val, buf) { \ ((unsigned char *)buf)[0] = ((val) >> 8) & 0xff; \ ((unsigned char *)buf)[1] = ((val) >> 0) & 0xff; \ } #define Ito24(val, buf) { \ ((unsigned char *)buf)[0] = ((val) >> 16) & 0xff; \ ((unsigned char *)buf)[1] = ((val) >> 8) & 0xff; \ ((unsigned char *)buf)[2] = ((val) >> 0) & 0xff; \ } #define Ito32(val, buf) { \ ((unsigned char *)buf)[0] = ((val) >> 24) & 0xff; \ ((unsigned char *)buf)[1] = ((val) >> 16) & 0xff; \ ((unsigned char *)buf)[2] = ((val) >> 8) & 0xff; \ ((unsigned char *)buf)[3] = ((val) >> 0) & 0xff; \ } #define MKSCSI_GET_DATA_BUFFER_STATUS(cdb, wait, buflen) \ cdb.data[0] = SCSI_GET_DATA_BUFFER_STATUS; \ cdb.data[1] = MKSCSI_BIT(wait, 0); \ cdb.data[2] = 0; \ cdb.data[3] = 0; \ cdb.data[4] = 0; \ cdb.data[5] = 0; \ cdb.data[6] = 0; \ cdb.data[7] = (((buflen) >> 8) & 0xff); \ cdb.data[8] = (((buflen) >> 0) & 0xff); \ cdb.data[9] = 0; \ cdb.len = 10; #define MKSCSI_INQUIRY(cdb, buflen) \ cdb.data[0] = SCSI_INQUIRY; \ cdb.data[1] = 0; \ cdb.data[2] = 0; \ cdb.data[3] = 0; \ cdb.data[4] = buflen; \ cdb.data[5] = 0; \ cdb.len = 6; #define MKSCSI_SCAN(cdb) \ cdb.data[0] = SCSI_SCAN; \ cdb.data[1] = 0; \ cdb.data[2] = 0; \ cdb.data[3] = 0; \ cdb.data[4] = 0; \ cdb.data[5] = 0; \ cdb.len = 6; #define MKSCSI_SEND_10(cdb, dtc, dtq, buflen) \ cdb.data[0] = SCSI_SEND_10; \ cdb.data[1] = 0; \ cdb.data[2] = (dtc); \ cdb.data[3] = 0; \ cdb.data[4] = (((dtq) >> 8) & 0xff); \ cdb.data[5] = (((dtq) >> 0) & 0xff); \ cdb.data[6] = (((buflen) >> 16) & 0xff); \ cdb.data[7] = (((buflen) >> 8) & 0xff); \ cdb.data[8] = (((buflen) >> 0) & 0xff); \ cdb.data[9] = 0; \ cdb.len = 10; #define MKSCSI_SET_WINDOW(cdb, buflen) \ cdb.data[0] = SCSI_SET_WINDOW; \ cdb.data[1] = 0; \ cdb.data[2] = 0; \ cdb.data[3] = 0; \ cdb.data[4] = 0; \ cdb.data[5] = 0; \ cdb.data[6] = (((buflen) >> 16) & 0xff); \ cdb.data[7] = (((buflen) >> 8) & 0xff); \ cdb.data[8] = (((buflen) >> 0) & 0xff); \ cdb.data[9] = 0; \ cdb.len = 10; #define MKSCSI_READ_10(cdb, dtc, dtq, buflen) \ cdb.data[0] = SCSI_READ_10; \ cdb.data[1] = 0; \ cdb.data[2] = (dtc); \ cdb.data[3] = 0; \ cdb.data[4] = (((dtq) >> 8) & 0xff); \ cdb.data[5] = (((dtq) >> 0) & 0xff); \ cdb.data[6] = (((buflen) >> 16) & 0xff); \ cdb.data[7] = (((buflen) >> 8) & 0xff); \ cdb.data[8] = (((buflen) >> 0) & 0xff); \ cdb.data[9] = 0; \ cdb.len = 10; #define MKSCSI_REQUEST_SENSE(cdb, buflen) \ cdb.data[0] = SCSI_REQUEST_SENSE; \ cdb.data[1] = 0; \ cdb.data[2] = 0; \ cdb.data[3] = 0; \ cdb.data[4] = (buflen); \ cdb.data[5] = 0; \ cdb.len = 6; #define MKSCSI_TEST_UNIT_READY(cdb) \ cdb.data[0] = SCSI_TEST_UNIT_READY; \ cdb.data[1] = 0; \ cdb.data[2] = 0; \ cdb.data[3] = 0; \ cdb.data[4] = 0; \ cdb.data[5] = 0; \ cdb.len = 6; /*--------------------------------------------------------------------------*/ static int getbitfield(unsigned char *pageaddr, int mask, int shift) { return ((*pageaddr >> shift) & mask); } /* defines for request sense return block */ #define get_RS_information_valid(b) getbitfield(b + 0x00, 1, 7) #define get_RS_error_code(b) getbitfield(b + 0x00, 0x7f, 0) #define get_RS_filemark(b) getbitfield(b + 0x02, 1, 7) #define get_RS_EOM(b) getbitfield(b + 0x02, 1, 6) #define get_RS_ILI(b) getbitfield(b + 0x02, 1, 5) #define get_RS_sense_key(b) getbitfield(b + 0x02, 0x0f, 0) #define get_RS_information(b) getnbyte(b+0x03, 4) #define get_RS_additional_length(b) b[0x07] #define get_RS_ASC(b) b[0x0c] #define get_RS_ASCQ(b) b[0x0d] #define get_RS_SKSV(b) getbitfield(b+0x0f,1,7) /*--------------------------------------------------------------------------*/ #define mmToIlu(mm) (((mm) * dev->x_resolution) / SANE_MM_PER_INCH) #define iluToMm(ilu) (((ilu) * SANE_MM_PER_INCH) / dev->x_resolution) /*--------------------------------------------------------------------------*/ #define GAMMA_LENGTH 0x100 /* number of value per color */ /*--------------------------------------------------------------------------*/ enum Leo_Option { /* Must come first */ OPT_NUM_OPTS = 0, OPT_MODE_GROUP, OPT_MODE, /* scanner modes */ OPT_RESOLUTION, /* X and Y resolution */ OPT_GEOMETRY_GROUP, OPT_TL_X, /* upper left X */ OPT_TL_Y, /* upper left Y */ OPT_BR_X, /* bottom right X */ OPT_BR_Y, /* bottom right Y */ OPT_ENHANCEMENT_GROUP, OPT_CUSTOM_GAMMA, /* Use the custom gamma tables */ OPT_GAMMA_VECTOR_R, /* Custom Red gamma table */ OPT_GAMMA_VECTOR_G, /* Custom Green Gamma table */ OPT_GAMMA_VECTOR_B, /* Custom Blue Gamma table */ OPT_GAMMA_VECTOR_GRAY, /* Custom Gray Gamma table */ OPT_HALFTONE_PATTERN, /* Halftone pattern */ OPT_PREVIEW, /* preview mode */ /* must come last: */ OPT_NUM_OPTIONS }; /*--------------------------------------------------------------------------*/ /* * Scanner supported by this backend. */ struct scanners_supported { int scsi_type; char scsi_vendor[9]; char scsi_product[17]; const char *real_vendor; const char *real_product; }; /*--------------------------------------------------------------------------*/ #define BLACK_WHITE_STR SANE_I18N("Black & White") #define GRAY_STR SANE_I18N("Grayscale") #define COLOR_STR SANE_I18N("Color") /*--------------------------------------------------------------------------*/ /* Define a scanner occurence. */ typedef struct Leo_Scanner { struct Leo_Scanner *next; SANE_Device sane; char *devicename; int sfd; /* device handle */ /* Infos from inquiry. */ char scsi_type; char scsi_vendor[9]; char scsi_product[17]; char scsi_version[5]; SANE_Range res_range; int x_resolution_max; /* maximum X dpi */ int y_resolution_max; /* maximum Y dpi */ /* SCSI handling */ size_t buffer_size; /* size of the buffer */ SANE_Byte *buffer; /* for SCSI transfer. */ /* Scanner infos. */ const struct scanners_supported *def; /* default options for that scanner */ /* Scanning handling. */ int scanning; /* TRUE if a scan is running. */ int x_resolution; /* X resolution in DPI */ int y_resolution; /* Y resolution in DPI */ int x_tl; /* X top left */ int y_tl; /* Y top left */ int x_br; /* X bottom right */ int y_br; /* Y bottom right */ int width; /* width of the scan area in mm */ int length; /* length of the scan area in mm */ int pass; /* current pass number */ enum { LEO_BW, LEO_HALFTONE, LEO_GRAYSCALE, LEO_COLOR } scan_mode; int depth; /* depth per color */ size_t bytes_left; /* number of bytes left to give to the backend */ size_t real_bytes_left; /* number of bytes left the scanner will return. */ SANE_Byte *image; /* keep the raw image here */ size_t image_size; /* allocated size of image */ size_t image_begin; /* first significant byte in image */ size_t image_end; /* first free byte in image */ SANE_Parameters params; /* Options */ SANE_Option_Descriptor opt[OPT_NUM_OPTIONS]; Option_Value val[OPT_NUM_OPTIONS]; /* Gamma table. 1 array per colour. */ SANE_Word gamma_R[GAMMA_LENGTH]; SANE_Word gamma_G[GAMMA_LENGTH]; SANE_Word gamma_B[GAMMA_LENGTH]; SANE_Word gamma_GRAY[GAMMA_LENGTH]; } Leo_Scanner; /*--------------------------------------------------------------------------*/ /* Debug levels. * Should be common to all backends. */ #define DBG_error0 0 #define DBG_error 1 #define DBG_sense 2 #define DBG_warning 3 #define DBG_inquiry 4 #define DBG_info 5 #define DBG_info2 6 #define DBG_proc 7 #define DBG_read 8 #define DBG_sane_init 10 #define DBG_sane_proc 11 #define DBG_sane_info 12 #define DBG_sane_option 13 /*--------------------------------------------------------------------------*/ /* 32 bits from an array to an integer (eg ntohl). */ #define B32TOI(buf) \ ((((unsigned char *)buf)[0] << 24) | \ (((unsigned char *)buf)[1] << 16) | \ (((unsigned char *)buf)[2] << 8) | \ (((unsigned char *)buf)[3] << 0)) #define B24TOI(buf) \ ((((unsigned char *)buf)[0] << 16) | \ (((unsigned char *)buf)[1] << 8) | \ (((unsigned char *)buf)[2] << 0)) #define B16TOI(buf) \ ((((unsigned char *)buf)[0] << 8) | \ (((unsigned char *)buf)[1] << 0)) /*--------------------------------------------------------------------------*/ /* Downloadable halftone patterns */ typedef unsigned char halftone_pattern_t[256]; static const halftone_pattern_t haltfone_pattern_diamond = { 0xF0, 0xE0, 0x60, 0x20, 0x00, 0x19, 0x61, 0xD8, 0xF0, 0xE0, 0x60, 0x20, 0x00, 0x19, 0x61, 0xD8, 0xC0, 0xA0, 0x88, 0x40, 0x38, 0x58, 0x80, 0xB8, 0xC0, 0xA0, 0x88, 0x40, 0x38, 0x58, 0x80, 0xB8, 0x30, 0x50, 0x98, 0xB0, 0xC8, 0xA8, 0x90, 0x48, 0x30, 0x50, 0x98, 0xB0, 0xC8, 0xA8, 0x90, 0x48, 0x08, 0x10, 0x70, 0xD0, 0xF8, 0xE8, 0x68, 0x28, 0x08, 0x10, 0x70, 0xD0, 0xF8, 0xE8, 0x68, 0x28, 0x00, 0x18, 0x78, 0xD8, 0xF0, 0xE0, 0x60, 0x20, 0x00, 0x18, 0x78, 0xD8, 0xF0, 0xE0, 0x60, 0x20, 0x38, 0x58, 0x80, 0xB8, 0xC0, 0xA0, 0x88, 0x40, 0x38, 0x58, 0x80, 0xB8, 0xC0, 0xA0, 0x88, 0x40, 0xC8, 0xA8, 0x90, 0x48, 0x30, 0x50, 0x9B, 0xB0, 0xC8, 0xA8, 0x90, 0x48, 0x30, 0x50, 0x9B, 0xB0, 0xF8, 0xE8, 0x68, 0x28, 0x08, 0x18, 0x70, 0xD0, 0xF8, 0xE8, 0x68, 0x28, 0x08, 0x18, 0x70, 0xD0, 0xF0, 0xE0, 0x60, 0x20, 0x00, 0x19, 0x61, 0xD8, 0xF0, 0xE0, 0x60, 0x20, 0x00, 0x19, 0x61, 0xD8, 0xC0, 0xA0, 0x88, 0x40, 0x38, 0x58, 0x80, 0xB8, 0xC0, 0xA0, 0x88, 0x40, 0x38, 0x58, 0x80, 0xB8, 0x30, 0x50, 0x98, 0xB0, 0xC8, 0xA8, 0x90, 0x48, 0x30, 0x50, 0x98, 0xB0, 0xC8, 0xA8, 0x90, 0x48, 0x08, 0x10, 0x70, 0xD0, 0xF8, 0xE8, 0x68, 0x28, 0x08, 0x10, 0x70, 0xD0, 0xF8, 0xE8, 0x68, 0x28, 0x00, 0x18, 0x78, 0xD8, 0xF0, 0xE0, 0x60, 0x20, 0x00, 0x18, 0x78, 0xD8, 0xF0, 0xE0, 0x60, 0x20, 0x38, 0x58, 0x80, 0xB8, 0xC0, 0xA0, 0x88, 0x40, 0x38, 0x58, 0x80, 0xB8, 0xC0, 0xA0, 0x88, 0x40, 0xC8, 0xA8, 0x90, 0x48, 0x30, 0x50, 0x9B, 0xB0, 0xC8, 0xA8, 0x90, 0x48, 0x30, 0x50, 0x9B, 0xB0, 0xF8, 0xE8, 0x68, 0x28, 0x08, 0x18, 0x70, 0xD0, 0xF8, 0xE8, 0x68, 0x28, 0x08, 0x18, 0x70, 0xD0 }; static const halftone_pattern_t haltfone_pattern_8x8_Coarse_Fatting = { 0x12, 0x3A, 0xD2, 0xEA, 0xE2, 0xB6, 0x52, 0x1A, 0x12, 0x3A, 0xD2, 0xEA, 0xE2, 0xB6, 0x52, 0x1A, 0x42, 0x6A, 0x9A, 0xCA, 0xC2, 0x92, 0x72, 0x4A, 0x42, 0x6A, 0x9A, 0xCA, 0xC2, 0x92, 0x72, 0x4A, 0xAE, 0x8E, 0x7E, 0x26, 0x2E, 0x66, 0x86, 0xA6, 0xAE, 0x8E, 0x7E, 0x26, 0x2E, 0x66, 0x86, 0xA6, 0xFA, 0xBA, 0x5E, 0x06, 0x0E, 0x36, 0xDE, 0xF6, 0xFA, 0xBA, 0x5E, 0x06, 0x0E, 0x36, 0xDE, 0xF6, 0xE6, 0xBE, 0x56, 0x1E, 0x16, 0x3E, 0xD6, 0xEE, 0xE6, 0xBE, 0x56, 0x1E, 0x16, 0x3E, 0xD6, 0xEE, 0xC6, 0x96, 0x76, 0x4E, 0x46, 0x6E, 0x9E, 0xCE, 0xC6, 0x96, 0x76, 0x4E, 0x46, 0x6E, 0x9E, 0xCE, 0x2A, 0x62, 0x82, 0xA2, 0xAA, 0x8A, 0x7A, 0x22, 0x2A, 0x62, 0x82, 0xA2, 0xAA, 0x8A, 0x7A, 0x22, 0x0A, 0x32, 0xDA, 0xF2, 0xFE, 0xB2, 0x5A, 0x02, 0x0A, 0x32, 0xDA, 0xF2, 0xFE, 0xB2, 0x5A, 0x02, 0x12, 0x3A, 0xD2, 0xEA, 0xE2, 0xB6, 0x52, 0x1A, 0x12, 0x3A, 0xD2, 0xEA, 0xE2, 0xB6, 0x52, 0x1A, 0x42, 0x6A, 0x9A, 0xCA, 0xC2, 0x92, 0x72, 0x4A, 0x42, 0x6A, 0x9A, 0xCA, 0xC2, 0x92, 0x72, 0x4A, 0xAE, 0x8E, 0x7E, 0x26, 0x2E, 0x66, 0x86, 0xA6, 0xAE, 0x8E, 0x7E, 0x26, 0x2E, 0x66, 0x86, 0xA6, 0xFA, 0xBA, 0x5E, 0x06, 0x0E, 0x36, 0xDE, 0xF6, 0xFA, 0xBA, 0x5E, 0x06, 0x0E, 0x36, 0xDE, 0xF6, 0xE6, 0xBE, 0x56, 0x1E, 0x16, 0x3E, 0xD6, 0xEE, 0xE6, 0xBE, 0x56, 0x1E, 0x16, 0x3E, 0xD6, 0xEE, 0xC6, 0x96, 0x76, 0x4E, 0x46, 0x6E, 0x9E, 0xCE, 0xC6, 0x96, 0x76, 0x4E, 0x46, 0x6E, 0x9E, 0xCE, 0x2A, 0x62, 0x82, 0xA2, 0xAA, 0x8A, 0x7A, 0x22, 0x2A, 0x62, 0x82, 0xA2, 0xAA, 0x8A, 0x7A, 0x22, 0x0A, 0x32, 0xDA, 0xF2, 0xFE, 0xB2, 0x5A, 0x02, 0x0A, 0x32, 0xDA, 0xF2, 0xFE, 0xB2, 0x5A, 0x02 }; static const halftone_pattern_t haltfone_pattern_8x8_Fine_Fatting = { 0x02, 0x22, 0x92, 0xB2, 0x0A, 0x2A, 0x9A, 0xBA, 0x02, 0x22, 0x92, 0xB2, 0x0A, 0x2A, 0x9A, 0xBA, 0x42, 0x62, 0xD2, 0xF2, 0x4A, 0x6A, 0xDA, 0xFA, 0x42, 0x62, 0xD2, 0xF2, 0x4A, 0x6A, 0xDA, 0xFA, 0x82, 0xA2, 0x12, 0x32, 0x8A, 0xAA, 0x1A, 0x3A, 0x82, 0xA2, 0x12, 0x32, 0x8A, 0xAA, 0x1A, 0x3A, 0xC2, 0xE2, 0x52, 0x72, 0xCA, 0xEA, 0x5A, 0x7A, 0xC2, 0xE2, 0x52, 0x72, 0xCA, 0xEA, 0x5A, 0x7A, 0x0E, 0x2E, 0x9E, 0xBE, 0x06, 0x26, 0x96, 0xB6, 0x0E, 0x2E, 0x9E, 0xBE, 0x06, 0x26, 0x96, 0xB6, 0x4C, 0x6E, 0xDE, 0xFE, 0x46, 0x66, 0xD6, 0xF6, 0x4C, 0x6E, 0xDE, 0xFE, 0x46, 0x66, 0xD6, 0xF6, 0x8E, 0xAE, 0x1E, 0x3E, 0x86, 0xA6, 0x16, 0x36, 0x8E, 0xAE, 0x1E, 0x3E, 0x86, 0xA6, 0x16, 0x36, 0xCE, 0xEE, 0x60, 0x7E, 0xC6, 0xE6, 0x56, 0x76, 0xCE, 0xEE, 0x60, 0x7E, 0xC6, 0xE6, 0x56, 0x76, 0x02, 0x22, 0x92, 0xB2, 0x0A, 0x2A, 0x9A, 0xBA, 0x02, 0x22, 0x92, 0xB2, 0x0A, 0x2A, 0x9A, 0xBA, 0x42, 0x62, 0xD2, 0xF2, 0x4A, 0x6A, 0xDA, 0xFA, 0x42, 0x62, 0xD2, 0xF2, 0x4A, 0x6A, 0xDA, 0xFA, 0x82, 0xA2, 0x12, 0x32, 0x8A, 0xAA, 0x1A, 0x3A, 0x82, 0xA2, 0x12, 0x32, 0x8A, 0xAA, 0x1A, 0x3A, 0xC2, 0xE2, 0x52, 0x72, 0xCA, 0xEA, 0x5A, 0x7A, 0xC2, 0xE2, 0x52, 0x72, 0xCA, 0xEA, 0x5A, 0x7A, 0x0E, 0x2E, 0x9E, 0xBE, 0x06, 0x26, 0x96, 0xB6, 0x0E, 0x2E, 0x9E, 0xBE, 0x06, 0x26, 0x96, 0xB6, 0x4C, 0x6E, 0xDE, 0xFE, 0x46, 0x66, 0xD6, 0xF6, 0x4C, 0x6E, 0xDE, 0xFE, 0x46, 0x66, 0xD6, 0xF6, 0x8E, 0xAE, 0x1E, 0x3E, 0x86, 0xA6, 0x16, 0x36, 0x8E, 0xAE, 0x1E, 0x3E, 0x86, 0xA6, 0x16, 0x36, 0xCE, 0xEE, 0x60, 0x7E, 0xC6, 0xE6, 0x56, 0x76, 0xCE, 0xEE, 0x60, 0x7E, 0xC6, 0xE6, 0x56, 0x76 }; static const halftone_pattern_t haltfone_pattern_8x8_Bayer = { 0xF2, 0x42, 0x82, 0xC2, 0xFA, 0x4A, 0x8A, 0xCA, 0xF2, 0x42, 0x82, 0xC2, 0xFA, 0x4A, 0x8A, 0xCA, 0xB2, 0x02, 0x12, 0x52, 0xBA, 0x0A, 0x1A, 0x5A, 0xB2, 0x02, 0x12, 0x52, 0xBA, 0x0A, 0x1A, 0x5A, 0x72, 0x32, 0x22, 0x92, 0x7A, 0x3A, 0x2A, 0x9A, 0x72, 0x32, 0x22, 0x92, 0x7A, 0x3A, 0x2A, 0x9A, 0xE2, 0xA2, 0x62, 0xD2, 0xEA, 0xAA, 0x6A, 0xDA, 0xE2, 0xA2, 0x62, 0xD2, 0xEA, 0xAA, 0x6A, 0xDA, 0xFE, 0x4E, 0x8E, 0xCE, 0xF6, 0x46, 0xD6, 0xC6, 0xFE, 0x4E, 0x8E, 0xCE, 0xF6, 0x46, 0xD6, 0xC6, 0xBE, 0x0E, 0x1E, 0x5E, 0xB6, 0x06, 0x16, 0x56, 0xBE, 0x0E, 0x1E, 0x5E, 0xB6, 0x06, 0x16, 0x56, 0x7E, 0x3E, 0x2E, 0x9E, 0x76, 0x36, 0x26, 0x96, 0x7E, 0x3E, 0x2E, 0x9E, 0x76, 0x36, 0x26, 0x96, 0xEE, 0xAE, 0x6E, 0xDE, 0xE6, 0xA6, 0x66, 0xD6, 0xEE, 0xAE, 0x6E, 0xDE, 0xE6, 0xA6, 0x66, 0xD6, 0xF2, 0x42, 0x82, 0xC2, 0xFA, 0x4A, 0x8A, 0xCA, 0xF2, 0x42, 0x82, 0xC2, 0xFA, 0x4A, 0x8A, 0xCA, 0xB2, 0x02, 0x12, 0x52, 0xBA, 0x0A, 0x1A, 0x5A, 0xB2, 0x02, 0x12, 0x52, 0xBA, 0x0A, 0x1A, 0x5A, 0x72, 0x32, 0x22, 0x92, 0x7A, 0x3A, 0x2A, 0x9A, 0x72, 0x32, 0x22, 0x92, 0x7A, 0x3A, 0x2A, 0x9A, 0xE2, 0xA2, 0x62, 0xD2, 0xEA, 0xAA, 0x6A, 0xDA, 0xE2, 0xA2, 0x62, 0xD2, 0xEA, 0xAA, 0x6A, 0xDA, 0xFE, 0x4E, 0x8E, 0xCE, 0xF6, 0x46, 0xD6, 0xC6, 0xFE, 0x4E, 0x8E, 0xCE, 0xF6, 0x46, 0xD6, 0xC6, 0xBE, 0x0E, 0x1E, 0x5E, 0xB6, 0x06, 0x16, 0x56, 0xBE, 0x0E, 0x1E, 0x5E, 0xB6, 0x06, 0x16, 0x56, 0x7E, 0x3E, 0x2E, 0x9E, 0x76, 0x36, 0x26, 0x96, 0x7E, 0x3E, 0x2E, 0x9E, 0x76, 0x36, 0x26, 0x96, 0xEE, 0xAE, 0x6E, 0xDE, 0xE6, 0xA6, 0x66, 0xD6, 0xEE, 0xAE, 0x6E, 0xDE, 0xE6, 0xA6, 0x66, 0xD6 }; static const halftone_pattern_t haltfone_pattern_8x8_Vertical_Line = { 0x02, 0x42, 0x82, 0xC4, 0x0A, 0x4C, 0x8A, 0xCA, 0x02, 0x42, 0x82, 0xC4, 0x0A, 0x4C, 0x8A, 0xCA, 0x12, 0x52, 0x92, 0xD2, 0x1A, 0x5A, 0x9A, 0xDA, 0x12, 0x52, 0x92, 0xD2, 0x1A, 0x5A, 0x9A, 0xDA, 0x22, 0x62, 0xA2, 0xE2, 0x2A, 0x6A, 0xAA, 0xEA, 0x22, 0x62, 0xA2, 0xE2, 0x2A, 0x6A, 0xAA, 0xEA, 0x32, 0x72, 0xB2, 0xF2, 0x3A, 0x7A, 0xBA, 0xFA, 0x32, 0x72, 0xB2, 0xF2, 0x3A, 0x7A, 0xBA, 0xFA, 0x0E, 0x4E, 0x8E, 0xCE, 0x06, 0x46, 0x86, 0xC6, 0x0E, 0x4E, 0x8E, 0xCE, 0x06, 0x46, 0x86, 0xC6, 0x1E, 0x5E, 0x9E, 0xDE, 0x16, 0x56, 0x96, 0xD6, 0x1E, 0x5E, 0x9E, 0xDE, 0x16, 0x56, 0x96, 0xD6, 0x2E, 0x6E, 0xAE, 0xEE, 0x26, 0x66, 0xA6, 0xE6, 0x2E, 0x6E, 0xAE, 0xEE, 0x26, 0x66, 0xA6, 0xE6, 0x3E, 0x7E, 0xBE, 0xFE, 0x36, 0x76, 0xB6, 0xF6, 0x3E, 0x7E, 0xBE, 0xFE, 0x36, 0x76, 0xB6, 0xF6, 0x02, 0x42, 0x82, 0xC4, 0x0A, 0x4C, 0x8A, 0xCA, 0x02, 0x42, 0x82, 0xC4, 0x0A, 0x4C, 0x8A, 0xCA, 0x12, 0x52, 0x92, 0xD2, 0x1A, 0x5A, 0x9A, 0xDA, 0x12, 0x52, 0x92, 0xD2, 0x1A, 0x5A, 0x9A, 0xDA, 0x22, 0x62, 0xA2, 0xE2, 0x2A, 0x6A, 0xAA, 0xEA, 0x22, 0x62, 0xA2, 0xE2, 0x2A, 0x6A, 0xAA, 0xEA, 0x32, 0x72, 0xB2, 0xF2, 0x3A, 0x7A, 0xBA, 0xFA, 0x32, 0x72, 0xB2, 0xF2, 0x3A, 0x7A, 0xBA, 0xFA, 0x0E, 0x4E, 0x8E, 0xCE, 0x06, 0x46, 0x86, 0xC6, 0x0E, 0x4E, 0x8E, 0xCE, 0x06, 0x46, 0x86, 0xC6, 0x1E, 0x5E, 0x9E, 0xDE, 0x16, 0x56, 0x96, 0xD6, 0x1E, 0x5E, 0x9E, 0xDE, 0x16, 0x56, 0x96, 0xD6, 0x2E, 0x6E, 0xAE, 0xEE, 0x26, 0x66, 0xA6, 0xE6, 0x2E, 0x6E, 0xAE, 0xEE, 0x26, 0x66, 0xA6, 0xE6, 0x3E, 0x7E, 0xBE, 0xFE, 0x36, 0x76, 0xB6, 0xF6, 0x3E, 0x7E, 0xBE, 0xFE, 0x36, 0x76, 0xB6, 0xF6 };
dwery/sane-evolution
backend/leo.h
C
gpl-2.0
19,478
/* * AlwaysLowestAdaptationLogic.cpp ***************************************************************************** * Copyright (C) 2014 - VideoLAN authors * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "AlwaysLowestAdaptationLogic.hpp" #include "Representationselectors.hpp" using namespace adaptative::logic; using namespace adaptative::playlist; AlwaysLowestAdaptationLogic::AlwaysLowestAdaptationLogic(): AbstractAdaptationLogic() { } BaseRepresentation *AlwaysLowestAdaptationLogic::getCurrentRepresentation(BaseAdaptationSet *adaptSet) const { RepresentationSelector selector; return selector.select(adaptSet, 0); }
sachdeep/vlc
modules/demux/adaptative/logic/AlwaysLowestAdaptationLogic.cpp
C++
gpl-2.0
1,424
package com.oa.bean; public class FeedBackInfo { private Long id; private String feedbackinfo; private String userid; private String date; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFeedbackinfo() { return feedbackinfo; } public void setFeedbackinfo(String feedbackinfo) { this.feedbackinfo = feedbackinfo; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } }
yiyuweier/OA-project
src/com/oa/bean/FeedBackInfo.java
Java
gpl-2.0
617
<?php include('../../../operaciones.php'); conectar(); apruebadeintrusos(); if($_SESSION['cargo_user']!="Bodeguero"){ header('Location: ../../../login.php'); } ?> <html lang="en"> <head> <title>PNKS Inventario - Estadística de Productos</title> <!-- BEGIN META --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="keywords" content="your,keywords"> <meta name="description" content="Short explanation about this website"> <!-- END META --> <!-- BEGIN STYLESHEETS --> <link href='http://fonts.googleapis.com/css?family=Roboto:300italic,400italic,300,400,500,700,900' rel='stylesheet' type='text/css'/> <link type="text/css" rel="stylesheet" href="../../../css/bootstrap.css" /> <link type="text/css" rel="stylesheet" href="../../../css/materialadmin.css" /> <link type="text/css" rel="stylesheet" href="../../../css/font-awesome.min.css" /> <link type="text/css" rel="stylesheet" href="../../../css/material-design-iconic-font.min.css" /> <link type="text/css" rel="stylesheet" href="../../../css/libs/DataTables/jquery.dataTables.css" /> <link type="text/css" rel="stylesheet" href="../../../css/libs/DataTables/extensions/dataTables.colVis.css" /> <link type="text/css" rel="stylesheet" href="../../../css/libs/DataTables/extensions/dataTables.tableTools.css" /> <!-- END STYLESHEETS --> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script type="text/javascript" src="js/libs/utils/html5shiv.js?1403934957"></script> <script type="text/javascript" src="js/libs/utils/respond.min.js?1403934956"></script> <![endif]--> </head> <body class="menubar-hoverable header-fixed menubar-first menubar-visible menubar-pin"> <!-- BEGIN HEADER--> <header id="header" > <div class="headerbar"> <!-- Brand and toggle get grouped for better mobile display --> <div class="headerbar-left"> <ul class="header-nav header-nav-options"> <li class="header-nav-brand" > <div class="brand-holder"> <a href=""> <span class="text-lg text-bold text-primary">PNKS LTDA</span> </a> </div> </li> <li> <a class="btn btn-icon-toggle menubar-toggle" data-toggle="menubar" href="javascript:void(0);"> <i class="fa fa-bars"></i> </a> </li> </ul> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="headerbar-right"> <ul class="header-nav header-nav-profile"> <li class="dropdown"> <a href="javascript:void(0);" class="dropdown-toggle ink-reaction" data-toggle="dropdown"> <?php if(file_exists('../../../img/usuarios/'.$_SESSION['foto_user'])){ ?> <img src="../../../img/usuarios/<?php echo $_SESSION['foto_user']; ?>" alt="" /> <?php } else { ?> <img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNzEiIGhlaWdodD0iMTgwIj48cmVjdCB3aWR0aD0iMTcxIiBoZWlnaHQ9IjE4MCIgZmlsbD0iI2VlZSI+PC9yZWN0Pjx0ZXh0IHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9Ijg1LjUiIHk9IjkwIiBzdHlsZT0iZmlsbDojYWFhO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjEycHg7Zm9udC1mYW1pbHk6QXJpYWwsSGVsdmV0aWNhLHNhbnMtc2VyaWY7ZG9taW5hbnQtYmFzZWxpbmU6Y2VudHJhbCI+MTcxeDE4MDwvdGV4dD48L3N2Zz4="/> <?php } ?> <span class="profile-info"> <?php echo $_SESSION['usuario_session']; ?> <small><?php echo $_SESSION['cargo_user']; ?></small> </span> </a> <ul class="dropdown-menu animation-dock"> <li class="dropdown-header">Opciones de Cuenta</li> <li><a href="../../opcion/cambiarclave.php">Cambiar Clave</a></li> <li><a href="../../opcion/cambiarficha.php">Cambiar Datos Personales</a></li> <li><a href="../../opcion/cambiarfoto.php">Cambiar Foto de Perfil</a></li> <li class="divider"></li> <li><a href="../../../login.php" onClick=""><i class="fa fa-fw fa-power-off text-danger"></i> Salir</a></li> </ul><!--end .dropdown-menu --> </li><!--end .dropdown --> </ul><!--end .header-nav-profile --> </div><!--end #header-navbar-collapse --> </div> </header> <!-- END HEADER--> <!-- BEGIN BASE--> <div id="base"> <!-- BEGIN OFFCANVAS LEFT --> <div class="offcanvas"> </div><!--end .offcanvas--> <!-- END OFFCANVAS LEFT --> <!-- BEGIN CONTENT--> <div id="content"> <section> <div class="section-body"> <div class="row"> </div><!--end .row --> </div><!--end .section-body --> </section> </div><!--end #content--> <!-- END CONTENT --> <div id="menubar" class="menubar-first"> <div class="menubar-fixed-panel"> <div> <a class="btn btn-icon-toggle btn-default menubar-toggle" data-toggle="menubar" href="javascript:void(0);"> <i class="fa fa-bars"></i> </a> </div> <div class="expanded"> <a href=""> <span class="text-lg text-bold text-primary ">PNKS&nbsp;LTDA</span> </a> </div> </div> <div class="menubar-scroll-panel"> <!-- BEGIN MAIN MENU --> <ul id="main-menu" class="gui-controls"> <!-- BEGIN DASHBOARD --> <li> <a href="../index.php"> <div class="gui-icon"><i class="md md-home"></i></div> <span class="title">Inicio</span> </a> </li> <li> <a href="../producto.php"> <div class="gui-icon"><i class="md md-web"></i></div> <span class="title">Ficha Producto</span> </a> </li><!--end /menu-li --> <!-- END DASHBOARD --> <!-- BEGIN EMAIL --> <li> <a href="../etiqueta.php"> <div class="gui-icon"><i class="md md-chat"></i></div> <span class="title">Emisión de Etiqueta</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <li> <a href="../bodega.php"> <div class="gui-icon"><i class="glyphicon glyphicon-list-alt"></i></div> <span class="title">Administración de Bodega</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <li> <a href="../reserva.php"> <div class="gui-icon"><i class="md md-view-list"></i></div> <span class="title">Control de Reservas</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <a href="../inventario.php"> <div class="gui-icon"><i class="fa fa-table"></i></div> <span class="title">Inventario</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <a href="../stock.php"> <div class="gui-icon"><i class="md md-assignment-turned-in"></i></div> <span class="title">Control de Stock</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <a href="../precio.php"> <div class="gui-icon"><i class="md md-assignment"></i></div> <span class="title">Lista de Precio</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <a href="../cliente.php"> <div class="gui-icon"><i class="md md-description"></i></div> <span class="title">Ficha Cliente</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li class="gui-folder"> <a> <div class="gui-icon"><i class="md md-assessment"></i></div> <span class="title">Informes</span> </a> <!--start submenu --> <ul> <li><a href="stockbodega.php"><span class="title">Stock por Bodega</span></a></li> <li><a href="guia.php"><span class="title">Entrada y Salida</span></a></li> <li><a href="stock.php"><span class="title">Control de Stock</span></a></li> <li><a href="consumo.php"><span class="title">Consumo Interno</span></a></li> <li><a href="consignacion.php"><span class="title">Consignaciones</span></a></li> <li><a href="estadistica.php" class="active"><span class="title">Estadística de Producto</span></a></li> <li><a href="serie.php"><span class="title">Control de Serie</span></a></li> <li><a href="vencimiento.php" ><span class="title">Vencimiento de Producto</span></a></li> <li><a href="rotacion.php"><span class="title">Rotación de Inventario</span></a></li> <li><a href="toma.php"><span class="title">Toma de Inventario</span></a></li> </ul><!--end /submenu --> </li><!--end /menu-li --> <!-- END EMAIL --> </ul><!--end .main-menu --> <!-- END MAIN MENU --> <div class="menubar-foot-panel"> <small class="no-linebreak hidden-folded"> <span class="opacity-75">&copy; 2015</span> <strong>GH Soluciones Informáticas</strong> </small> </div> </div><!--end .menubar-scroll-panel--> </div><!--end #menubar--> <!-- END MENUBAR --> </div><!--end #base--> <!-- END BASE --> <!-- BEGIN JAVASCRIPT --> <script src="../../../js/libs/jquery/jquery-1.11.2.min.js"></script> <script src="../../../js/libs/jquery/jquery-migrate-1.2.1.min.js"></script> <script src="../../../js/libs/bootstrap/bootstrap.min.js"></script> <script src="../../../js/libs/spin.js/spin.min.js"></script> <script src="../../../js/libs/autosize/jquery.autosize.min.js"></script> <script src="../../../js/libs/DataTables/jquery.dataTables.min.js"></script> <script src="../../../js/libs/DataTables/extensions/ColVis/js/dataTables.colVis.min.js"></script> <script src="../../../js/libs/DataTables/extensions/TableTools/js/dataTables.tableTools.min.js"></script> <script src="../../../js/libs/nanoscroller/jquery.nanoscroller.min.js"></script> <script src="../../../js/core/source/App.js"></script> <script src="../../../js/core/source/AppNavigation.js"></script> <script src="../../../js/core/source/AppOffcanvas.js"></script> <script src="../../../js/core/source/AppCard.js"></script> <script src="../../../js/core/source/AppForm.js"></script> <script src="../../../js/core/source/AppVendor.js"></script> <!-- END JAVASCRIPT --> </body> </html>
DerKow/erp
admin/bodega/informe/estadistica.php
PHP
gpl-2.0
11,126
<?php /** * Vanillicon plugin. * * @author Todd Burry <[email protected]> * @copyright 2009-2017 Vanilla Forums Inc. * @license http://www.opensource.org/licenses/gpl-2.0.php GNU GPL v2 * @package vanillicon */ /** * Class VanilliconPlugin */ class VanilliconPlugin extends Gdn_Plugin { /** * Set up the plugin. */ public function setup() { $this->structure(); } /** * Perform any necessary database or configuration updates. */ public function structure() { touchConfig('Plugins.Vanillicon.Type', 'v2'); } /** * Set the vanillicon on the user' profile. * * @param ProfileController $sender * @param array $args */ public function profileController_afterAddSideMenu_handler($sender, $args) { if (!$sender->User->Photo) { $sender->User->Photo = userPhotoDefaultUrl($sender->User, ['Size' => 200]); } } /** * The settings page for vanillicon. * * @param Gdn_Controller $sender */ public function settingsController_vanillicon_create($sender) { $sender->permission('Garden.Settings.Manage'); $cf = new ConfigurationModule($sender); $items = [ 'v1' => 'Vanillicon 1', 'v2' => 'Vanillicon 2' ]; $cf->initialize([ 'Plugins.Vanillicon.Type' => [ 'LabelCode' => 'Vanillicon Set', 'Control' => 'radiolist', 'Description' => 'Which vanillicon set do you want to use?', 'Items' => $items, 'Options' => ['display' => 'after'], 'Default' => 'v1' ] ]); $sender->setData('Title', sprintf(t('%s Settings'), 'Vanillicon')); $cf->renderAll(); } /** * Overrides allowing admins to set the default avatar, since it has no effect when Vanillicon is on. * Adds messages to the top of avatar settings page and to the help panel asset. * * @param SettingsController $sender */ public function settingsController_avatarSettings_handler($sender) { // We check if Gravatar is enabled before adding any messages as Gravatar overrides Vanillicon. if (!Gdn::addonManager()->isEnabled('gravatar', \Vanilla\Addon::TYPE_ADDON)) { $message = t('You\'re using Vanillicon avatars as your default avatars.'); $message .= ' '.t('To set a custom default avatar, disable the Vanillicon plugin.'); $messages = $sender->data('messages', []); $messages = array_merge($messages, [$message]); $sender->setData('messages', $messages); $sender->setData('canSetDefaultAvatar', false); $help = t('Your users\' default avatars are Vanillicon avatars.'); helpAsset(t('How are my users\' default avatars set?'), $help); } } } if (!function_exists('userPhotoDefaultUrl')) { /** * Calculate the user's default photo url. * * @param array|object $user The user to examine. * @param array $options An array of options. * - Size: The size of the photo. * @return string Returns the vanillicon url for the user. */ function userPhotoDefaultUrl($user, $options = []) { static $iconSize = null, $type = null; if ($iconSize === null) { $thumbSize = c('Garden.Thumbnail.Size'); $iconSize = $thumbSize <= 50 ? 50 : 100; } if ($type === null) { $type = c('Plugins.Vanillicon.Type'); } $size = val('Size', $options, $iconSize); $email = val('Email', $user); if (!$email) { $email = val('UserID', $user, 100); } $hash = md5($email); $px = substr($hash, 0, 1); switch ($type) { case 'v2': $photoUrl = "//w$px.vanillicon.com/v2/{$hash}.svg"; break; default: $photoUrl = "//w$px.vanillicon.com/{$hash}_{$size}.png"; break; } return $photoUrl; } }
adrianspeyer/vanilla
plugins/vanillicon/class.vanillicon.plugin.php
PHP
gpl-2.0
4,131
/** * 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("/BenchmarkTest17998") public class BenchmarkTest17998 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 param = ""; java.util.Enumeration<String> names = request.getParameterNames(); if (names.hasMoreElements()) { param = names.nextElement(); // just grab first element } String bar = doSomething(param); java.io.FileOutputStream fos = new java.io.FileOutputStream(new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir + bar),false); } // end doPost private static String doSomething(String param) throws ServletException, IOException { String bar = "safe!"; java.util.HashMap<String,Object> map37923 = new java.util.HashMap<String,Object>(); map37923.put("keyA-37923", "a_Value"); // put some stuff in the collection map37923.put("keyB-37923", param.toString()); // put it in a collection map37923.put("keyC", "another_Value"); // put some stuff in the collection bar = (String)map37923.get("keyB-37923"); // get it back out bar = (String)map37923.get("keyA-37923"); // get safe value back out return bar; } }
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest17998.java
Java
gpl-2.0
2,474
package Classes::Sentry4; our @ISA = qw(Classes::Device); sub init { my $self = shift; if ($self->mode =~ /device::hardware::health/) { $self->analyze_and_check_environmental_subsystem('Classes::Sentry4::Components::EnvironmentalSubsystem'); } elsif ($self->mode =~ /device::power::health/) { $self->analyze_and_check_environmental_subsystem('Classes::Sentry4::Components::PowerSubsystem'); } else { $self->no_such_mode(); } if (! $self->check_messages()) { $self->add_ok('hardware working fine'); } }
lausser/check_pdu_health
plugins-scripts/Classes/Sentry4.pm
Perl
gpl-2.0
534
using System.Windows.Controls; namespace HomeControl { /// <summary> /// Interaction logic for UserControl1.xaml /// </summary> public partial class HomeCtrl : UserControl { public HomeCtrl() { InitializeComponent(); // doug's change... } } }
AceSyntax/DnvGitApp
DemoSolution/HomeControl/HomeCtrl.xaml.cs
C#
gpl-2.0
319
package adamros.mods.transducers.item; import java.util.List; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import adamros.mods.transducers.Transducers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; public class ItemElectricEngine extends ItemBlock { public ItemElectricEngine(int par1) { super(par1); setHasSubtypes(true); setMaxDamage(0); setUnlocalizedName("itemElectricEngine"); setCreativeTab(Transducers.tabTransducers); } @Override public int getMetadata(int meta) { return meta; } @Override public String getUnlocalizedName(ItemStack is) { String suffix; switch (is.getItemDamage()) { case 0: suffix = "lv"; break; case 1: suffix = "mv"; break; case 2: suffix = "hv"; break; case 3: suffix = "ev"; break; default: suffix = "lv"; break; } return getUnlocalizedName() + "." + suffix; } @Override @SideOnly(Side.CLIENT) public void addInformation(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, List par3List, boolean par4) { super.addInformation(par1ItemStack, par2EntityPlayer, par3List, par4); String type; switch (par1ItemStack.getItemDamage()) { case 0: type = "lv"; break; case 1: type = "mv"; break; case 2: type = "hv"; break; case 3: type = "ev"; break; default: type = "lv"; break; } par3List.add(StatCollector.translateToLocal("tip.electricEngine." + type).trim()); } }
adamros/Transducers
adamros/mods/transducers/item/ItemElectricEngine.java
Java
gpl-2.0
2,146
cmd_sound/soc/s6000/built-in.o := rm -f sound/soc/s6000/built-in.o; ../prebuilt/linux-x86/toolchain/arm-eabi-4.4.0/bin/arm-eabi-ar rcs sound/soc/s6000/built-in.o
venkatkamesh/2.6.35-kernel-for-lg-optimus-me-
sound/soc/s6000/.built-in.o.cmd
Batchfile
gpl-2.0
163
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>Sunible</title> <link rel="shortcut icon" href="images/favicon.ico"/> <!-- CSS --> <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/> <link rel="stylesheet" type="text/css" href="css/flat-ui.css"/> <link rel="stylesheet" type="text/css" href="css/general.css"/> <link rel="stylesheet" type="text/css" href="css/fonts.css"/> <link rel="stylesheet" type="text/css" href="css/forms.css"/> <link rel="stylesheet" type="text/css" href="css/layout.css"/> <link rel="stylesheet" type="text/css" href="css/pages.css"/> <!-- IE code --> <script type="text/javascript">var ie;</script> <!-- HTML5 shim, for IE6-8 support of HTML5 elements. All other JS at the end of file. --> <!--[if IE 8]> <link rel="stylesheet" type="text/css" href="css/ie8.css"/> <script type="text/javascript">ie = 8;</script> <![endif]--> <!--[if IE 9]> <link rel="stylesheet" type="text/css" href="css/ie8.css"/> <script type="text/javascript">ie = 9;</script> <![endif]--> <!--[if lt IE 9]> <script type="text/javascript" src="js/html5shiv.js"></script> <![endif]--> <link href="css/socialproof.css" rel="stylesheet" type="text/css"> </head> <body> <div class="pages"> <header class="page_header homepage dashboard social_proof registration message"> <!-- header has those classes to be toggled with those pages. With that approach, no need to duplicate the header on each page we have it--> <div class="questions"> <span class="question why_solar" data-toggle="tooltip" data-placement="bottom" title="Solar is the cleanest. most abundant source of energy on earth. Also, a solar-powered home can save on electricity from day one.">Why solar?</span><span class="question why_sunible" data-toggle="tooltip" data-placement="bottom" title="Like with flights, hotels, insurance or mobile services, there are lots of solar providers out there. We will help you compare, select and contact them. Choice is good!">Why Sunible?</span> </div> <a href="/" class="logo sunible"><img src="images/_project/logo_sunible.png"/></a> </header> <!-- HOMEPAGE --> <div class="page homepage show_header" id="page-homepage" data-page="homepage"> <section class="ad teaser container"> <a href="#" class="teaser" id="homepage_teaser_heading"> <span class="save">Save</span> <span class="money_with">Money with</span> <span class="solar">Solar</span> </a> <form class="zip search providers container" id="homepage-search_providers_by_zip-container"> <span class="field_container"> <input type="text" class="field zip" id="homepage-field-zip_code" name="zipcode" placeholder="Zip Code" pattern="\d{5}(?:[-\s]\d{4})?" value="93210"/> <span class="validation message"></span> </span> <button type="button" class="btn search providers zip" id="homepage-search_providers_by_zip-button">Go</button> </form> </section> </div> <!-- /HOMEPAGE --> <!-- SOCIAL PROOF --> <div class="page social_proof" id="page-social_proof" data-page="social_proof"> <h1>Fantastic, your area is very Sunible!</h1> <div class="block"> <p> You have selected<br/> <span class="counter selected providers number" id="dashboard-block-number_of_providers_selected">0</span> <br/> providers </p> <p class="max_length message">30 providers max</p> </div> <table align="center" width="80%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="25%" align="center"><table width="65px" height="65px" border="0" cellspacing="0" cellpadding="0" style="background-image:url(images/yellowdot.png);"> <tr> <td width="65px" align="center"><span class="socialproofaligncenterbig">23</span></td> </tr> </table> <p class="socialProofAlignCenter">homes have gone solar in your area</p></td> <td width="25%" align="center"><table width="65px" height="65px" border="0" cellspacing="0" cellpadding="0" style="background-image:url(images/yellowdot.png);"> <tr> <td width="65" align="center"><span class="socialproofaligncenterbig">18</span></td> </tr> </table> <p class="socialProofAlignCenter">of them started saving from day one</p></td> <td width="25%" align="center"><table width="65px" height="65px" border="0" cellspacing="0" cellpadding="0" style="background-image:url(images/yellowdot.png);"> <tr> <td width="65" align="center"><span class="socialproofaligncenterbig">14</span></td> </tr> </table> <p class="socialProofAlignCenter">experienced solar providers in your area</p></td> <td width="25%"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td> <div id="map" style="width: 250px; height: 250px"></div> <script src="js/leaflet.js"></script> <script> var map = L.map('map').setView([51.505, -0.09], 13); L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', { maxZoom: 18, attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>' }).addTo(map); L.marker([51.5, -0.09]).addTo(map) .bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup(); L.circle([51.508, -0.11], 500, { color: 'red', fillColor: '#f03', fillOpacity: 0.5 }).addTo(map).bindPopup("I am a circle."); L.polygon([ [51.509, -0.08], [51.503, -0.06], [51.51, -0.047] ]).addTo(map).bindPopup("I am a polygon."); var popup = L.popup(); function onMapClick(e) { popup .setLatLng(e.latlng) .setContent("You clicked the map at " + e.latlng.toString()) .openOn(map); } map.on('click', onMapClick); </script> </td> </tr> </table> <p class="socialProofAlignCenter">Number of solar homes in zip codes around you</p></td> </tr> </table> <button type="button" class="btn view providers" id="social_proof-view_providers">View providers</button> </div> <!-- /SOCIAL PROOF --> <!-- DASHBOARD --> <div class="page dashboard" id="page-dashboard" data-page="dashboard"> <!-- <aside class="logo"> <a href="/" class="logo sunible"><img src="images/_project/logo_sunible.png"/></a> </aside> --> <section class="providers number_of_selected"> <div class="block"> <p> You have selected<br/> <span class="counter selected providers number" id="dashboard-block-number_of_providers_selected">0</span> <br/> providers </p> <p class="max_length message">30 providers max</p> </div> <button type="button" class="btn register" id="dashboard-open_registration_page">Let's get Sunible</button> </section> <section class="providers container"> <header> <p> <span class="text">Showing</span> <span class="counter found providers number" id="dashboard-header-number_of_providers_found">25</span><!-- HARDCODE --> <span class="text">providers. Click to sort by Provider, $/Watt, Homes Installed or Rating</span> </p> </header> <div class="table container"> <table class="providers list grid" id="dashboard-grid-providers-list"> <thead> <tr> <th class="checkboxes"> <span class="text">Select</span> </th> <th class="name"> <span class="question_mark light" data-toggle="tooltip" data-placement="bottom" title="Some tooltip for 'Homes Installed' column.">?</span><br/> <span class="text">Solar Providers</span> </th> <th class="cost"> <span class="question_mark light" data-toggle="tooltip" data-placement="bottom" title="Some tooltip for 'Homes Installed' column.">?</span><br/> <span class="text">$/Watt</span> </th> <th class="number_of_homes_installed"> <span class="question_mark light" data-toggle="tooltip" data-placement="bottom" title="Some tooltip for 'Homes Installed' column.">?</span> <br/> <span class="text">Homes Installed</span> </th> <th class="rating"> <span class="question_mark light" data-toggle="tooltip" data-placement="bottom" title="Some tooltip for 'Homes Installed' column.">?</span><br/> <span class="text">Rating</span> </th> </tr> </thead> <tbody> <tr id="provider-10" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-10-checkbox"> <input type="checkbox" value="" id="provider-10-checkbox"/> </label> </td> <td class="name">Arise Solar<img src="images/_project/providers_logos/logo_AriseSolar.png"/></td> <td class="cost">100</td> <td class="number_of_homes_installed">12</td> <td class="rating"><span class="rating_stars has-4_5">*********</span></td> </tr> <tr id="provider-09" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-09-checkbox"> <input type="checkbox" value="" id="provider-09-checkbox"/> </label> </td> <td class="name">Real Goods Solar<img src="images/_project/providers_logos/logo_RealGoodsSolar.png"/></td> <td class="cost">96</td> <td class="number_of_homes_installed">123</td> <td class="rating"><span class="rating_stars has-2">****</span></td> </tr> <tr id="provider-08" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-08-checkbox"> <input type="checkbox" value="" id="provider-08-checkbox"/> </label> </td> <td class="name">Solar City<img src="images/_project/providers_logos/logo_SolarCity.png"/></td> <td class="cost">96</td> <td class="number_of_homes_installed">123</td> <td class="rating"><span class="rating_stars has-5">**********</span></td> </tr> <tr id="provider-07" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-07-checkbox"> <input type="checkbox" value="" id="provider-07-checkbox"/> </label> </td> <td class="name">Sungevity<img src="images/_project/providers_logos/logo_Sungevity.png"/></td> <td class="cost">96</td> <td class="number_of_homes_installed">123</td> <td class="rating"><span class="rating_stars has-1">**</span></td> </tr> <tr id="provider-06" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-06-checkbox"> <input type="checkbox" value="" id="provider-06-checkbox"/> </label> </td> <td class="name">Verengo Solar<img src="images/_project/providers_logos/logo_VerengoSolar.png"/></td> <td class="cost">96</td> <td class="number_of_homes_installed">123</td> <td class="rating"><span class="rating_stars has-5">**********</span></td> </tr> <tr id="provider-05" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-05-checkbox"> <input type="checkbox" value="" id="provider-05-checkbox"/> </label> </td> <td class="name">Arise Solar<img src="images/_project/providers_logos/logo_AriseSolar.png"/></td> <td class="cost">100</td> <td class="number_of_homes_installed">12</td> <td class="rating"><span class="rating_stars has-3">******</span></td> </tr> <tr id="provider-04" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-04-checkbox"> <input type="checkbox" value="" id="provider-04-checkbox"/> </label> </td> <td class="name">Real Goods Solar<img src="images/_project/providers_logos/logo_RealGoodsSolar.png"/></td> <td class="cost">96</td> <td class="number_of_homes_installed">123</td> <td class="rating"><span class="rating_stars has-4">********</span></td> </tr> <tr id="provider-03" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-03-checkbox"> <input type="checkbox" value="" id="provider-03-checkbox"/> </label> </td> <td class="name">Solar City<img src="images/_project/providers_logos/logo_SolarCity.png"/></td> <td class="cost">96</td> <td class="number_of_homes_installed">123</td> <td class="rating"><span class="rating_stars has-2_5">*****</span></td> </tr> <tr id="provider-02" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-02-checkbox"> <input type="checkbox" value="" id="provider-02-checkbox"/> </label> </td> <td class="name">Sungevity<img src="images/_project/providers_logos/logo_Sungevity.png"/></td> <td class="cost">96</td> <td class="number_of_homes_installed">123</td> <td class="rating"><span class="rating_stars has-2">****</span></td> </tr> <tr id="provider-01" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-01-checkbox"> <input type="checkbox" value="" id="provider-01-checkbox"/> </label> </td> <td class="name">Verengo Solar<img src="images/_project/providers_logos/logo_VerengoSolar.png"/></td> <td class="cost">96</td> <td class="number_of_homes_installed">123</td> <td class="rating"><span class="rating_stars has-3">******</span></td> </tr> </tbody> </table> </div> </section> </div> <!-- /DASHBOARD --> <!-- REGISTRATION --> <div class="page registration" id="page-registration" data-page="registration"> <h1> Registration <small>(Why do we collect this information <span class="question_mark dark" data-toggle="tooltip" data-placement="bottom" title="We collect this information to provide you better service">?</span>)</small> </h1> <form id="page-registration-form-register" class="registration_form" name="registration_form"> <p> My name is <!-- first name --> <span class="field_container"> <input type="text" class="field first_name" name="first_name" placeholder="First Name" required /> <span class="validation message"></span> </span> <!-- last name --> <span class="field_container"> <input type="text" class="field last_name" name="last_name" placeholder="Last Name" required/> <span class="validation message"></span> </span>, but you can call me <!-- nickname --> <span class="field_container"> <input type="text" class="field nickname" name="nickname" placeholder="Nickname" /> <span class="validation message"></span> </span>. <br/> I live at <!-- street address --> <span class="field_container"> <input type="text" class="field street_address" name="street_address" placeholder="Street Address" required/> <span class="validation message"></span> </span>, and can be reached on</span> <!-- phone number --> <span class="field_container"> <input type="tel" class="field phone_number" name="phone_number" placeholder="Phone Number (xxx)xxx-xxxx" pattern="^\(\d{3}\)\d{3}-\d{4}$" required/> <span class="validation message"></span> </span> <br/> or <!-- email --> <span class="field_container"> <input type="email" class="field email" name="email" placeholder="Email" pattern='(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))' required/> <span class="validation message"></span> </span>. I <!-- property type --> <span class="field_container"> <select class="field property_type" name="property_type" id="registration-select-appartment-property-type"> <option>rent</option> <option>own</option> </select> <span class="validation message"></span> </span> my place and pay about <!-- cost per month --> <span class="field_container"> <input type="text" class="field cost_per_month" name="cost_per_month" placeholder="$/month" min="0" required/> <span class="validation message"></span> </span> <br/> for electricity to the <!-- people nature --> <span class="field_container"> <select class="field people_nature" name="people_nature" id="registration-select-people-nature-type"> <option>good</option> <option>bad</option> <option>crazy</option> </select> <span class="validation message"></span> </span> people at <!-- electricity provider name --> <span class="field_container"> <select class="field electricity_provider_name" name="electricity_provider_name" id="registration-select-electricity-company-provider"> <option>Pacific Gas &amp; Electric (PG&amp;E)</option> <option>Southern California Edison</option> </select> <span class="validation message"></span> </span> I have a <!-- roof type --> <span class="field_container"> <select class="field roof_type" name="roof_type" id="registration-select-roof-type"> <option>tiled</option> <option>wood shake</option> <option>composite</option> <option>flat</option> <option>“no idea what”</option> </select> <span class="validation message"></span> </span> roof. </p> <button type="button" class="btn send_registration" id="registration-submit_registration_info">Go</button> </form> </div> <!-- /REGISTRATION --> <!-- THANK YOU --> <div class="page message" id="page-message" data-page="message"> <!-- This page is dynamic. Use it for messages like "Thank you", "Sorry", "Error", etc --> <p class="loading message">loading...</p> </div> <!-- /THANK YOU --> <!-- FOOTER --> <footer class="page_footer homepage social_proof dashboard registration message"> <!-- footer has those classes to be toggled with those pages. With that approach, no need to duplicate the footer on each page we have it--> <nav class="bottom navigation"> <a href="#">Blog</a> <a href="#">FAQ</a> <a href="#">Jobs</a> <a href="#">Contact</a> <a href="#">Terms</a> </nav> <span class="copyright">&copy; Sunible Inc. 2013</span> </footer> </div> <!-- JS --> <script type="text/javascript" src="js/jquery/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="js/jquery/jquery.placeholder.js"></script> <script type="text/javascript" src="js/jquery/jquery.validate.min.js"></script> <script type="text/javascript" src="js/jquery/additional-methods.min.js"></script> <script type="text/javascript" src="js/jquery/jquery.dropkick-1.0.0.js"></script> <script type="text/javascript" src="js/jquery/jquery.dataTables.min.js"></script> <script type="text/javascript" src="js/bootstrap/bootstrap-tooltip.js"></script> <script type="text/javascript" src="js/custom_checkbox_and_radio.js"></script> <script type="text/javascript" src="js/global_methods.js"></script> <script type="text/javascript" src="js/server_calls.js"></script> <script type="text/javascript" src="js/validation.js"></script> <script type="text/javascript" src="js/pages.js"></script> <script type="text/javascript" src="js/dashboard.js"></script> <script type="text/javascript" src="js/application_init.js"></script> </body> </html>
dhanur/Sunible-Beta
socialProofTest_Tanner.html
HTML
gpl-2.0
20,503
<?php /** * @file * Opigno Learning Record Store stats - Course content - Course contexts statistics template file * * @param array $course_contexts_statistics */ ?> <div class="lrs-stats-widget" id="lrs-stats-widget-course-content-course-contexts-statistics"> <h2><?php print t('Course context statistics'); ?></h2> <?php print theme('opigno_lrs_stats_course_content_widget_course_contexts_statistics_list', compact('course_contexts_statistics')); ?> </div>
ksen-pol/univerico
profiles/opigno_lms/modules/opigno/opigno_tincan_api/modules/opigno_tincan_api_stats/templates/course_content/widgets/course_contexts_statistics/course_contexts_statistics.tpl.php
PHP
gpl-2.0
467
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef GLK_DETECTION_H #define GLK_DETECTION_H #include "engines/advancedDetector.h" #include "engines/game.h" #define MAX_SAVES 99 /** * ScummVM Meta Engine interface */ class GlkMetaEngine : public MetaEngine { private: Common::String findFileByGameId(const Common::String &gameId) const; public: GlkMetaEngine() : MetaEngine() {} virtual const char *getName() const { return "ScummGlk"; } virtual const char *getOriginalCopyright() const { return "Infocom games (C) Infocom\nScott Adams games (C) Scott Adams"; } virtual bool hasFeature(MetaEngineFeature f) const override; virtual Common::Error createInstance(OSystem *syst, Engine **engine) const override; virtual SaveStateList listSaves(const char *target) const; virtual int getMaximumSaveSlot() const; virtual void removeSaveState(const char *target, int slot) const; SaveStateDescriptor querySaveMetaInfos(const char *target, int slot) const; /** * Returns a list of games supported by this engine. */ virtual PlainGameList getSupportedGames() const override; /** * Runs the engine's game detector on the given list of files, and returns a * (possibly empty) list of games supported by the engine which it was able * to detect amongst the given files. */ virtual DetectedGames detectGames(const Common::FSList &fslist) const override; /** * Query the engine for a PlainGameDescriptor for the specified gameid, if any. */ virtual PlainGameDescriptor findGame(const char *gameId) const override; /** * Calls each sub-engine in turn to ensure no game Id accidentally shares the same Id */ void detectClashes() const; }; namespace Glk { /** * Holds the name of a recognised game */ struct GameDescriptor { const char *_gameId; const char *_description; uint _options; GameDescriptor(const char *gameId, const char *description, uint options) : _gameId(gameId), _description(description), _options(options) {} GameDescriptor(const PlainGameDescriptor &gd) : _gameId(gd.gameId), _description(gd.description), _options(0) {} static PlainGameDescriptor empty() { return GameDescriptor(nullptr, nullptr, 0); } operator PlainGameDescriptor() const { PlainGameDescriptor pd; pd.gameId = _gameId; pd.description = _description; return pd; } }; } // End of namespace Glk #endif
alexbevi/scummvm
engines/glk/detection.h
C
gpl-2.0
3,263
showWord(["v. ","vin jòn.<br>"])
georgejhunt/HaitiDictionary.activity
data/words/joni.js
JavaScript
gpl-2.0
33
## ## Copyright 2007, Red Hat, Inc ## see AUTHORS ## ## This software may be freely redistributed under the terms of the GNU ## general public license. ## ## 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. ## import inspect from func import logger from func.config import read_config, BaseConfig from func.commonconfig import FuncdConfig from func.minion.func_arg import * #the arg getter stuff class FuncModule(object): # the version is meant to version = "0.0.0" api_version = "0.0.0" description = "No Description provided" class Config(BaseConfig): pass def __init__(self): config_file = '/etc/func/minion.conf' self.config = read_config(config_file, FuncdConfig) self.__init_log() self.__base_methods = { # __'s so we don't clobber useful names "module_version" : self.__module_version, "module_api_version" : self.__module_api_version, "module_description" : self.__module_description, "list_methods" : self.__list_methods, "get_method_args" : self.__get_method_args, } self.__init_options() def __init_log(self): log = logger.Logger() self.logger = log.logger def __init_options(self): options_file = '/etc/func/modules/'+self.__class__.__name__+'.conf' self.options = read_config(options_file, self.Config) return def register_rpc(self, handlers, module_name): # add the internal methods, note that this means they # can get clobbbered by subclass versions for meth in self.__base_methods: handlers["%s.%s" % (module_name, meth)] = self.__base_methods[meth] # register our module's handlers for name, handler in self.__list_handlers().items(): handlers["%s.%s" % (module_name, name)] = handler def __list_handlers(self): """ Return a dict of { handler_name, method, ... }. All methods that do not being with an underscore will be exposed. We also make sure to not expose our register_rpc method. """ handlers = {} for attr in dir(self): if self.__is_public_valid_method(attr): handlers[attr] = getattr(self, attr) return handlers def __list_methods(self): return self.__list_handlers().keys() + self.__base_methods.keys() def __module_version(self): return self.version def __module_api_version(self): return self.api_version def __module_description(self): return self.description def __is_public_valid_method(self,attr): if inspect.ismethod(getattr(self, attr)) and attr[0] != '_' and\ attr != 'register_rpc' and attr!='register_method_args': return True return False def __get_method_args(self): """ Gets arguments with their formats according to ArgCompatibility class' rules. @return : dict with args or Raise Exception if something wrong happens """ tmp_arg_dict = self.register_method_args() #if it is not implemeted then return empty stuff if not tmp_arg_dict: return {} #see if user tried to register an not implemented method :) for method in tmp_arg_dict.iterkeys(): if not hasattr(self,method): raise NonExistingMethodRegistered("%s is not in %s "%(method,self.__class__.__name__)) #create argument validation instance self.arg_comp = ArgCompatibility(tmp_arg_dict) #see if all registered arguments are there for method in tmp_arg_dict.iterkeys(): self.arg_comp.is_all_arguments_registered(self,method,tmp_arg_dict[method]['args']) #see if the options that were used are OK.. self.arg_comp.validate_all() return tmp_arg_dict def register_method_args(self): """ That is the method where users should override in their modules according to be able to send their method arguments to the Overlord. If they dont have it nothing breaks just that one in the base class is called @return : empty {} """ # to know they didnt implement it return {}
pombredanne/func
func/minion/modules/func_module.py
Python
gpl-2.0
4,487
package lambda; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class Esempio extends JFrame { public Esempio() { init(); } private void init() { BorderLayout b=new BorderLayout(); this.setLayout(b); JButton button=new JButton("Ok"); this.add(button,BorderLayout.SOUTH); this.setSize(400, 300); this.setVisible(true); ActionListener l=new Azione(); button.addActionListener(( e) -> System.out.println("ciao")); } public static void main(String[] args) { Esempio e=new Esempio(); } }
manuelgentile/MAP
java8/java8_lambda/src/main/java/lambda/Esempio.java
Java
gpl-2.0
663
/* DC++ Widget Toolkit Copyright (c) 2007-2013, Jacek Sieka All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the DWT nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <dwt/widgets/ProgressBar.h> namespace dwt { const TCHAR ProgressBar::windowClass[] = PROGRESS_CLASS; ProgressBar::Seed::Seed() : BaseType::Seed(WS_CHILD | PBS_SMOOTH) { } }
hjpotter92/dcplusplus
dwt/src/widgets/ProgressBar.cpp
C++
gpl-2.0
1,771
<?php require "tableinitiateclass.php"; require "../queryinitiateclass.php"; $tbl = new AddTable; ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Table index</title> </head> <style> table { width:100%; } </style> <body> <?php // just the headers $arrayheaders = array("head1","head2","head3"); // just the rows $arrayrows = array(array("row1-1","row1-2","row1-3"), array("row2-1","row2-2","row2-3"), array("row3-1","row3-2","row3-3"), array("row4-1","row4-2","row4-3"), array("row5-1","row5-2","row5-3")); $query = new AddSql("root","","map_directory_uphrm","localhost"); $arraycolumns = $query->getallColumn("rooms_uphrm"); $arrayfields = $query->getallascolQuery("rooms_uphrm"); // display table styling still unfinished echo $tbl->settblQuery(sizeof($arrayfields),sizeof($arraycolumns),$arraycolumns,$arrayfields); // display search for row and column numbers echo $tbl->gettableData(2,1); // set search query $tbl->searchRows("-3"); // display search query echo $tbl->getsearchResults(); // reset table $tbl->resetAll(); // get query string $getquery = 'current'; // next page $nextpage = $tbl->checkSet($getquery) + 1; // back page $backpage = $tbl->checkSet($getquery) - 1; // display table with restriction of 2 echo $tbl->settblrestrictQuery(sizeof($arrayfields),sizeof($arraycolumns), $arraycolumns,$arrayfields,5, $tbl->checkSet($getquery)); // display back button $totaldist = sizeof($arrayfields) / 5; echo $tbl->toBack($backpage,$getquery); // display next button echo $tbl->toNext($nextpage,$getquery); ?> <button onclick = "ajaxNav()" > Next </button> <button onclick = "ajaxNavb()" > Back </button> <div id = "tableDiv" > </div> <?php echo $tbl->popupDelete(); ?> <script> var count = 1; function ajaxNav() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("tableDiv").innerHTML=xmlhttp.responseText; } } if(count<<?php echo $totaldist; ?>); count++; xmlhttp.open("GET","ajaxnav.php?<?php echo $getquery; ?>="+ count,true); xmlhttp.send(); } function ajaxNavb() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("tableDiv").innerHTML=xmlhttp.responseText; } } if(count>0); count--; xmlhttp.open("GET","ajaxnav.php?<?php echo $getquery; ?>="+ count,true); xmlhttp.send(); } </script> </body> </html>
cominteract/htmlwrapper_v1
htmlwrapper/table/tableindex.php
PHP
gpl-2.0
3,108
/* You may freely copy, distribute, modify and use this class as long as the original author attribution remains intact. See message below. Copyright (C) 1998-2006 Christian Pesch. All Rights Reserved. */ package slash.carcosts; import slash.gui.model.AbstractModel; /** * An CurrencyModel holds a Currency and provides get and set * methods for it. * * @author Christian Pesch */ public class CurrencyModel extends AbstractModel { /** * Construct a new CurrencyModel. */ public CurrencyModel() { this(Currency.getCurrency("DM")); } /** * Construct a new CurrencyModel. */ public CurrencyModel(Currency value) { setValue(value); } /** * Get the Currency value that is holded by the model. */ public Currency getValue() { return value; } /** * Set the Currency value to hold. */ public void setValue(Currency newValue) { if (value != newValue) { this.value = newValue; fireStateChanged(); } } public String toString() { return "CurrencyModel(" + value + ")"; } private Currency value; }
cpesch/CarCosts
car-costs/src/main/java/slash/carcosts/CurrencyModel.java
Java
gpl-2.0
1,184
/* c) The receipt screen */ .point-of-sale .pos-receipt-container { font-size: 10pt; } .point-of-sale .pos-sale-ticket { text-align: left; /* width: 76mm; */ width: 255px; /* background-color: white; */ margin: 0mm,0mm,0mm,0mm; /* padding: 1px; */ /* padding-bottom:1px; */ display: inline-block; font-family: "Tahoma","Inconsolata","Lucida Console", "monospace"; /* font-family: "Inconsolata"; */ /* border-radius: 2px; */ /* box-shadow: 0px 1px 0px white, 0px 3px 0px #C1B9D6, 0px 8px 16px rgba(0, 0, 0, 0.3);*/ } .point-of-sale .pos-sale-ticket .emph{ font-size: 12pt; margin:5px; font-weight: bolder; } .point-of-sale .pos-sale-ticket .ticket{ font-size: 16pt; font-weight: bolder; } .point-of-sale .pos-sale-ticket .titulo{ font-size: 16pt; font-weight: bolder; text-align: center; } .point-of-sale .pos-sale-ticket table { width: 100%; border: 0; table-layout: fixed; border-spacing: 1px 1px; border-collapse: collapse; } .point-of-sale .pos-sale-ticket p { font-size: 9pt; margin: 0px !important; padding: 0 !important; padding-bottom:0px !important; } .point-of-sale .pos-sale-ticket table td { font-size: 9pt; border: 0; margin: 0px !important; word-wrap: break-word; } @media print { .point-of-sale #topheader, .point-of-sale #leftpane { display: none !important; } .point-of-sale #content { top: 0px !important; } .point-of-sale #rightpane { left: 0px !important; background-color: white; } #receipt-screen header { display: none !important; } #receipt-screen { text-align: left; } .pos-actionbar { display: none !important; } .pos-sale-ticket { margin: 0px !important; } .debug-widget{ display: none !important; } .point-of-sale *{ text-shadow: none !important; box-shadow: none !important; background: transparent !important; } .point-of-sale .pos-sale-ticket{ margin-left: 0px !important; margin-right: 0px !important; border: none !important; } }
silvau/Addons_Odoo
qweb_pos_ticket/static/src/css/pos.css
CSS
gpl-2.0
2,204
/** * Ядро булевой логики */ /** * @author Алексей Кляузер <[email protected]> * Ядро булевой логики */ package org.deneblingvo.booleans.core;
AlexAbak/ReversibleComputing
package/src/org/deneblingvo/booleans/core/package-info.java
Java
gpl-2.0
192
#ifndef __LINUX_USB_H #define __LINUX_USB_H #include <linux/mod_devicetable.h> #include <linux/usb/ch9.h> #define USB_MAJOR 180 #define USB_DEVICE_MAJOR 189 #ifdef __KERNEL__ #include <linux/errno.h> /* for -ENODEV */ #include <linux/delay.h> /* for mdelay() */ #include <linux/interrupt.h> /* for in_interrupt() */ #include <linux/list.h> /* for struct list_head */ #include <linux/kref.h> /* for struct kref */ #include <linux/device.h> /* for struct device */ #include <linux/fs.h> /* for struct file_operations */ #include <linux/completion.h> /* for struct completion */ #include <linux/sched.h> /* for current && schedule_timeout */ #include <linux/mutex.h> /* for struct mutex */ #include <linux/pm_runtime.h> /* for runtime PM */ struct usb_device; struct usb_driver; struct wusb_dev; /*-------------------------------------------------------------------------*/ /* * Host-side wrappers for standard USB descriptors ... these are parsed * from the data provided by devices. Parsing turns them from a flat * sequence of descriptors into a hierarchy: * * - devices have one (usually) or more configs; * - configs have one (often) or more interfaces; * - interfaces have one (usually) or more settings; * - each interface setting has zero or (usually) more endpoints. * - a SuperSpeed endpoint has a companion descriptor * * And there might be other descriptors mixed in with those. * * Devices may also have class-specific or vendor-specific descriptors. */ struct ep_device; /** * struct usb_host_endpoint - host-side endpoint descriptor and queue * @desc: descriptor for this endpoint, wMaxPacketSize in native byteorder * @ss_ep_comp: SuperSpeed companion descriptor for this endpoint * @urb_list: urbs queued to this endpoint; maintained by usbcore * @hcpriv: for use by HCD; typically holds hardware dma queue head (QH) * with one or more transfer descriptors (TDs) per urb * @ep_dev: ep_device for sysfs info * @extra: descriptors following this endpoint in the configuration * @extralen: how many bytes of "extra" are valid * @enabled: URBs may be submitted to this endpoint * * USB requests are always queued to a given endpoint, identified by a * descriptor within an active interface in a given USB configuration. */ struct usb_host_endpoint { struct usb_endpoint_descriptor desc; struct usb_ss_ep_comp_descriptor ss_ep_comp; struct list_head urb_list; void *hcpriv; struct ep_device *ep_dev; /* For sysfs info */ unsigned char *extra; /* Extra descriptors */ int extralen; int enabled; }; /* host-side wrapper for one interface setting's parsed descriptors */ struct usb_host_interface { struct usb_interface_descriptor desc; /* array of desc.bNumEndpoint endpoints associated with this * interface setting. these will be in no particular order. */ struct usb_host_endpoint *endpoint; char *string; /* iInterface string, if present */ unsigned char *extra; /* Extra descriptors */ int extralen; }; enum usb_interface_condition { USB_INTERFACE_UNBOUND = 0, USB_INTERFACE_BINDING, USB_INTERFACE_BOUND, USB_INTERFACE_UNBINDING, }; /** * struct usb_interface - what usb device drivers talk to * @altsetting: array of interface structures, one for each alternate * setting that may be selected. Each one includes a set of * endpoint configurations. They will be in no particular order. * @cur_altsetting: the current altsetting. * @num_altsetting: number of altsettings defined. * @intf_assoc: interface association descriptor * @minor: the minor number assigned to this interface, if this * interface is bound to a driver that uses the USB major number. * If this interface does not use the USB major, this field should * be unused. The driver should set this value in the probe() * function of the driver, after it has been assigned a minor * number from the USB core by calling usb_register_dev(). * @condition: binding state of the interface: not bound, binding * (in probe()), bound to a driver, or unbinding (in disconnect()) * @sysfs_files_created: sysfs attributes exist * @ep_devs_created: endpoint child pseudo-devices exist * @unregistering: flag set when the interface is being unregistered * @needs_remote_wakeup: flag set when the driver requires remote-wakeup * capability during autosuspend. * @needs_altsetting0: flag set when a set-interface request for altsetting 0 * has been deferred. * @needs_binding: flag set when the driver should be re-probed or unbound * following a reset or suspend operation it doesn't support. * @dev: driver model's view of this device * @usb_dev: if an interface is bound to the USB major, this will point * to the sysfs representation for that device. * @pm_usage_cnt: PM usage counter for this interface * @reset_ws: Used for scheduling resets from atomic context. * @reset_running: set to 1 if the interface is currently running a * queued reset so that usb_cancel_queued_reset() doesn't try to * remove from the workqueue when running inside the worker * thread. See __usb_queue_reset_device(). * @resetting_device: USB core reset the device, so use alt setting 0 as * current; needs bandwidth alloc after reset. * * USB device drivers attach to interfaces on a physical device. Each * interface encapsulates a single high level function, such as feeding * an audio stream to a speaker or reporting a change in a volume control. * Many USB devices only have one interface. The protocol used to talk to * an interface's endpoints can be defined in a usb "class" specification, * or by a product's vendor. The (default) control endpoint is part of * every interface, but is never listed among the interface's descriptors. * * The driver that is bound to the interface can use standard driver model * calls such as dev_get_drvdata() on the dev member of this structure. * * Each interface may have alternate settings. The initial configuration * of a device sets altsetting 0, but the device driver can change * that setting using usb_set_interface(). Alternate settings are often * used to control the use of periodic endpoints, such as by having * different endpoints use different amounts of reserved USB bandwidth. * All standards-conformant USB devices that use isochronous endpoints * will use them in non-default settings. * * The USB specification says that alternate setting numbers must run from * 0 to one less than the total number of alternate settings. But some * devices manage to mess this up, and the structures aren't necessarily * stored in numerical order anyhow. Use usb_altnum_to_altsetting() to * look up an alternate setting in the altsetting array based on its number. */ struct usb_interface { /* array of alternate settings for this interface, * stored in no particular order */ struct usb_host_interface *altsetting; struct usb_host_interface *cur_altsetting; /* the currently * active alternate setting */ unsigned num_altsetting; /* number of alternate settings */ /* If there is an interface association descriptor then it will list * the associated interfaces */ struct usb_interface_assoc_descriptor *intf_assoc; int minor; /* minor number this interface is * bound to */ enum usb_interface_condition condition; /* state of binding */ unsigned sysfs_files_created:1; /* the sysfs attributes exist */ unsigned ep_devs_created:1; /* endpoint "devices" exist */ unsigned unregistering:1; /* unregistration is in progress */ unsigned needs_remote_wakeup:1; /* driver requires remote wakeup */ unsigned needs_altsetting0:1; /* switch to altsetting 0 is pending */ unsigned needs_binding:1; /* needs delayed unbind/rebind */ unsigned reset_running:1; unsigned resetting_device:1; /* true: bandwidth alloc after reset */ struct device dev; /* interface specific device info */ struct device *usb_dev; atomic_t pm_usage_cnt; /* usage counter for autosuspend */ struct work_struct reset_ws; /* for resets in atomic context */ }; #define to_usb_interface(d) container_of(d, struct usb_interface, dev) static inline void *usb_get_intfdata(struct usb_interface *intf) { return dev_get_drvdata(&intf->dev); } static inline void usb_set_intfdata(struct usb_interface *intf, void *data) { dev_set_drvdata(&intf->dev, data); } struct usb_interface *usb_get_intf(struct usb_interface *intf); void usb_put_intf(struct usb_interface *intf); /* this maximum is arbitrary */ #define USB_MAXINTERFACES 32 #define USB_MAXIADS (USB_MAXINTERFACES/2) /** * struct usb_interface_cache - long-term representation of a device interface * @num_altsetting: number of altsettings defined. * @ref: reference counter. * @altsetting: variable-length array of interface structures, one for * each alternate setting that may be selected. Each one includes a * set of endpoint configurations. They will be in no particular order. * * These structures persist for the lifetime of a usb_device, unlike * struct usb_interface (which persists only as long as its configuration * is installed). The altsetting arrays can be accessed through these * structures at any time, permitting comparison of configurations and * providing support for the /proc/bus/usb/devices pseudo-file. */ struct usb_interface_cache { unsigned num_altsetting; /* number of alternate settings */ struct kref ref; /* reference counter */ /* variable-length array of alternate settings for this interface, * stored in no particular order */ struct usb_host_interface altsetting[0]; }; #define ref_to_usb_interface_cache(r) \ container_of(r, struct usb_interface_cache, ref) #define altsetting_to_usb_interface_cache(a) \ container_of(a, struct usb_interface_cache, altsetting[0]) /** * struct usb_host_config - representation of a device's configuration * @desc: the device's configuration descriptor. * @string: pointer to the cached version of the iConfiguration string, if * present for this configuration. * @intf_assoc: list of any interface association descriptors in this config * @interface: array of pointers to usb_interface structures, one for each * interface in the configuration. The number of interfaces is stored * in desc.bNumInterfaces. These pointers are valid only while the * the configuration is active. * @intf_cache: array of pointers to usb_interface_cache structures, one * for each interface in the configuration. These structures exist * for the entire life of the device. * @extra: pointer to buffer containing all extra descriptors associated * with this configuration (those preceding the first interface * descriptor). * @extralen: length of the extra descriptors buffer. * * USB devices may have multiple configurations, but only one can be active * at any time. Each encapsulates a different operational environment; * for example, a dual-speed device would have separate configurations for * full-speed and high-speed operation. The number of configurations * available is stored in the device descriptor as bNumConfigurations. * * A configuration can contain multiple interfaces. Each corresponds to * a different function of the USB device, and all are available whenever * the configuration is active. The USB standard says that interfaces * are supposed to be numbered from 0 to desc.bNumInterfaces-1, but a lot * of devices get this wrong. In addition, the interface array is not * guaranteed to be sorted in numerical order. Use usb_ifnum_to_if() to * look up an interface entry based on its number. * * Device drivers should not attempt to activate configurations. The choice * of which configuration to install is a policy decision based on such * considerations as available power, functionality provided, and the user's * desires (expressed through userspace tools). However, drivers can call * usb_reset_configuration() to reinitialize the current configuration and * all its interfaces. */ struct usb_host_config { struct usb_config_descriptor desc; char *string; /* iConfiguration string, if present */ /* List of any Interface Association Descriptors in this * configuration. */ struct usb_interface_assoc_descriptor *intf_assoc[USB_MAXIADS]; /* the interfaces associated with this configuration, * stored in no particular order */ struct usb_interface *interface[USB_MAXINTERFACES]; /* Interface information available even when this is not the * active configuration */ struct usb_interface_cache *intf_cache[USB_MAXINTERFACES]; unsigned char *extra; /* Extra descriptors */ int extralen; }; int __usb_get_extra_descriptor(char *buffer, unsigned size, unsigned char type, void **ptr); #define usb_get_extra_descriptor(ifpoint, type, ptr) \ __usb_get_extra_descriptor((ifpoint)->extra, \ (ifpoint)->extralen, \ type, (void **)ptr) /* ----------------------------------------------------------------------- */ /* USB device number allocation bitmap */ struct usb_devmap { unsigned long devicemap[128 / (8*sizeof(unsigned long))]; }; /* * Allocated per bus (tree of devices) we have: */ struct usb_bus { struct device *controller; /* host/master side hardware */ int busnum; /* Bus number (in order of reg) */ const char *bus_name; /* stable id (PCI slot_name etc) */ u8 uses_dma; /* Does the host controller use DMA? */ u8 uses_pio_for_control; /* * Does the host controller use PIO * for control transfers? */ u8 otg_port; /* 0, or number of OTG/HNP port */ unsigned is_b_host:1; /* true during some HNP roleswitches */ unsigned b_hnp_enable:1; /* OTG: did A-Host enable HNP? */ unsigned sg_tablesize; /* 0 or largest number of sg list entries */ int devnum_next; /* Next open device number in * round-robin allocation */ struct usb_devmap devmap; /* device address allocation map */ struct usb_device *root_hub; /* Root hub */ struct usb_bus *hs_companion; /* Companion EHCI bus, if any */ struct list_head bus_list; /* list of busses */ int bandwidth_allocated; /* on this bus: how much of the time * reserved for periodic (intr/iso) * requests is used, on average? * Units: microseconds/frame. * Limits: Full/low speed reserve 90%, * while high speed reserves 80%. */ int bandwidth_int_reqs; /* number of Interrupt requests */ int bandwidth_isoc_reqs; /* number of Isoc. requests */ #ifdef CONFIG_USB_DEVICEFS struct dentry *usbfs_dentry; /* usbfs dentry entry for the bus */ #endif #if defined(CONFIG_USB_MON) || defined(CONFIG_USB_MON_MODULE) struct mon_bus *mon_bus; /* non-null when associated */ int monitored; /* non-zero when monitored */ #endif }; /* ----------------------------------------------------------------------- */ /* This is arbitrary. * From USB 2.0 spec Table 11-13, offset 7, a hub can * have up to 255 ports. The most yet reported is 10. * * Current Wireless USB host hardware (Intel i1480 for example) allows * up to 22 devices to connect. Upcoming hardware might raise that * limit. Because the arrays need to add a bit for hub status data, we * do 31, so plus one evens out to four bytes. */ #define USB_MAXCHILDREN (31) struct usb_tt; /** * struct usb_device - kernel's representation of a USB device * @devnum: device number; address on a USB bus * @devpath: device ID string for use in messages (e.g., /port/...) * @route: tree topology hex string for use with xHCI * @state: device state: configured, not attached, etc. * @speed: device speed: high/full/low (or error) * @tt: Transaction Translator info; used with low/full speed dev, highspeed hub * @ttport: device port on that tt hub * @toggle: one bit for each endpoint, with ([0] = IN, [1] = OUT) endpoints * @parent: our hub, unless we're the root * @bus: bus we're part of * @ep0: endpoint 0 data (default control pipe) * @dev: generic device interface * @descriptor: USB device descriptor * @config: all of the device's configs * @actconfig: the active configuration * @ep_in: array of IN endpoints * @ep_out: array of OUT endpoints * @rawdescriptors: raw descriptors for each config * @bus_mA: Current available from the bus * @portnum: parent port number (origin 1) * @level: number of USB hub ancestors * @can_submit: URBs may be submitted * @persist_enabled: USB_PERSIST enabled for this device * @have_langid: whether string_langid is valid * @authorized: policy has said we can use it; * (user space) policy determines if we authorize this device to be * used or not. By default, wired USB devices are authorized. * WUSB devices are not, until we authorize them from user space. * FIXME -- complete doc * @authenticated: Crypto authentication passed * @wusb: device is Wireless USB * @string_langid: language ID for strings * @product: iProduct string, if present (static) * @manufacturer: iManufacturer string, if present (static) * @serial: iSerialNumber string, if present (static) * @filelist: usbfs files that are open to this device * @usb_classdev: USB class device that was created for usbfs device * access from userspace * @usbfs_dentry: usbfs dentry entry for the device * @maxchild: number of ports if hub * @children: child devices - USB devices that are attached to this hub * @quirks: quirks of the whole device * @urbnum: number of URBs submitted for the whole device * @active_duration: total time device is not suspended * @connect_time: time device was first connected * @do_remote_wakeup: remote wakeup should be enabled * @reset_resume: needs reset instead of resume * @wusb_dev: if this is a Wireless USB device, link to the WUSB * specific data for the device. * @slot_id: Slot ID assigned by xHCI * * Notes: * Usbcore drivers should not set usbdev->state directly. Instead use * usb_set_device_state(). */ struct usb_device { int devnum; char devpath[16]; u32 route; enum usb_device_state state; enum usb_device_speed speed; struct usb_tt *tt; int ttport; unsigned int toggle[2]; struct usb_device *parent; struct usb_bus *bus; struct usb_host_endpoint ep0; struct device dev; struct usb_device_descriptor descriptor; struct usb_host_config *config; struct usb_host_config *actconfig; struct usb_host_endpoint *ep_in[16]; struct usb_host_endpoint *ep_out[16]; char **rawdescriptors; unsigned short bus_mA; u8 portnum; u8 level; unsigned can_submit:1; unsigned persist_enabled:1; unsigned have_langid:1; unsigned authorized:1; unsigned authenticated:1; unsigned wusb:1; int string_langid; /* static strings from the device */ char *product; char *manufacturer; char *serial; struct list_head filelist; #ifdef CONFIG_USB_DEVICE_CLASS struct device *usb_classdev; #endif #ifdef CONFIG_USB_DEVICEFS struct dentry *usbfs_dentry; #endif int maxchild; struct usb_device *children[USB_MAXCHILDREN]; u32 quirks; atomic_t urbnum; unsigned long active_duration; #ifdef CONFIG_PM unsigned long connect_time; unsigned do_remote_wakeup:1; unsigned reset_resume:1; #endif struct wusb_dev *wusb_dev; int slot_id; }; #define to_usb_device(d) container_of(d, struct usb_device, dev) static inline struct usb_device *interface_to_usbdev(struct usb_interface *intf) { return to_usb_device(intf->dev.parent); } extern struct usb_device *usb_get_dev(struct usb_device *dev); extern void usb_put_dev(struct usb_device *dev); /* USB device locking */ #define usb_lock_device(udev) device_lock(&(udev)->dev) #define usb_unlock_device(udev) device_unlock(&(udev)->dev) #define usb_trylock_device(udev) device_trylock(&(udev)->dev) extern int usb_lock_device_for_reset(struct usb_device *udev, const struct usb_interface *iface); /* USB port reset for device reinitialization */ extern int usb_reset_device(struct usb_device *dev); extern void usb_queue_reset_device(struct usb_interface *dev); /* USB autosuspend and autoresume */ #ifdef CONFIG_USB_SUSPEND extern void usb_enable_autosuspend(struct usb_device *udev); extern void usb_disable_autosuspend(struct usb_device *udev); extern int usb_autopm_get_interface(struct usb_interface *intf); extern void usb_autopm_put_interface(struct usb_interface *intf); extern int usb_autopm_get_interface_async(struct usb_interface *intf); extern void usb_autopm_put_interface_async(struct usb_interface *intf); extern void usb_autopm_get_interface_no_resume(struct usb_interface *intf); extern void usb_autopm_put_interface_no_suspend(struct usb_interface *intf); static inline void usb_mark_last_busy(struct usb_device *udev) { pm_runtime_mark_last_busy(&udev->dev); } #else static inline int usb_enable_autosuspend(struct usb_device *udev) { return 0; } static inline int usb_disable_autosuspend(struct usb_device *udev) { return 0; } static inline int usb_autopm_get_interface(struct usb_interface *intf) { return 0; } static inline int usb_autopm_get_interface_async(struct usb_interface *intf) { return 0; } static inline void usb_autopm_put_interface(struct usb_interface *intf) { } static inline void usb_autopm_put_interface_async(struct usb_interface *intf) { } static inline void usb_autopm_get_interface_no_resume( struct usb_interface *intf) { } static inline void usb_autopm_put_interface_no_suspend( struct usb_interface *intf) { } static inline void usb_mark_last_busy(struct usb_device *udev) { } #endif /*-------------------------------------------------------------------------*/ /* for drivers using iso endpoints */ extern int usb_get_current_frame_number(struct usb_device *usb_dev); /* Sets up a group of bulk endpoints to support multiple stream IDs. */ extern int usb_alloc_streams(struct usb_interface *interface, struct usb_host_endpoint **eps, unsigned int num_eps, unsigned int num_streams, gfp_t mem_flags); /* Reverts a group of bulk endpoints back to not using stream IDs. */ extern void usb_free_streams(struct usb_interface *interface, struct usb_host_endpoint **eps, unsigned int num_eps, gfp_t mem_flags); /* used these for multi-interface device registration */ extern int usb_driver_claim_interface(struct usb_driver *driver, struct usb_interface *iface, void *priv); /** * usb_interface_claimed - returns true iff an interface is claimed * @iface: the interface being checked * * Returns true (nonzero) iff the interface is claimed, else false (zero). * Callers must own the driver model's usb bus readlock. So driver * probe() entries don't need extra locking, but other call contexts * may need to explicitly claim that lock. * */ static inline int usb_interface_claimed(struct usb_interface *iface) { return (iface->dev.driver != NULL); } extern void usb_driver_release_interface(struct usb_driver *driver, struct usb_interface *iface); const struct usb_device_id *usb_match_id(struct usb_interface *interface, const struct usb_device_id *id); extern int usb_match_one_id(struct usb_interface *interface, const struct usb_device_id *id); extern struct usb_interface *usb_find_interface(struct usb_driver *drv, int minor); extern struct usb_interface *usb_ifnum_to_if(const struct usb_device *dev, unsigned ifnum); extern struct usb_host_interface *usb_altnum_to_altsetting( const struct usb_interface *intf, unsigned int altnum); extern struct usb_host_interface *usb_find_alt_setting( struct usb_host_config *config, unsigned int iface_num, unsigned int alt_num); /** * usb_make_path - returns stable device path in the usb tree * @dev: the device whose path is being constructed * @buf: where to put the string * @size: how big is "buf"? * * Returns length of the string (> 0) or negative if size was too small. * * This identifier is intended to be "stable", reflecting physical paths in * hardware such as physical bus addresses for host controllers or ports on * USB hubs. That makes it stay the same until systems are physically * reconfigured, by re-cabling a tree of USB devices or by moving USB host * controllers. Adding and removing devices, including virtual root hubs * in host controller driver modules, does not change these path identifiers; * neither does rebooting or re-enumerating. These are more useful identifiers * than changeable ("unstable") ones like bus numbers or device addresses. * * With a partial exception for devices connected to USB 2.0 root hubs, these * identifiers are also predictable. So long as the device tree isn't changed, * plugging any USB device into a given hub port always gives it the same path. * Because of the use of "companion" controllers, devices connected to ports on * USB 2.0 root hubs (EHCI host controllers) will get one path ID if they are * high speed, and a different one if they are full or low speed. */ static inline int usb_make_path(struct usb_device *dev, char *buf, size_t size) { int actual; actual = snprintf(buf, size, "usb-%s-%s", dev->bus->bus_name, dev->devpath); return (actual >= (int)size) ? -1 : actual; } /*-------------------------------------------------------------------------*/ #define USB_DEVICE_ID_MATCH_DEVICE \ (USB_DEVICE_ID_MATCH_VENDOR | USB_DEVICE_ID_MATCH_PRODUCT) #define USB_DEVICE_ID_MATCH_DEV_RANGE \ (USB_DEVICE_ID_MATCH_DEV_LO | USB_DEVICE_ID_MATCH_DEV_HI) #define USB_DEVICE_ID_MATCH_DEVICE_AND_VERSION \ (USB_DEVICE_ID_MATCH_DEVICE | USB_DEVICE_ID_MATCH_DEV_RANGE) #define USB_DEVICE_ID_MATCH_DEV_INFO \ (USB_DEVICE_ID_MATCH_DEV_CLASS | \ USB_DEVICE_ID_MATCH_DEV_SUBCLASS | \ USB_DEVICE_ID_MATCH_DEV_PROTOCOL) #define USB_DEVICE_ID_MATCH_INT_INFO \ (USB_DEVICE_ID_MATCH_INT_CLASS | \ USB_DEVICE_ID_MATCH_INT_SUBCLASS | \ USB_DEVICE_ID_MATCH_INT_PROTOCOL) /** * USB_DEVICE - macro used to describe a specific usb device * @vend: the 16 bit USB Vendor ID * @prod: the 16 bit USB Product ID * * This macro is used to create a struct usb_device_id that matches a * specific device. */ #define USB_DEVICE(vend, prod) \ .match_flags = USB_DEVICE_ID_MATCH_DEVICE, \ .idVendor = (vend), \ .idProduct = (prod) /** * USB_DEVICE_VER - describe a specific usb device with a version range * @vend: the 16 bit USB Vendor ID * @prod: the 16 bit USB Product ID * @lo: the bcdDevice_lo value * @hi: the bcdDevice_hi value * * This macro is used to create a struct usb_device_id that matches a * specific device, with a version range. */ #define USB_DEVICE_VER(vend, prod, lo, hi) \ .match_flags = USB_DEVICE_ID_MATCH_DEVICE_AND_VERSION, \ .idVendor = (vend), \ .idProduct = (prod), \ .bcdDevice_lo = (lo), \ .bcdDevice_hi = (hi) /** * USB_DEVICE_INTERFACE_PROTOCOL - describe a usb device with a specific interface protocol * @vend: the 16 bit USB Vendor ID * @prod: the 16 bit USB Product ID * @pr: bInterfaceProtocol value * * This macro is used to create a struct usb_device_id that matches a * specific interface protocol of devices. */ #define USB_DEVICE_INTERFACE_PROTOCOL(vend, prod, pr) \ .match_flags = USB_DEVICE_ID_MATCH_DEVICE | \ USB_DEVICE_ID_MATCH_INT_PROTOCOL, \ .idVendor = (vend), \ .idProduct = (prod), \ .bInterfaceProtocol = (pr) /** * USB_DEVICE_INFO - macro used to describe a class of usb devices * @cl: bDeviceClass value * @sc: bDeviceSubClass value * @pr: bDeviceProtocol value * * This macro is used to create a struct usb_device_id that matches a * specific class of devices. */ #define USB_DEVICE_INFO(cl, sc, pr) \ .match_flags = USB_DEVICE_ID_MATCH_DEV_INFO, \ .bDeviceClass = (cl), \ .bDeviceSubClass = (sc), \ .bDeviceProtocol = (pr) /** * USB_INTERFACE_INFO - macro used to describe a class of usb interfaces * @cl: bInterfaceClass value * @sc: bInterfaceSubClass value * @pr: bInterfaceProtocol value * * This macro is used to create a struct usb_device_id that matches a * specific class of interfaces. */ #define USB_INTERFACE_INFO(cl, sc, pr) \ .match_flags = USB_DEVICE_ID_MATCH_INT_INFO, \ .bInterfaceClass = (cl), \ .bInterfaceSubClass = (sc), \ .bInterfaceProtocol = (pr) /** * USB_DEVICE_AND_INTERFACE_INFO - describe a specific usb device with a class of usb interfaces * @vend: the 16 bit USB Vendor ID * @prod: the 16 bit USB Product ID * @cl: bInterfaceClass value * @sc: bInterfaceSubClass value * @pr: bInterfaceProtocol value * * This macro is used to create a struct usb_device_id that matches a * specific device with a specific class of interfaces. * * This is especially useful when explicitly matching devices that have * vendor specific bDeviceClass values, but standards-compliant interfaces. */ #define USB_DEVICE_AND_INTERFACE_INFO(vend, prod, cl, sc, pr) \ .match_flags = USB_DEVICE_ID_MATCH_INT_INFO \ | USB_DEVICE_ID_MATCH_DEVICE, \ .idVendor = (vend), \ .idProduct = (prod), \ .bInterfaceClass = (cl), \ .bInterfaceSubClass = (sc), \ .bInterfaceProtocol = (pr) /* ----------------------------------------------------------------------- */ /* Stuff for dynamic usb ids */ struct usb_dynids { spinlock_t lock; struct list_head list; }; struct usb_dynid { struct list_head node; struct usb_device_id id; }; extern ssize_t usb_store_new_id(struct usb_dynids *dynids, struct device_driver *driver, const char *buf, size_t count); /** * struct usbdrv_wrap - wrapper for driver-model structure * @driver: The driver-model core driver structure. * @for_devices: Non-zero for device drivers, 0 for interface drivers. */ struct usbdrv_wrap { struct device_driver driver; int for_devices; }; /** * struct usb_driver - identifies USB interface driver to usbcore * @name: The driver name should be unique among USB drivers, * and should normally be the same as the module name. * @probe: Called to see if the driver is willing to manage a particular * interface on a device. If it is, probe returns zero and uses * usb_set_intfdata() to associate driver-specific data with the * interface. It may also use usb_set_interface() to specify the * appropriate altsetting. If unwilling to manage the interface, * return -ENODEV, if genuine IO errors occurred, an appropriate * negative errno value. * @disconnect: Called when the interface is no longer accessible, usually * because its device has been (or is being) disconnected or the * driver module is being unloaded. * @unlocked_ioctl: Used for drivers that want to talk to userspace through * the "usbfs" filesystem. This lets devices provide ways to * expose information to user space regardless of where they * do (or don't) show up otherwise in the filesystem. * @suspend: Called when the device is going to be suspended by the system. * @resume: Called when the device is being resumed by the system. * @reset_resume: Called when the suspended device has been reset instead * of being resumed. * @pre_reset: Called by usb_reset_device() when the device is about to be * reset. This routine must not return until the driver has no active * URBs for the device, and no more URBs may be submitted until the * post_reset method is called. * @post_reset: Called by usb_reset_device() after the device * has been reset * @id_table: USB drivers use ID table to support hotplugging. * Export this with MODULE_DEVICE_TABLE(usb,...). This must be set * or your driver's probe function will never get called. * @dynids: used internally to hold the list of dynamically added device * ids for this driver. * @drvwrap: Driver-model core structure wrapper. * @no_dynamic_id: if set to 1, the USB core will not allow dynamic ids to be * added to this driver by preventing the sysfs file from being created. * @supports_autosuspend: if set to 0, the USB core will not allow autosuspend * for interfaces bound to this driver. * @soft_unbind: if set to 1, the USB core will not kill URBs and disable * endpoints before calling the driver's disconnect method. * * USB interface drivers must provide a name, probe() and disconnect() * methods, and an id_table. Other driver fields are optional. * * The id_table is used in hotplugging. It holds a set of descriptors, * and specialized data may be associated with each entry. That table * is used by both user and kernel mode hotplugging support. * * The probe() and disconnect() methods are called in a context where * they can sleep, but they should avoid abusing the privilege. Most * work to connect to a device should be done when the device is opened, * and undone at the last close. The disconnect code needs to address * concurrency issues with respect to open() and close() methods, as * well as forcing all pending I/O requests to complete (by unlinking * them as necessary, and blocking until the unlinks complete). */ struct usb_driver { const char *name; int (*probe) (struct usb_interface *intf, const struct usb_device_id *id); void (*disconnect) (struct usb_interface *intf); int (*unlocked_ioctl) (struct usb_interface *intf, unsigned int code, void *buf); int (*suspend) (struct usb_interface *intf, pm_message_t message); int (*resume) (struct usb_interface *intf); int (*reset_resume)(struct usb_interface *intf); int (*pre_reset)(struct usb_interface *intf); int (*post_reset)(struct usb_interface *intf); const struct usb_device_id *id_table; struct usb_dynids dynids; struct usbdrv_wrap drvwrap; unsigned int no_dynamic_id:1; unsigned int supports_autosuspend:1; unsigned int soft_unbind:1; }; #define to_usb_driver(d) container_of(d, struct usb_driver, drvwrap.driver) /** * struct usb_device_driver - identifies USB device driver to usbcore * @name: The driver name should be unique among USB drivers, * and should normally be the same as the module name. * @probe: Called to see if the driver is willing to manage a particular * device. If it is, probe returns zero and uses dev_set_drvdata() * to associate driver-specific data with the device. If unwilling * to manage the device, return a negative errno value. * @disconnect: Called when the device is no longer accessible, usually * because it has been (or is being) disconnected or the driver's * module is being unloaded. * @suspend: Called when the device is going to be suspended by the system. * @resume: Called when the device is being resumed by the system. * @drvwrap: Driver-model core structure wrapper. * @supports_autosuspend: if set to 0, the USB core will not allow autosuspend * for devices bound to this driver. * * USB drivers must provide all the fields listed above except drvwrap. */ struct usb_device_driver { const char *name; int (*probe) (struct usb_device *udev); void (*disconnect) (struct usb_device *udev); int (*suspend) (struct usb_device *udev, pm_message_t message); int (*resume) (struct usb_device *udev, pm_message_t message); struct usbdrv_wrap drvwrap; unsigned int supports_autosuspend:1; }; #define to_usb_device_driver(d) container_of(d, struct usb_device_driver, \ drvwrap.driver) extern struct bus_type usb_bus_type; /** * struct usb_class_driver - identifies a USB driver that wants to use the USB major number * @name: the usb class device name for this driver. Will show up in sysfs. * @devnode: Callback to provide a naming hint for a possible * device node to create. * @fops: pointer to the struct file_operations of this driver. * @minor_base: the start of the minor range for this driver. * * This structure is used for the usb_register_dev() and * usb_unregister_dev() functions, to consolidate a number of the * parameters used for them. */ struct usb_class_driver { char *name; char *(*devnode)(struct device *dev, umode_t *mode); const struct file_operations *fops; int minor_base; }; /* * use these in module_init()/module_exit() * and don't forget MODULE_DEVICE_TABLE(usb, ...) */ extern int usb_register_driver(struct usb_driver *, struct module *, const char *); /* use a define to avoid include chaining to get THIS_MODULE & friends */ #define usb_register(driver) \ usb_register_driver(driver, THIS_MODULE, KBUILD_MODNAME) extern void usb_deregister(struct usb_driver *); extern int usb_register_device_driver(struct usb_device_driver *, struct module *); extern void usb_deregister_device_driver(struct usb_device_driver *); extern int usb_register_dev(struct usb_interface *intf, struct usb_class_driver *class_driver); extern void usb_deregister_dev(struct usb_interface *intf, struct usb_class_driver *class_driver); extern int usb_disabled(void); /* ----------------------------------------------------------------------- */ /* * URB support, for asynchronous request completions */ /* * urb->transfer_flags: * * Note: URB_DIR_IN/OUT is automatically set in usb_submit_urb(). */ #define URB_SHORT_NOT_OK 0x0001 /* report short reads as errors */ #define URB_ISO_ASAP 0x0002 /* iso-only, urb->start_frame * ignored */ #define URB_NO_TRANSFER_DMA_MAP 0x0004 /* urb->transfer_dma valid on submit */ #define URB_NO_FSBR 0x0020 /* UHCI-specific */ #define URB_ZERO_PACKET 0x0040 /* Finish bulk OUT with short packet */ #define URB_NO_INTERRUPT 0x0080 /* HINT: no non-error interrupt * needed */ #define URB_FREE_BUFFER 0x0100 /* Free transfer buffer with the URB */ /* The following flags are used internally by usbcore and HCDs */ #define URB_DIR_IN 0x0200 /* Transfer from device to host */ #define URB_DIR_OUT 0 #define URB_DIR_MASK URB_DIR_IN #define URB_DMA_MAP_SINGLE 0x00010000 /* Non-scatter-gather mapping */ #define URB_DMA_MAP_PAGE 0x00020000 /* HCD-unsupported S-G */ #define URB_DMA_MAP_SG 0x00040000 /* HCD-supported S-G */ #define URB_MAP_LOCAL 0x00080000 /* HCD-local-memory mapping */ #define URB_SETUP_MAP_SINGLE 0x00100000 /* Setup packet DMA mapped */ #define URB_SETUP_MAP_LOCAL 0x00200000 /* HCD-local setup packet */ #define URB_DMA_SG_COMBINED 0x00400000 /* S-G entries were combined */ #define URB_ALIGNED_TEMP_BUFFER 0x00800000 /* Temp buffer was alloc'd */ struct usb_iso_packet_descriptor { unsigned int offset; unsigned int length; /* expected length */ unsigned int actual_length; int status; }; struct urb; struct usb_anchor { struct list_head urb_list; wait_queue_head_t wait; spinlock_t lock; unsigned int poisoned:1; }; static inline void init_usb_anchor(struct usb_anchor *anchor) { INIT_LIST_HEAD(&anchor->urb_list); init_waitqueue_head(&anchor->wait); spin_lock_init(&anchor->lock); } typedef void (*usb_complete_t)(struct urb *); /** * struct urb - USB Request Block * @urb_list: For use by current owner of the URB. * @anchor_list: membership in the list of an anchor * @anchor: to anchor URBs to a common mooring * @ep: Points to the endpoint's data structure. Will eventually * replace @pipe. * @pipe: Holds endpoint number, direction, type, and more. * Create these values with the eight macros available; * usb_{snd,rcv}TYPEpipe(dev,endpoint), where the TYPE is "ctrl" * (control), "bulk", "int" (interrupt), or "iso" (isochronous). * For example usb_sndbulkpipe() or usb_rcvintpipe(). Endpoint * numbers range from zero to fifteen. Note that "in" endpoint two * is a different endpoint (and pipe) from "out" endpoint two. * The current configuration controls the existence, type, and * maximum packet size of any given endpoint. * @stream_id: the endpoint's stream ID for bulk streams * @dev: Identifies the USB device to perform the request. * @status: This is read in non-iso completion functions to get the * status of the particular request. ISO requests only use it * to tell whether the URB was unlinked; detailed status for * each frame is in the fields of the iso_frame-desc. * @transfer_flags: A variety of flags may be used to affect how URB * submission, unlinking, or operation are handled. Different * kinds of URB can use different flags. * @transfer_buffer: This identifies the buffer to (or from) which the I/O * request will be performed unless URB_NO_TRANSFER_DMA_MAP is set * (however, do not leave garbage in transfer_buffer even then). * This buffer must be suitable for DMA; allocate it with * kmalloc() or equivalent. For transfers to "in" endpoints, contents * of this buffer will be modified. This buffer is used for the data * stage of control transfers. * @transfer_dma: When transfer_flags includes URB_NO_TRANSFER_DMA_MAP, * the device driver is saying that it provided this DMA address, * which the host controller driver should use in preference to the * transfer_buffer. * @sg: scatter gather buffer list * @num_sgs: number of entries in the sg list * @transfer_buffer_length: How big is transfer_buffer. The transfer may * be broken up into chunks according to the current maximum packet * size for the endpoint, which is a function of the configuration * and is encoded in the pipe. When the length is zero, neither * transfer_buffer nor transfer_dma is used. * @actual_length: This is read in non-iso completion functions, and * it tells how many bytes (out of transfer_buffer_length) were * transferred. It will normally be the same as requested, unless * either an error was reported or a short read was performed. * The URB_SHORT_NOT_OK transfer flag may be used to make such * short reads be reported as errors. * @setup_packet: Only used for control transfers, this points to eight bytes * of setup data. Control transfers always start by sending this data * to the device. Then transfer_buffer is read or written, if needed. * @setup_dma: DMA pointer for the setup packet. The caller must not use * this field; setup_packet must point to a valid buffer. * @start_frame: Returns the initial frame for isochronous transfers. * @number_of_packets: Lists the number of ISO transfer buffers. * @interval: Specifies the polling interval for interrupt or isochronous * transfers. The units are frames (milliseconds) for full and low * speed devices, and microframes (1/8 millisecond) for highspeed * and SuperSpeed devices. * @error_count: Returns the number of ISO transfers that reported errors. * @context: For use in completion functions. This normally points to * request-specific driver context. * @complete: Completion handler. This URB is passed as the parameter to the * completion function. The completion function may then do what * it likes with the URB, including resubmitting or freeing it. * @iso_frame_desc: Used to provide arrays of ISO transfer buffers and to * collect the transfer status for each buffer. * * This structure identifies USB transfer requests. URBs must be allocated by * calling usb_alloc_urb() and freed with a call to usb_free_urb(). * Initialization may be done using various usb_fill_*_urb() functions. URBs * are submitted using usb_submit_urb(), and pending requests may be canceled * using usb_unlink_urb() or usb_kill_urb(). * * Data Transfer Buffers: * * Normally drivers provide I/O buffers allocated with kmalloc() or otherwise * taken from the general page pool. That is provided by transfer_buffer * (control requests also use setup_packet), and host controller drivers * perform a dma mapping (and unmapping) for each buffer transferred. Those * mapping operations can be expensive on some platforms (perhaps using a dma * bounce buffer or talking to an IOMMU), * although they're cheap on commodity x86 and ppc hardware. * * Alternatively, drivers may pass the URB_NO_TRANSFER_DMA_MAP transfer flag, * which tells the host controller driver that no such mapping is needed for * the transfer_buffer since * the device driver is DMA-aware. For example, a device driver might * allocate a DMA buffer with usb_alloc_coherent() or call usb_buffer_map(). * When this transfer flag is provided, host controller drivers will * attempt to use the dma address found in the transfer_dma * field rather than determining a dma address themselves. * * Note that transfer_buffer must still be set if the controller * does not support DMA (as indicated by bus.uses_dma) and when talking * to root hub. If you have to trasfer between highmem zone and the device * on such controller, create a bounce buffer or bail out with an error. * If transfer_buffer cannot be set (is in highmem) and the controller is DMA * capable, assign NULL to it, so that usbmon knows not to use the value. * The setup_packet must always be set, so it cannot be located in highmem. * * Initialization: * * All URBs submitted must initialize the dev, pipe, transfer_flags (may be * zero), and complete fields. All URBs must also initialize * transfer_buffer and transfer_buffer_length. They may provide the * URB_SHORT_NOT_OK transfer flag, indicating that short reads are * to be treated as errors; that flag is invalid for write requests. * * Bulk URBs may * use the URB_ZERO_PACKET transfer flag, indicating that bulk OUT transfers * should always terminate with a short packet, even if it means adding an * extra zero length packet. * * Control URBs must provide a valid pointer in the setup_packet field. * Unlike the transfer_buffer, the setup_packet may not be mapped for DMA * beforehand. * * Interrupt URBs must provide an interval, saying how often (in milliseconds * or, for highspeed devices, 125 microsecond units) * to poll for transfers. After the URB has been submitted, the interval * field reflects how the transfer was actually scheduled. * The polling interval may be more frequent than requested. * For example, some controllers have a maximum interval of 32 milliseconds, * while others support intervals of up to 1024 milliseconds. * Isochronous URBs also have transfer intervals. (Note that for isochronous * endpoints, as well as high speed interrupt endpoints, the encoding of * the transfer interval in the endpoint descriptor is logarithmic. * Device drivers must convert that value to linear units themselves.) * * Isochronous URBs normally use the URB_ISO_ASAP transfer flag, telling * the host controller to schedule the transfer as soon as bandwidth * utilization allows, and then set start_frame to reflect the actual frame * selected during submission. Otherwise drivers must specify the start_frame * and handle the case where the transfer can't begin then. However, drivers * won't know how bandwidth is currently allocated, and while they can * find the current frame using usb_get_current_frame_number () they can't * know the range for that frame number. (Ranges for frame counter values * are HC-specific, and can go from 256 to 65536 frames from "now".) * * Isochronous URBs have a different data transfer model, in part because * the quality of service is only "best effort". Callers provide specially * allocated URBs, with number_of_packets worth of iso_frame_desc structures * at the end. Each such packet is an individual ISO transfer. Isochronous * URBs are normally queued, submitted by drivers to arrange that * transfers are at least double buffered, and then explicitly resubmitted * in completion handlers, so * that data (such as audio or video) streams at as constant a rate as the * host controller scheduler can support. * * Completion Callbacks: * * The completion callback is made in_interrupt(), and one of the first * things that a completion handler should do is check the status field. * The status field is provided for all URBs. It is used to report * unlinked URBs, and status for all non-ISO transfers. It should not * be examined before the URB is returned to the completion handler. * * The context field is normally used to link URBs back to the relevant * driver or request state. * * When the completion callback is invoked for non-isochronous URBs, the * actual_length field tells how many bytes were transferred. This field * is updated even when the URB terminated with an error or was unlinked. * * ISO transfer status is reported in the status and actual_length fields * of the iso_frame_desc array, and the number of errors is reported in * error_count. Completion callbacks for ISO transfers will normally * (re)submit URBs to ensure a constant transfer rate. * * Note that even fields marked "public" should not be touched by the driver * when the urb is owned by the hcd, that is, since the call to * usb_submit_urb() till the entry into the completion routine. */ struct urb { /* private: usb core and host controller only fields in the urb */ struct kref kref; /* reference count of the URB */ void *hcpriv; /* private data for host controller */ atomic_t use_count; /* concurrent submissions counter */ atomic_t reject; /* submissions will fail */ int unlinked; /* unlink error code */ /* public: documented fields in the urb that can be used by drivers */ struct list_head urb_list; /* list head for use by the urb's * current owner */ struct list_head anchor_list; /* the URB may be anchored */ struct usb_anchor *anchor; struct usb_device *dev; /* (in) pointer to associated device */ struct usb_host_endpoint *ep; /* (internal) pointer to endpoint */ unsigned int pipe; /* (in) pipe information */ unsigned int stream_id; /* (in) stream ID */ int status; /* (return) non-ISO status */ unsigned int transfer_flags; /* (in) URB_SHORT_NOT_OK | ...*/ void *transfer_buffer; /* (in) associated data buffer */ dma_addr_t transfer_dma; /* (in) dma addr for transfer_buffer */ struct scatterlist *sg; /* (in) scatter gather buffer list */ int num_mapped_sgs; /* (internal) mapped sg entries */ int num_sgs; /* (in) number of entries in the sg list */ u32 transfer_buffer_length; /* (in) data buffer length */ u32 actual_length; /* (return) actual transfer length */ unsigned char *setup_packet; /* (in) setup packet (control only) */ dma_addr_t setup_dma; /* (in) dma addr for setup_packet */ int start_frame; /* (modify) start frame (ISO) */ int number_of_packets; /* (in) number of ISO packets */ int interval; /* (modify) transfer interval * (INT/ISO) */ int error_count; /* (return) number of ISO errors */ void *context; /* (in) context for completion */ usb_complete_t complete; /* (in) completion routine */ struct usb_iso_packet_descriptor iso_frame_desc[0]; /* (in) ISO ONLY */ }; /* ----------------------------------------------------------------------- */ /** * usb_fill_control_urb - initializes a control urb * @urb: pointer to the urb to initialize. * @dev: pointer to the struct usb_device for this urb. * @pipe: the endpoint pipe * @setup_packet: pointer to the setup_packet buffer * @transfer_buffer: pointer to the transfer buffer * @buffer_length: length of the transfer buffer * @complete_fn: pointer to the usb_complete_t function * @context: what to set the urb context to. * * Initializes a control urb with the proper information needed to submit * it to a device. */ static inline void usb_fill_control_urb(struct urb *urb, struct usb_device *dev, unsigned int pipe, unsigned char *setup_packet, void *transfer_buffer, int buffer_length, usb_complete_t complete_fn, void *context) { urb->dev = dev; urb->pipe = pipe; urb->setup_packet = setup_packet; urb->transfer_buffer = transfer_buffer; urb->transfer_buffer_length = buffer_length; urb->complete = complete_fn; urb->context = context; } /** * usb_fill_bulk_urb - macro to help initialize a bulk urb * @urb: pointer to the urb to initialize. * @dev: pointer to the struct usb_device for this urb. * @pipe: the endpoint pipe * @transfer_buffer: pointer to the transfer buffer * @buffer_length: length of the transfer buffer * @complete_fn: pointer to the usb_complete_t function * @context: what to set the urb context to. * * Initializes a bulk urb with the proper information needed to submit it * to a device. */ static inline void usb_fill_bulk_urb(struct urb *urb, struct usb_device *dev, unsigned int pipe, void *transfer_buffer, int buffer_length, usb_complete_t complete_fn, void *context) { urb->dev = dev; urb->pipe = pipe; urb->transfer_buffer = transfer_buffer; urb->transfer_buffer_length = buffer_length; urb->complete = complete_fn; urb->context = context; } /** * usb_fill_int_urb - macro to help initialize a interrupt urb * @urb: pointer to the urb to initialize. * @dev: pointer to the struct usb_device for this urb. * @pipe: the endpoint pipe * @transfer_buffer: pointer to the transfer buffer * @buffer_length: length of the transfer buffer * @complete_fn: pointer to the usb_complete_t function * @context: what to set the urb context to. * @interval: what to set the urb interval to, encoded like * the endpoint descriptor's bInterval value. * * Initializes a interrupt urb with the proper information needed to submit * it to a device. * * Note that High Speed and SuperSpeed interrupt endpoints use a logarithmic * encoding of the endpoint interval, and express polling intervals in * microframes (eight per millisecond) rather than in frames (one per * millisecond). * * Wireless USB also uses the logarithmic encoding, but specifies it in units of * 128us instead of 125us. For Wireless USB devices, the interval is passed * through to the host controller, rather than being translated into microframe * units. */ static inline void usb_fill_int_urb(struct urb *urb, struct usb_device *dev, unsigned int pipe, void *transfer_buffer, int buffer_length, usb_complete_t complete_fn, void *context, int interval) { urb->dev = dev; urb->pipe = pipe; urb->transfer_buffer = transfer_buffer; urb->transfer_buffer_length = buffer_length; urb->complete = complete_fn; urb->context = context; if (dev->speed == USB_SPEED_HIGH || dev->speed == USB_SPEED_SUPER) urb->interval = 1 << (interval - 1); else urb->interval = interval; urb->start_frame = -1; } extern void usb_init_urb(struct urb *urb); extern struct urb *usb_alloc_urb(int iso_packets, gfp_t mem_flags); extern void usb_free_urb(struct urb *urb); #define usb_put_urb usb_free_urb extern struct urb *usb_get_urb(struct urb *urb); extern int usb_submit_urb(struct urb *urb, gfp_t mem_flags); extern int usb_unlink_urb(struct urb *urb); extern void usb_kill_urb(struct urb *urb); extern void usb_poison_urb(struct urb *urb); extern void usb_unpoison_urb(struct urb *urb); extern void usb_kill_anchored_urbs(struct usb_anchor *anchor); extern void usb_poison_anchored_urbs(struct usb_anchor *anchor); extern void usb_unpoison_anchored_urbs(struct usb_anchor *anchor); extern void usb_unlink_anchored_urbs(struct usb_anchor *anchor); extern void usb_anchor_urb(struct urb *urb, struct usb_anchor *anchor); extern void usb_unanchor_urb(struct urb *urb); extern int usb_wait_anchor_empty_timeout(struct usb_anchor *anchor, unsigned int timeout); extern struct urb *usb_get_from_anchor(struct usb_anchor *anchor); extern void usb_scuttle_anchored_urbs(struct usb_anchor *anchor); extern int usb_anchor_empty(struct usb_anchor *anchor); /** * usb_urb_dir_in - check if an URB describes an IN transfer * @urb: URB to be checked * * Returns 1 if @urb describes an IN transfer (device-to-host), * otherwise 0. */ static inline int usb_urb_dir_in(struct urb *urb) { return (urb->transfer_flags & URB_DIR_MASK) == URB_DIR_IN; } /** * usb_urb_dir_out - check if an URB describes an OUT transfer * @urb: URB to be checked * * Returns 1 if @urb describes an OUT transfer (host-to-device), * otherwise 0. */ static inline int usb_urb_dir_out(struct urb *urb) { return (urb->transfer_flags & URB_DIR_MASK) == URB_DIR_OUT; } void *usb_alloc_coherent(struct usb_device *dev, size_t size, gfp_t mem_flags, dma_addr_t *dma); void usb_free_coherent(struct usb_device *dev, size_t size, void *addr, dma_addr_t dma); #if 0 struct urb *usb_buffer_map(struct urb *urb); void usb_buffer_dmasync(struct urb *urb); void usb_buffer_unmap(struct urb *urb); #endif struct scatterlist; int usb_buffer_map_sg(const struct usb_device *dev, int is_in, struct scatterlist *sg, int nents); #if 0 void usb_buffer_dmasync_sg(const struct usb_device *dev, int is_in, struct scatterlist *sg, int n_hw_ents); #endif void usb_buffer_unmap_sg(const struct usb_device *dev, int is_in, struct scatterlist *sg, int n_hw_ents); /*-------------------------------------------------------------------* * SYNCHRONOUS CALL SUPPORT * *-------------------------------------------------------------------*/ extern int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype, __u16 value, __u16 index, void *data, __u16 size, int timeout); extern int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe, void *data, int len, int *actual_length, int timeout); extern int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe, void *data, int len, int *actual_length, int timeout); /* wrappers around usb_control_msg() for the most common standard requests */ extern int usb_get_descriptor(struct usb_device *dev, unsigned char desctype, unsigned char descindex, void *buf, int size); extern int usb_get_status(struct usb_device *dev, int type, int target, void *data); extern int usb_string(struct usb_device *dev, int index, char *buf, size_t size); /* wrappers that also update important state inside usbcore */ extern int usb_clear_halt(struct usb_device *dev, int pipe); extern int usb_reset_configuration(struct usb_device *dev); extern int usb_set_interface(struct usb_device *dev, int ifnum, int alternate); extern void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr); /* this request isn't really synchronous, but it belongs with the others */ extern int usb_driver_set_configuration(struct usb_device *udev, int config); /* * timeouts, in milliseconds, used for sending/receiving control messages * they typically complete within a few frames (msec) after they're issued * USB identifies 5 second timeouts, maybe more in a few cases, and a few * slow devices (like some MGE Ellipse UPSes) actually push that limit. */ #define USB_CTRL_GET_TIMEOUT 5000 #define USB_CTRL_SET_TIMEOUT 5000 /** * struct usb_sg_request - support for scatter/gather I/O * @status: zero indicates success, else negative errno * @bytes: counts bytes transferred. * * These requests are initialized using usb_sg_init(), and then are used * as request handles passed to usb_sg_wait() or usb_sg_cancel(). Most * members of the request object aren't for driver access. * * The status and bytecount values are valid only after usb_sg_wait() * returns. If the status is zero, then the bytecount matches the total * from the request. * * After an error completion, drivers may need to clear a halt condition * on the endpoint. */ struct usb_sg_request { int status; size_t bytes; /* private: * members below are private to usbcore, * and are not provided for driver access! */ spinlock_t lock; struct usb_device *dev; int pipe; int entries; struct urb **urbs; int count; struct completion complete; }; int usb_sg_init( struct usb_sg_request *io, struct usb_device *dev, unsigned pipe, unsigned period, struct scatterlist *sg, int nents, size_t length, gfp_t mem_flags ); void usb_sg_cancel(struct usb_sg_request *io); void usb_sg_wait(struct usb_sg_request *io); /* ----------------------------------------------------------------------- */ /* * For various legacy reasons, Linux has a small cookie that's paired with * a struct usb_device to identify an endpoint queue. Queue characteristics * are defined by the endpoint's descriptor. This cookie is called a "pipe", * an unsigned int encoded as: * * - direction: bit 7 (0 = Host-to-Device [Out], * 1 = Device-to-Host [In] ... * like endpoint bEndpointAddress) * - device address: bits 8-14 ... bit positions known to uhci-hcd * - endpoint: bits 15-18 ... bit positions known to uhci-hcd * - pipe type: bits 30-31 (00 = isochronous, 01 = interrupt, * 10 = control, 11 = bulk) * * Given the device address and endpoint descriptor, pipes are redundant. */ /* NOTE: these are not the standard USB_ENDPOINT_XFER_* values!! */ /* (yet ... they're the values used by usbfs) */ #define PIPE_ISOCHRONOUS 0 #define PIPE_INTERRUPT 1 #define PIPE_CONTROL 2 #define PIPE_BULK 3 #define usb_pipein(pipe) ((pipe) & USB_DIR_IN) #define usb_pipeout(pipe) (!usb_pipein(pipe)) #define usb_pipedevice(pipe) (((pipe) >> 8) & 0x7f) #define usb_pipeendpoint(pipe) (((pipe) >> 15) & 0xf) #define usb_pipetype(pipe) (((pipe) >> 30) & 3) #define usb_pipeisoc(pipe) (usb_pipetype((pipe)) == PIPE_ISOCHRONOUS) #define usb_pipeint(pipe) (usb_pipetype((pipe)) == PIPE_INTERRUPT) #define usb_pipecontrol(pipe) (usb_pipetype((pipe)) == PIPE_CONTROL) #define usb_pipebulk(pipe) (usb_pipetype((pipe)) == PIPE_BULK) static inline unsigned int __create_pipe(struct usb_device *dev, unsigned int endpoint) { return (dev->devnum << 8) | (endpoint << 15); } /* Create various pipes... */ #define usb_sndctrlpipe(dev, endpoint) \ ((PIPE_CONTROL << 30) | __create_pipe(dev, endpoint)) #define usb_rcvctrlpipe(dev, endpoint) \ ((PIPE_CONTROL << 30) | __create_pipe(dev, endpoint) | USB_DIR_IN) #define usb_sndisocpipe(dev, endpoint) \ ((PIPE_ISOCHRONOUS << 30) | __create_pipe(dev, endpoint)) #define usb_rcvisocpipe(dev, endpoint) \ ((PIPE_ISOCHRONOUS << 30) | __create_pipe(dev, endpoint) | USB_DIR_IN) #define usb_sndbulkpipe(dev, endpoint) \ ((PIPE_BULK << 30) | __create_pipe(dev, endpoint)) #define usb_rcvbulkpipe(dev, endpoint) \ ((PIPE_BULK << 30) | __create_pipe(dev, endpoint) | USB_DIR_IN) #define usb_sndintpipe(dev, endpoint) \ ((PIPE_INTERRUPT << 30) | __create_pipe(dev, endpoint)) #define usb_rcvintpipe(dev, endpoint) \ ((PIPE_INTERRUPT << 30) | __create_pipe(dev, endpoint) | USB_DIR_IN) static inline struct usb_host_endpoint * usb_pipe_endpoint(struct usb_device *dev, unsigned int pipe) { struct usb_host_endpoint **eps; eps = usb_pipein(pipe) ? dev->ep_in : dev->ep_out; return eps[usb_pipeendpoint(pipe)]; } /*-------------------------------------------------------------------------*/ static inline __u16 usb_maxpacket(struct usb_device *udev, int pipe, int is_out) { struct usb_host_endpoint *ep; unsigned epnum = usb_pipeendpoint(pipe); if (is_out) { WARN_ON(usb_pipein(pipe)); ep = udev->ep_out[epnum]; } else { WARN_ON(usb_pipeout(pipe)); ep = udev->ep_in[epnum]; } if (!ep) return 0; /* NOTE: only 0x07ff bits are for packet size... */ return le16_to_cpu(ep->desc.wMaxPacketSize); } /* ----------------------------------------------------------------------- */ /* Events from the usb core */ #define USB_DEVICE_ADD 0x0001 #define USB_DEVICE_REMOVE 0x0002 #define USB_BUS_ADD 0x0003 #define USB_BUS_REMOVE 0x0004 extern void usb_register_notify(struct notifier_block *nb); extern void usb_unregister_notify(struct notifier_block *nb); #ifdef DEBUG #define dbg(format, arg...) \ printk(KERN_DEBUG "%s: " format "\n", __FILE__, ##arg) #else #define dbg(format, arg...) \ do { \ if (0) \ printk(KERN_DEBUG "%s: " format "\n", __FILE__, ##arg); \ } while (0) #endif #define err(format, arg...) \ printk(KERN_ERR KBUILD_MODNAME ": " format "\n", ##arg) /* debugfs stuff */ extern struct dentry *usb_debug_root; #endif /* __KERNEL__ */ #endif
alfsamsung/LG_X3_P880_v20a
include/linux/usb.h
C
gpl-2.0
63,429
/** @copyright Copyright (c) 2008 - 2010, AuthenTec Oy. All rights reserved. wince_wan_interface.h This file contains the type definitions and function declarations for Windows CE WAN Interfaces (i.e. dial-up interfaces). */ #ifndef SSH_WINCE_WAN_INTERFACE_H #define SSH_WINCE_WAN_INTERFACE_H #ifdef __cplusplus extern "C" { #endif #ifdef _WIN32_WCE /*-------------------------------------------------------------------------- DEFINITIONS --------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------- ENUMERATIONS --------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------- TYPE DEFINITIONS --------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------- EXPORTED FUNCTIONS --------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------- Frees buffer returned by ssh_wan_alloc_buffer_send(). Can be called from a WanSendComplete handler. --------------------------------------------------------------------------*/ void ssh_wan_free_buffer_send(PNDIS_WAN_PACKET wan_pkt); /*-------------------------------------------------------------------------- Inspects a PPP-encapsulated packet received from a WAN protocol. If it is an IPv4 or IPv6 packet, removes the PPP header from the packet, leaving a bare IPv4 or IPv6 packet, stores the protocol (IPv4 or IPv6) in *protocol and returns TRUE. Otherwise leaves the packet untouched and returns FALSE. --------------------------------------------------------------------------*/ Boolean ssh_wan_intercept_from_protocol(SshNdisIMAdapter adapter, PNDIS_WAN_PACKET packet, SshInterceptorProtocol *protocol); /*-------------------------------------------------------------------------- Processes a PPP-encapsulated non-IP packet received from a WAN protocol. The packet will be either dropped, rejected or passed directly to the corresponding WAN adapter. The status stored in *status should be returned to NDIS by the caller. --------------------------------------------------------------------------*/ void ssh_wan_process_from_protocol(SshNdisIMAdapter adapter, PNDIS_WAN_PACKET packet, PNDIS_STATUS status); /*-------------------------------------------------------------------------- Inspects a PPP-encapsulated packet received from a WAN adapter. If it is an IPv4 or IPv6 packet, removes the PPP header from the packet, leaving a bare IPv4 or IPv6 packet, stores the protocol (IPv4 or IPv6) in *protocol and returns TRUE. Otherwise leaves the packet untouched and returns FALSE. --------------------------------------------------------------------------*/ Boolean ssh_wan_intercept_from_adapter(SshNdisIMAdapter adapter, PUCHAR *packet, ULONG *packet_size, SshInterceptorProtocol *protocol); /*-------------------------------------------------------------------------- Processes a PPP-encapsulated non-IP packet received from a WAN adapter. The packet will be either dropped, rejected or passed directly to the corresponding WAN protocol. The status stored in *status should be returned to NDIS by the caller. --------------------------------------------------------------------------*/ void ssh_wan_process_from_adapter(SshNdisIMAdapter adapter, PUCHAR packet, ULONG packet_size, PNDIS_STATUS status); /*-------------------------------------------------------------------------- PPP-encapsulates an IPv4 or IPv6 packet and sends it to WAN adapter. If successful, returns TRUE, otherwise returns FALSE. --------------------------------------------------------------------------*/ Boolean ssh_wan_send_to_adapter(SshNdisIMAdapter adapter, SshNdisPacket packet, SshInterceptorProtocol protocol); /*-------------------------------------------------------------------------- PPP-encapsulates an IPv4 or IPv6 packet and indicates it to WAN protocol. If successful, returns TRUE, otherwise returns FALSE. --------------------------------------------------------------------------*/ Boolean ssh_wan_send_to_protocol(SshNdisIMAdapter adapter, SshNdisPacket packet, SshInterceptorProtocol protocol); #endif /* _WIN32_WCE */ #ifdef __cplusplus } #endif #endif /* SSH_WINCE_WAN_INTERCFACE */
invisiblek/kernel_808l
drivers/net/eip93_drivers/quickSec/src/interceptor/windows/winim/wince_wan_interface.h
C
gpl-2.0
4,932
package de.superioz.moo.network.client; import de.superioz.moo.network.server.NetworkServer; import lombok.Getter; import de.superioz.moo.api.collection.UnmodifiableList; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * The hub for storing the client connections * * @see MooClient */ public final class ClientManager { /** * It is only necessary to only have one ClientHub instance so this is the static access for this * class after it has been initialised by the network server */ @Getter private static ClientManager instance; /** * The connected {@link MooClient}'s by the type of them */ private ConcurrentMap<ClientType, Map<InetSocketAddress, MooClient>> clientsByType = new ConcurrentHashMap<>(); /** * The ram usage of every daemon (as socketaddress) as percent */ @Getter private Map<InetSocketAddress, Integer> daemonRamUsage = new HashMap<>(); /** * The netty server the clients are connected to */ private NetworkServer netServer; public ClientManager(NetworkServer netServer) { instance = this; this.netServer = netServer; for(ClientType clientType : ClientType.values()) { clientsByType.put(clientType, new HashMap<>()); } } /** * Updates the ramUsage of a daemon * * @param address The address of the daemon/server * @param ramUsage The ramUsage in per cent */ public void updateRamUsage(InetSocketAddress address, int ramUsage) { Map<InetSocketAddress, MooClient> daemonClients = clientsByType.get(ClientType.DAEMON); if(!daemonClients.containsKey(address)) return; daemonRamUsage.put(address, ramUsage); } /** * Gets the best available daemon where the ram usage is the lowest * * @return The client */ public MooClient getBestDaemon() { Map<InetSocketAddress, MooClient> daemonClients = clientsByType.get(ClientType.DAEMON); if(daemonClients.isEmpty()) return null; int lowesRamUsage = -1; MooClient lowestRamUsageClient = null; for(InetSocketAddress address : daemonClients.keySet()) { if(!daemonRamUsage.containsKey(address)) continue; MooClient client = daemonClients.get(address); int ramUsage = daemonRamUsage.get(address); if((lowesRamUsage == -1 || lowesRamUsage > ramUsage) && !((lowesRamUsage = ramUsage) >= (Integer) netServer.getConfig().get("slots-ram-usage"))) { lowestRamUsageClient = client; } } return lowestRamUsageClient; } /** * Adds a client to the hub * * @param cl The client * @return The size of the map */ public int add(MooClient cl) { Map<InetSocketAddress, MooClient> map = clientsByType.get(cl.getType()); map.put(cl.getAddress(), cl); if(cl.getType() == ClientType.DAEMON) { daemonRamUsage.put(cl.getAddress(), 0); } return map.size(); } /** * Removes a client from the hub * * @param address The address (the key) * @return This */ public ClientManager remove(InetSocketAddress address) { for(Map<InetSocketAddress, MooClient> m : clientsByType.values()) { m.entrySet().removeIf(entry -> entry.getKey().equals(address)); } return this; } public ClientManager remove(MooClient cl) { return remove(cl.getAddress()); } /** * Gets a client from address * * @param address The address * @return The client */ public MooClient get(InetSocketAddress address) { MooClient client = null; for(Map.Entry<ClientType, Map<InetSocketAddress, MooClient>> entry : clientsByType.entrySet()) { if(entry.getValue().containsKey(address)) { client = entry.getValue().get(address); } } return client; } public boolean contains(InetSocketAddress address) { return get(address) != null; } /** * Get clients (from type) * * @param type The type * @return The list of clients (unmodifiable) */ public UnmodifiableList<MooClient> getClients(ClientType type) { Map<InetSocketAddress, MooClient> map = clientsByType.get(type); return new UnmodifiableList<>(map.values()); } /** * Get all clients inside one list * * @return The list of clients */ public List<MooClient> getAll() { List<MooClient> clients = new ArrayList<>(); for(ClientType clientType : ClientType.values()) { clients.addAll(getClients(clientType)); } return clients; } public UnmodifiableList<MooClient> getMinecraftClients() { List<MooClient> clients = new ArrayList<>(); clients.addAll(getClients(ClientType.PROXY)); clients.addAll(getClients(ClientType.SERVER)); return new UnmodifiableList<>(clients); } public UnmodifiableList<MooClient> getServerClients() { return getClients(ClientType.SERVER); } public UnmodifiableList<MooClient> getProxyClients() { return getClients(ClientType.PROXY); } public UnmodifiableList<MooClient> getCustomClients() { return getClients(ClientType.CUSTOM); } public UnmodifiableList<MooClient> getDaemonClients() { return getClients(ClientType.DAEMON); } }
Superioz/MooProject
network/src/main/java/de/superioz/moo/network/client/ClientManager.java
Java
gpl-2.0
5,716
#include <stdio.h> #include <stdlib.h> #include <unistd.h> int f1(int limite); int f2(int limite) { int i; for (i = 1; i < limite; i ++) f1(i); } int f1(int limite) { int i; for (i = 1; i < limite; i ++) f2(i); } int main(void) { f1(25); }
Logilin/ils
exemples/chapitre-01/test_gprof.c
C
gpl-2.0
256
package models.planners import java.awt.Color import java.awt.image.BufferedImage import utils._ import models.{Yarn, Needle} import models.units.Stitches object Helper { /** First/last needle for the knitting with the given width when center alignment. */ def center(width: Stitches): (Needle, Needle) = { (Needle.middle - (width / 2).approx, Needle.middle + (width / 2).approx) } /** Convert two color image into a yarn pattern. */ def monochromeToPattern(img: BufferedImage, yarnWhite: Yarn, yarnBlack: Yarn): Matrix[Yarn] = { val rgbs = IndexedSeq.tabulate(img.getHeight, img.getWidth)((y, x) => new Color(img.getRGB(x, y))) val colors = rgbs.flatten.toSet.toSeq require(colors.size <= 2, s"not monochrome: ${colors.toList}") val white = if (colors.size > 1 && colors(0).getRGB > colors(1).getRGB) colors(1) else colors(0) rgbs.matrixMap(c => if (c == white) yarnWhite else yarnBlack) } /** Convert the image into a pattern, yarns are take from colors. */ def imageToPattern(img: BufferedImage): Matrix[Yarn] = { val rgbs = IndexedSeq.tabulate(img.getHeight, img.getWidth)((y, x) => new Color(img.getRGB(x, y))) val yarns = colorsToYarns(rgbs.flatten.toSet) val pattern = rgbs.matrixMap(yarns).reverseBoth pattern } def colorsToYarns(colors: Set[Color]) = { colors.zipWithIndex.map { case ([email protected], i) => c -> Yarn(s"White", new Color(0xf4f4f4)) case ([email protected], i) => c -> Yarn(s"Black", c) case ([email protected], i) => c -> Yarn(s"Yellow", c) case ([email protected], i) => c -> Yarn(s"Red", c) case ([email protected], i) => c -> Yarn(s"Green", c) case ([email protected], i) => c -> Yarn(s"Blue", c) case (color, i) => color -> Yarn(s"Yarn $i", color) }.toMap } }
knittery/knittery-ui
app/models/planners/Helper.scala
Scala
gpl-2.0
1,801
/* dnsmasq is Copyright (c) 2000-2015 Simon Kelley 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 dated June, 1991, or (at your option) version 3 dated 29 June, 2007. 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 "dnsmasq.h" #ifdef HAVE_LOOP static ssize_t loop_make_probe(u32 uid); void loop_send_probes() { struct server *serv; if (!option_bool(OPT_LOOP_DETECT)) return; /* Loop through all upstream servers not for particular domains, and send a query to that server which is identifiable, via the uid. If we see that query back again, then the server is looping, and we should not use it. */ for (serv = daemon->servers; serv; serv = serv->next) if (!(serv->flags & (SERV_LITERAL_ADDRESS | SERV_NO_ADDR | SERV_USE_RESOLV | SERV_NO_REBIND | SERV_HAS_DOMAIN | SERV_FOR_NODOTS | SERV_LOOP))) { ssize_t len = loop_make_probe(serv->uid); int fd; struct randfd *rfd = NULL; if (serv->sfd) fd = serv->sfd->fd; else { if (!(rfd = allocate_rfd(serv->addr.sa.sa_family))) continue; fd = rfd->fd; } while (retry_send(sendto(fd, daemon->packet, len, 0, &serv->addr.sa, sa_len(&serv->addr)))); free_rfd(rfd); } } static ssize_t loop_make_probe(u32 uid) { struct dns_header *header = (struct dns_header *)daemon->packet; unsigned char *p = (unsigned char *)(header+1); /* packet buffer overwritten */ daemon->srv_save = NULL; header->id = rand16(); header->ancount = header->nscount = header->arcount = htons(0); header->qdcount = htons(1); header->hb3 = HB3_RD; header->hb4 = 0; SET_OPCODE(header, QUERY); *p++ = 8; sprintf((char *)p, "%.8x", uid); p += 8; *p++ = strlen(LOOP_TEST_DOMAIN); strcpy((char *)p, LOOP_TEST_DOMAIN); /* Add terminating zero */ p += strlen(LOOP_TEST_DOMAIN) + 1; PUTSHORT(LOOP_TEST_TYPE, p); PUTSHORT(C_IN, p); return p - (unsigned char *)header; } int detect_loop(char *query, int type) { int i; u32 uid; struct server *serv; if (!option_bool(OPT_LOOP_DETECT)) return 0; if (type != LOOP_TEST_TYPE || strlen(LOOP_TEST_DOMAIN) + 9 != strlen(query) || strstr(query, LOOP_TEST_DOMAIN) != query + 9) return 0; for (i = 0; i < 8; i++) if (!isxdigit(query[i])) return 0; uid = strtol(query, NULL, 16); for (serv = daemon->servers; serv; serv = serv->next) if (!(serv->flags & (SERV_LITERAL_ADDRESS | SERV_NO_ADDR | SERV_USE_RESOLV | SERV_NO_REBIND | SERV_HAS_DOMAIN | SERV_FOR_NODOTS | SERV_LOOP)) && uid == serv->uid) { serv->flags |= SERV_LOOP; check_servers(); /* log new state */ return 1; } return 0; } #endif
ghmajx/asuswrt-merlin
release/src/router/dnsmasq/src/loop.c
C
gpl-2.0
3,165
import math as mth import numpy as np #---------------------- # J Matthews, 21/02 # This is a file containing useful constants for python coding # # Units in CGS unless stated # #---------------------- #H=6.62606957E-27 HEV=4.13620e-15 #C=29979245800.0 #BOLTZMANN=1.3806488E-16 VERY_BIG=1e50 H=6.6262e-27 HC=1.98587e-16 HEV=4.13620e-15 # Planck's constant in eV HRYD=3.04005e-16 # NSH 1204 Planck's constant in Rydberg C =2.997925e10 G=6.670e-8 BOLTZMANN =1.38062e-16 WIEN= 5.879e10 # NSH 1208 Wien Disp Const in frequency units H_OVER_K=4.799437e-11 STEFAN_BOLTZMANN =5.6696e-5 THOMPSON=0.66524e-24 PI = 3.1415927 MELEC = 9.10956e-28 E= 4.8035e-10 # Electric charge in esu MPROT = 1.672661e-24 MSOL = 1.989e33 PC= 3.08e18 YR = 3.1556925e7 PI_E2_OVER_MC=0.02655103 # Classical cross-section PI_E2_OVER_M =7.96e8 ALPHA= 7.297351e-3 # Fine structure constant BOHR= 0.529175e-8 # Bohr radius CR= 3.288051e15 #Rydberg frequency for H != Ryd freq for infinite mass ANGSTROM = 1.e-8 #Definition of an Angstrom in units of this code, e.g. cm EV2ERGS =1.602192e-12 RADIAN= 57.29578 RYD2ERGS =2.1798741e-11 PARSEC=3.086E18
jhmatthews/panlens
constants.py
Python
gpl-2.0
1,157
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; namespace WeifenLuo.WinFormsUI.Docking { #region DockPanelSkin classes /// <summary> /// The skin to use when displaying the DockPanel. /// The skin allows custom gradient color schemes to be used when drawing the /// DockStrips and Tabs. /// </summary> [TypeConverter(typeof(DockPanelSkinConverter))] public class DockPanelSkin { private AutoHideStripSkin m_autoHideStripSkin; private DockPaneStripSkin m_dockPaneStripSkin; public DockPanelSkin() { m_autoHideStripSkin = new AutoHideStripSkin(); m_dockPaneStripSkin = new DockPaneStripSkin(); } /// <summary> /// The skin used to display the auto hide strips and tabs. /// </summary> public AutoHideStripSkin AutoHideStripSkin { get { return m_autoHideStripSkin; } set { m_autoHideStripSkin = value; } } /// <summary> /// The skin used to display the Document and ToolWindow style DockStrips and Tabs. /// </summary> public DockPaneStripSkin DockPaneStripSkin { get { return m_dockPaneStripSkin; } set { m_dockPaneStripSkin = value; } } } /// <summary> /// The skin used to display the auto hide strip and tabs. /// </summary> [TypeConverter(typeof(AutoHideStripConverter))] public class AutoHideStripSkin { private DockPanelGradient m_dockStripGradient; private TabGradient m_TabGradient; public AutoHideStripSkin() { m_dockStripGradient = new DockPanelGradient(); m_dockStripGradient.StartColor = SystemColors.ControlLight; m_dockStripGradient.EndColor = SystemColors.ControlLight; m_TabGradient = new TabGradient(); m_TabGradient.TextColor = SystemColors.ControlDarkDark; } /// <summary> /// The gradient color skin for the DockStrips. /// </summary> public DockPanelGradient DockStripGradient { get { return m_dockStripGradient; } set { m_dockStripGradient = value; } } /// <summary> /// The gradient color skin for the Tabs. /// </summary> public TabGradient TabGradient { get { return m_TabGradient; } set { m_TabGradient = value; } } } /// <summary> /// The skin used to display the document and tool strips and tabs. /// </summary> [TypeConverter(typeof(DockPaneStripConverter))] public class DockPaneStripSkin { private DockPaneStripGradient m_DocumentGradient; private DockPaneStripToolWindowGradient m_ToolWindowGradient; public DockPaneStripSkin() { m_DocumentGradient = new DockPaneStripGradient(); m_DocumentGradient.DockStripGradient.StartColor = SystemColors.Control; m_DocumentGradient.DockStripGradient.EndColor = SystemColors.Control; m_DocumentGradient.ActiveTabGradient.StartColor = SystemColors.ControlLightLight; m_DocumentGradient.ActiveTabGradient.EndColor = SystemColors.ControlLightLight; m_DocumentGradient.InactiveTabGradient.StartColor = SystemColors.ControlLight; m_DocumentGradient.InactiveTabGradient.EndColor = SystemColors.ControlLight; m_ToolWindowGradient = new DockPaneStripToolWindowGradient(); m_ToolWindowGradient.DockStripGradient.StartColor = SystemColors.ControlLight; m_ToolWindowGradient.DockStripGradient.EndColor = SystemColors.ControlLight; m_ToolWindowGradient.ActiveTabGradient.StartColor = SystemColors.Control; m_ToolWindowGradient.ActiveTabGradient.EndColor = SystemColors.Control; m_ToolWindowGradient.InactiveTabGradient.StartColor = Color.Transparent; m_ToolWindowGradient.InactiveTabGradient.EndColor = Color.Transparent; m_ToolWindowGradient.InactiveTabGradient.TextColor = SystemColors.ControlDarkDark; m_ToolWindowGradient.ActiveCaptionGradient.StartColor = SystemColors.GradientActiveCaption; m_ToolWindowGradient.ActiveCaptionGradient.EndColor = SystemColors.ActiveCaption; m_ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; m_ToolWindowGradient.ActiveCaptionGradient.TextColor = SystemColors.ActiveCaptionText; m_ToolWindowGradient.InactiveCaptionGradient.StartColor = SystemColors.GradientInactiveCaption; m_ToolWindowGradient.InactiveCaptionGradient.EndColor = SystemColors.GradientInactiveCaption; m_ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; m_ToolWindowGradient.InactiveCaptionGradient.TextColor = SystemColors.ControlText; } /// <summary> /// The skin used to display the Document style DockPane strip and tab. /// </summary> public DockPaneStripGradient DocumentGradient { get { return m_DocumentGradient; } set { m_DocumentGradient = value; } } /// <summary> /// The skin used to display the ToolWindow style DockPane strip and tab. /// </summary> public DockPaneStripToolWindowGradient ToolWindowGradient { get { return m_ToolWindowGradient; } set { m_ToolWindowGradient = value; } } } /// <summary> /// The skin used to display the DockPane ToolWindow strip and tab. /// </summary> [TypeConverter(typeof(DockPaneStripGradientConverter))] public class DockPaneStripToolWindowGradient : DockPaneStripGradient { private TabGradient m_activeCaptionGradient; private TabGradient m_inactiveCaptionGradient; public DockPaneStripToolWindowGradient() { m_activeCaptionGradient = new TabGradient(); m_inactiveCaptionGradient = new TabGradient(); } /// <summary> /// The skin used to display the active ToolWindow caption. /// </summary> public TabGradient ActiveCaptionGradient { get { return m_activeCaptionGradient; } set { m_activeCaptionGradient = value; } } /// <summary> /// The skin used to display the inactive ToolWindow caption. /// </summary> public TabGradient InactiveCaptionGradient { get { return m_inactiveCaptionGradient; } set { m_inactiveCaptionGradient = value; } } } /// <summary> /// The skin used to display the DockPane strip and tab. /// </summary> [TypeConverter(typeof(DockPaneStripGradientConverter))] public class DockPaneStripGradient { private DockPanelGradient m_dockStripGradient; private TabGradient m_activeTabGradient; private TabGradient m_inactiveTabGradient; public DockPaneStripGradient() { m_dockStripGradient = new DockPanelGradient(); m_activeTabGradient = new TabGradient(); m_inactiveTabGradient = new TabGradient(); } /// <summary> /// The gradient color skin for the DockStrip. /// </summary> public DockPanelGradient DockStripGradient { get { return m_dockStripGradient; } set { m_dockStripGradient = value; } } /// <summary> /// The skin used to display the active DockPane tabs. /// </summary> public TabGradient ActiveTabGradient { get { return m_activeTabGradient; } set { m_activeTabGradient = value; } } /// <summary> /// The skin used to display the inactive DockPane tabs. /// </summary> public TabGradient InactiveTabGradient { get { return m_inactiveTabGradient; } set { m_inactiveTabGradient = value; } } } /// <summary> /// The skin used to display the dock pane tab /// </summary> [TypeConverter(typeof(DockPaneTabGradientConverter))] public class TabGradient : DockPanelGradient { private Color m_textColor; public TabGradient() { m_textColor = SystemColors.ControlText; } /// <summary> /// The text color. /// </summary> [DefaultValue(typeof(SystemColors), "ControlText")] public Color TextColor { get { return m_textColor; } set { m_textColor = value; } } } /// <summary> /// The gradient color skin. /// </summary> [TypeConverter(typeof(DockPanelGradientConverter))] public class DockPanelGradient { private Color m_startColor; private Color m_endColor; private LinearGradientMode m_linearGradientMode; public DockPanelGradient() { m_startColor = SystemColors.Control; m_endColor = SystemColors.Control; m_linearGradientMode = LinearGradientMode.Horizontal; } /// <summary> /// The beginning gradient color. /// </summary> [DefaultValue(typeof(SystemColors), "Control")] public Color StartColor { get { return m_startColor; } set { m_startColor = value; } } /// <summary> /// The ending gradient color. /// </summary> [DefaultValue(typeof(SystemColors), "Control")] public Color EndColor { get { return m_endColor; } set { m_endColor = value; } } /// <summary> /// The gradient mode to display the colors. /// </summary> [DefaultValue(LinearGradientMode.Horizontal)] public LinearGradientMode LinearGradientMode { get { return m_linearGradientMode; } set { m_linearGradientMode = value; } } } #endregion DockPanelSkin classes #region Converters public class DockPanelSkinConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(DockPanelSkin)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is DockPanelSkin) { return "DockPanelSkin"; } return base.ConvertTo(context, culture, value, destinationType); } } public class DockPanelGradientConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(DockPanelGradient)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is DockPanelGradient) { return "DockPanelGradient"; } return base.ConvertTo(context, culture, value, destinationType); } } public class AutoHideStripConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(AutoHideStripSkin)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is AutoHideStripSkin) { return "AutoHideStripSkin"; } return base.ConvertTo(context, culture, value, destinationType); } } public class DockPaneStripConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(DockPaneStripSkin)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is DockPaneStripSkin) { return "DockPaneStripSkin"; } return base.ConvertTo(context, culture, value, destinationType); } } public class DockPaneStripGradientConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(DockPaneStripGradient)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is DockPaneStripGradient) { return "DockPaneStripGradient"; } return base.ConvertTo(context, culture, value, destinationType); } } public class DockPaneTabGradientConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(TabGradient)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is TabGradient) { return "DockPaneTabGradient"; } return base.ConvertTo(context, culture, value, destinationType); } } #endregion Converters }
DragonFiestaTeam/DragonFiesta_Tools
QuestAnalyser/src/Docking/DockPanelSkin.cs
C#
gpl-2.0
14,802
/* * General control styling */ .control-table .table-container { border: 1px solid #e0e0e0; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; overflow: hidden; margin-bottom: 15px; } .control-table .table-container:last-child { margin-bottom: 0; } .control-table.active .table-container { border-color: #808c8d; } .control-table table { width: 100%; border-collapse: collapse; table-layout: fixed; } .control-table table td, .control-table table th { padding: 0; font-size: 13px; color: #555555; } .control-table table [data-view-container] { padding: 5px 10px; width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-height: 28px; } .control-table table.headers:after { content: ' '; display: block; position: absolute; left: 1px; right: 1px; margin-top: -1px; border-bottom: 1px solid #e0e0e0; } .control-table table.headers th { padding: 7px 10px; font-size: 13px; text-transform: uppercase; font-weight: 600; color: #333333; background: white; border-right: 1px solid #ecf0f1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .control-table table.headers th [data-view-container] { padding-bottom: 6px; } .control-table table.headers th:last-child { border-right: none; } .control-table.active table.headers:after { border-bottom-color: #808c8d; } .control-table table.data td { border: 1px solid #ecf0f1; } .control-table table.data td .content-container { position: relative; padding: 1px; } .control-table table.data td.active { border-color: #5fb6f5 !important; } .control-table table.data td.active .content-container { padding: 0; border: 1px solid #5fb6f5; } .control-table table.data td.active .content-container:before, .control-table table.data td.active .content-container:after { content: ' '; background: #5fb6f5; position: absolute; left: -2px; top: -2px; } .control-table table.data td.active .content-container:before { width: 1px; bottom: -2px; } .control-table table.data td.active .content-container:after { right: -2px; height: 1px; } .control-table table.data tr { background-color: white; } .control-table table.data tr.error { background-color: #fbecec!important; } .control-table table.data tr.error td.active.error { border-color: #ec0000!important; } .control-table table.data tr.error td.active.error .content-container { border-color: #ec0000!important; } .control-table table.data tr.error td.active.error .content-container:before, .control-table table.data tr.error td.active.error .content-container:after { background-color: #ec0000!important; } .control-table table.data tr:nth-child(2n) { background-color: #fbfbfb; } .control-table table.data tr:first-child td { border-top: none; } .control-table table.data tr:last-child td { border-bottom: none; } .control-table table.data td:first-child { border-left: none; } .control-table table.data td:last-child { border-right: none; } .control-table .control-scrollbar > div { border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; overflow: hidden; } .control-table .control-scrollbar table.data tr:last-child td { border-bottom: 1px solid #ecf0f1; } .control-table .toolbar { background: white; border-bottom: 1px solid #e0e0e0; } .control-table .toolbar a.btn { color: #323e50; padding: 10px; opacity: 0.5; filter: alpha(opacity=50); } .control-table .toolbar a.btn:hover { opacity: 1; filter: alpha(opacity=100); } .control-table .toolbar a.table-icon:before { display: inline-block; content: ' '; width: 16px; height: 16px; margin-right: 8px; position: relative; top: 3px; background: transparent url(../images/table-icons.gif) no-repeat; background-position: 0 0; background-size: 32px auto; } .control-table .toolbar a.table-icon.add-table-row-above:before { background-position: 0 -56px; } .control-table .toolbar a.table-icon.delete-table-row:before { background-position: 0 -113px; } .control-table.active .toolbar { border-bottom-color: #808c8d; } .control-table .pagination ul { padding: 0; margin-bottom: 15px; } .control-table .pagination ul li { list-style: none; padding: 4px 6px; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; display: inline-block; margin-right: 5px; font-size: 12px; background: #ecf0f1; line-height: 100%; } .control-table .pagination ul li a { text-decoration: none; color: #95a5a6; } .control-table .pagination ul li.active { background: #5fb6f5; } .control-table .pagination ul li.active a { color: #ffffff; } @media only screen and (-moz-min-device-pixel-ratio: 1.5), only screen and (-o-min-device-pixel-ratio: 3/2), only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min-devicepixel-ratio: 1.5), only screen and (min-resolution: 1.5dppx) { .control-table .toolbar a:before { background-position: 0px -9px; background-size: 16px auto; } .control-table .toolbar a.add-table-row-above:before { background-position: 0 -39px; } .control-table .toolbar a.delete-table-row:before { background-position: 0 -66px; } } /* * String editor */ .control-table td[data-column-type=string] input[type=text] { width: 100%; height: 100%; display: block; outline: none; border: none; padding: 5px 10px; } /* * Checkbox editor */ .control-table td[data-column-type=checkbox] div[data-checkbox-element] { width: 16px; height: 16px; border-radius: 2px; background-color: #FFFFFF; border: 1px solid #999999; margin: 5px 5px 5px 10px; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .control-table td[data-column-type=checkbox] div[data-checkbox-element]:hover { border-color: #808080; color: #4d4d4d; } .control-table td[data-column-type=checkbox] div[data-checkbox-element].checked { border-width: 2px; } .control-table td[data-column-type=checkbox] div[data-checkbox-element].checked:before { font-family: FontAwesome; font-weight: normal; font-style: normal; text-decoration: inherit; -webkit-font-smoothing: antialiased; *margin-right: .3em; content: "\f00c"; font-size: 10px; position: relative; left: 1px; top: -4px; } .control-table td[data-column-type=checkbox] div[data-checkbox-element]:focus { border-color: #5fb6f5; outline: none; } /* * Dropdown editor */ .control-table td[data-column-type=dropdown] { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .control-table td[data-column-type=dropdown] [data-view-container] { padding-right: 20px; position: relative; cursor: pointer; } .control-table td[data-column-type=dropdown] [data-view-container]:after { font-family: FontAwesome; font-weight: normal; font-style: normal; text-decoration: inherit; -webkit-font-smoothing: antialiased; *margin-right: .3em; content: "\f107"; font-size: 13px; line-height: 100%; color: #95a5a6; position: absolute; top: 8px; right: 10px; } .control-table td[data-column-type=dropdown] [data-view-container]:hover:after { color: #0181b9; } .control-table td[data-column-type=dropdown] [data-dropdown-open=true] { background: white; } .control-table td[data-column-type=dropdown] [data-dropdown-open=true] [data-view-container]:after { font-family: FontAwesome; font-weight: normal; font-style: normal; text-decoration: inherit; -webkit-font-smoothing: antialiased; *margin-right: .3em; content: "\f106"; } .control-table td[data-column-type=dropdown] .content-container { outline: none; } /* Frameless control styles start */ .widget-field.frameless .control-table .table-container { border-top: none; border-left: none; border-right: none; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .widget-field.frameless .control-table .toolbar { background: transparent; } /* Frameless control styles end */ html.cssanimations .control-table td[data-column-type=dropdown] [data-view-container].loading:after { background-image: url('../../../../../../modules/system/assets/ui/images/loader-transparent.svg'); background-size: 15px 15px; background-position: 50% 50%; position: absolute; width: 15px; height: 15px; top: 6px; right: 5px; content: ' '; -webkit-animation: spin 1s linear infinite; animation: spin 1s linear infinite; } .table-control-dropdown-list { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; position: absolute; background: white; border: 1px solid #808c8d; border-top: none; padding-top: 1px; overflow: hidden; z-index: 1000; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; } .table-control-dropdown-list ul { border-top: 1px solid #ecf0f1; padding: 0; margin: 0; max-height: 200px; overflow: auto; } .table-control-dropdown-list li { list-style: none; font-size: 13px; color: #555555; padding: 5px 10px; cursor: pointer; outline: none; } .table-control-dropdown-list li:hover, .table-control-dropdown-list li:focus, .table-control-dropdown-list li.selected { background: #5fb6f5; color: white; }
quamis/PriceMonitor
PriceMonitor/html/october/modules/backend/widgets/table/assets/css/table.css
CSS
gpl-2.0
9,377
def format_path( str ): while( str.find( '//' ) != -1 ): str = str.replace( '//', '/' ) return str
tencent-wechat/phxsql
phxrpc_package_config/tools/phxsql_utils.py
Python
gpl-2.0
103
/* page layout styles */ *{ margin:0; padding:0; } body { background-color:#eee; color:#fff; font:14px/1.3 Arial,sans-serif; } header { background-color:#212121; box-shadow: 0 -1px 2px #111111; display:block; height:70px; position:relative; width:100%; z-index:100; } header h2{ font-size:22px; font-weight:normal; left:50%; margin-left:-400px; padding:22px 0; position:absolute; width:540px; } header a.stuts,a.stuts:visited{ border:none; text-decoration:none; color:#fcfcfc; font-size:14px; left:50%; line-height:31px; margin:23px 0 0 110px; position:absolute; top:0; } header .stuts span { font-size:22px; font-weight:bold; margin-left:5px; } .container { color: #000; margin: 20px auto; overflow: hidden; position: relative; width: 600px; height: 400px; } .controls { border: 1px dashed gray; color: #000; margin: 20px auto; padding: 25px; position: relative; width: 550px; } .controls p { margin-bottom: 10px; } .controls input { margin-left: 10px; }
elephunk84/centralheating
resources/css/graphstyle.css
CSS
gpl-2.0
1,136
#!/usr/bin/env bash # Usage example: # PLot the chirp signal and its frequency domain presentation: # (while true; do echo line; sleep 0.01; done)| \ # awk 'BEGIN{PI=atan2(0,-1);t=0;f0=1;f1=32;T=256;k=(f1-f0)/T;}{print sin(2*PI*(t*f0+k/2*t*t));t+=0.1;fflush()}'| \ # tee >(bin/dsp/fft.sh 64 "w1;0.5;0.5"|bin/dsp/fftabs.sh 64| \ # bin/gp/gnuplotblock.sh '-0.5:31.5;0:0.5' 'Chirp signal spectrum;1')| \ # bin/gp/gnuplotwindow.sh 128 "-1:1" "Chirp signal;2" N=${1:-64} # number of samples, default 64 wd=${2:-w0} # window function description, w0-rectangular window (default), w1-hanning window col=${3:-1} # input stream column to calculate fft for awk -v N="$N" -v col="$col" -v win_desc="$wd" ' function compl_add(a, b, ara,arb) { split(a, ara);split(b, arb); return ara[1]+arb[1]" "ara[2]+arb[2]; } function compl_sub(a, b, ara,arb) { split(a, ara);split(b, arb); return ara[1]-arb[1]" "ara[2]-arb[2]; } function compl_mul(a, b, ara,arb) { split(a, ara);split(b, arb); return ara[1]*arb[1]-ara[2]*arb[2]" "ara[1]*arb[2]+ara[2]*arb[1]; } function init_hanning_window(N,a,b, i) { for(i=0;i<N;++i) { w[i] = a - b*cos(2*PI*i/(N-1)); } } function init_window(N,win_desc, i,wa,a,b,win_type) { split(win_desc, wa, ";"); switch(wa[1]) { case "w1": # hanning window win_type = 1; if (2 in wa) a = wa[2]; else a = 0.5; if (3 in wa) b = wa[3]; else b = 0.5; init_hanning_window(N,a,b); break; case "w0": default: win_type = 0; break; } return win_type; } function apply_window(N, i) { for(i=0;i<N;++i) { c[i]*=w[i]; } } function calc_pow2(N, pow) { pow = 0; while(N = rshift(N,1)) { ++pow; }; return pow; } function bit_reverse(n,pow, i,r) { r = 0; pow-=1; for(i=pow;i>=0;--i) { r = or(r,lshift(and(rshift(n,i),1), pow-i)); } return r; } function binary_inversion(N,pow, tmp,i,j) { # pow = calc_pow2(N); for(i=0;i<N;++i) { j = bit_reverse(i,pow); if (i<j) { tmp = c[i]; c[i] = c[j]; c[j] = tmp; } } } function fft(start,end,e, N,N2,k,t,et) { N = end - start; if (N<2) return; N2 = N/2; et = e; for (k=0;k<N2;++k) { t = c[start+k]; c[start+k] = compl_add(t,c[start+k+N2]); c[start+k+N2] = compl_sub(t,c[start+k+N2]); if (k>0) { c[start+k+N2] = compl_mul(et,c[start+k+N2]); et = compl_mul(et,e); } } et = compl_mul(e,e); fft(start, start+N2, et); fft(start+N2, end, et); } function print_fft(N, N2,i) { N2 = N/2; for(i=1;i<=N2;++i) { print c[i]; } } BEGIN { if (and(N,N-1)!=0) { print "Error: Signal width shall be power of two!" > "/dev/stderr"; exit(1); } start=0;end=0; for(i=0;i<N;++i) a[i]=0; PI = atan2(0,-1); expN = cos(2*PI/N) " " (-sin(2*PI/N)); N2 = N/2; pow = calc_pow2(N); # win_type = 0; # rectangular window by default # win_type = 1; # hanning window win_type = init_window(N, win_desc); } { if (match($0,/^.+$/)) { a[end] = $col; ++end; if (end>start+N) { delete a[start]; start++; } for (i=start;i<N+start;++i) { (i<end)?c[i-start] = a[i]:c[i-start] = 0; } if (win_type!=0) { apply_window(N); } fft(0,N,expN); binary_inversion(N,pow); # N = 2^pow; print_fft(N); printf("\n"); fflush(); } } ' -
flux242/dotfiles
.bin/dsp/fft.sh
Shell
gpl-2.0
3,368
document.addEventListener("DOMContentLoaded", function (event) { 'use strict'; var paragraph, url, proxy; paragraph = document.querySelectorAll('p.error_text'); chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) { url = tabs[0].url; if (url.indexOf('chrome://') == 0) { paragraph[0].innerHTML = 'Sorry, you can\'t activate Browse Google Cache on a page with a "chrome://" URL.'; } else if (url.indexOf('https://chrome.google.com/webstore') == 0) { paragraph[0].innerHTML = 'Sorry, you can\'t activate Browse Google Cache on the Chrome Web Store.'; } else { chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) { chrome.runtime.sendMessage({ action : 'extensionButtonClicked', 'tab': tabs[0] }); window.close(); }); } }); });
joelself/GoogleCacheBrowser
src/popup.js
JavaScript
gpl-2.0
815
using Deployer.Services.Config; using Deployer.Services.Config.Interfaces; using Moq; using NUnit.Framework; using System.Collections; namespace Deployer.Tests.Config { [TestFixture] public class ConfigBuildParamTests { private Mock<IJsonPersistence> _jsonPersist; private Mock<ISlugCreator> _slugCreator; private RealConfigurationService _sut; [SetUp] public void BeforeEachTest() { _jsonPersist = new Mock<IJsonPersistence>(); _slugCreator = new Mock<ISlugCreator>(); _sut = new RealConfigurationService(@"\root\", _jsonPersist.Object, _slugCreator.Object); } [Test] public void Empty_build_params() { _jsonPersist.Setup(x => x.Read(@"\root\config\slug-1.json")).Returns(new Hashtable()); var hash = _sut.GetBuildParams("slug-1"); Assert.IsNotNull(hash); Assert.AreEqual(0, hash.Count); _jsonPersist.Verify(x => x.Read(It.IsAny<string>()), Times.Once); _jsonPersist.Verify(x => x.Read(@"\root\config\slug-1.json"), Times.Once); } [Test] public void Read_params() { var mockHash = new Hashtable { {"key1", "value1"}, {"key2", "value2"} }; _jsonPersist.Setup(x => x.Read(@"\root\config\slug-1.json")).Returns(mockHash); var actualHash = _sut.GetBuildParams("slug-1"); Assert.IsNotNull(actualHash); Assert.AreEqual(2, actualHash.Count); Assert.AreEqual("value1", actualHash["key1"]); Assert.AreEqual("value2", actualHash["key2"]); _jsonPersist.Verify(x => x.Read(It.IsAny<string>()), Times.Once); _jsonPersist.Verify(x => x.Read(@"\root\config\slug-1.json"), Times.Once); } [Test] public void Write_params() { var mockHash = new Hashtable { {"key1", "value1"}, {"key2", "value2"} }; _jsonPersist.Setup(x => x.Write(@"\root\config\slug-1.json", It.IsAny<Hashtable>())) .Callback((string path, Hashtable hash) => { Assert.AreEqual(2, hash.Count); Assert.AreEqual("value1", hash["key1"]); Assert.AreEqual("value2", hash["key2"]); }); _sut.SaveBuildParams("slug-1", mockHash); _jsonPersist.Verify(x => x.Write(@"\root\config\slug-1.json", It.IsAny<Hashtable>()), Times.Once); } } }
DevOpsGear/DeployerOfCodes
Deployer.Tests/Deployer.Services.Tests/Config/ConfigBuildParamTests.cs
C#
gpl-2.0
2,233
package ch.hgdev.toposuite.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Useful static method for manipulating String. * * @author HGdev */ public class StringUtils { public static final String UTF8_BOM = "\uFEFF"; /** * This method assumes that the String contains a number. * * @param str A String. * @return The String incremented by 1. * @throws IllegalArgumentException Thrown if the input String does not end with a suitable * number. */ public static String incrementAsNumber(String str) throws IllegalArgumentException { if (str == null) { throw new IllegalArgumentException("The input String must not be null!"); } Pattern p = Pattern.compile("([0-9]+)$"); Matcher m = p.matcher(str); if (!m.find()) { throw new IllegalArgumentException( "Invalid input argument! The input String must end with a valid number"); } String number = m.group(1); String prefix = str.substring(0, str.length() - number.length()); return prefix + String.valueOf(Integer.valueOf(number) + 1); } }
hgdev-ch/toposuite-android
app/src/main/java/ch/hgdev/toposuite/utils/StringUtils.java
Java
gpl-2.0
1,224
package org.currconv.services.impl; import java.util.List; import org.currconv.dao.UserDao; import org.currconv.entities.user.User; import org.currconv.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service("userService") @Transactional public class UserServiceImpl implements UserService { @Autowired private UserDao dao; public void saveUser(User user) { dao.saveUser(user); } public List<User> findAllUsers(){ return dao.findAllUsers(); } public User findByUserName(String name){ return dao.findByUserName(name); } }
miguel-gr/currency-converter
src/main/java/org/currconv/services/impl/UserServiceImpl.java
Java
gpl-2.0
738
package com.debugtoday.htmldecoder.output; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.regex.Matcher; import org.slf4j.Logger; import com.debugtoday.htmldecoder.decoder.GeneralDecoder; import com.debugtoday.htmldecoder.exception.GeneralException; import com.debugtoday.htmldecoder.log.CommonLog; import com.debugtoday.htmldecoder.output.object.FileOutputArg; import com.debugtoday.htmldecoder.output.object.PaginationOutputArg; import com.debugtoday.htmldecoder.output.object.TagFileOutputArg; import com.debugtoday.htmldecoder.output.object.TagOutputArg; import com.debugtoday.htmldecoder.output.object.TagWrapper; import com.debugtoday.htmldecoder.output.object.TemplateFullTextWrapper; /** * base class for output relative to file output, i.g. article/article page/tag page/category page * @author zydecx * */ public class AbstractFileOutput implements Output { private static final Logger logger = CommonLog.getLogger(); @Override public String export(Object object) throws GeneralException { // TODO Auto-generated method stub return DONE; } /** * @param file * @param template * @param arg * @throws GeneralException */ public void writeToFile(File file, TemplateFullTextWrapper template, FileOutputArg arg) throws GeneralException { File parentFile = file.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { throw new GeneralException("fail to create file[" + file.getAbsolutePath() + "]", e); } } try ( PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); ) { String formattedHead = ""; if (arg.getPageTitle() != null) { formattedHead += "<title>" + arg.getPageTitle() + "</title>"; } if (arg.getHead() != null) { formattedHead += "\n" + arg.getHead(); } String templateFullText = template.getFullText() .replace(GeneralDecoder.formatPlaceholderRegex("head"), formattedHead); if (arg.getBodyTitle() != null) { templateFullText = templateFullText .replace(GeneralDecoder.formatPlaceholderRegex("body_title"), arg.getBodyTitle()); } if (arg.getBody() != null) { templateFullText = templateFullText .replace(GeneralDecoder.formatPlaceholderRegex("body"), arg.getBody()); } if (arg.getPagination() != null) { templateFullText = templateFullText .replace(GeneralDecoder.formatPlaceholderRegex("pagination"), arg.getPagination()); } pw.write(templateFullText); } catch (FileNotFoundException | UnsupportedEncodingException e) { throw new GeneralException("fail to write to file[" + file.getAbsolutePath() + "]", e); } } /** * used for tag page/category page output * @param templateFullTextWrapper * @param arg * @throws GeneralException */ public void exportTagPage(TemplateFullTextWrapper templateFullTextWrapper, TagFileOutputArg arg) throws GeneralException { List<TagWrapper> itemList = arg.getTagList(); int itemSize = itemList.size(); int pagination = arg.getPagination(); int pageSize = (int) Math.ceil(itemSize * 1.0 / pagination); Output tagOutput = arg.getTagOutput(); Output paginationOutput = arg.getPaginationOutput(); for (int i = 1; i <= pageSize; i++) { List<TagWrapper> subList = itemList.subList((i - 1) * pagination, Math.min(itemSize, i * pagination)); StringBuilder sb = new StringBuilder(); for (TagWrapper item : subList) { String itemName = item.getName(); TagOutputArg tagArg = new TagOutputArg(itemName, arg.getRootUrl() + "/" + item.getName(), item.getArticleList().size()); sb.append(tagOutput.export(tagArg)); } File file = new File(formatPageFilePath(arg.getRootFile().getAbsolutePath(), i)); FileOutputArg fileOutputArg = new FileOutputArg(); fileOutputArg.setBodyTitle(arg.getBodyTitle()); fileOutputArg.setBody(sb.toString()); fileOutputArg.setPageTitle(arg.getBodyTitle()); fileOutputArg.setPagination(paginationOutput.export(new PaginationOutputArg(arg.getRootUrl(), pageSize, i))); writeToFile(file, templateFullTextWrapper, fileOutputArg); } } protected String formatPageUrl(String rootUrl, int index) { return PaginationOutput.formatPaginationUrl(rootUrl, index); } protected String formatPageFilePath(String rootPath, int index) { return PaginationOutput.formatPaginationFilePath(rootPath, index); } }
zydecx/htmldecoder
src/main/java/com/debugtoday/htmldecoder/output/AbstractFileOutput.java
Java
gpl-2.0
4,685
void dflu_pack_fin(DFluPack *p) { UC(dmap_fin(NFRAGS, /**/ &p->map)); UC(comm_bags_fin(PINNED, NONE, /**/ &p->hpp, &p->dpp)); if (p->opt.ids) UC(comm_bags_fin(PINNED, NONE, /**/ &p->hii, &p->dii)); if (p->opt.colors) UC(comm_bags_fin(PINNED, NONE, /**/ &p->hcc, &p->dcc)); EFREE(p); } void dflu_comm_fin(DFluComm *c) { UC(comm_fin(c->pp)); if (c->opt.ids) UC(comm_fin(c->ii)); if (c->opt.colors) UC(comm_fin(c->cc)); EFREE(c); } void dflu_unpack_fin(DFluUnpack *u) { UC(comm_bags_fin(HST_ONLY, NONE, &u->hpp, NULL)); if (u->opt.ids) UC(comm_bags_fin(HST_ONLY, NONE, &u->hii, NULL)); if (u->opt.colors) UC(comm_bags_fin(HST_ONLY, NONE, &u->hcc, NULL)); CC(d::Free(u->ppre)); if (u->opt.ids) CC(d::Free(u->iire)); if (u->opt.colors) CC(d::Free(u->ccre)); EFREE(u); }
slitvinov/uDeviceX
src/distr/flu/imp/fin.h
C
gpl-2.0
849
/* MobileRobots Advanced Robotics Interface for Applications (ARIA) Copyright (C) 2004, 2005 ActivMedia Robotics LLC Copyright (C) 2006, 2007, 2008, 2009 MobileRobots Inc. Copyright (C) 2010, 2011 Adept Technology, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA If you wish to redistribute ARIA under different terms, contact Adept MobileRobots for information about a commercial version of ARIA at [email protected] or Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; 800-639-9481 */ #include "Aria.h" #include "ArExport.h" #include "ArServerModeRatioDrive.h" #include "ArServerHandlerCommands.h" AREXPORT ArServerModeRatioDrive::ArServerModeRatioDrive( ArServerBase *server, ArRobot *robot, bool takeControlOnJoystick, bool useComputerJoystick, bool useRobotJoystick, bool useServerCommands, const char *name, bool robotJoystickOverridesLocks) : ArServerMode(robot, server, name), myRatioDriveGroup(robot), myJoyUserTaskCB(this, &ArServerModeRatioDrive::joyUserTask), myServerSetSafeDriveCB(this, &ArServerModeRatioDrive::serverSetSafeDrive), myServerGetSafeDriveCB(this, &ArServerModeRatioDrive::serverGetSafeDrive), myServerRatioDriveCB(this, &ArServerModeRatioDrive::serverRatioDrive), myRatioFireCB(this, &ArServerModeRatioDrive::ratioFireCallback), myServerSafeDrivingEnableCB(this, &ArServerModeRatioDrive::serverSafeDrivingEnable), myServerSafeDrivingDisableCB(this, &ArServerModeRatioDrive::serverSafeDrivingDisable) { myHandlerCommands = NULL; myDriveSafely = true; myTakeControlOnJoystick = takeControlOnJoystick; myUseComputerJoystick = useComputerJoystick; myUseRobotJoystick = useRobotJoystick; myUseServerCommands = useServerCommands; myUseLocationDependentDevices = true; myRobotJoystickOverridesLock = robotJoystickOverridesLocks; myTimeout = 2; myGotServerCommand = true; myLastTimedOut = false; // SEEKUR mySentRecenter = false; // add the actions, put the ratio input on top, then have the // limiters since the ratio doesn't touch decel except lightly // whereas the limiter will touch it strongly myRatioAction = new ArActionRatioInput; myRatioDriveGroup.addAction(myRatioAction, 50); myLimiterForward = new ArActionDeceleratingLimiter( "DeceleratingLimiterForward", ArActionDeceleratingLimiter::FORWARDS); myRatioDriveGroup.addAction(myLimiterForward, 40); myLimiterBackward = new ArActionDeceleratingLimiter( "DeceleratingLimiterBackward", ArActionDeceleratingLimiter::BACKWARDS); myRatioDriveGroup.addAction(myLimiterBackward, 39); myLimiterLateralLeft = NULL; myLimiterLateralRight = NULL; if (myRobot->hasLatVel()) { myLimiterLateralLeft = new ArActionDeceleratingLimiter( "DeceleratingLimiterLateralLeft", ArActionDeceleratingLimiter::LATERAL_LEFT); myRatioDriveGroup.addAction(myLimiterLateralLeft, 38); myLimiterLateralRight = new ArActionDeceleratingLimiter( "DeceleratingLimiterLateralRight", ArActionDeceleratingLimiter::LATERAL_RIGHT); myRatioDriveGroup.addAction(myLimiterLateralRight, 37); } myMovementParameters = new ArActionMovementParameters("TeleopMovementParameters", false); myRatioDriveGroup.addAction(myMovementParameters, 1); myRatioFireCB.setName("ArServerModeRatioDrive"); myRatioAction->addFireCallback(30, &myRatioFireCB); myLastRobotSafeDrive = true; if (myServer != NULL && myUseServerCommands) { addModeData("ratioDrive", "drives the robot as with a joystick", &myServerRatioDriveCB, "double: transRatio; double: rotRatio; double: throttleRatio ", "none", "Movement", "RETURN_NONE"); myServer->addData("setSafeDrive", "sets whether we drive the robot safely or not", &myServerSetSafeDriveCB, "byte: 1 == drive safely, 0 == drive unsafely", "none", "UnsafeMovement", "RETURN_NONE"); myServer->addData("getSafeDrive", "gets whether we drive the robot safely or not", &myServerGetSafeDriveCB, "none", "byte: 1 == driving safely, 0 == driving unsafely", "Movement", "RETURN_SINGLE"); } if (myUseComputerJoystick) { myJoydrive = new ArRatioInputJoydrive(robot, myRatioAction); if ((myJoyHandler = Aria::getJoyHandler()) == NULL) { myJoyHandler = new ArJoyHandler; myJoyHandler->init(); Aria::setJoyHandler(myJoyHandler); } } if (myUseRobotJoystick) { myRobotJoydrive = new ArRatioInputRobotJoydrive(robot, myRatioAction); if ((myRobotJoyHandler = Aria::getRobotJoyHandler()) == NULL) { myRobotJoyHandler = new ArRobotJoyHandler(robot); Aria::setRobotJoyHandler(myRobotJoyHandler); } } if (myUseRobotJoystick || myUseComputerJoystick) { std::string taskName = name; taskName += "::joyUserTask"; myRobot->addUserTask(taskName.c_str(), 75, &myJoyUserTaskCB); } myPrinting = false; } AREXPORT ArServerModeRatioDrive::~ArServerModeRatioDrive() { } AREXPORT void ArServerModeRatioDrive::addToConfig(ArConfig *config, const char *section) { config->addParam( ArConfigArg( "Timeout", &myTimeout, "If there are no commands for this period of time, then the robot will stop. 0 Disables. This is a double so you can do like .1 seconds if you want.", 0), section, ArPriority::ADVANCED); myRatioAction->addToConfig(config, section); myLimiterForward->addToConfig(config, section, "Forward"); myLimiterBackward->addToConfig(config, section, "Backward"); if (myLimiterLateralLeft != NULL) myLimiterLateralLeft->addToConfig(config, section, "Lateral"); if (myLimiterLateralRight != NULL) myLimiterLateralRight->addToConfig(config, section, "Lateral"); myMovementParameters->addToConfig(config, section, "Teleop"); } AREXPORT void ArServerModeRatioDrive::activate(void) { //if (!baseActivate()) { // return; //} ratioDrive(0, 0, 100, true); } AREXPORT void ArServerModeRatioDrive::deactivate(void) { myRatioDriveGroup.deactivate(); baseDeactivate(); } AREXPORT void ArServerModeRatioDrive::setSafeDriving(bool safe, bool internal) { if (!internal) myRobot->lock(); // if this is a change then print it if (safe != myDriveSafely) { if (safe) { ArLog::log(ArLog::Normal, "%s: Driving safely again", myName.c_str()); } else { ArLog::log(ArLog::Normal, "%s: Driving UNSAFELY", myName.c_str()); } myNewDriveSafely = true; } myDriveSafely = safe; // ratioDrive is only called if this mode is already active if (isActive()) ratioDrive(myRatioAction->getTransRatio(), myRatioAction->getRotRatio(), myRatioAction->getThrottleRatio()); if (!internal) myRobot->unlock(); } AREXPORT bool ArServerModeRatioDrive::getSafeDriving(void) { return myDriveSafely; } AREXPORT void ArServerModeRatioDrive::serverSafeDrivingEnable(void) { setSafeDriving(true); } AREXPORT void ArServerModeRatioDrive::serverSafeDrivingDisable(void) { setSafeDriving(false); } AREXPORT void ArServerModeRatioDrive::addControlCommands(ArServerHandlerCommands *handlerCommands) { if (!myUseServerCommands) { ArLog::log(ArLog::Normal, "ArServerModeRatioDrive::addControlCommands: Tried to add control commands to a ratio drive not using the server"); return; } myHandlerCommands = handlerCommands; myHandlerCommands->addCommand( "safeRatioDrivingEnable", "Enables safe driving with ratioDrive, which will attempt to prevent collisions (default)", &myServerSafeDrivingEnableCB, "UnsafeMovement"); myHandlerCommands->addCommand( "safeRatioDrivingDisable", "Disables safe driving with ratioDrive, this is UNSAFE and will let you drive your robot into things or down stairs, use at your own risk", &myServerSafeDrivingDisableCB, "UnsafeMovement"); } /** * @param isActivating a bool set to true only if this method is called from the activate() * method, otherwise false * @param transRatio Amount of forward velocity to request * @param rotRatio Amount of rotational velocity to request * @param throttleRatio Amount of speed to request * @param latRatio amount of lateral velocity to request (if robot supports it) **/ AREXPORT void ArServerModeRatioDrive::ratioDrive( double transRatio, double rotRatio, double throttleRatio, bool isActivating, double latRatio) { bool wasActive; wasActive = isActive(); myTransRatio = transRatio; myRotRatio = rotRatio; myThrottleRatio = throttleRatio; myLatRatio = latRatio; // KMC: Changed the following test to include isActivating. // if (!wasActive && !baseActivate()) // return; // The baseActivate() method should only be called in the context of the activate() // method. if (isActivating && !wasActive) { if (!baseActivate()) { return; } } // end if activating and wasn't previously active // This is to handle the case where ratioDrive is called outside the // activate() method, and the activation was not successful. if (!isActive()) { return; } if (!wasActive || myNewDriveSafely) { myRobot->clearDirectMotion(); if (myDriveSafely) { myRatioDriveGroup.activateExclusive(); myMode = "Drive"; ArLog::log(ArLog::Normal, "%s: Driving safely", myName.c_str()); } else { myRobot->deactivateActions(); myRatioAction->activate(); myMode = "UNSAFE Drive"; ArLog::log(ArLog::Normal, "%s: Driving unsafely", myName.c_str()); } if (myDriveSafely) mySafeDrivingCallbacks.invoke(); else myUnsafeDrivingCallbacks.invoke(); } myNewDriveSafely = false; // MPL why is this here twice? myTransRatio = transRatio; myRotRatio = rotRatio; myThrottleRatio = throttleRatio; myLatRatio = latRatio; setActivityTimeToNow(); // SEEKUR mySentRecenter = false; if (myPrinting) printf("cmd %.0f %.0f %.0f %.0f\n", transRatio, rotRatio, throttleRatio, latRatio); if (myTransRatio < -0.1) myDrivingBackwardsCallbacks.invoke(); //myRatioAction.setRatios(transRatio, rotRatio, throttleRatio); } AREXPORT void ArServerModeRatioDrive::serverRatioDrive(ArServerClient *client, ArNetPacket *packet) { double transRatio = packet->bufToDouble(); double rotRatio = packet->bufToDouble(); double throttleRatio = packet->bufToDouble(); double lateralRatio = packet->bufToDouble(); myGotServerCommand = true; if (!myDriveSafely && !client->hasGroupAccess("UnsafeMovement")) serverSafeDrivingEnable(); myRobot->lock(); // Activate if necessary. Note that this is done before the ratioDrive // call because we want the new ratio values to be applied after the // default ones. if (!isActive()) { activate(); } /* ArLog::log(ArLog::Normal, "RatioDrive trans %.0f rot %.0f lat %.0f ratio %.0f", transRatio, rotRatio, lateralRatio, throttleRatio); */ ratioDrive(transRatio, rotRatio, throttleRatio, false, lateralRatio); myRobot->unlock(); } AREXPORT void ArServerModeRatioDrive::serverSetSafeDrive( ArServerClient *client, ArNetPacket *packet) { if (packet->bufToUByte() == 0) setSafeDriving(false); else setSafeDriving(true); } AREXPORT void ArServerModeRatioDrive::serverGetSafeDrive( ArServerClient *client, ArNetPacket *packet) { ArNetPacket sendPacket; if (getSafeDriving()) sendPacket.uByteToBuf(1); else sendPacket.uByteToBuf(0); client->sendPacketTcp(&sendPacket); } AREXPORT void ArServerModeRatioDrive::joyUserTask(void) { // if we're not active but we should be if (myTakeControlOnJoystick && !isActive() && ((myUseComputerJoystick && myJoyHandler->haveJoystick() && myJoyHandler->getButton(1)) || (myUseRobotJoystick && myRobotJoyHandler->gotData() && myRobotJoyHandler->getButton1()))) { if (ArServerMode::getActiveMode() != NULL) ArLog::log(ArLog::Normal, "%s: Activating instead of %s because of local joystick", ArServerMode::getActiveMode()->getName(), myName.c_str()); else ArLog::log(ArLog::Normal, "%s: Activating because of local joystick", myName.c_str()); // if we're locked and are overriding that lock for the robot // joystick and it was the robot joystick that caused it to happen if (myUseRobotJoystick && myRobotJoyHandler->gotData() && myRobotJoyHandler->getButton1() && myRobotJoystickOverridesLock && ArServerMode::ourActiveModeLocked) { ArLog::log(ArLog::Terse, "Robot joystick is overriding locked mode %s", ourActiveMode->getName()); ourActiveMode->forceUnlock(); myRobot->enableMotors(); } activate(); } bool unsafeRobotDrive; if (myUseRobotJoystick && myRobotJoyHandler->gotData() && ((unsafeRobotDrive = (bool)(myRobot->getFaultFlags() & ArUtil::BIT15)) != !myLastRobotSafeDrive)) { myLastRobotSafeDrive = !unsafeRobotDrive; setSafeDriving(myLastRobotSafeDrive, true); } } AREXPORT void ArServerModeRatioDrive::userTask(void) { // Sets the robot so that we always think we're trying to move in // this mode myRobot->forceTryingToMove(); // if the joystick is pushed then set that we're active, server // commands'll go into ratioDrive and set it there too if ((myUseComputerJoystick && myJoyHandler->haveJoystick() && myJoyHandler->getButton(1)) || (myUseRobotJoystick && myRobotJoyHandler->gotData() && myRobotJoyHandler->getButton1()) || (myUseServerCommands && myGotServerCommand)) { setActivityTimeToNow(); } myGotServerCommand = false; bool timedOut = false; // if we're moving, and there is a timeout, and the activity time is // greater than the timeout, then stop the robot if ((fabs(myRobot->getVel()) > 0 || fabs(myRobot->getRotVel()) > 0 || fabs(myRobot->getLatVel()) > 0) && myTimeout > .0000001 && getActivityTime().mSecSince()/1000.0 >= myTimeout) { if (!myLastTimedOut) { ArLog::log(ArLog::Normal, "Stopping the robot since teleop timed out"); myRobot->stop(); myRobot->clearDirectMotion(); ratioDrive(0, 0, 0, 0); } timedOut = true; } myLastTimedOut = timedOut; // SEEKUR (needed for prototype versions) /* if (myRobot->hasLatVel() && !mySentRecenter && getActivityTime().secSince() >= 10) { mySentRecenter = true; myRobot->com(120); } */ if (!myStatusSetThisCycle) { if (myRobot->isLeftMotorStalled() || myRobot->isRightMotorStalled()) myStatus = "Stalled"; // this works because if the motors stalled above caught it, if // not and more values it means a stall else if (myRobot->getStallValue()) myStatus = "Bumped"; else if (ArMath::fabs(myRobot->getVel()) < 2 && ArMath::fabs(myRobot->getRotVel()) < 2 && (!myRobot->hasLatVel() || ArMath::fabs(myRobot->getLatVel()) < 2)) myStatus = "Stopped"; else myStatus = "Driving"; } myStatusSetThisCycle = false; } // end method userTask AREXPORT void ArServerModeRatioDrive::ratioFireCallback(void) { if (myPrinting) ArLog::log(ArLog::Normal, "ArServerModeRatioDrive: TransRatio=%.0f RotRatio=%.0f ThrottleRatio=%.0f LatRatio=%.0f", myTransRatio, myRotRatio, myThrottleRatio, myLatRatio); myRatioAction->setRatios(myTransRatio, myRotRatio, myThrottleRatio, myLatRatio); } AREXPORT void ArServerModeRatioDrive::setUseLocationDependentDevices( bool useLocationDependentDevices, bool internal) { if (!internal) myRobot->lock(); // if this is a change then print it if (useLocationDependentDevices != myUseLocationDependentDevices) { if (useLocationDependentDevices) { ArLog::log(ArLog::Normal, "%s: Using location dependent range devices", myName.c_str()); } else { ArLog::log(ArLog::Normal, "%s: Not using location dependent range devices", myName.c_str()); } myUseLocationDependentDevices = useLocationDependentDevices; myLimiterForward->setUseLocationDependentDevices( myUseLocationDependentDevices); myLimiterBackward->setUseLocationDependentDevices( myUseLocationDependentDevices); if (myLimiterLateralLeft != NULL) myLimiterLateralLeft->setUseLocationDependentDevices( myUseLocationDependentDevices); if (myLimiterLateralRight != NULL) myLimiterLateralRight->setUseLocationDependentDevices( myUseLocationDependentDevices); } if (!internal) myRobot->unlock(); } AREXPORT bool ArServerModeRatioDrive::getUseLocationDependentDevices(void) { return myUseLocationDependentDevices; }
admo/aria
arnetworking/ArServerModeRatioDrive.cpp
C++
gpl-2.0
17,363
package com.networkprofiles.widget; /** Service to refresh the widget **/ import android.app.Service; import android.appwidget.AppWidgetManager; import android.content.Intent; import android.graphics.Color; import android.os.IBinder; import android.provider.Settings; import android.widget.RemoteViews; import com.networkprofiles.R; import com.networkprofiles.utils.MyNetControll; public class NPWidgetService extends Service { private Boolean mobile; private Boolean cell; private Boolean gps; private Boolean display; private Boolean sound; private int [] widgetIds; private RemoteViews rv; private AppWidgetManager wm; private MyNetControll myController; public void onCreate() { wm = AppWidgetManager.getInstance(NPWidgetService.this);//this.getApplicationContext() myController = new MyNetControll(NPWidgetService.this); myController.myStart(); //rv = new RemoteViews(getPackageName(), R.layout.npwidgetwifi); } public int onStartCommand(Intent intent, int flags, int startId) { // /** Check the state of the network devices and set the text for the text fields **/ // //set the TextView for 3G data // if(telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED || telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTING) { // rv.setTextViewText(R.id.textMobile, "3G data is ON"); // } // if(telephonyManager.getDataState() == TelephonyManager.DATA_DISCONNECTED) { // rv.setTextViewText(R.id.textMobile, "3G data is OFF"); // } // //set the TextView for WiFi // if(wifim.getWifiState() == WifiManager.WIFI_STATE_ENABLED || wifim.getWifiState() == WifiManager.WIFI_STATE_ENABLING) { // rv.setTextViewText(R.id.textWifi, "Wifi is ON"); // } // if(wifim.getWifiState() == WifiManager.WIFI_STATE_DISABLED || wifim.getWifiState() == WifiManager.WIFI_STATE_DISABLING) { // rv.setTextViewText(R.id.textWifi, "Wifi is OFF"); // } // //set the TextView for Bluetooth // if(myBluetooth.getState() == BluetoothAdapter.STATE_ON || myBluetooth.getState() == BluetoothAdapter.STATE_TURNING_ON) { // rv.setTextViewText(R.id.textBluetooth, "Bluetooth is ON"); // } // if(myBluetooth.getState() == BluetoothAdapter.STATE_OFF || myBluetooth.getState() == BluetoothAdapter.STATE_TURNING_OFF) { // rv.setTextViewText(R.id.textBluetooth, "Bluetooth is Off"); // } // //set the TextView for Cell voice // if(Settings.System.getInt(NPWidgetService.this.getContentResolver(), // Settings.System.AIRPLANE_MODE_ON, 0) == 0) { // rv.setTextViewText(R.id.textCell, "Cell is ON"); // } else { // rv.setTextViewText(R.id.textCell, "Cell is OFF"); // } // //set the TextView for GPS // locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); // if(locationProviders.contains("gps")) { // rv.setTextViewText(R.id.textGps, "GPS is ON"); // } else { // rv.setTextViewText(R.id.textGps, "GPS is OFF"); // } /** Check which textView was clicked and switch the state of the corresponding device **/ widgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS); mobile = intent.getBooleanExtra("mobile", false); cell = intent.getBooleanExtra("cell", false); gps = intent.getBooleanExtra("gps", false); display = intent.getBooleanExtra("display", false); sound = intent.getBooleanExtra("sound", false); if(widgetIds.length > 0) { if(mobile) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetmobiledata); rv.setTextColor(R.id.textWidgetMobileData, Color.GREEN); updateWidgets(); rv.setTextColor(R.id.textWidgetMobileData, Color.WHITE); myController.mobileOnOff(); } if(cell) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetcell); rv.setTextColor(R.id.textWidgetCell, Color.GREEN); if(Settings.System.getInt(NPWidgetService.this.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 0) { myController.cellOff(); } else { myController.cellOn(); } if(Settings.System.getInt(NPWidgetService.this.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 0) { rv.setTextViewText(R.id.textWidgetCell, "Cell ON"); } else { rv.setTextViewText(R.id.textWidgetCell, "Cell OFF"); } updateWidgets(); rv.setTextColor(R.id.textWidgetCell, Color.WHITE); } if(gps) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetgps); rv.setTextColor(R.id.textWidgetGps, Color.GREEN); updateWidgets(); rv.setTextColor(R.id.textWidgetGps, Color.WHITE); myController.gpsOnOff(); } if(display) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetdisplay); rv.setTextColor(R.id.textWidgetDisplay, Color.GREEN); updateWidgets(); rv.setTextColor(R.id.textWidgetDisplay, Color.WHITE); myController.displayOnOff(); } if(sound) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetsound); rv.setTextColor(R.id.textViewWidgetSound, Color.GREEN); updateWidgets(); rv.setTextColor(R.id.textViewWidgetSound, Color.WHITE); myController.soundSettings(); } } updateWidgets(); stopSelf(); return 1; } public void onStart(Intent intent, int startId) { } public IBinder onBind(Intent arg0) { return null; } private void updateWidgets() { for(int id : widgetIds) { wm.updateAppWidget(id, rv); } } }//close class NPWidgetService
ektodorov/ShortcutsOfPower_Android
src/com/networkprofiles/widget/NPWidgetService.java
Java
gpl-2.0
5,416
#!/usr/bin/env python3 # Copyright (c) 2008-9 Qtrac Ltd. All rights reserved. # This program or module 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 # version 3 of the License, or (at your option) any later version. It is # provided for educational purposes and 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. """Provides the Item example classes. """ class Item(object): def __init__(self, artist, title, year=None): self.__artist = artist self.__title = title self.__year = year def artist(self): return self.__artist def setArtist(self, artist): self.__artist = artist def title(self): return self.__title def setTitle(self, title): self.__title = title def year(self): return self.__year def setYear(self, year): self.__year = year def __str__(self): year = "" if self.__year is not None: year = " in {0}".format(self.__year) return "{0} by {1}{2}".format(self.__title, self.__artist, year) class Painting(Item): def __init__(self, artist, title, year=None): super(Painting, self).__init__(artist, title, year) class Sculpture(Item): def __init__(self, artist, title, year=None, material=None): super(Sculpture, self).__init__(artist, title, year) self.__material = material def material(self): return self.__material def setMaterial(self, material): self.__material = material def __str__(self): materialString = "" if self.__material is not None: materialString = " ({0})".format(self.__material) return "{0}{1}".format(super(Sculpture, self).__str__(), materialString) class Dimension(object): def __init__(self, width, height, depth=None): self.__width = width self.__height = height self.__depth = depth def width(self): return self.__width def setWidth(self, width): self.__width = width def height(self): return self.__height def setHeight(self, height): self.__height = height def depth(self): return self.__depth def setDepth(self, depth): self.__depth = depth def area(self): raise NotImplemented def volume(self): raise NotImplemented if __name__ == "__main__": items = [] items.append(Painting("Cecil Collins", "The Poet", 1941)) items.append(Painting("Cecil Collins", "The Sleeping Fool", 1943)) items.append(Painting("Edvard Munch", "The Scream", 1893)) items.append(Painting("Edvard Munch", "The Sick Child", 1896)) items.append(Painting("Edvard Munch", "The Dance of Life", 1900)) items.append(Sculpture("Auguste Rodin", "Eternal Springtime", 1917, "plaster")) items.append(Sculpture("Auguste Rodin", "Naked Balzac", 1917, "plaster")) items.append(Sculpture("Auguste Rodin", "The Secret", 1925, "bronze")) uniquematerials = set() for item in items: print(item) if hasattr(item, "material"): uniquematerials.add(item.material()) print("Sculptures use {0} unique materials".format( len(uniquematerials)))
paradiseOffice/Bash_and_Cplus-plus
CPP/full_examples/pyqt/chap03/item.py
Python
gpl-2.0
3,660
<?php /** * The template for displaying all posts having layout like: sidebar/content/sidebar. * * @package Sage Theme */ ?> <?php get_sidebar('second'); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'single' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || get_comments_number() ) : comments_template(); endif; ?> <?php endwhile; // end of the loop. ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); ?>
jbs321/wahad-humus
wp-content/themes/sage/layouts/blog/sidebar-content-sidebar.php
PHP
gpl-2.0
774
/* GNU ddrescue - Data recovery tool Copyright (C) 2004-2019 Antonio Diaz Diaz. 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/>. */ #define _FILE_OFFSET_BITS 64 #include <algorithm> #include <cctype> #include <cerrno> #include <climits> #include <cstdio> #include <cstdlib> #include <ctime> #include <string> #include <vector> #include <stdint.h> #include <termios.h> #include <unistd.h> #include "block.h" #include "mapbook.h" namespace { void input_pos_error( const long long pos, const long long insize ) { char buf[128]; snprintf( buf, sizeof buf, "Can't start reading at pos %s.\n" " Input file is only %s bytes long.", format_num3( pos ), format_num3( insize ) ); show_error( buf ); } } // end namespace bool Mapbook::save_mapfile( const char * const name ) { std::remove( name ); FILE * const f = std::fopen( name, "w" ); if( f && write_mapfile( f, true, true ) && std::fclose( f ) == 0 ) { char buf[80]; snprintf( buf, sizeof buf, "Mapfile saved in '%s'\n", name ); final_msg( buf ); return true; } return false; } bool Mapbook::emergency_save() { static bool first_time = true; static std::string home_name; const std::string dead_name( "ddrescue.map" ); if( filename() != dead_name && save_mapfile( dead_name.c_str() ) ) return true; if( first_time ) { first_time = false; const char * const p = std::getenv( "HOME" ); if( p ) { home_name = p; home_name += '/'; home_name += dead_name; } } if( home_name.size() && filename() != home_name && save_mapfile( home_name.c_str() ) ) return true; show_error( "Emergency save failed." ); return false; } Mapbook::Mapbook( const long long offset, const long long insize, Domain & dom, const Mb_options & mb_opts, const char * const mapname, const int cluster, const int hardbs, const bool complete_only, const bool rescue ) : Mapfile( mapname ), Mb_options( mb_opts ), offset_( offset ), mapfile_insize_( 0 ), domain_( dom ), hardbs_( hardbs ), softbs_( cluster * hardbs_ ), iobuf_size_( softbs_ + hardbs_ ), // +hardbs for direct unaligned reads final_errno_( 0 ), um_t1( 0 ), um_t1s( 0 ), um_prev_mf_sync( false ), mapfile_exists_( false ) { long alignment = sysconf( _SC_PAGESIZE ); if( alignment < hardbs_ || alignment % hardbs_ ) alignment = hardbs_; if( alignment < 2 ) alignment = 0; iobuf_ = iobuf_base = new uint8_t[ alignment + iobuf_size_ + hardbs_ ]; if( alignment > 1 ) // align iobuf for direct disc access { const int disp = alignment - ( reinterpret_cast<unsigned long long> (iobuf_) % alignment ); if( disp > 0 && disp < alignment ) iobuf_ += disp; } if( insize > 0 ) { if( domain_.pos() >= insize ) { input_pos_error( domain_.pos(), insize ); std::exit( 1 ); } domain_.crop_by_file_size( insize ); } if( filename() ) { mapfile_exists_ = read_mapfile( 0, false ); if( mapfile_exists_ ) mapfile_insize_ = extent().end(); } if( !complete_only ) extend_sblock_vector( insize ); else domain_.crop( extent() ); // limit domain to blocks read from mapfile compact_sblock_vector(); if( rescue ) join_subsectors( hardbs_ ); split_by_domain_borders( domain_ ); if( sblocks() == 0 ) domain_.clear(); } // Writes periodically the mapfile to disc. // Returns false only if update is attempted and fails. // bool Mapbook::update_mapfile( const int odes, const bool force ) { if( !filename() ) return true; const int interval = ( mapfile_save_interval >= 0 ) ? mapfile_save_interval : 30 + std::min( 270L, sblocks() / 38 ); // auto, 30s to 5m const long t2 = std::time( 0 ); if( um_t1 == 0 || um_t1 > t2 ) um_t1 = um_t1s = t2; // initialize if( !force && t2 - um_t1 < interval ) return true; const bool mf_sync = ( force || t2 - um_t1s >= mapfile_sync_interval ); if( odes >= 0 ) fsync( odes ); if( um_prev_mf_sync ) { std::string mapname_bak( filename() ); mapname_bak += ".bak"; std::remove( mapname_bak.c_str() ); // break possible hard link std::rename( filename(), mapname_bak.c_str() ); } um_prev_mf_sync = mf_sync; while( true ) { errno = 0; if( write_mapfile( 0, true, mf_sync ) ) // update times here to exclude writing time from intervals { um_t1 = std::time( 0 ); if( mf_sync ) um_t1s = um_t1; return true; } if( verbosity < 0 ) return false; const int saved_errno = errno; std::fputc( '\n', stderr ); char buf[80]; snprintf( buf, sizeof buf, "Error writing mapfile '%s'", filename() ); show_error( buf, saved_errno ); std::fputs( "Fix the problem and press ENTER to retry,\n" " or E+ENTER for an emergency save and exit,\n" " or Q+ENTER to abort.\n", stderr ); std::fflush( stderr ); while( true ) { tcflush( STDIN_FILENO, TCIFLUSH ); const int c = std::tolower( std::fgetc( stdin ) ); int tmp = c; while( tmp != '\n' && tmp != EOF ) tmp = std::fgetc( stdin ); if( c == '\r' || c == '\n' || c == 'e' || c == 'q' ) { if( c == 'q' || ( c == 'e' && emergency_save() ) ) { if( !force ) std::fputs( "\n\n\n\n", stdout ); return false; } break; } } } }
mruffalo/ddrescue
mapbook.cc
C++
gpl-2.0
6,040
/* Copyright (c) 2008 The Board of Trustees of The Leland Stanford * Junior University * * We are making the OpenFlow specification and associated documentation * (Software) available for public use and benefit with the expectation * that others will use, modify and enhance the Software and contribute * those enhancements back to the community. However, since we would * like to make the Software available for broadest use, with as few * restrictions as possible permission is hereby granted, free of * charge, to any person obtaining a copy of this Software to deal in * the Software under the copyrights 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. * * The name and trademarks of copyright holder(s) may NOT be used in * advertising or publicity pertaining to the Software or any * derivatives without specific, written prior permission. */ #include "../include/config.h" #include "csum.hh" CLICK_DECLS /* Returns the IP checksum of the 'n' bytes in 'data'. */ uint16_t csum(const void *data, size_t n) { return csum_finish(csum_continue(0, data, n)); } /* Adds the 16 bits in 'new' to the partial IP checksum 'partial' and returns * the updated checksum. (To start a new checksum, pass 0 for 'partial'. To * obtain the finished checksum, pass the return value to csum_finish().) */ uint32_t csum_add16(uint32_t partial, uint16_t New) { return partial + New; } /* Adds the 32 bits in 'new' to the partial IP checksum 'partial' and returns * the updated checksum. (To start a new checksum, pass 0 for 'partial'. To * obtain the finished checksum, pass the return value to csum_finish().) */ uint32_t csum_add32(uint32_t partial, uint32_t New) { return partial + (New >> 16) + (New & 0xffff); } /* Adds the 'n' bytes in 'data' to the partial IP checksum 'partial' and * returns the updated checksum. (To start a new checksum, pass 0 for * 'partial'. To obtain the finished checksum, pass the return value to * csum_finish().) */ uint32_t csum_continue(uint32_t partial, const void *data_, size_t n) { const uint16_t *data = (const uint16_t*)data_; for (; n > 1; n -= 2) { partial = csum_add16(partial, *data++); } if (n) { partial += *(uint8_t *) data; } return partial; } /* Returns the IP checksum corresponding to 'partial', which is a value updated * by some combination of csum_add16(), csum_add32(), and csum_continue(). */ uint16_t csum_finish(uint32_t partial) { return ~((partial & 0xffff) + (partial >> 16)); } /* Returns the new checksum for a packet in which the checksum field previously * contained 'old_csum' and in which a field that contained 'old_u16' was * changed to contain 'new_u16'. */ uint16_t recalc_csum16(uint16_t old_csum, uint16_t old_u16, uint16_t new_u16) { /* Ones-complement arithmetic is endian-independent, so this code does not * use htons() or ntohs(). * * See RFC 1624 for formula and explanation. */ uint16_t hc_complement = ~old_csum; uint16_t m_complement = ~old_u16; uint16_t m_prime = new_u16; uint32_t sum = hc_complement + m_complement + m_prime; uint16_t hc_prime_complement = sum + (sum >> 16); return ~hc_prime_complement; } /* Returns the new checksum for a packet in which the checksum field previously * contained 'old_csum' and in which a field that contained 'old_u32' was * changed to contain 'new_u32'. */ uint16_t recalc_csum32(uint16_t old_csum, uint32_t old_u32, uint32_t new_u32) { return recalc_csum16(recalc_csum16(old_csum, old_u32, new_u32), old_u32 >> 16, new_u32 >> 16); } CLICK_ENDDECLS ELEMENT_PROVIDES(Of_Csum)
JaeyongYoo/VisualXSwitch
elements/local/OpenFlow/lib/csum.cc
C++
gpl-2.0
4,507
#!/usr/bin/env python # -*- coding:utf-8 -*- """ @author: Will """ from django import forms from app01 import models class ImportFrom(forms.Form): HOST_TYPE=((1,"001"),(2,"002")) #替換爲文件 host_type = forms.IntegerField( widget=forms.Select(choices=HOST_TYPE) ) hostname = forms.CharField() def __init__(self,*args,**kwargs): super(ImportFrom,self).__init__(*args,**kwargs) HOST_TYPE=((1,"001"),(2,"002")) #替換爲文件 self.fields['host_type'].widget.choices = models.userInfo.objects.all().values_list("id","name") models.userInfo.objects.get() models.userInfo.objects.filter()
willre/homework
day19/web/app01/forms/home.py
Python
gpl-2.0
723