code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
<?php
/* core/themes/classy/templates/navigation/menu-local-task.html.twig */
class __TwigTemplate_0969a23526138fcc37f60cc805db1d447beeec2f58012651e0e2200d57c77ec5 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$tags = array();
$filters = array();
$functions = array();
try {
$this->env->getExtension('sandbox')->checkSecurity(
array(),
array(),
array()
);
} catch (Twig_Sandbox_SecurityError $e) {
$e->setTemplateFile($this->getTemplateName());
if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
$e->setTemplateLine($tags[$e->getTagName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
$e->setTemplateLine($filters[$e->getFilterName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
$e->setTemplateLine($functions[$e->getFunctionName()]);
}
throw $e;
}
// line 17
echo "<li";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["attributes"]) ? $context["attributes"] : null), "addClass", array(0 => (((isset($context["is_active"]) ? $context["is_active"] : null)) ? ("is-active") : (""))), "method"), "html", null, true));
echo ">";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["link"]) ? $context["link"] : null), "html", null, true));
echo "</li>
";
}
public function getTemplateName()
{
return "core/themes/classy/templates/navigation/menu-local-task.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 43 => 17,);
}
}
/* {#*/
/* /***/
/* * @file*/
/* * Theme override for a local task link.*/
/* **/
/* * Available variables:*/
/* * - attributes: HTML attributes for the wrapper element.*/
/* * - is_active: Whether the task item is an active tab.*/
/* * - link: A rendered link element.*/
/* **/
/* * Note: This template renders the content for each task item in*/
/* * menu-local-tasks.html.twig.*/
/* **/
/* * @see template_preprocess_menu_local_task()*/
/* *//* */
/* #}*/
/* <li{{ attributes.addClass(is_active ? 'is-active') }}>{{ link }}</li>*/
/* */
| Java |
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk 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 in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# ails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
import config
loaded_with_language = False
# .----------------------------------------------------------------------.
# | ____ _ _ |
# | | _ \ ___ _ __ _ __ ___ (_)___ ___(_) ___ _ __ ___ |
# | | |_) / _ \ '__| '_ ` _ \| / __/ __| |/ _ \| '_ \/ __| |
# | | __/ __/ | | | | | | | \__ \__ \ | (_) | | | \__ \ |
# | |_| \___|_| |_| |_| |_|_|___/___/_|\___/|_| |_|___/ |
# | |
# +----------------------------------------------------------------------+
# | Declare general permissions for Multisite |
# '----------------------------------------------------------------------'
def load():
global loaded_with_language
if loaded_with_language == current_language:
return
config.declare_permission_section("general", _('General Permissions'), 10)
config.declare_permission("general.use",
_("Use Multisite at all"),
_("Users without this permission are not let in at all"),
[ "admin", "user", "guest" ])
config.declare_permission("general.see_all",
_("See all Nagios objects"),
_("See all objects regardless of contacts and contact groups. "
"If combined with 'perform commands' then commands may be done on all objects."),
[ "admin", "guest" ])
declare_visual_permissions('views', _("views"))
declare_visual_permissions('dashboards', _("dashboards"))
config.declare_permission("general.view_option_columns",
_("Change view display columns"),
_("Interactively change the number of columns being displayed by a view (does not edit or customize the view)"),
[ "admin", "user", "guest" ])
config.declare_permission("general.view_option_refresh",
_("Change view display refresh"),
_("Interactively change the automatic browser reload of a view being displayed (does not edit or customize the view)"),
[ "admin", "user" ])
config.declare_permission("general.painter_options",
_("Change column display options"),
_("Some of the display columns offer options for customizing their output. "
"For example time stamp columns can be displayed absolute, relative or "
"in a mixed style. This permission allows the user to modify display options"),
[ "admin", "user", "guest" ])
config.declare_permission("general.act",
_("Perform commands"),
_("Allows users to perform Nagios commands. If no further permissions "
"are granted, actions can only be done on objects one is a contact for"),
[ "admin", "user" ])
config.declare_permission("general.see_sidebar",
_("Use Check_MK sidebar"),
_("Without this permission the Check_MK sidebar will be invisible"),
[ "admin", "user", "guest" ])
config.declare_permission("general.configure_sidebar",
_("Configure sidebar"),
_("This allows the user to add, move and remove sidebar snapins."),
[ "admin", "user" ])
config.declare_permission('general.edit_profile',
_('Edit the user profile'),
_('Permits the user to change the user profile settings.'),
[ 'admin', 'user' ]
)
config.declare_permission('general.edit_notifications',
_('Edit personal notification settings'),
_('This allows a user to edit his personal notification settings. You also need the permission '
'<i>Edit the user profile</i> in order to do this.'),
[ 'admin', 'user' ]
)
config.declare_permission('general.disable_notifications',
_('Disable all personal notifications'),
_('This permissions provides a checkbox in the personal settings of the user that '
'allows him to completely disable all of his notifications. Use with caution.'),
[ 'admin', ]
)
config.declare_permission('general.edit_user_attributes',
_('Edit personal user attributes'),
_('This allows a user to edit his personal user attributes. You also need the permission '
'<i>Edit the user profile</i> in order to do this.'),
[ 'admin', 'user' ]
)
config.declare_permission('general.change_password',
_('Edit the user password'),
_('Permits the user to change the password.'),
[ 'admin', 'user' ]
)
config.declare_permission('general.logout',
_('Logout'),
_('Permits the user to logout.'),
[ 'admin', 'user', 'guest' ]
)
config.declare_permission("general.ignore_soft_limit",
_("Ignore soft query limit"),
_("Allows to ignore the soft query limit imposed upon the number of datasets returned by a query"),
[ "admin", "user" ])
config.declare_permission("general.ignore_hard_limit",
_("Ignore hard query limit"),
_("Allows to ignore the hard query limit imposed upon the number of datasets returned by a query"),
[ "admin" ])
loaded_with_language = current_language
# TODO: This has been obsoleted by pagetypes.py
def declare_visual_permissions(what, what_plural):
config.declare_permission("general.edit_" + what,
_("Customize %s and use them") % what_plural,
_("Allows to create own %s, customize builtin %s and use them.") % (what_plural, what_plural),
[ "admin", "user" ])
config.declare_permission("general.publish_" + what,
_("Publish %s") % what_plural,
_("Make %s visible and usable for other users.") % what_plural,
[ "admin", "user" ])
config.declare_permission("general.see_user_" + what,
_("See user %s") % what_plural,
_("Is needed for seeing %s that other users have created.") % what_plural,
[ "admin", "user", "guest" ])
config.declare_permission("general.force_" + what,
_("Modify builtin %s") % what_plural,
_("Make own published %s override builtin %s for all users.") % (what_plural, what_plural),
[ "admin" ])
config.declare_permission("general.delete_foreign_" + what,
_("Delete foreign %s") % what_plural,
_("Allows to delete %s created by other users.") % what_plural,
[ "admin" ])
| Java |
/*
* Copyright (c) 2017, 2020, Oracle and/or its affiliates.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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 HOLDER 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 <graalvm/llvm/polyglot.h>
#include <graalvm/llvm/handles.h>
int main() {
void *p = polyglot_import("object");
void *p1 = create_handle(p);
void *p2 = resolve_handle(p1);
if (p != p2) {
return 1;
}
return 0;
}
| Java |
#! /bin/sh
modprobe ib_core
modprobe ib_uverbs
modprobe ib_addr
modprobe ib_umad
modprobe ib_cm
modprobe ib_mad
# modprobe ib_ipoib
modprobe ib_sa
modprobe iw_cm
modprobe ib_ucm
modprobe rdma_ucm
modprobe rdma_cm
| Java |
package mrdev023.opengl;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.*;
import java.awt.*;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import mrdev023.exception.*;
public class Display {
private static DisplayMode displayMode;
private static String TITLE = "";
private static long window;
private static boolean hasResized = false;
public static void create(String title,int width,int height){
if ( !glfwInit() )
throw new IllegalStateException("Unable to initialize GLFW");
TITLE = title;
displayMode = new DisplayMode(width,height);
window = glfwCreateWindow(displayMode.getWidth(),displayMode.getHeight(), TITLE, NULL, NULL);
}
public static void create(String title,int width,int height,int major,int minor){
if ( !glfwInit() )
throw new IllegalStateException("Unable to initialize GLFW");
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major); // Nous voulons OpenGL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
TITLE = title;
displayMode = new DisplayMode(width,height);
window = glfwCreateWindow(displayMode.getWidth(),displayMode.getHeight(), TITLE, NULL, NULL);
}
public static void setMouseGrabbed(boolean a){
if(a){
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
}else{
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
}
public static void setVSync(boolean a) throws DisplayException{
if(a)glfwSwapInterval(1);
else glfwSwapInterval(0);
}
public static void create(String title,int width,int height,int major,int minor,int sample){
if ( !glfwInit() )
throw new IllegalStateException("Unable to initialize GLFW");
glfwWindowHint(GLFW_SAMPLES, sample); // antialiasing 4x
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major); // Nous voulons OpenGL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
TITLE = title;
displayMode = new DisplayMode(width,height);
window = glfwCreateWindow(displayMode.getWidth(),displayMode.getHeight(), TITLE, NULL, NULL);
}
public static void setSample(int sample){
glfwWindowHint(GLFW_SAMPLES, sample);
}
public static void setResizable(boolean a){
if(a)glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
else glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
}
public static void setTitle(String title){
TITLE = title;
glfwSetWindowTitle(window, TITLE);
}
public static String getTitle(){
return TITLE;
}
public static boolean wasResized(){
IntBuffer w = BufferUtils.createIntBuffer(1);
IntBuffer h = BufferUtils.createIntBuffer(1);
glfwGetWindowSize(window, w, h);
int width = w.get(0);
int height = h.get(0);
if(Display.getDisplayMode().getWidth() != width || Display.getDisplayMode().getHeight() != height || hasResized){
setDisplayMode(new DisplayMode(width, height));
hasResized = false;
return true;
}else{
return false;
}
}
public static void printMonitorsInfo(){
PointerBuffer monitors = glfwGetMonitors();
GLFWVidMode m;
if(monitors == null){
System.out.println("No monitor detected !");
return;
}
for(int i = 0;i < monitors.capacity();i++){
m = glfwGetVideoMode(monitors.get(i));
System.out.println(glfwGetMonitorName(monitors.get(i)) + "(" + i + ") : " + m.width() + "x" + m.height() + ":" + m.refreshRate() + "Hz");
}
}
public static boolean isCloseRequested(){
return glfwWindowShouldClose(window);
}
public static void createContext(){
glfwMakeContextCurrent(window);
GL.createCapabilities();
}
public static void updateEvent(){
glfwPollEvents();
}
public static void updateFrame(){
glfwSwapBuffers(window);
}
public static DisplayMode getDisplayMode() {
return displayMode;
}
public static void setDisplayMode(DisplayMode displayMode) {
if(Display.displayMode == null || displayMode == null)return;
Display.displayMode.setDisplayMode(displayMode);
hasResized = true;
}
public static void destroy(){
glfwDestroyWindow(window);
glfwTerminate();
}
public static long getWindow() {
return window;
}
}
| Java |
/*
#Date of creation : 9 Jan 2016.
#Aim of program : To print power set of a set of characters.
#Coded by : Rishikesh Agrawani.
*/
package main
import "fmt"
func main() {
var n, r, i, j uint
fmt.Print("Enter the number of binary variables(for which you want the binary combinations): ")
fmt.Scanf("%d", &n)
fmt.Print("\nEnter ", n, " binary variables name( name should be only 1 character long) separated by space: ")
a := make([]string, n)
r = 1
for i = 0; i < n; i++ {
fmt.Scanf("%s", &a[i])
r *= 2
}
fmt.Println("\nColumns => ", n, "\nRows => ", r)
for i = 0; i < r; i++ {
for j = 0; j < n; j++ {
if (i>>j)&1 == 1 {
fmt.Print(a[j], " ")
} else {
fmt.Print("- ")
}
}
fmt.Println()
}
}
/*1st RUN:
Enter the number of binary variables(for which you want the binary combinations): 4
Enter 4 binary variables name( name should be only 1 character long) separated by space: a b c d
Columns => 4
Rows => 16
- - - -
a - - -
- b - -
a b - -
- - c -
a - c -
- b c -
a b c -
- - - d
a - - d
- b - d
a b - d
- - c d
a - c d
- b c d
a b c d
*/
/*2nd RUN:
Enter the number of binary variables(for which you want the binary combinations):
Enter 5 binary variables name( name should be only 1 character long) separated by space:
Columns => 5
Rows => 32
- - - - -
p - - - -
- q - - -
p q - - -
- - r - -
p - r - -
- q r - -
p q r - -
- - - s -
p - - s -
- q - s -
p q - s -
- - r s -
p - r s -
- q r s -
p q r s -
- - - - t
p - - - t
- q - - t
p q - - t
- - r - t
p - r - t
- q r - t
p q r - t
- - - s t
p - - s t
- q - s t
p q - s t
- - r s t
p - r s t
- q r s t
p q r s t
*/
| Java |
/*
** Copyright (C) 1991, 1997 Free Software Foundation, Inc.
**
** This file is part of TACK.
**
** TACK is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2, or (at your option)
** any later version.
**
** TACK 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 TACK; see the file COPYING. If not, write to
** the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
** Boston, MA 02111-1307, USA.
*/
#include <tack.h>
MODULE_ID("$Id: menu.c,v 1.1.1.1 2004/03/24 19:53:07 sure Exp $")
/*
Menu control
*/
static void test_byname(struct test_menu *, int *, int *);
struct test_list *augment_test;
char prompt_string[80]; /* menu prompt storage */
/*
** menu_prompt()
**
** Print the menu prompt string.
*/
void
menu_prompt(void)
{
ptext(&prompt_string[1]);
}
/*
** menu_test_loop(test-structure, state, control-character)
**
** This function implements the repeat test function.
*/
static void
menu_test_loop(
struct test_list *test,
int *state,
int *ch)
{
int nch, p;
if ((test->flags & MENU_REP_MASK) && (augment_test != test)) {
/* set the augment variable (first time only) */
p = (test->flags >> 8) & 15;
if ((test->flags & MENU_REP_MASK) == MENU_LM1) {
augment = lines - 1;
} else
if ((test->flags & MENU_ONE_MASK) == MENU_ONE) {
augment = 1;
} else
if ((test->flags & MENU_LC_MASK) == MENU_lines) {
augment = lines * p / 10;
} else
if ((test->flags & MENU_LC_MASK) == MENU_columns) {
augment = columns * p / 10;
} else {
augment = 1;
}
augment_test = test;
set_augment_txt();
}
do {
if ((test->flags | *state) & MENU_CLEAR) {
put_clear();
} else
if (line_count + test->lines_needed >= lines) {
put_clear();
}
nch = 0;
if (test->test_procedure) {
/* The procedure takes precedence so I can pass
the menu entry as an argument.
*/
can_test(test->caps_done, FLAG_TESTED);
can_test(test->caps_tested, FLAG_TESTED);
test->test_procedure(test, state, &nch);
} else
if (test->sub_menu) {
/* nested menu's */
menu_display(test->sub_menu, &nch);
*state = 0;
if (nch == 'q' || nch == 's') {
/* Quit and skip are killed here */
nch = '?';
}
} else {
break; /* cya */
}
if (nch == '\r' || nch == '\n' || nch == 'n') {
nch = 0;
break;
}
} while (nch == 'r');
*ch = nch;
}
/*
** menu_display(menu-structure, flags)
**
** This function implements menu control.
*/
void
menu_display(
struct test_menu *menu,
int *last_ch)
{
int test_state = 0, run_standard_tests;
int hot_topic, ch = 0, nch = 0;
struct test_list *mt;
struct test_list *repeat_tests = 0;
int repeat_state = 0;
int prompt_length;
prompt_length = strlen(prompt_string);
if (menu->ident) {
sprintf(&prompt_string[prompt_length], "/%s", menu->ident);
}
hot_topic = menu->default_action;
run_standard_tests = menu->standard_tests ?
menu->standard_tests[0] : -1;
if (!last_ch) {
last_ch = &ch;
}
while (1) {
if (ch == 0) {
/* Display the menu */
put_crlf();
if (menu->menu_function) {
/*
this function may be used to restrict menu
entries. If used it must print the title.
*/
menu->menu_function(menu);
} else
if (menu->menu_title) {
ptextln(menu->menu_title);
}
for (mt = menu->tests; (mt->flags & MENU_LAST) == 0; mt++) {
if (mt->menu_entry) {
ptext(" ");
ptextln(mt->menu_entry);
}
}
if (menu->standard_tests) {
ptext(" ");
ptextln(menu->standard_tests);
ptextln(" r) repeat test");
ptextln(" s) skip to next test");
}
ptextln(" q) quit");
ptextln(" ?) help");
}
if (ch == 0 || ch == REQUEST_PROMPT) {
put_crlf();
ptext(&prompt_string[1]);
if (hot_topic) {
ptext(" [");
putchp(hot_topic);
ptext("]");
}
ptext(" > ");
/* read a character */
ch = wait_here();
}
if (ch == '\r' || ch == '\n') {
ch = hot_topic;
}
if (ch == 'q') {
break;
}
if (ch == '?') {
ch = 0;
continue;
}
nch = ch;
ch = 0;
/* Run one of the standard tests (by request) */
for (mt = menu->tests; (mt->flags & MENU_LAST) == 0; mt++) {
if (mt->menu_entry && (nch == mt->menu_entry[0])) {
if (mt->flags & MENU_MENU) {
test_byname(menu, &test_state, &nch);
} else {
menu_test_loop(mt, &test_state, &nch);
}
ch = nch;
if ((mt->flags & MENU_COMPLETE) && ch == 0) {
/* top level */
hot_topic = 'q';
ch = '?';
}
}
}
if (menu->standard_tests && nch == 'r') {
menu->resume_tests = repeat_tests;
test_state = repeat_state;
nch = run_standard_tests;
}
if (nch == run_standard_tests) {
if (!(mt = menu->resume_tests)) {
mt = menu->tests;
}
if (mt->flags & MENU_LAST) {
mt = menu->tests;
}
/* Run the standard test suite */
for ( ; (mt->flags & MENU_LAST) == 0; ) {
if ((mt->flags & MENU_NEXT) == MENU_NEXT) {
repeat_tests = mt;
repeat_state = test_state;
nch = run_standard_tests;
menu_test_loop(mt, &test_state, &nch);
if (nch != 0 && nch != 'n') {
ch = nch;
break;
}
if (test_state & MENU_STOP) {
break;
}
}
mt++;
}
if (ch == 0) {
ch = hot_topic;
}
menu->resume_tests = mt;
menu->resume_state = test_state;
menu->resume_char = ch;
if (ch == run_standard_tests) {
/* pop up a level */
break;
}
}
}
*last_ch = ch;
prompt_string[prompt_length] = '\0';
}
/*
** generic_done_message(test_list)
**
** Print the Done message and request input.
*/
void
generic_done_message(
struct test_list *test,
int *state,
int *ch)
{
char done_message[128];
if (test->caps_done) {
sprintf(done_message, "(%s) Done ", test->caps_done);
ptext(done_message);
} else {
ptext("Done ");
}
*ch = wait_here();
if (*ch == '\r' || *ch == '\n' || *ch == 'n') {
*ch = 0;
}
if (*ch == 's') {
*state |= MENU_STOP;
*ch = 0;
}
}
/*
** menu_clear_screen(test, state, ch)
**
** Just clear the screen.
*/
void
menu_clear_screen(
struct test_list *test GCC_UNUSED,
int *state GCC_UNUSED,
int *ch GCC_UNUSED)
{
put_clear();
}
/*
** menu_reset_init(test, state, ch)
**
** Send the reset and init strings.
*/
void
menu_reset_init(
struct test_list *test GCC_UNUSED,
int *state GCC_UNUSED,
int *ch GCC_UNUSED)
{
reset_init();
put_crlf();
}
/*
** subtest_menu(test, state, ch)
**
** Scan the menu looking for something to execute
** Return TRUE if we found anything.
*/
int
subtest_menu(
struct test_list *test,
int *state,
int *ch)
{
struct test_list *mt;
if (*ch) {
for (mt = test; (mt->flags & MENU_LAST) == 0; mt++) {
if (mt->menu_entry && (*ch == mt->menu_entry[0])) {
*ch = 0;
menu_test_loop(mt, state, ch);
return TRUE;
}
}
}
return FALSE;
}
/*
** menu_can_scan(menu-structure)
**
** Recursively scan the menu tree and find which cap names can be tested.
*/
void
menu_can_scan(
const struct test_menu *menu)
{
struct test_list *mt;
for (mt = menu->tests; (mt->flags & MENU_LAST) == 0; mt++) {
can_test(mt->caps_done, FLAG_CAN_TEST);
can_test(mt->caps_tested, FLAG_CAN_TEST);
if (!(mt->test_procedure)) {
if (mt->sub_menu) {
menu_can_scan(mt->sub_menu);
}
}
}
}
/*
** menu_search(menu-structure, cap)
**
** Recursively search the menu tree and execute any tests that use cap.
*/
static void
menu_search(
struct test_menu *menu,
int *state,
int *ch,
char *cap)
{
struct test_list *mt;
int nch;
for (mt = menu->tests; (mt->flags & MENU_LAST) == 0; mt++) {
nch = 0;
if (cap_match(mt->caps_done, cap)
|| cap_match(mt->caps_tested, cap)) {
menu_test_loop(mt, state, &nch);
}
if (!(mt->test_procedure)) {
if (mt->sub_menu) {
menu_search(mt->sub_menu, state, &nch, cap);
}
}
if (*state & MENU_STOP) {
break;
}
if (nch != 0 && nch != 'n') {
*ch = nch;
break;
}
}
}
/*
** test_byname(menu, state, ch)
**
** Get a cap name then run all tests that use that cap.
*/
static void
test_byname(
struct test_menu *menu,
int *state GCC_UNUSED,
int *ch)
{
int test_state = 0;
char cap[32];
if (tty_can_sync == SYNC_NOT_TESTED) {
verify_time();
}
ptext("enter name: ");
read_string(cap, sizeof(cap));
if (cap[0]) {
menu_search(menu, &test_state, ch, cap);
}
*ch = '?';
}
| Java |
/*
* UriMapFeature.hpp
*
* Copyright (c) 2010 Paul Giblock <pgib/at/users.sourceforge.net>
*
* This file is part of Unison - http://unison.sourceforge.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#ifndef UNISON_LV2_URI_MAP_FEATURE_H
#define UNISON_LV2_URI_MAP_FEATURE_H
#include "Feature.hpp"
#include <lv2/uri-map.lv2/uri-map.h>
namespace Lv2 {
namespace Internal {
class UriMap;
class UriMapFeature : public Feature
{
public:
UriMapFeature (UriMap* uriMap);
LV2_Feature* lv2Feature ();
void initialize (LV2_Feature*, const Lv2Plugin&) const {};
void cleanup (LV2_Feature*) const {};
private:
static uint32_t uriToId (LV2_URI_Map_Callback_Data cbData, const char* map, const char* uri);
LV2_Feature m_feature;
LV2_URI_Map_Feature m_data;
UriMap* m_uriMap;
};
} // Internal
} // Lv2
#endif
// vim: tw=90 ts=8 sw=2 sts=2 et sta noai
| Java |
<div class="wide form">
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl($this->route),
'method'=>'get',
)); ?>
<div class="row">
<?php echo $form->label($model,'id'); ?>
<?php echo $form->textField($model,'id',array('size'=>20,'maxlength'=>20)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'executed_at'); ?>
<?php echo $form->textField($model,'executed_at'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'class'); ?>
<?php echo $form->textField($model,'class',array('size'=>8,'maxlength'=>8)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'amount'); ?>
<?php echo $form->textField($model,'amount',array('size'=>20,'maxlength'=>20)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'charge_account'); ?>
<?php echo $form->textField($model,'charge_account',array('size'=>10,'maxlength'=>10)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'deposit_account'); ?>
<?php echo $form->textField($model,'deposit_account',array('size'=>10,'maxlength'=>10)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'charge_user'); ?>
<?php echo $form->textField($model,'charge_user',array('size'=>10,'maxlength'=>10)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'deposit_user'); ?>
<?php echo $form->textField($model,'deposit_user',array('size'=>10,'maxlength'=>10)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'subject'); ?>
<?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>255)); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Search'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- search-form --> | Java |
import tkinter
FRAME_BORDER = 5
class PageView(object):
__root = None
bd = None
def __init__(self, root=None, main_frame=None):
param = self.params()
if root is None:
# standalone
self.__root = tkinter.Tk()
self.__root.title(param['title'])
self.__root.geometry('%sx%s+%s+%s' % (param['w'],
param['h'],
param['x'],
param['y']
))
else:
# inside
self.__root = root
self.bd = param['bd']
if main_frame is None:
# standalone
main_f = tkinter.Frame(master=self.__root, bg='black', bd=self.bd)
main_f.pack(fill='both', expand=True)
else:
# inside
main_f = main_frame
self.make_widgets(main_f)
@property
def root(self):
return self.__root
def close(self):
self.__root.destroy()
self.__root.quit()
# Override
def make_widgets(self, main_frame):
pass
# Override
def params(self):
param = {
'x': 0,
'y': 0,
'w': 500,
'h': 500,
'title': '% Type Prog Title Here %',
}
return param
def mk_scrollable_area(obj, obj_frame, sbars):
obj.grid(row=0, column=0, sticky='NSWE')
if 'y' in sbars:
y_scrollbar = tkinter.ttk.Scrollbar(obj_frame)
y_scrollbar.grid(row=0, column=1, sticky='NS')
y_scrollbar['command'] = obj.yview
obj['yscrollcommand'] = y_scrollbar.set
if 'x' in sbars:
x_scrollbar = tkinter.ttk.Scrollbar(obj_frame, orient='horizontal')
x_scrollbar.grid(row=1, column=0, sticky='WE')
x_scrollbar['command'] = obj.xview
obj['xscrollcommand'] = x_scrollbar.set
obj_frame.columnconfigure(1, 'minsize')
obj_frame.columnconfigure(0, weight=1)
obj_frame.rowconfigure(1, 'minsize')
obj_frame.rowconfigure(0, weight=1)
def mk_listbox(frame, side='top', sbars='y', sel_mode=tkinter.EXTENDED):
BORDER = 0
COLOR = 'grey'
listbox_frame = tkinter.Frame(frame, bg=COLOR, bd=BORDER)
listbox_frame.pack(side=side, fill='both', expand=True)
listbox = tkinter.Listbox(listbox_frame, selectmode=sel_mode)
mk_scrollable_area(listbox, listbox_frame, sbars)
return listbox
def mk_treeview(frame, side='top', sbars='y'):
BORDER = 0
COLOR = 'grey'
treeview_frame = tkinter.Frame(frame, bg=COLOR, bd=BORDER)
treeview_frame.pack(side=side, fill='both', expand=True)
treeview = tkinter.ttk.Treeview(treeview_frame)
mk_scrollable_area(treeview, treeview_frame, sbars)
return treeview
| Java |
// Copyright (C) 2012 Markus Fischer
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// Contact: info@doctor-doc.com
package ch.dbs.actions.bestellung;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.lang.StringEscapeUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import util.CodeUrl;
import util.Http;
import ch.dbs.form.JournalDetails;
import enums.Connect;
/**
* This class reads answers from the normal EZB UI searched with the parameter
* xmloutput=1 to get XML.
*/
public class EZBXML {
private static final Logger LOG = LoggerFactory.getLogger(EZBXML.class);
public List<JournalDetails> searchByTitle(final String jtitle, final String bibid) {
final Http http = new Http();
final CodeUrl coder = new CodeUrl();
final StringBuffer link = new StringBuffer(
"http://ezb.uni-regensburg.de/ezeit/searchres.phtml?xmloutput=1&colors=7&lang=de&jq_type1=KT&jq_bool2=AND&jq_not2=+&jq_type2=KS&jq_term2=&jq_bool3=AND&jq_not3=+&jq_type3=PU&jq_term3=&offset=-1&hits_per_page=30&search_journal=Suche+starten&Notations%5B%5D=all&selected_colors%5B%5D=1&selected_colors%5B%5D=2&selected_colors%5B%5D=4&bibid=");
link.append(bibid);
link.append("&jq_term1=");
link.append(coder.encode(jtitle, "ISO-8859-1"));
String content = http.getContent(link.toString(), Connect.TIMEOUT_2.getValue(), Connect.TRIES_2.getValue(),
null);
// if we have > 30 hits, try a more concise search using: &jq_type1=KS (title starts with) instead of &jq_type1=KT (words in title)
if (content != null && content.contains("<search_count>")) {
final int x = Integer.parseInt(content.substring(content.indexOf("<search_count>") + 14,
content.indexOf("</search_count>")));
if (x > 30) {
final StringBuffer link2 = new StringBuffer(
"http://ezb.uni-regensburg.de/ezeit/searchres.phtml?xmloutput=1&colors=7&lang=de&jq_type1=KS&jq_bool2=AND&jq_not2=+&jq_type2=KS&jq_term2=&jq_bool3=AND&jq_not3=+&jq_type3=PU&jq_term3=&offset=-1&hits_per_page=30&search_journal=Suche+starten&Notations%5B%5D=all&selected_colors%5B%5D=1&selected_colors%5B%5D=2&selected_colors%5B%5D=4&bibid=");
link2.append(bibid);
link2.append("&jq_term1=");
link2.append(coder.encode(jtitle, "ISO-8859-1"));
content = http.getContent(link2.toString(), Connect.TIMEOUT_2.getValue(), Connect.TRIES_2.getValue(),
null);
}
}
final List<String> jourids = getJourids(content);
return searchByJourids(jourids, bibid);
}
public List<JournalDetails> searchByIssn(final String issn, final String bibid) {
final Http http = new Http();
final StringBuffer link = new StringBuffer(
"http://ezb.uni-regensburg.de/ezeit/searchres.phtml?xmloutput=1&colors=5&lang=de&jq_type1=KT&jq_term1=&jq_bool2=AND&jq_not2=+&jq_type2=KS&jq_term2=&jq_bool3=AND&jq_not3=+&jq_type3=PU&jq_term3=&jq_bool4=AND&jq_not4=+&jq_type4=IS&offset=-1&hits_per_page=50&search_journal=Suche+starten&Notations%5B%5D=all&selected_colors%5B%5D=1&selected_colors%5B%5D=2&selected_colors%5B%5D=4&bibid=");
link.append(bibid);
link.append("&jq_term4=");
link.append(issn);
final String content = http.getContent(link.toString(), Connect.TIMEOUT_2.getValue(),
Connect.TRIES_2.getValue(), null);
final List<String> jourids = getJourids(content);
return searchByJourids(jourids, bibid);
}
public List<JournalDetails> searchByJourids(final List<String> jourids, final String bibid) {
final List<JournalDetails> list = new ArrayList<JournalDetails>();
final Http http = new Http();
final StringBuffer link = new StringBuffer(
"http://rzblx1.uni-regensburg.de/ezeit/detail.phtml?xmloutput=1&colors=7&lang=de&bibid=");
link.append(bibid);
link.append("&jour_id=");
final StringBuffer infoLink = new StringBuffer(
"http://ezb.uni-regensburg.de/ezeit/detail.phtml?colors=7&lang=de&bibid=");
infoLink.append(bibid);
infoLink.append("&jour_id=");
try {
for (final String jourid : jourids) {
final JournalDetails jd = new JournalDetails();
final String content = http.getContent(link.toString() + jourid, Connect.TIMEOUT_1.getValue(),
Connect.TRIES_1.getValue(), null);
if (content != null) {
final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
final DocumentBuilder builder = domFactory.newDocumentBuilder();
final Document doc = builder.parse(new InputSource(new StringReader(content)));
final XPathFactory factory = XPathFactory.newInstance();
final XPath xpath = factory.newXPath();
final XPathExpression exprJournal = xpath.compile("//journal");
final XPathExpression exprPissns = xpath.compile("//journal/detail/P_ISSNs");
final XPathExpression exprEissns = xpath.compile("//journal/detail/E_ISSNs");
final NodeList resultJournal = (NodeList) exprJournal.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < resultJournal.getLength(); i++) {
final Node firstResultNode = resultJournal.item(i);
final Element journal = (Element) firstResultNode;
// Title
String title = getValue(journal.getElementsByTagName("title"));
if (title != null) {
title = Jsoup.clean(title, Whitelist.none());
title = Jsoup.parse(title).text();
}
jd.setZeitschriftentitel(title);
// P-ISSNs
final NodeList resultPissns = (NodeList) exprPissns.evaluate(doc, XPathConstants.NODESET);
// get first pissn
for (int z = 0; z < resultPissns.getLength(); z++) {
final Node firstPissnsNode = resultPissns.item(i);
final Element pissnElement = (Element) firstPissnsNode;
final String pissn = getValue(pissnElement.getElementsByTagName("P_ISSN"));
jd.setIssn(pissn);
}
// try to get Eissn if we have no Pissn
if (jd.getIssn() == null) {
// E-ISSNs
final NodeList resultEissns = (NodeList) exprEissns.evaluate(doc, XPathConstants.NODESET);
// get first eissn
for (int z = 0; z < resultEissns.getLength(); z++) {
final Node firstEissnsNode = resultEissns.item(i);
final Element eissnElement = (Element) firstEissnsNode;
final String eissn = getValue(eissnElement.getElementsByTagName("E_ISSN"));
jd.setIssn(eissn);
}
}
// add info link
jd.setLink(infoLink.toString() + jourid);
list.add(jd);
}
}
}
} catch (final XPathExpressionException e) {
LOG.error(e.toString());
} catch (final SAXParseException e) {
LOG.error(e.toString());
} catch (final SAXException e) {
LOG.error(e.toString());
} catch (final IOException e) {
LOG.error(e.toString());
} catch (final ParserConfigurationException e) {
LOG.error(e.toString());
} catch (final Exception e) {
LOG.error(e.toString());
}
return list;
}
private List<String> getJourids(final String content) {
final List<String> result = new ArrayList<String>();
try {
if (content != null) {
final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
final DocumentBuilder builder = domFactory.newDocumentBuilder();
final Document doc = builder.parse(new InputSource(new StringReader(content)));
final XPathFactory factory = XPathFactory.newInstance();
final XPath xpath = factory.newXPath();
final XPathExpression exprJournals = xpath.compile("//journals/journal");
final NodeList journals = (NodeList) exprJournals.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < journals.getLength(); i++) {
final Node firstResultNode = journals.item(i);
final Element journal = (Element) firstResultNode;
final String id = journal.getAttribute("jourid");
if (id != null) {
result.add(id);
}
}
}
} catch (final XPathExpressionException e) {
LOG.error(e.toString());
} catch (final SAXParseException e) {
LOG.error(e.toString());
} catch (final SAXException e) {
LOG.error(e.toString());
} catch (final IOException e) {
LOG.error(e.toString());
} catch (final ParserConfigurationException e) {
LOG.error(e.toString());
} catch (final Exception e) {
LOG.error(e.toString());
}
return result;
}
private String getValue(final NodeList list) {
String result = null;
final Element listElement = (Element) list.item(0);
if (listElement != null) {
final NodeList textList = listElement.getChildNodes();
if (textList.getLength() > 0) {
result = StringEscapeUtils.unescapeXml(textList.item(0).getNodeValue());
}
}
return result;
}
}
| Java |
/*
* linux/fs/namei.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
/*
* Some corrections by tytso.
*/
/* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname
* lookup logic.
*/
/* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture.
*/
#include <linux/init.h>
#include <linux/export.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/namei.h>
#include <linux/pagemap.h>
#include <linux/fsnotify.h>
#include <linux/personality.h>
#include <linux/security.h>
#include <linux/ima.h>
#include <linux/syscalls.h>
#include <linux/mount.h>
#include <linux/audit.h>
#include <linux/capability.h>
#include <linux/file.h>
#include <linux/fcntl.h>
#include <linux/device_cgroup.h>
#include <linux/fs_struct.h>
#include <linux/posix_acl.h>
#include <linux/hash.h>
#include <asm/uaccess.h>
#include "internal.h"
#include "mount.h"
/* [Feb-1997 T. Schoebel-Theuer]
* Fundamental changes in the pathname lookup mechanisms (namei)
* were necessary because of omirr. The reason is that omirr needs
* to know the _real_ pathname, not the user-supplied one, in case
* of symlinks (and also when transname replacements occur).
*
* The new code replaces the old recursive symlink resolution with
* an iterative one (in case of non-nested symlink chains). It does
* this with calls to <fs>_follow_link().
* As a side effect, dir_namei(), _namei() and follow_link() are now
* replaced with a single function lookup_dentry() that can handle all
* the special cases of the former code.
*
* With the new dcache, the pathname is stored at each inode, at least as
* long as the refcount of the inode is positive. As a side effect, the
* size of the dcache depends on the inode cache and thus is dynamic.
*
* [29-Apr-1998 C. Scott Ananian] Updated above description of symlink
* resolution to correspond with current state of the code.
*
* Note that the symlink resolution is not *completely* iterative.
* There is still a significant amount of tail- and mid- recursion in
* the algorithm. Also, note that <fs>_readlink() is not used in
* lookup_dentry(): lookup_dentry() on the result of <fs>_readlink()
* may return different results than <fs>_follow_link(). Many virtual
* filesystems (including /proc) exhibit this behavior.
*/
/* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation:
* New symlink semantics: when open() is called with flags O_CREAT | O_EXCL
* and the name already exists in form of a symlink, try to create the new
* name indicated by the symlink. The old code always complained that the
* name already exists, due to not following the symlink even if its target
* is nonexistent. The new semantics affects also mknod() and link() when
* the name is a symlink pointing to a non-existent name.
*
* I don't know which semantics is the right one, since I have no access
* to standards. But I found by trial that HP-UX 9.0 has the full "new"
* semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the
* "old" one. Personally, I think the new semantics is much more logical.
* Note that "ln old new" where "new" is a symlink pointing to a non-existing
* file does succeed in both HP-UX and SunOs, but not in Solaris
* and in the old Linux semantics.
*/
/* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink
* semantics. See the comments in "open_namei" and "do_link" below.
*
* [10-Sep-98 Alan Modra] Another symlink change.
*/
/* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks:
* inside the path - always follow.
* in the last component in creation/removal/renaming - never follow.
* if LOOKUP_FOLLOW passed - follow.
* if the pathname has trailing slashes - follow.
* otherwise - don't follow.
* (applied in that order).
*
* [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT
* restored for 2.4. This is the last surviving part of old 4.2BSD bug.
* During the 2.4 we need to fix the userland stuff depending on it -
* hopefully we will be able to get rid of that wart in 2.5. So far only
* XEmacs seems to be relying on it...
*/
/*
* [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland)
* implemented. Let's see if raised priority of ->s_vfs_rename_mutex gives
* any extra contention...
*/
/* In order to reduce some races, while at the same time doing additional
* checking and hopefully speeding things up, we copy filenames to the
* kernel data space before using them..
*
* POSIX.1 2.4: an empty pathname is invalid (ENOENT).
* PATH_MAX includes the nul terminator --RR.
*/
static int do_getname(const char __user *filename, char *page)
{
int retval;
unsigned long len = PATH_MAX;
if (!segment_eq(get_fs(), KERNEL_DS)) {
if ((unsigned long) filename >= TASK_SIZE)
return -EFAULT;
if (TASK_SIZE - (unsigned long) filename < PATH_MAX)
len = TASK_SIZE - (unsigned long) filename;
}
retval = strncpy_from_user(page, filename, len);
if (retval > 0) {
if (retval < len)
return 0;
return -ENAMETOOLONG;
} else if (!retval)
retval = -ENOENT;
return retval;
}
static char *getname_flags(const char __user *filename, int flags, int *empty)
{
char *result = __getname();
int retval;
if (!result)
return ERR_PTR(-ENOMEM);
retval = do_getname(filename, result);
if (retval < 0) {
if (retval == -ENOENT && empty)
*empty = 1;
if (retval != -ENOENT || !(flags & LOOKUP_EMPTY)) {
__putname(result);
return ERR_PTR(retval);
}
}
audit_getname(result);
return result;
}
char *getname(const char __user * filename)
{
return getname_flags(filename, 0, NULL);
}
#ifdef CONFIG_AUDITSYSCALL
void putname(const char *name)
{
if (unlikely(!audit_dummy_context()))
audit_putname(name);
else
__putname(name);
}
EXPORT_SYMBOL(putname);
#endif
static int check_acl(struct inode *inode, int mask)
{
#ifdef CONFIG_FS_POSIX_ACL
struct posix_acl *acl;
if (mask & MAY_NOT_BLOCK) {
acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
if (!acl)
return -EAGAIN;
/* no ->get_acl() calls in RCU mode... */
if (acl == ACL_NOT_CACHED)
return -ECHILD;
return posix_acl_permission(inode, acl, mask & ~MAY_NOT_BLOCK);
}
acl = get_cached_acl(inode, ACL_TYPE_ACCESS);
/*
* A filesystem can force a ACL callback by just never filling the
* ACL cache. But normally you'd fill the cache either at inode
* instantiation time, or on the first ->get_acl call.
*
* If the filesystem doesn't have a get_acl() function at all, we'll
* just create the negative cache entry.
*/
if (acl == ACL_NOT_CACHED) {
if (inode->i_op->get_acl) {
acl = inode->i_op->get_acl(inode, ACL_TYPE_ACCESS);
if (IS_ERR(acl))
return PTR_ERR(acl);
} else {
set_cached_acl(inode, ACL_TYPE_ACCESS, NULL);
return -EAGAIN;
}
}
if (acl) {
int error = posix_acl_permission(inode, acl, mask);
posix_acl_release(acl);
return error;
}
#endif
return -EAGAIN;
}
/*
* This does the basic permission checking
*/
static int acl_permission_check(struct inode *inode, int mask)
{
unsigned int mode = inode->i_mode;
if (current_user_ns() != inode_userns(inode))
goto other_perms;
if (likely(current_fsuid() == inode->i_uid))
mode >>= 6;
else {
if (IS_POSIXACL(inode) && (mode & S_IRWXG)) {
int error = check_acl(inode, mask);
if (error != -EAGAIN)
return error;
}
if (in_group_p(inode->i_gid))
mode >>= 3;
}
other_perms:
/*
* If the DACs are ok we don't need any capability check.
*/
if ((mask & ~mode & (MAY_READ | MAY_WRITE | MAY_EXEC)) == 0)
return 0;
return -EACCES;
}
/**
* generic_permission - check for access rights on a Posix-like filesystem
* @inode: inode to check access rights for
* @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC, ...)
*
* Used to check for read/write/execute permissions on a file.
* We use "fsuid" for this, letting us set arbitrary permissions
* for filesystem access without changing the "normal" uids which
* are used for other things.
*
* generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
* request cannot be satisfied (eg. requires blocking or too much complexity).
* It would then be called again in ref-walk mode.
*/
int generic_permission(struct inode *inode, int mask)
{
int ret;
/*
* Do the basic permission checks.
*/
ret = acl_permission_check(inode, mask);
if (ret != -EACCES)
return ret;
if (S_ISDIR(inode->i_mode)) {
/* DACs are overridable for directories */
if (ns_capable(inode_userns(inode), CAP_DAC_OVERRIDE))
return 0;
if (!(mask & MAY_WRITE))
if (ns_capable(inode_userns(inode), CAP_DAC_READ_SEARCH))
return 0;
return -EACCES;
}
/*
* Read/write DACs are always overridable.
* Executable DACs are overridable when there is
* at least one exec bit set.
*/
if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
if (ns_capable(inode_userns(inode), CAP_DAC_OVERRIDE))
return 0;
/*
* Searching includes executable on directories, else just read.
*/
mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
if (mask == MAY_READ)
if (ns_capable(inode_userns(inode), CAP_DAC_READ_SEARCH))
return 0;
return -EACCES;
}
/*
* We _really_ want to just do "generic_permission()" without
* even looking at the inode->i_op values. So we keep a cache
* flag in inode->i_opflags, that says "this has not special
* permission function, use the fast case".
*/
static inline int do_inode_permission(struct inode *inode, int mask)
{
if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) {
if (likely(inode->i_op->permission))
return inode->i_op->permission(inode, mask);
/* This gets set once for the inode lifetime */
spin_lock(&inode->i_lock);
inode->i_opflags |= IOP_FASTPERM;
spin_unlock(&inode->i_lock);
}
return generic_permission(inode, mask);
}
/**
* inode_permission - check for access rights to a given inode
* @inode: inode to check permission on
* @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC, ...)
*
* Used to check for read/write/execute permissions on an inode.
* We use "fsuid" for this, letting us set arbitrary permissions
* for filesystem access without changing the "normal" uids which
* are used for other things.
*
* When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
*/
int inode_permission(struct inode *inode, int mask)
{
int retval;
if (unlikely(mask & MAY_WRITE)) {
umode_t mode = inode->i_mode;
/*
* Nobody gets write access to a read-only fs.
*/
if (IS_RDONLY(inode) &&
(S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
return -EROFS;
/*
* Nobody gets write access to an immutable file.
*/
if (IS_IMMUTABLE(inode))
return -EACCES;
}
retval = do_inode_permission(inode, mask);
if (retval)
return retval;
retval = devcgroup_inode_permission(inode, mask);
if (retval)
return retval;
return security_inode_permission(inode, mask);
}
/**
* path_get - get a reference to a path
* @path: path to get the reference to
*
* Given a path increment the reference count to the dentry and the vfsmount.
*/
void path_get(struct path *path)
{
mntget(path->mnt);
dget(path->dentry);
}
EXPORT_SYMBOL(path_get);
/**
* path_put - put a reference to a path
* @path: path to put the reference to
*
* Given a path decrement the reference count to the dentry and the vfsmount.
*/
void path_put(struct path *path)
{
dput(path->dentry);
mntput(path->mnt);
}
EXPORT_SYMBOL(path_put);
/*
* Path walking has 2 modes, rcu-walk and ref-walk (see
* Documentation/filesystems/path-lookup.txt). In situations when we can't
* continue in RCU mode, we attempt to drop out of rcu-walk mode and grab
* normal reference counts on dentries and vfsmounts to transition to rcu-walk
* mode. Refcounts are grabbed at the last known good point before rcu-walk
* got stuck, so ref-walk may continue from there. If this is not successful
* (eg. a seqcount has changed), then failure is returned and it's up to caller
* to restart the path walk from the beginning in ref-walk mode.
*/
/**
* unlazy_walk - try to switch to ref-walk mode.
* @nd: nameidata pathwalk data
* @dentry: child of nd->path.dentry or NULL
* Returns: 0 on success, -ECHILD on failure
*
* unlazy_walk attempts to legitimize the current nd->path, nd->root and dentry
* for ref-walk mode. @dentry must be a path found by a do_lookup call on
* @nd or NULL. Must be called from rcu-walk context.
*/
static int unlazy_walk(struct nameidata *nd, struct dentry *dentry)
{
struct fs_struct *fs = current->fs;
struct dentry *parent = nd->path.dentry;
int want_root = 0;
BUG_ON(!(nd->flags & LOOKUP_RCU));
if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) {
want_root = 1;
spin_lock(&fs->lock);
if (nd->root.mnt != fs->root.mnt ||
nd->root.dentry != fs->root.dentry)
goto err_root;
}
spin_lock(&parent->d_lock);
if (!dentry) {
if (!__d_rcu_to_refcount(parent, nd->seq))
goto err_parent;
BUG_ON(nd->inode != parent->d_inode);
} else {
if (dentry->d_parent != parent)
goto err_parent;
spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
if (!__d_rcu_to_refcount(dentry, nd->seq))
goto err_child;
/*
* If the sequence check on the child dentry passed, then
* the child has not been removed from its parent. This
* means the parent dentry must be valid and able to take
* a reference at this point.
*/
BUG_ON(!IS_ROOT(dentry) && dentry->d_parent != parent);
BUG_ON(!parent->d_count);
parent->d_count++;
spin_unlock(&dentry->d_lock);
}
spin_unlock(&parent->d_lock);
if (want_root) {
path_get(&nd->root);
spin_unlock(&fs->lock);
}
mntget(nd->path.mnt);
rcu_read_unlock();
br_read_unlock(&vfsmount_lock);
nd->flags &= ~LOOKUP_RCU;
return 0;
err_child:
spin_unlock(&dentry->d_lock);
err_parent:
spin_unlock(&parent->d_lock);
err_root:
if (want_root)
spin_unlock(&fs->lock);
return -ECHILD;
}
/**
* release_open_intent - free up open intent resources
* @nd: pointer to nameidata
*/
void release_open_intent(struct nameidata *nd)
{
struct file *file = nd->intent.open.file;
if (file && !IS_ERR(file)) {
if (file->f_path.dentry == NULL)
put_filp(file);
else
fput(file);
}
}
static inline int d_revalidate(struct dentry *dentry, struct nameidata *nd)
{
return dentry->d_op->d_revalidate(dentry, nd);
}
/**
* complete_walk - successful completion of path walk
* @nd: pointer nameidata
*
* If we had been in RCU mode, drop out of it and legitimize nd->path.
* Revalidate the final result, unless we'd already done that during
* the path walk or the filesystem doesn't ask for it. Return 0 on
* success, -error on failure. In case of failure caller does not
* need to drop nd->path.
*/
static int complete_walk(struct nameidata *nd)
{
struct dentry *dentry = nd->path.dentry;
int status;
if (nd->flags & LOOKUP_RCU) {
nd->flags &= ~LOOKUP_RCU;
if (!(nd->flags & LOOKUP_ROOT))
nd->root.mnt = NULL;
spin_lock(&dentry->d_lock);
if (unlikely(!__d_rcu_to_refcount(dentry, nd->seq))) {
spin_unlock(&dentry->d_lock);
rcu_read_unlock();
br_read_unlock(&vfsmount_lock);
return -ECHILD;
}
BUG_ON(nd->inode != dentry->d_inode);
spin_unlock(&dentry->d_lock);
mntget(nd->path.mnt);
rcu_read_unlock();
br_read_unlock(&vfsmount_lock);
}
if (likely(!(nd->flags & LOOKUP_JUMPED)))
return 0;
if (likely(!(dentry->d_flags & DCACHE_OP_REVALIDATE)))
return 0;
if (likely(!(dentry->d_sb->s_type->fs_flags & FS_REVAL_DOT)))
return 0;
/* Note: we do not d_invalidate() */
status = d_revalidate(dentry, nd);
if (status > 0)
return 0;
if (!status)
status = -ESTALE;
path_put(&nd->path);
return status;
}
static __always_inline void set_root(struct nameidata *nd)
{
if (!nd->root.mnt)
get_fs_root(current->fs, &nd->root);
}
static int link_path_walk(const char *, struct nameidata *);
static __always_inline void set_root_rcu(struct nameidata *nd)
{
if (!nd->root.mnt) {
struct fs_struct *fs = current->fs;
unsigned seq;
do {
seq = read_seqcount_begin(&fs->seq);
nd->root = fs->root;
nd->seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
} while (read_seqcount_retry(&fs->seq, seq));
}
}
static __always_inline int __vfs_follow_link(struct nameidata *nd, const char *link)
{
int ret;
if (IS_ERR(link))
goto fail;
if (*link == '/') {
set_root(nd);
path_put(&nd->path);
nd->path = nd->root;
path_get(&nd->root);
nd->flags |= LOOKUP_JUMPED;
}
nd->inode = nd->path.dentry->d_inode;
ret = link_path_walk(link, nd);
return ret;
fail:
path_put(&nd->path);
return PTR_ERR(link);
}
static void path_put_conditional(struct path *path, struct nameidata *nd)
{
dput(path->dentry);
if (path->mnt != nd->path.mnt)
mntput(path->mnt);
}
static inline void path_to_nameidata(const struct path *path,
struct nameidata *nd)
{
if (!(nd->flags & LOOKUP_RCU)) {
dput(nd->path.dentry);
if (nd->path.mnt != path->mnt)
mntput(nd->path.mnt);
}
nd->path.mnt = path->mnt;
nd->path.dentry = path->dentry;
}
static inline void put_link(struct nameidata *nd, struct path *link, void *cookie)
{
struct inode *inode = link->dentry->d_inode;
if (!IS_ERR(cookie) && inode->i_op->put_link)
inode->i_op->put_link(link->dentry, nd, cookie);
path_put(link);
}
static __always_inline int
follow_link(struct path *link, struct nameidata *nd, void **p)
{
int error;
struct dentry *dentry = link->dentry;
BUG_ON(nd->flags & LOOKUP_RCU);
if (link->mnt == nd->path.mnt)
mntget(link->mnt);
if (unlikely(current->total_link_count >= 40)) {
*p = ERR_PTR(-ELOOP); /* no ->put_link(), please */
path_put(&nd->path);
return -ELOOP;
}
cond_resched();
current->total_link_count++;
touch_atime(link);
nd_set_link(nd, NULL);
error = security_inode_follow_link(link->dentry, nd);
if (error) {
*p = ERR_PTR(error); /* no ->put_link(), please */
path_put(&nd->path);
return error;
}
nd->last_type = LAST_BIND;
*p = dentry->d_inode->i_op->follow_link(dentry, nd);
error = PTR_ERR(*p);
if (!IS_ERR(*p)) {
char *s = nd_get_link(nd);
error = 0;
if (s)
error = __vfs_follow_link(nd, s);
else if (nd->last_type == LAST_BIND) {
nd->flags |= LOOKUP_JUMPED;
nd->inode = nd->path.dentry->d_inode;
if (nd->inode->i_op->follow_link) {
/* stepped on a _really_ weird one */
path_put(&nd->path);
error = -ELOOP;
}
}
}
return error;
}
static int follow_up_rcu(struct path *path)
{
struct mount *mnt = real_mount(path->mnt);
struct mount *parent;
struct dentry *mountpoint;
parent = mnt->mnt_parent;
if (&parent->mnt == path->mnt)
return 0;
mountpoint = mnt->mnt_mountpoint;
path->dentry = mountpoint;
path->mnt = &parent->mnt;
return 1;
}
/*
* follow_up - Find the mountpoint of path's vfsmount
*
* Given a path, find the mountpoint of its source file system.
* Replace @path with the path of the mountpoint in the parent mount.
* Up is towards /.
*
* Return 1 if we went up a level and 0 if we were already at the
* root.
*/
int follow_up(struct path *path)
{
struct mount *mnt = real_mount(path->mnt);
struct mount *parent;
struct dentry *mountpoint;
br_read_lock(&vfsmount_lock);
parent = mnt->mnt_parent;
if (&parent->mnt == path->mnt) {
br_read_unlock(&vfsmount_lock);
return 0;
}
mntget(&parent->mnt);
mountpoint = dget(mnt->mnt_mountpoint);
br_read_unlock(&vfsmount_lock);
dput(path->dentry);
path->dentry = mountpoint;
mntput(path->mnt);
path->mnt = &parent->mnt;
return 1;
}
/*
* Perform an automount
* - return -EISDIR to tell follow_managed() to stop and return the path we
* were called with.
*/
static int follow_automount(struct path *path, unsigned flags,
bool *need_mntput)
{
struct vfsmount *mnt;
int err;
if (!path->dentry->d_op || !path->dentry->d_op->d_automount)
return -EREMOTE;
/* We don't want to mount if someone's just doing a stat -
* unless they're stat'ing a directory and appended a '/' to
* the name.
*
* We do, however, want to mount if someone wants to open or
* create a file of any type under the mountpoint, wants to
* traverse through the mountpoint or wants to open the
* mounted directory. Also, autofs may mark negative dentries
* as being automount points. These will need the attentions
* of the daemon to instantiate them before they can be used.
*/
if (!(flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
path->dentry->d_inode)
return -EISDIR;
current->total_link_count++;
if (current->total_link_count >= 40)
return -ELOOP;
mnt = path->dentry->d_op->d_automount(path);
if (IS_ERR(mnt)) {
/*
* The filesystem is allowed to return -EISDIR here to indicate
* it doesn't want to automount. For instance, autofs would do
* this so that its userspace daemon can mount on this dentry.
*
* However, we can only permit this if it's a terminal point in
* the path being looked up; if it wasn't then the remainder of
* the path is inaccessible and we should say so.
*/
if (PTR_ERR(mnt) == -EISDIR && (flags & LOOKUP_PARENT))
return -EREMOTE;
return PTR_ERR(mnt);
}
if (!mnt) /* mount collision */
return 0;
if (!*need_mntput) {
/* lock_mount() may release path->mnt on error */
mntget(path->mnt);
*need_mntput = true;
}
err = finish_automount(mnt, path);
switch (err) {
case -EBUSY:
/* Someone else made a mount here whilst we were busy */
return 0;
case 0:
path_put(path);
path->mnt = mnt;
path->dentry = dget(mnt->mnt_root);
return 0;
default:
return err;
}
}
/*
* Handle a dentry that is managed in some way.
* - Flagged for transit management (autofs)
* - Flagged as mountpoint
* - Flagged as automount point
*
* This may only be called in refwalk mode.
*
* Serialization is taken care of in namespace.c
*/
static int follow_managed(struct path *path, unsigned flags)
{
struct vfsmount *mnt = path->mnt; /* held by caller, must be left alone */
unsigned managed;
bool need_mntput = false;
int ret = 0;
/* Given that we're not holding a lock here, we retain the value in a
* local variable for each dentry as we look at it so that we don't see
* the components of that value change under us */
while (managed = ACCESS_ONCE(path->dentry->d_flags),
managed &= DCACHE_MANAGED_DENTRY,
unlikely(managed != 0)) {
/* Allow the filesystem to manage the transit without i_mutex
* being held. */
if (managed & DCACHE_MANAGE_TRANSIT) {
BUG_ON(!path->dentry->d_op);
BUG_ON(!path->dentry->d_op->d_manage);
ret = path->dentry->d_op->d_manage(path->dentry, false);
if (ret < 0)
break;
}
/* Transit to a mounted filesystem. */
if (managed & DCACHE_MOUNTED) {
struct vfsmount *mounted = lookup_mnt(path);
if (mounted) {
dput(path->dentry);
if (need_mntput)
mntput(path->mnt);
path->mnt = mounted;
path->dentry = dget(mounted->mnt_root);
need_mntput = true;
continue;
}
/* Something is mounted on this dentry in another
* namespace and/or whatever was mounted there in this
* namespace got unmounted before we managed to get the
* vfsmount_lock */
}
/* Handle an automount point */
if (managed & DCACHE_NEED_AUTOMOUNT) {
ret = follow_automount(path, flags, &need_mntput);
if (ret < 0)
break;
continue;
}
/* We didn't change the current path point */
break;
}
if (need_mntput && path->mnt == mnt)
mntput(path->mnt);
if (ret == -EISDIR)
ret = 0;
return ret < 0 ? ret : need_mntput;
}
int follow_down_one(struct path *path)
{
struct vfsmount *mounted;
mounted = lookup_mnt(path);
if (mounted) {
dput(path->dentry);
mntput(path->mnt);
path->mnt = mounted;
path->dentry = dget(mounted->mnt_root);
return 1;
}
return 0;
}
static inline bool managed_dentry_might_block(struct dentry *dentry)
{
return (dentry->d_flags & DCACHE_MANAGE_TRANSIT &&
dentry->d_op->d_manage(dentry, true) < 0);
}
/*
* Try to skip to top of mountpoint pile in rcuwalk mode. Fail if
* we meet a managed dentry that would need blocking.
*/
static bool __follow_mount_rcu(struct nameidata *nd, struct path *path,
struct inode **inode)
{
for (;;) {
struct mount *mounted;
/*
* Don't forget we might have a non-mountpoint managed dentry
* that wants to block transit.
*/
if (unlikely(managed_dentry_might_block(path->dentry)))
return false;
if (!d_mountpoint(path->dentry))
break;
mounted = __lookup_mnt(path->mnt, path->dentry, 1);
if (!mounted)
break;
path->mnt = &mounted->mnt;
path->dentry = mounted->mnt.mnt_root;
nd->flags |= LOOKUP_JUMPED;
nd->seq = read_seqcount_begin(&path->dentry->d_seq);
/*
* Update the inode too. We don't need to re-check the
* dentry sequence number here after this d_inode read,
* because a mount-point is always pinned.
*/
*inode = path->dentry->d_inode;
}
return true;
}
static void follow_mount_rcu(struct nameidata *nd)
{
while (d_mountpoint(nd->path.dentry)) {
struct mount *mounted;
mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry, 1);
if (!mounted)
break;
nd->path.mnt = &mounted->mnt;
nd->path.dentry = mounted->mnt.mnt_root;
nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
}
}
static int follow_dotdot_rcu(struct nameidata *nd)
{
set_root_rcu(nd);
while (1) {
if (nd->path.dentry == nd->root.dentry &&
nd->path.mnt == nd->root.mnt) {
break;
}
if (nd->path.dentry != nd->path.mnt->mnt_root) {
struct dentry *old = nd->path.dentry;
struct dentry *parent = old->d_parent;
unsigned seq;
seq = read_seqcount_begin(&parent->d_seq);
if (read_seqcount_retry(&old->d_seq, nd->seq))
goto failed;
nd->path.dentry = parent;
nd->seq = seq;
break;
}
if (!follow_up_rcu(&nd->path))
break;
nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
}
follow_mount_rcu(nd);
nd->inode = nd->path.dentry->d_inode;
return 0;
failed:
nd->flags &= ~LOOKUP_RCU;
if (!(nd->flags & LOOKUP_ROOT))
nd->root.mnt = NULL;
rcu_read_unlock();
br_read_unlock(&vfsmount_lock);
return -ECHILD;
}
/*
* Follow down to the covering mount currently visible to userspace. At each
* point, the filesystem owning that dentry may be queried as to whether the
* caller is permitted to proceed or not.
*/
int follow_down(struct path *path)
{
unsigned managed;
int ret;
while (managed = ACCESS_ONCE(path->dentry->d_flags),
unlikely(managed & DCACHE_MANAGED_DENTRY)) {
/* Allow the filesystem to manage the transit without i_mutex
* being held.
*
* We indicate to the filesystem if someone is trying to mount
* something here. This gives autofs the chance to deny anyone
* other than its daemon the right to mount on its
* superstructure.
*
* The filesystem may sleep at this point.
*/
if (managed & DCACHE_MANAGE_TRANSIT) {
BUG_ON(!path->dentry->d_op);
BUG_ON(!path->dentry->d_op->d_manage);
ret = path->dentry->d_op->d_manage(
path->dentry, false);
if (ret < 0)
return ret == -EISDIR ? 0 : ret;
}
/* Transit to a mounted filesystem. */
if (managed & DCACHE_MOUNTED) {
struct vfsmount *mounted = lookup_mnt(path);
if (!mounted)
break;
dput(path->dentry);
mntput(path->mnt);
path->mnt = mounted;
path->dentry = dget(mounted->mnt_root);
continue;
}
/* Don't handle automount points here */
break;
}
return 0;
}
/*
* Skip to top of mountpoint pile in refwalk mode for follow_dotdot()
*/
static void follow_mount(struct path *path)
{
while (d_mountpoint(path->dentry)) {
struct vfsmount *mounted = lookup_mnt(path);
if (!mounted)
break;
dput(path->dentry);
mntput(path->mnt);
path->mnt = mounted;
path->dentry = dget(mounted->mnt_root);
}
}
static void follow_dotdot(struct nameidata *nd)
{
set_root(nd);
while(1) {
struct dentry *old = nd->path.dentry;
if (nd->path.dentry == nd->root.dentry &&
nd->path.mnt == nd->root.mnt) {
break;
}
if (nd->path.dentry != nd->path.mnt->mnt_root) {
/* rare case of legitimate dget_parent()... */
nd->path.dentry = dget_parent(nd->path.dentry);
dput(old);
break;
}
if (!follow_up(&nd->path))
break;
}
follow_mount(&nd->path);
nd->inode = nd->path.dentry->d_inode;
}
/*
* This looks up the name in dcache, possibly revalidates the old dentry and
* allocates a new one if not found or not valid. In the need_lookup argument
* returns whether i_op->lookup is necessary.
*
* dir->d_inode->i_mutex must be held
*/
static struct dentry *lookup_dcache(struct qstr *name, struct dentry *dir,
struct nameidata *nd, bool *need_lookup)
{
struct dentry *dentry;
int error;
*need_lookup = false;
dentry = d_lookup(dir, name);
if (dentry) {
if (d_need_lookup(dentry)) {
*need_lookup = true;
} else if (dentry->d_flags & DCACHE_OP_REVALIDATE) {
error = d_revalidate(dentry, nd);
if (unlikely(error <= 0)) {
if (error < 0) {
dput(dentry);
return ERR_PTR(error);
} else if (!d_invalidate(dentry)) {
dput(dentry);
dentry = NULL;
}
}
}
}
if (!dentry) {
dentry = d_alloc(dir, name);
if (unlikely(!dentry))
return ERR_PTR(-ENOMEM);
*need_lookup = true;
}
return dentry;
}
/*
* Call i_op->lookup on the dentry. The dentry must be negative but may be
* hashed if it was pouplated with DCACHE_NEED_LOOKUP.
*
* dir->d_inode->i_mutex must be held
*/
static struct dentry *lookup_real(struct inode *dir, struct dentry *dentry,
struct nameidata *nd)
{
struct dentry *old;
/* Don't create child dentry for a dead directory. */
if (unlikely(IS_DEADDIR(dir))) {
dput(dentry);
return ERR_PTR(-ENOENT);
}
old = dir->i_op->lookup(dir, dentry, nd);
if (unlikely(old)) {
dput(dentry);
dentry = old;
}
return dentry;
}
static struct dentry *__lookup_hash(struct qstr *name,
struct dentry *base, struct nameidata *nd)
{
bool need_lookup;
struct dentry *dentry;
dentry = lookup_dcache(name, base, nd, &need_lookup);
if (!need_lookup)
return dentry;
return lookup_real(base->d_inode, dentry, nd);
}
/*
* It's more convoluted than I'd like it to be, but... it's still fairly
* small and for now I'd prefer to have fast path as straight as possible.
* It _is_ time-critical.
*/
static int do_lookup(struct nameidata *nd, struct qstr *name,
struct path *path, struct inode **inode)
{
struct vfsmount *mnt = nd->path.mnt;
struct dentry *dentry, *parent = nd->path.dentry;
int need_reval = 1;
int status = 1;
int err;
/*
* Rename seqlock is not required here because in the off chance
* of a false negative due to a concurrent rename, we're going to
* do the non-racy lookup, below.
*/
if (nd->flags & LOOKUP_RCU) {
unsigned seq;
*inode = nd->inode;
dentry = __d_lookup_rcu(parent, name, &seq, inode);
if (!dentry)
goto unlazy;
/* Memory barrier in read_seqcount_begin of child is enough */
if (__read_seqcount_retry(&parent->d_seq, nd->seq))
return -ECHILD;
nd->seq = seq;
if (unlikely(d_need_lookup(dentry)))
goto unlazy;
if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE)) {
status = d_revalidate(dentry, nd);
if (unlikely(status <= 0)) {
if (status != -ECHILD)
need_reval = 0;
goto unlazy;
}
}
path->mnt = mnt;
path->dentry = dentry;
if (unlikely(!__follow_mount_rcu(nd, path, inode)))
goto unlazy;
if (unlikely(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT))
goto unlazy;
return 0;
unlazy:
if (unlazy_walk(nd, dentry))
return -ECHILD;
} else {
dentry = __d_lookup(parent, name);
}
if (unlikely(!dentry))
goto need_lookup;
if (unlikely(d_need_lookup(dentry))) {
dput(dentry);
goto need_lookup;
}
if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE) && need_reval)
status = d_revalidate(dentry, nd);
if (unlikely(status <= 0)) {
if (status < 0) {
dput(dentry);
return status;
}
if (!d_invalidate(dentry)) {
dput(dentry);
goto need_lookup;
}
}
done:
path->mnt = mnt;
path->dentry = dentry;
err = follow_managed(path, nd->flags);
if (unlikely(err < 0)) {
path_put_conditional(path, nd);
return err;
}
if (err)
nd->flags |= LOOKUP_JUMPED;
*inode = path->dentry->d_inode;
return 0;
need_lookup:
BUG_ON(nd->inode != parent->d_inode);
mutex_lock(&parent->d_inode->i_mutex);
dentry = __lookup_hash(name, parent, nd);
mutex_unlock(&parent->d_inode->i_mutex);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
goto done;
}
static inline int may_lookup(struct nameidata *nd)
{
if (nd->flags & LOOKUP_RCU) {
int err = inode_permission(nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
if (err != -ECHILD)
return err;
if (unlazy_walk(nd, NULL))
return -ECHILD;
}
return inode_permission(nd->inode, MAY_EXEC);
}
static inline int handle_dots(struct nameidata *nd, int type)
{
if (type == LAST_DOTDOT) {
if (nd->flags & LOOKUP_RCU) {
if (follow_dotdot_rcu(nd))
return -ECHILD;
} else
follow_dotdot(nd);
}
return 0;
}
static void terminate_walk(struct nameidata *nd)
{
if (!(nd->flags & LOOKUP_RCU)) {
path_put(&nd->path);
} else {
nd->flags &= ~LOOKUP_RCU;
if (!(nd->flags & LOOKUP_ROOT))
nd->root.mnt = NULL;
rcu_read_unlock();
br_read_unlock(&vfsmount_lock);
}
}
/*
* Do we need to follow links? We _really_ want to be able
* to do this check without having to look at inode->i_op,
* so we keep a cache of "no, this doesn't need follow_link"
* for the common case.
*/
static inline int should_follow_link(struct inode *inode, int follow)
{
if (unlikely(!(inode->i_opflags & IOP_NOFOLLOW))) {
if (likely(inode->i_op->follow_link))
return follow;
/* This gets set once for the inode lifetime */
spin_lock(&inode->i_lock);
inode->i_opflags |= IOP_NOFOLLOW;
spin_unlock(&inode->i_lock);
}
return 0;
}
static inline int walk_component(struct nameidata *nd, struct path *path,
struct qstr *name, int type, int follow)
{
struct inode *inode;
int err;
/*
* "." and ".." are special - ".." especially so because it has
* to be able to know about the current root directory and
* parent relationships.
*/
if (unlikely(type != LAST_NORM))
return handle_dots(nd, type);
err = do_lookup(nd, name, path, &inode);
if (unlikely(err)) {
terminate_walk(nd);
return err;
}
if (!inode) {
path_to_nameidata(path, nd);
terminate_walk(nd);
return -ENOENT;
}
if (should_follow_link(inode, follow)) {
if (nd->flags & LOOKUP_RCU) {
if (unlikely(unlazy_walk(nd, path->dentry))) {
terminate_walk(nd);
return -ECHILD;
}
}
BUG_ON(inode != path->dentry->d_inode);
return 1;
}
path_to_nameidata(path, nd);
nd->inode = inode;
return 0;
}
/*
* This limits recursive symlink follows to 8, while
* limiting consecutive symlinks to 40.
*
* Without that kind of total limit, nasty chains of consecutive
* symlinks can cause almost arbitrarily long lookups.
*/
static inline int nested_symlink(struct path *path, struct nameidata *nd)
{
int res;
if (unlikely(current->link_count >= MAX_NESTED_LINKS)) {
path_put_conditional(path, nd);
path_put(&nd->path);
return -ELOOP;
}
BUG_ON(nd->depth >= MAX_NESTED_LINKS);
nd->depth++;
current->link_count++;
do {
struct path link = *path;
void *cookie;
res = follow_link(&link, nd, &cookie);
if (!res)
res = walk_component(nd, path, &nd->last,
nd->last_type, LOOKUP_FOLLOW);
put_link(nd, &link, cookie);
} while (res > 0);
current->link_count--;
nd->depth--;
return res;
}
/*
* We really don't want to look at inode->i_op->lookup
* when we don't have to. So we keep a cache bit in
* the inode ->i_opflags field that says "yes, we can
* do lookup on this inode".
*/
static inline int can_lookup(struct inode *inode)
{
if (likely(inode->i_opflags & IOP_LOOKUP))
return 1;
if (likely(!inode->i_op->lookup))
return 0;
/* We do this once for the lifetime of the inode */
spin_lock(&inode->i_lock);
inode->i_opflags |= IOP_LOOKUP;
spin_unlock(&inode->i_lock);
return 1;
}
/*
* We can do the critical dentry name comparison and hashing
* operations one word at a time, but we are limited to:
*
* - Architectures with fast unaligned word accesses. We could
* do a "get_unaligned()" if this helps and is sufficiently
* fast.
*
* - Little-endian machines (so that we can generate the mask
* of low bytes efficiently). Again, we *could* do a byte
* swapping load on big-endian architectures if that is not
* expensive enough to make the optimization worthless.
*
* - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
* do not trap on the (extremely unlikely) case of a page
* crossing operation.
*
* - Furthermore, we need an efficient 64-bit compile for the
* 64-bit case in order to generate the "number of bytes in
* the final mask". Again, that could be replaced with a
* efficient population count instruction or similar.
*/
#ifdef CONFIG_DCACHE_WORD_ACCESS
#include <asm/word-at-a-time.h>
#ifdef CONFIG_64BIT
static inline unsigned int fold_hash(unsigned long hash)
{
return hash_64(hash, 32);
}
#else /* 32-bit case */
#define fold_hash(x) (x)
#endif
unsigned int full_name_hash(const unsigned char *name, unsigned int len)
{
unsigned long a, mask;
unsigned long hash = 0;
for (;;) {
a = load_unaligned_zeropad(name);
if (len < sizeof(unsigned long))
break;
hash += a;
hash *= 9;
name += sizeof(unsigned long);
len -= sizeof(unsigned long);
if (!len)
goto done;
}
mask = ~(~0ul << len*8);
hash += mask & a;
done:
return fold_hash(hash);
}
EXPORT_SYMBOL(full_name_hash);
/*
* Calculate the length and hash of the path component, and
* return the length of the component;
*/
static inline unsigned long hash_name(const char *name, unsigned int *hashp)
{
unsigned long a, mask, hash, len;
hash = a = 0;
len = -sizeof(unsigned long);
do {
hash = (hash + a) * 9;
len += sizeof(unsigned long);
a = load_unaligned_zeropad(name+len);
/* Do we have any NUL or '/' bytes in this word? */
mask = has_zero(a) | has_zero(a ^ REPEAT_BYTE('/'));
} while (!mask);
/* The mask *below* the first high bit set */
mask = (mask - 1) & ~mask;
mask >>= 7;
hash += a & mask;
*hashp = fold_hash(hash);
return len + count_masked_bytes(mask);
}
#else
unsigned int full_name_hash(const unsigned char *name, unsigned int len)
{
unsigned long hash = init_name_hash();
while (len--)
hash = partial_name_hash(*name++, hash);
return end_name_hash(hash);
}
EXPORT_SYMBOL(full_name_hash);
/*
* We know there's a real path component here of at least
* one character.
*/
static inline unsigned long hash_name(const char *name, unsigned int *hashp)
{
unsigned long hash = init_name_hash();
unsigned long len = 0, c;
c = (unsigned char)*name;
do {
len++;
hash = partial_name_hash(c, hash);
c = (unsigned char)name[len];
} while (c && c != '/');
*hashp = end_name_hash(hash);
return len;
}
#endif
/*
* Name resolution.
* This is the basic name resolution function, turning a pathname into
* the final dentry. We expect 'base' to be positive and a directory.
*
* Returns 0 and nd will have valid dentry and mnt on success.
* Returns error and drops reference to input namei data on failure.
*/
static int link_path_walk(const char *name, struct nameidata *nd)
{
struct path next;
int err;
while (*name=='/')
name++;
if (!*name)
return 0;
/* At this point we know we have a real path component. */
for(;;) {
struct qstr this;
long len;
int type;
err = may_lookup(nd);
if (err)
break;
len = hash_name(name, &this.hash);
this.name = name;
this.len = len;
type = LAST_NORM;
if (name[0] == '.') switch (len) {
case 2:
if (name[1] == '.') {
type = LAST_DOTDOT;
nd->flags |= LOOKUP_JUMPED;
}
break;
case 1:
type = LAST_DOT;
}
if (likely(type == LAST_NORM)) {
struct dentry *parent = nd->path.dentry;
nd->flags &= ~LOOKUP_JUMPED;
if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
err = parent->d_op->d_hash(parent, nd->inode,
&this);
if (err < 0)
break;
}
}
if (!name[len])
goto last_component;
/*
* If it wasn't NUL, we know it was '/'. Skip that
* slash, and continue until no more slashes.
*/
do {
len++;
} while (unlikely(name[len] == '/'));
if (!name[len])
goto last_component;
name += len;
err = walk_component(nd, &next, &this, type, LOOKUP_FOLLOW);
if (err < 0)
return err;
if (err) {
err = nested_symlink(&next, nd);
if (err)
return err;
}
if (can_lookup(nd->inode))
continue;
err = -ENOTDIR;
break;
/* here ends the main loop */
last_component:
nd->last = this;
nd->last_type = type;
return 0;
}
terminate_walk(nd);
return err;
}
static int path_init(int dfd, const char *name, unsigned int flags,
struct nameidata *nd, struct file **fp)
{
int retval = 0;
int fput_needed;
struct file *file;
nd->last_type = LAST_ROOT; /* if there are only slashes... */
nd->flags = flags | LOOKUP_JUMPED;
nd->depth = 0;
if (flags & LOOKUP_ROOT) {
struct inode *inode = nd->root.dentry->d_inode;
if (*name) {
if (!inode->i_op->lookup)
return -ENOTDIR;
retval = inode_permission(inode, MAY_EXEC);
if (retval)
return retval;
}
nd->path = nd->root;
nd->inode = inode;
if (flags & LOOKUP_RCU) {
br_read_lock(&vfsmount_lock);
rcu_read_lock();
nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
} else {
path_get(&nd->path);
}
return 0;
}
nd->root.mnt = NULL;
if (*name=='/') {
if (flags & LOOKUP_RCU) {
br_read_lock(&vfsmount_lock);
rcu_read_lock();
set_root_rcu(nd);
} else {
set_root(nd);
path_get(&nd->root);
}
nd->path = nd->root;
} else if (dfd == AT_FDCWD) {
if (flags & LOOKUP_RCU) {
struct fs_struct *fs = current->fs;
unsigned seq;
br_read_lock(&vfsmount_lock);
rcu_read_lock();
do {
seq = read_seqcount_begin(&fs->seq);
nd->path = fs->pwd;
nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
} while (read_seqcount_retry(&fs->seq, seq));
} else {
get_fs_pwd(current->fs, &nd->path);
}
} else {
struct dentry *dentry;
file = fget_raw_light(dfd, &fput_needed);
retval = -EBADF;
if (!file)
goto out_fail;
dentry = file->f_path.dentry;
if (*name) {
retval = -ENOTDIR;
if (!S_ISDIR(dentry->d_inode->i_mode))
goto fput_fail;
retval = inode_permission(dentry->d_inode, MAY_EXEC);
if (retval)
goto fput_fail;
}
nd->path = file->f_path;
if (flags & LOOKUP_RCU) {
if (fput_needed)
*fp = file;
nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
br_read_lock(&vfsmount_lock);
rcu_read_lock();
} else {
path_get(&file->f_path);
fput_light(file, fput_needed);
}
}
nd->inode = nd->path.dentry->d_inode;
return 0;
fput_fail:
fput_light(file, fput_needed);
out_fail:
return retval;
}
static inline int lookup_last(struct nameidata *nd, struct path *path)
{
if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
nd->flags &= ~LOOKUP_PARENT;
return walk_component(nd, path, &nd->last, nd->last_type,
nd->flags & LOOKUP_FOLLOW);
}
/* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
static int path_lookupat(int dfd, const char *name,
unsigned int flags, struct nameidata *nd)
{
struct file *base = NULL;
struct path path;
int err;
/*
* Path walking is largely split up into 2 different synchronisation
* schemes, rcu-walk and ref-walk (explained in
* Documentation/filesystems/path-lookup.txt). These share much of the
* path walk code, but some things particularly setup, cleanup, and
* following mounts are sufficiently divergent that functions are
* duplicated. Typically there is a function foo(), and its RCU
* analogue, foo_rcu().
*
* -ECHILD is the error number of choice (just to avoid clashes) that
* is returned if some aspect of an rcu-walk fails. Such an error must
* be handled by restarting a traditional ref-walk (which will always
* be able to complete).
*/
err = path_init(dfd, name, flags | LOOKUP_PARENT, nd, &base);
if (unlikely(err))
goto out;
current->total_link_count = 0;
err = link_path_walk(name, nd);
if (!err && !(flags & LOOKUP_PARENT)) {
err = lookup_last(nd, &path);
while (err > 0) {
void *cookie;
struct path link = path;
nd->flags |= LOOKUP_PARENT;
err = follow_link(&link, nd, &cookie);
if (!err)
err = lookup_last(nd, &path);
put_link(nd, &link, cookie);
}
}
if (!err)
err = complete_walk(nd);
if (!err && nd->flags & LOOKUP_DIRECTORY) {
if (!nd->inode->i_op->lookup) {
path_put(&nd->path);
err = -ENOTDIR;
}
}
out:
if (base)
fput(base);
if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) {
path_put(&nd->root);
nd->root.mnt = NULL;
}
return err;
}
static int do_path_lookup(int dfd, const char *name,
unsigned int flags, struct nameidata *nd)
{
int retval = path_lookupat(dfd, name, flags | LOOKUP_RCU, nd);
if (unlikely(retval == -ECHILD))
retval = path_lookupat(dfd, name, flags, nd);
if (unlikely(retval == -ESTALE))
retval = path_lookupat(dfd, name, flags | LOOKUP_REVAL, nd);
if (likely(!retval)) {
if (unlikely(!audit_dummy_context())) {
if (nd->path.dentry && nd->inode)
audit_inode(name, nd->path.dentry);
}
}
return retval;
}
/* does lookup, returns the object with parent locked */
struct dentry *kern_path_locked(const char *name, struct path *path)
{
struct nameidata nd;
struct dentry *d;
int err = do_path_lookup(AT_FDCWD, name, LOOKUP_PARENT, &nd);
if (err)
return ERR_PTR(err);
if (nd.last_type != LAST_NORM) {
path_put(&nd.path);
return ERR_PTR(-EINVAL);
}
mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
d = lookup_one_len(nd.last.name, nd.path.dentry, nd.last.len);
if (IS_ERR(d)) {
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
path_put(&nd.path);
return d;
}
*path = nd.path;
return d;
}
int kern_path(const char *name, unsigned int flags, struct path *path)
{
struct nameidata nd;
int res = do_path_lookup(AT_FDCWD, name, flags, &nd);
if (!res)
*path = nd.path;
return res;
}
/**
* vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
* @dentry: pointer to dentry of the base directory
* @mnt: pointer to vfs mount of the base directory
* @name: pointer to file name
* @flags: lookup flags
* @path: pointer to struct path to fill
*/
int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
const char *name, unsigned int flags,
struct path *path)
{
struct nameidata nd;
int err;
nd.root.dentry = dentry;
nd.root.mnt = mnt;
BUG_ON(flags & LOOKUP_PARENT);
/* the first argument of do_path_lookup() is ignored with LOOKUP_ROOT */
err = do_path_lookup(AT_FDCWD, name, flags | LOOKUP_ROOT, &nd);
if (!err)
*path = nd.path;
return err;
}
/*
* Restricted form of lookup. Doesn't follow links, single-component only,
* needs parent already locked. Doesn't follow mounts.
* SMP-safe.
*/
static struct dentry *lookup_hash(struct nameidata *nd)
{
return __lookup_hash(&nd->last, nd->path.dentry, nd);
}
/**
* lookup_one_len - filesystem helper to lookup single pathname component
* @name: pathname component to lookup
* @base: base directory to lookup from
* @len: maximum length @len should be interpreted to
*
* Note that this routine is purely a helper for filesystem usage and should
* not be called by generic code. Also note that by using this function the
* nameidata argument is passed to the filesystem methods and a filesystem
* using this helper needs to be prepared for that.
*/
struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
{
struct qstr this;
unsigned int c;
int err;
WARN_ON_ONCE(!mutex_is_locked(&base->d_inode->i_mutex));
this.name = name;
this.len = len;
this.hash = full_name_hash(name, len);
if (!len)
return ERR_PTR(-EACCES);
while (len--) {
c = *(const unsigned char *)name++;
if (c == '/' || c == '\0')
return ERR_PTR(-EACCES);
}
/*
* See if the low-level filesystem might want
* to use its own hash..
*/
if (base->d_flags & DCACHE_OP_HASH) {
int err = base->d_op->d_hash(base, base->d_inode, &this);
if (err < 0)
return ERR_PTR(err);
}
err = inode_permission(base->d_inode, MAY_EXEC);
if (err)
return ERR_PTR(err);
return __lookup_hash(&this, base, NULL);
}
int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
struct path *path, int *empty)
{
struct nameidata nd;
char *tmp = getname_flags(name, flags, empty);
int err = PTR_ERR(tmp);
if (!IS_ERR(tmp)) {
BUG_ON(flags & LOOKUP_PARENT);
err = do_path_lookup(dfd, tmp, flags, &nd);
putname(tmp);
if (!err)
*path = nd.path;
}
return err;
}
int user_path_at(int dfd, const char __user *name, unsigned flags,
struct path *path)
{
return user_path_at_empty(dfd, name, flags, path, NULL);
}
static int user_path_parent(int dfd, const char __user *path,
struct nameidata *nd, char **name)
{
char *s = getname(path);
int error;
if (IS_ERR(s))
return PTR_ERR(s);
error = do_path_lookup(dfd, s, LOOKUP_PARENT, nd);
if (error)
putname(s);
else
*name = s;
return error;
}
/*
* It's inline, so penalty for filesystems that don't use sticky bit is
* minimal.
*/
static inline int check_sticky(struct inode *dir, struct inode *inode)
{
uid_t fsuid = current_fsuid();
if (!(dir->i_mode & S_ISVTX))
return 0;
if (current_user_ns() != inode_userns(inode))
goto other_userns;
if (inode->i_uid == fsuid)
return 0;
if (dir->i_uid == fsuid)
return 0;
other_userns:
return !ns_capable(inode_userns(inode), CAP_FOWNER);
}
/*
* Check whether we can remove a link victim from directory dir, check
* whether the type of victim is right.
* 1. We can't do it if dir is read-only (done in permission())
* 2. We should have write and exec permissions on dir
* 3. We can't remove anything from append-only dir
* 4. We can't do anything with immutable dir (done in permission())
* 5. If the sticky bit on dir is set we should either
* a. be owner of dir, or
* b. be owner of victim, or
* c. have CAP_FOWNER capability
* 6. If the victim is append-only or immutable we can't do antyhing with
* links pointing to it.
* 7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
* 8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
* 9. We can't remove a root or mountpoint.
* 10. We don't allow removal of NFS sillyrenamed files; it's handled by
* nfs_async_unlink().
*/
static int may_delete(struct inode *dir,struct dentry *victim,int isdir)
{
int error;
if (!victim->d_inode)
return -ENOENT;
BUG_ON(victim->d_parent->d_inode != dir);
audit_inode_child(victim, dir);
error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
if (error)
return error;
if (IS_APPEND(dir))
return -EPERM;
if (check_sticky(dir, victim->d_inode)||IS_APPEND(victim->d_inode)||
IS_IMMUTABLE(victim->d_inode) || IS_SWAPFILE(victim->d_inode))
return -EPERM;
if (isdir) {
if (!S_ISDIR(victim->d_inode->i_mode))
return -ENOTDIR;
if (IS_ROOT(victim))
return -EBUSY;
} else if (S_ISDIR(victim->d_inode->i_mode))
return -EISDIR;
if (IS_DEADDIR(dir))
return -ENOENT;
if (victim->d_flags & DCACHE_NFSFS_RENAMED)
return -EBUSY;
return 0;
}
/* Check whether we can create an object with dentry child in directory
* dir.
* 1. We can't do it if child already exists (open has special treatment for
* this case, but since we are inlined it's OK)
* 2. We can't do it if dir is read-only (done in permission())
* 3. We should have write and exec permissions on dir
* 4. We can't do it if dir is immutable (done in permission())
*/
static inline int may_create(struct inode *dir, struct dentry *child)
{
if (child->d_inode)
return -EEXIST;
if (IS_DEADDIR(dir))
return -ENOENT;
return inode_permission(dir, MAY_WRITE | MAY_EXEC);
}
/*
* p1 and p2 should be directories on the same fs.
*/
struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
{
struct dentry *p;
if (p1 == p2) {
mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
return NULL;
}
mutex_lock(&p1->d_inode->i_sb->s_vfs_rename_mutex);
p = d_ancestor(p2, p1);
if (p) {
mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT);
mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_CHILD);
return p;
}
p = d_ancestor(p1, p2);
if (p) {
mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD);
return p;
}
mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD);
return NULL;
}
void unlock_rename(struct dentry *p1, struct dentry *p2)
{
mutex_unlock(&p1->d_inode->i_mutex);
if (p1 != p2) {
mutex_unlock(&p2->d_inode->i_mutex);
mutex_unlock(&p1->d_inode->i_sb->s_vfs_rename_mutex);
}
}
int vfs_create(struct inode *dir, struct dentry *dentry, umode_t mode,
struct nameidata *nd)
{
int error = may_create(dir, dentry);
if (error)
return error;
if (!dir->i_op->create)
return -EACCES; /* shouldn't it be ENOSYS? */
mode &= S_IALLUGO;
mode |= S_IFREG;
error = security_inode_create(dir, dentry, mode);
if (error)
return error;
error = dir->i_op->create(dir, dentry, mode, nd);
if (!error)
fsnotify_create(dir, dentry);
return error;
}
static int may_open(struct path *path, int acc_mode, int flag)
{
struct dentry *dentry = path->dentry;
struct inode *inode = dentry->d_inode;
int error;
/* O_PATH? */
if (!acc_mode)
return 0;
if (!inode)
return -ENOENT;
switch (inode->i_mode & S_IFMT) {
case S_IFLNK:
return -ELOOP;
case S_IFDIR:
if (acc_mode & MAY_WRITE)
return -EISDIR;
break;
case S_IFBLK:
case S_IFCHR:
if (path->mnt->mnt_flags & MNT_NODEV)
return -EACCES;
/*FALLTHRU*/
case S_IFIFO:
case S_IFSOCK:
flag &= ~O_TRUNC;
break;
}
error = inode_permission(inode, acc_mode);
if (error)
return error;
/*
* An append-only file must be opened in append mode for writing.
*/
if (IS_APPEND(inode)) {
if ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
return -EPERM;
if (flag & O_TRUNC)
return -EPERM;
}
/* O_NOATIME can only be set by the owner or superuser */
if (flag & O_NOATIME && !inode_owner_or_capable(inode))
return -EPERM;
return 0;
}
static int handle_truncate(struct file *filp)
{
struct path *path = &filp->f_path;
struct inode *inode = path->dentry->d_inode;
int error = get_write_access(inode);
if (error)
return error;
/*
* Refuse to truncate files with mandatory locks held on them.
*/
error = locks_verify_locked(inode);
if (!error)
error = security_path_truncate(path);
if (!error) {
error = do_truncate(path->dentry, 0,
ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
filp);
}
put_write_access(inode);
return error;
}
static inline int open_to_namei_flags(int flag)
{
if ((flag & O_ACCMODE) == 3)
flag--;
return flag;
}
/*
* Handle the last step of open()
*/
static struct file *do_last(struct nameidata *nd, struct path *path,
const struct open_flags *op, const char *pathname)
{
struct dentry *dir = nd->path.dentry;
struct dentry *dentry;
int open_flag = op->open_flag;
int will_truncate = open_flag & O_TRUNC;
int want_write = 0;
int acc_mode = op->acc_mode;
struct file *filp;
int error;
nd->flags &= ~LOOKUP_PARENT;
nd->flags |= op->intent;
switch (nd->last_type) {
case LAST_DOTDOT:
case LAST_DOT:
error = handle_dots(nd, nd->last_type);
if (error)
return ERR_PTR(error);
/* fallthrough */
case LAST_ROOT:
error = complete_walk(nd);
if (error)
return ERR_PTR(error);
audit_inode(pathname, nd->path.dentry);
if (open_flag & O_CREAT) {
error = -EISDIR;
goto exit;
}
goto ok;
case LAST_BIND:
error = complete_walk(nd);
if (error)
return ERR_PTR(error);
audit_inode(pathname, dir);
goto ok;
}
if (!(open_flag & O_CREAT)) {
int symlink_ok = 0;
if (nd->last.name[nd->last.len])
nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
if (open_flag & O_PATH && !(nd->flags & LOOKUP_FOLLOW))
symlink_ok = 1;
/* we _can_ be in RCU mode here */
error = walk_component(nd, path, &nd->last, LAST_NORM,
!symlink_ok);
if (error < 0)
return ERR_PTR(error);
if (error) /* symlink */
return NULL;
/* sayonara */
error = complete_walk(nd);
if (error)
return ERR_PTR(error);
error = -ENOTDIR;
if (nd->flags & LOOKUP_DIRECTORY) {
if (!nd->inode->i_op->lookup)
goto exit;
}
audit_inode(pathname, nd->path.dentry);
goto ok;
}
/* create side of things */
/*
* This will *only* deal with leaving RCU mode - LOOKUP_JUMPED has been
* cleared when we got to the last component we are about to look up
*/
error = complete_walk(nd);
if (error)
return ERR_PTR(error);
audit_inode(pathname, dir);
error = -EISDIR;
/* trailing slashes? */
if (nd->last.name[nd->last.len])
goto exit;
mutex_lock(&dir->d_inode->i_mutex);
dentry = lookup_hash(nd);
error = PTR_ERR(dentry);
if (IS_ERR(dentry)) {
mutex_unlock(&dir->d_inode->i_mutex);
goto exit;
}
path->dentry = dentry;
path->mnt = nd->path.mnt;
/* Negative dentry, just create the file */
if (!dentry->d_inode) {
umode_t mode = op->mode;
if (!IS_POSIXACL(dir->d_inode))
mode &= ~current_umask();
/*
* This write is needed to ensure that a
* rw->ro transition does not occur between
* the time when the file is created and when
* a permanent write count is taken through
* the 'struct file' in nameidata_to_filp().
*/
error = mnt_want_write(nd->path.mnt);
if (error)
goto exit_mutex_unlock;
want_write = 1;
/* Don't check for write permission, don't truncate */
open_flag &= ~O_TRUNC;
will_truncate = 0;
acc_mode = MAY_OPEN;
error = security_path_mknod(&nd->path, dentry, mode, 0);
if (error)
goto exit_mutex_unlock;
error = vfs_create(dir->d_inode, dentry, mode, nd);
if (error)
goto exit_mutex_unlock;
mutex_unlock(&dir->d_inode->i_mutex);
dput(nd->path.dentry);
nd->path.dentry = dentry;
goto common;
}
/*
* It already exists.
*/
mutex_unlock(&dir->d_inode->i_mutex);
audit_inode(pathname, path->dentry);
error = -EEXIST;
if (open_flag & O_EXCL)
goto exit_dput;
error = follow_managed(path, nd->flags);
if (error < 0)
goto exit_dput;
if (error)
nd->flags |= LOOKUP_JUMPED;
error = -ENOENT;
if (!path->dentry->d_inode)
goto exit_dput;
if (path->dentry->d_inode->i_op->follow_link)
return NULL;
path_to_nameidata(path, nd);
nd->inode = path->dentry->d_inode;
/* Why this, you ask? _Now_ we might have grown LOOKUP_JUMPED... */
error = complete_walk(nd);
if (error)
return ERR_PTR(error);
error = -EISDIR;
if (S_ISDIR(nd->inode->i_mode))
goto exit;
ok:
if (!S_ISREG(nd->inode->i_mode))
will_truncate = 0;
if (will_truncate) {
error = mnt_want_write(nd->path.mnt);
if (error)
goto exit;
want_write = 1;
}
common:
error = may_open(&nd->path, acc_mode, open_flag);
if (error)
goto exit;
filp = nameidata_to_filp(nd);
if (!IS_ERR(filp)) {
error = ima_file_check(filp, op->acc_mode);
if (error) {
fput(filp);
filp = ERR_PTR(error);
}
}
if (!IS_ERR(filp)) {
if (will_truncate) {
error = handle_truncate(filp);
if (error) {
fput(filp);
filp = ERR_PTR(error);
}
}
}
out:
if (want_write)
mnt_drop_write(nd->path.mnt);
path_put(&nd->path);
return filp;
exit_mutex_unlock:
mutex_unlock(&dir->d_inode->i_mutex);
exit_dput:
path_put_conditional(path, nd);
exit:
filp = ERR_PTR(error);
goto out;
}
static struct file *path_openat(int dfd, const char *pathname,
struct nameidata *nd, const struct open_flags *op, int flags)
{
struct file *base = NULL;
struct file *filp;
struct path path;
int error;
filp = get_empty_filp();
if (!filp)
return ERR_PTR(-ENFILE);
filp->f_flags = op->open_flag;
nd->intent.open.file = filp;
nd->intent.open.flags = open_to_namei_flags(op->open_flag);
nd->intent.open.create_mode = op->mode;
error = path_init(dfd, pathname, flags | LOOKUP_PARENT, nd, &base);
if (unlikely(error))
goto out_filp;
current->total_link_count = 0;
error = link_path_walk(pathname, nd);
if (unlikely(error))
goto out_filp;
filp = do_last(nd, &path, op, pathname);
while (unlikely(!filp)) { /* trailing symlink */
struct path link = path;
void *cookie;
if (!(nd->flags & LOOKUP_FOLLOW)) {
path_put_conditional(&path, nd);
path_put(&nd->path);
filp = ERR_PTR(-ELOOP);
break;
}
nd->flags |= LOOKUP_PARENT;
nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
error = follow_link(&link, nd, &cookie);
if (unlikely(error))
filp = ERR_PTR(error);
else
filp = do_last(nd, &path, op, pathname);
put_link(nd, &link, cookie);
}
out:
if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT))
path_put(&nd->root);
if (base)
fput(base);
release_open_intent(nd);
return filp;
out_filp:
filp = ERR_PTR(error);
goto out;
}
struct file *do_filp_open(int dfd, const char *pathname,
const struct open_flags *op, int flags)
{
struct nameidata nd;
struct file *filp;
filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_RCU);
if (unlikely(filp == ERR_PTR(-ECHILD)))
filp = path_openat(dfd, pathname, &nd, op, flags);
if (unlikely(filp == ERR_PTR(-ESTALE)))
filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_REVAL);
return filp;
}
struct file *do_file_open_root(struct dentry *dentry, struct vfsmount *mnt,
const char *name, const struct open_flags *op, int flags)
{
struct nameidata nd;
struct file *file;
nd.root.mnt = mnt;
nd.root.dentry = dentry;
flags |= LOOKUP_ROOT;
if (dentry->d_inode->i_op->follow_link && op->intent & LOOKUP_OPEN)
return ERR_PTR(-ELOOP);
file = path_openat(-1, name, &nd, op, flags | LOOKUP_RCU);
if (unlikely(file == ERR_PTR(-ECHILD)))
file = path_openat(-1, name, &nd, op, flags);
if (unlikely(file == ERR_PTR(-ESTALE)))
file = path_openat(-1, name, &nd, op, flags | LOOKUP_REVAL);
return file;
}
struct dentry *kern_path_create(int dfd, const char *pathname, struct path *path, int is_dir)
{
struct dentry *dentry = ERR_PTR(-EEXIST);
struct nameidata nd;
int error = do_path_lookup(dfd, pathname, LOOKUP_PARENT, &nd);
if (error)
return ERR_PTR(error);
/*
* Yucky last component or no last component at all?
* (foo/., foo/.., /////)
*/
if (nd.last_type != LAST_NORM)
goto out;
nd.flags &= ~LOOKUP_PARENT;
nd.flags |= LOOKUP_CREATE | LOOKUP_EXCL;
nd.intent.open.flags = O_EXCL;
/*
* Do the final lookup.
*/
mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
dentry = lookup_hash(&nd);
if (IS_ERR(dentry))
goto fail;
if (dentry->d_inode)
goto eexist;
/*
* Special case - lookup gave negative, but... we had foo/bar/
* From the vfs_mknod() POV we just have a negative dentry -
* all is fine. Let's be bastards - you had / on the end, you've
* been asking for (non-existent) directory. -ENOENT for you.
*/
if (unlikely(!is_dir && nd.last.name[nd.last.len])) {
dput(dentry);
dentry = ERR_PTR(-ENOENT);
goto fail;
}
*path = nd.path;
return dentry;
eexist:
dput(dentry);
dentry = ERR_PTR(-EEXIST);
fail:
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
out:
path_put(&nd.path);
return dentry;
}
EXPORT_SYMBOL(kern_path_create);
struct dentry *user_path_create(int dfd, const char __user *pathname, struct path *path, int is_dir)
{
char *tmp = getname(pathname);
struct dentry *res;
if (IS_ERR(tmp))
return ERR_CAST(tmp);
res = kern_path_create(dfd, tmp, path, is_dir);
putname(tmp);
return res;
}
EXPORT_SYMBOL(user_path_create);
int vfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
{
int error = may_create(dir, dentry);
if (error)
return error;
if ((S_ISCHR(mode) || S_ISBLK(mode)) &&
!ns_capable(inode_userns(dir), CAP_MKNOD))
return -EPERM;
if (!dir->i_op->mknod)
return -EPERM;
error = devcgroup_inode_mknod(mode, dev);
if (error)
return error;
error = security_inode_mknod(dir, dentry, mode, dev);
if (error)
return error;
error = dir->i_op->mknod(dir, dentry, mode, dev);
if (!error)
fsnotify_create(dir, dentry);
return error;
}
static int may_mknod(umode_t mode)
{
switch (mode & S_IFMT) {
case S_IFREG:
case S_IFCHR:
case S_IFBLK:
case S_IFIFO:
case S_IFSOCK:
case 0: /* zero mode translates to S_IFREG */
return 0;
case S_IFDIR:
return -EPERM;
default:
return -EINVAL;
}
}
SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
unsigned, dev)
{
struct dentry *dentry;
struct path path;
int error;
if (S_ISDIR(mode))
return -EPERM;
dentry = user_path_create(dfd, filename, &path, 0);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
if (!IS_POSIXACL(path.dentry->d_inode))
mode &= ~current_umask();
error = may_mknod(mode);
if (error)
goto out_dput;
error = mnt_want_write(path.mnt);
if (error)
goto out_dput;
error = security_path_mknod(&path, dentry, mode, dev);
if (error)
goto out_drop_write;
switch (mode & S_IFMT) {
case 0: case S_IFREG:
error = vfs_create(path.dentry->d_inode,dentry,mode,NULL);
break;
case S_IFCHR: case S_IFBLK:
error = vfs_mknod(path.dentry->d_inode,dentry,mode,
new_decode_dev(dev));
break;
case S_IFIFO: case S_IFSOCK:
error = vfs_mknod(path.dentry->d_inode,dentry,mode,0);
break;
}
out_drop_write:
mnt_drop_write(path.mnt);
out_dput:
dput(dentry);
mutex_unlock(&path.dentry->d_inode->i_mutex);
path_put(&path);
return error;
}
SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
{
return sys_mknodat(AT_FDCWD, filename, mode, dev);
}
int vfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
{
int error = may_create(dir, dentry);
unsigned max_links = dir->i_sb->s_max_links;
if (error)
return error;
if (!dir->i_op->mkdir)
return -EPERM;
mode &= (S_IRWXUGO|S_ISVTX);
error = security_inode_mkdir(dir, dentry, mode);
if (error)
return error;
if (max_links && dir->i_nlink >= max_links)
return -EMLINK;
error = dir->i_op->mkdir(dir, dentry, mode);
if (!error)
fsnotify_mkdir(dir, dentry);
return error;
}
SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
{
struct dentry *dentry;
struct path path;
int error;
dentry = user_path_create(dfd, pathname, &path, 1);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
if (!IS_POSIXACL(path.dentry->d_inode))
mode &= ~current_umask();
error = mnt_want_write(path.mnt);
if (error)
goto out_dput;
error = security_path_mkdir(&path, dentry, mode);
if (error)
goto out_drop_write;
error = vfs_mkdir(path.dentry->d_inode, dentry, mode);
out_drop_write:
mnt_drop_write(path.mnt);
out_dput:
dput(dentry);
mutex_unlock(&path.dentry->d_inode->i_mutex);
path_put(&path);
return error;
}
SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
{
return sys_mkdirat(AT_FDCWD, pathname, mode);
}
/*
* The dentry_unhash() helper will try to drop the dentry early: we
* should have a usage count of 1 if we're the only user of this
* dentry, and if that is true (possibly after pruning the dcache),
* then we drop the dentry now.
*
* A low-level filesystem can, if it choses, legally
* do a
*
* if (!d_unhashed(dentry))
* return -EBUSY;
*
* if it cannot handle the case of removing a directory
* that is still in use by something else..
*/
void dentry_unhash(struct dentry *dentry)
{
shrink_dcache_parent(dentry);
spin_lock(&dentry->d_lock);
if (dentry->d_count == 1)
__d_drop(dentry);
spin_unlock(&dentry->d_lock);
}
int vfs_rmdir(struct inode *dir, struct dentry *dentry)
{
int error = may_delete(dir, dentry, 1);
if (error)
return error;
if (!dir->i_op->rmdir)
return -EPERM;
dget(dentry);
mutex_lock(&dentry->d_inode->i_mutex);
error = -EBUSY;
if (d_mountpoint(dentry))
goto out;
error = security_inode_rmdir(dir, dentry);
if (error)
goto out;
shrink_dcache_parent(dentry);
error = dir->i_op->rmdir(dir, dentry);
if (error)
goto out;
dentry->d_inode->i_flags |= S_DEAD;
dont_mount(dentry);
out:
mutex_unlock(&dentry->d_inode->i_mutex);
dput(dentry);
if (!error)
d_delete(dentry);
return error;
}
static long do_rmdir(int dfd, const char __user *pathname)
{
int error = 0;
char * name;
struct dentry *dentry;
struct nameidata nd;
error = user_path_parent(dfd, pathname, &nd, &name);
if (error)
return error;
switch(nd.last_type) {
case LAST_DOTDOT:
error = -ENOTEMPTY;
goto exit1;
case LAST_DOT:
error = -EINVAL;
goto exit1;
case LAST_ROOT:
error = -EBUSY;
goto exit1;
}
nd.flags &= ~LOOKUP_PARENT;
mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
dentry = lookup_hash(&nd);
error = PTR_ERR(dentry);
if (IS_ERR(dentry))
goto exit2;
if (!dentry->d_inode) {
error = -ENOENT;
goto exit3;
}
error = mnt_want_write(nd.path.mnt);
if (error)
goto exit3;
error = security_path_rmdir(&nd.path, dentry);
if (error)
goto exit4;
error = vfs_rmdir(nd.path.dentry->d_inode, dentry);
exit4:
mnt_drop_write(nd.path.mnt);
exit3:
dput(dentry);
exit2:
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
exit1:
path_put(&nd.path);
putname(name);
return error;
}
SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
{
return do_rmdir(AT_FDCWD, pathname);
}
int vfs_unlink(struct inode *dir, struct dentry *dentry)
{
int error = may_delete(dir, dentry, 0);
if (error)
return error;
if (!dir->i_op->unlink)
return -EPERM;
mutex_lock(&dentry->d_inode->i_mutex);
if (d_mountpoint(dentry))
error = -EBUSY;
else {
error = security_inode_unlink(dir, dentry);
if (!error) {
error = dir->i_op->unlink(dir, dentry);
if (!error)
dont_mount(dentry);
}
}
mutex_unlock(&dentry->d_inode->i_mutex);
/* We don't d_delete() NFS sillyrenamed files--they still exist. */
if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) {
fsnotify_link_count(dentry->d_inode);
d_delete(dentry);
}
return error;
}
/*
* Make sure that the actual truncation of the file will occur outside its
* directory's i_mutex. Truncate can take a long time if there is a lot of
* writeout happening, and we don't want to prevent access to the directory
* while waiting on the I/O.
*/
static long do_unlinkat(int dfd, const char __user *pathname)
{
int error;
char *name;
struct dentry *dentry;
struct nameidata nd;
struct inode *inode = NULL;
error = user_path_parent(dfd, pathname, &nd, &name);
if (error)
return error;
error = -EISDIR;
if (nd.last_type != LAST_NORM)
goto exit1;
nd.flags &= ~LOOKUP_PARENT;
mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
dentry = lookup_hash(&nd);
error = PTR_ERR(dentry);
if (!IS_ERR(dentry)) {
/* Why not before? Because we want correct error value */
if (nd.last.name[nd.last.len])
goto slashes;
inode = dentry->d_inode;
if (!inode)
goto slashes;
ihold(inode);
error = mnt_want_write(nd.path.mnt);
if (error)
goto exit2;
error = security_path_unlink(&nd.path, dentry);
if (error)
goto exit3;
error = vfs_unlink(nd.path.dentry->d_inode, dentry);
exit3:
mnt_drop_write(nd.path.mnt);
exit2:
dput(dentry);
}
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
if (inode)
iput(inode); /* truncate the inode here */
exit1:
path_put(&nd.path);
putname(name);
return error;
slashes:
error = !dentry->d_inode ? -ENOENT :
S_ISDIR(dentry->d_inode->i_mode) ? -EISDIR : -ENOTDIR;
goto exit2;
}
SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
{
if ((flag & ~AT_REMOVEDIR) != 0)
return -EINVAL;
if (flag & AT_REMOVEDIR)
return do_rmdir(dfd, pathname);
return do_unlinkat(dfd, pathname);
}
SYSCALL_DEFINE1(unlink, const char __user *, pathname)
{
return do_unlinkat(AT_FDCWD, pathname);
}
int vfs_symlink(struct inode *dir, struct dentry *dentry, const char *oldname)
{
int error = may_create(dir, dentry);
if (error)
return error;
if (!dir->i_op->symlink)
return -EPERM;
error = security_inode_symlink(dir, dentry, oldname);
if (error)
return error;
error = dir->i_op->symlink(dir, dentry, oldname);
if (!error)
fsnotify_create(dir, dentry);
return error;
}
SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
int, newdfd, const char __user *, newname)
{
int error;
char *from;
struct dentry *dentry;
struct path path;
from = getname(oldname);
if (IS_ERR(from))
return PTR_ERR(from);
dentry = user_path_create(newdfd, newname, &path, 0);
error = PTR_ERR(dentry);
if (IS_ERR(dentry))
goto out_putname;
error = mnt_want_write(path.mnt);
if (error)
goto out_dput;
error = security_path_symlink(&path, dentry, from);
if (error)
goto out_drop_write;
error = vfs_symlink(path.dentry->d_inode, dentry, from);
out_drop_write:
mnt_drop_write(path.mnt);
out_dput:
dput(dentry);
mutex_unlock(&path.dentry->d_inode->i_mutex);
path_put(&path);
out_putname:
putname(from);
return error;
}
SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
{
return sys_symlinkat(oldname, AT_FDCWD, newname);
}
int vfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
{
struct inode *inode = old_dentry->d_inode;
unsigned max_links = dir->i_sb->s_max_links;
int error;
if (!inode)
return -ENOENT;
error = may_create(dir, new_dentry);
if (error)
return error;
if (dir->i_sb != inode->i_sb)
return -EXDEV;
/*
* A link to an append-only or immutable file cannot be created.
*/
if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
return -EPERM;
if (!dir->i_op->link)
return -EPERM;
if (S_ISDIR(inode->i_mode))
return -EPERM;
error = security_inode_link(old_dentry, dir, new_dentry);
if (error)
return error;
mutex_lock(&inode->i_mutex);
/* Make sure we don't allow creating hardlink to an unlinked file */
if (inode->i_nlink == 0)
error = -ENOENT;
else if (max_links && inode->i_nlink >= max_links)
error = -EMLINK;
else
error = dir->i_op->link(old_dentry, dir, new_dentry);
mutex_unlock(&inode->i_mutex);
if (!error)
fsnotify_link(dir, inode, new_dentry);
return error;
}
/*
* Hardlinks are often used in delicate situations. We avoid
* security-related surprises by not following symlinks on the
* newname. --KAB
*
* We don't follow them on the oldname either to be compatible
* with linux 2.0, and to avoid hard-linking to directories
* and other special files. --ADM
*/
SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
int, newdfd, const char __user *, newname, int, flags)
{
struct dentry *new_dentry;
struct path old_path, new_path;
int how = 0;
int error;
if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0)
return -EINVAL;
/*
* To use null names we require CAP_DAC_READ_SEARCH
* This ensures that not everyone will be able to create
* handlink using the passed filedescriptor.
*/
if (flags & AT_EMPTY_PATH) {
if (!capable(CAP_DAC_READ_SEARCH))
return -ENOENT;
how = LOOKUP_EMPTY;
}
if (flags & AT_SYMLINK_FOLLOW)
how |= LOOKUP_FOLLOW;
error = user_path_at(olddfd, oldname, how, &old_path);
if (error)
return error;
new_dentry = user_path_create(newdfd, newname, &new_path, 0);
error = PTR_ERR(new_dentry);
if (IS_ERR(new_dentry))
goto out;
error = -EXDEV;
if (old_path.mnt != new_path.mnt)
goto out_dput;
error = mnt_want_write(new_path.mnt);
if (error)
goto out_dput;
error = security_path_link(old_path.dentry, &new_path, new_dentry);
if (error)
goto out_drop_write;
error = vfs_link(old_path.dentry, new_path.dentry->d_inode, new_dentry);
out_drop_write:
mnt_drop_write(new_path.mnt);
out_dput:
dput(new_dentry);
mutex_unlock(&new_path.dentry->d_inode->i_mutex);
path_put(&new_path);
out:
path_put(&old_path);
return error;
}
SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
{
return sys_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
}
/*
* The worst of all namespace operations - renaming directory. "Perverted"
* doesn't even start to describe it. Somebody in UCB had a heck of a trip...
* Problems:
* a) we can get into loop creation. Check is done in is_subdir().
* b) race potential - two innocent renames can create a loop together.
* That's where 4.4 screws up. Current fix: serialization on
* sb->s_vfs_rename_mutex. We might be more accurate, but that's another
* story.
* c) we have to lock _three_ objects - parents and victim (if it exists).
* And that - after we got ->i_mutex on parents (until then we don't know
* whether the target exists). Solution: try to be smart with locking
* order for inodes. We rely on the fact that tree topology may change
* only under ->s_vfs_rename_mutex _and_ that parent of the object we
* move will be locked. Thus we can rank directories by the tree
* (ancestors first) and rank all non-directories after them.
* That works since everybody except rename does "lock parent, lookup,
* lock child" and rename is under ->s_vfs_rename_mutex.
* HOWEVER, it relies on the assumption that any object with ->lookup()
* has no more than 1 dentry. If "hybrid" objects will ever appear,
* we'd better make sure that there's no link(2) for them.
* d) conversion from fhandle to dentry may come in the wrong moment - when
* we are removing the target. Solution: we will have to grab ->i_mutex
* in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
* ->i_mutex on parents, which works but leads to some truly excessive
* locking].
*/
static int vfs_rename_dir(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
int error = 0;
struct inode *target = new_dentry->d_inode;
unsigned max_links = new_dir->i_sb->s_max_links;
/*
* If we are going to change the parent - check write permissions,
* we'll need to flip '..'.
*/
if (new_dir != old_dir) {
error = inode_permission(old_dentry->d_inode, MAY_WRITE);
if (error)
return error;
}
error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry);
if (error)
return error;
dget(new_dentry);
if (target)
mutex_lock(&target->i_mutex);
error = -EBUSY;
if (d_mountpoint(old_dentry) || d_mountpoint(new_dentry))
goto out;
error = -EMLINK;
if (max_links && !target && new_dir != old_dir &&
new_dir->i_nlink >= max_links)
goto out;
if (target)
shrink_dcache_parent(new_dentry);
error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry);
if (error)
goto out;
if (target) {
target->i_flags |= S_DEAD;
dont_mount(new_dentry);
}
out:
if (target)
mutex_unlock(&target->i_mutex);
dput(new_dentry);
if (!error)
if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE))
d_move(old_dentry,new_dentry);
return error;
}
static int vfs_rename_other(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
struct inode *target = new_dentry->d_inode;
int error;
error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry);
if (error)
return error;
dget(new_dentry);
if (target)
mutex_lock(&target->i_mutex);
error = -EBUSY;
if (d_mountpoint(old_dentry)||d_mountpoint(new_dentry))
goto out;
error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry);
if (error)
goto out;
if (target)
dont_mount(new_dentry);
if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE))
d_move(old_dentry, new_dentry);
out:
if (target)
mutex_unlock(&target->i_mutex);
dput(new_dentry);
return error;
}
int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
int error;
int is_dir = S_ISDIR(old_dentry->d_inode->i_mode);
const unsigned char *old_name;
if (old_dentry->d_inode == new_dentry->d_inode)
return 0;
error = may_delete(old_dir, old_dentry, is_dir);
if (error)
return error;
if (!new_dentry->d_inode)
error = may_create(new_dir, new_dentry);
else
error = may_delete(new_dir, new_dentry, is_dir);
if (error)
return error;
if (!old_dir->i_op->rename)
return -EPERM;
old_name = fsnotify_oldname_init(old_dentry->d_name.name);
if (is_dir)
error = vfs_rename_dir(old_dir,old_dentry,new_dir,new_dentry);
else
error = vfs_rename_other(old_dir,old_dentry,new_dir,new_dentry);
if (!error)
fsnotify_move(old_dir, new_dir, old_name, is_dir,
new_dentry->d_inode, old_dentry);
fsnotify_oldname_free(old_name);
return error;
}
SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
int, newdfd, const char __user *, newname)
{
struct dentry *old_dir, *new_dir;
struct dentry *old_dentry, *new_dentry;
struct dentry *trap;
struct nameidata oldnd, newnd;
char *from;
char *to;
int error;
error = user_path_parent(olddfd, oldname, &oldnd, &from);
if (error)
goto exit;
error = user_path_parent(newdfd, newname, &newnd, &to);
if (error)
goto exit1;
error = -EXDEV;
if (oldnd.path.mnt != newnd.path.mnt)
goto exit2;
old_dir = oldnd.path.dentry;
error = -EBUSY;
if (oldnd.last_type != LAST_NORM)
goto exit2;
new_dir = newnd.path.dentry;
if (newnd.last_type != LAST_NORM)
goto exit2;
oldnd.flags &= ~LOOKUP_PARENT;
newnd.flags &= ~LOOKUP_PARENT;
newnd.flags |= LOOKUP_RENAME_TARGET;
trap = lock_rename(new_dir, old_dir);
old_dentry = lookup_hash(&oldnd);
error = PTR_ERR(old_dentry);
if (IS_ERR(old_dentry))
goto exit3;
/* source must exist */
error = -ENOENT;
if (!old_dentry->d_inode)
goto exit4;
/* unless the source is a directory trailing slashes give -ENOTDIR */
if (!S_ISDIR(old_dentry->d_inode->i_mode)) {
error = -ENOTDIR;
if (oldnd.last.name[oldnd.last.len])
goto exit4;
if (newnd.last.name[newnd.last.len])
goto exit4;
}
/* source should not be ancestor of target */
error = -EINVAL;
if (old_dentry == trap)
goto exit4;
new_dentry = lookup_hash(&newnd);
error = PTR_ERR(new_dentry);
if (IS_ERR(new_dentry))
goto exit4;
/* target should not be an ancestor of source */
error = -ENOTEMPTY;
if (new_dentry == trap)
goto exit5;
error = mnt_want_write(oldnd.path.mnt);
if (error)
goto exit5;
error = security_path_rename(&oldnd.path, old_dentry,
&newnd.path, new_dentry);
if (error)
goto exit6;
error = vfs_rename(old_dir->d_inode, old_dentry,
new_dir->d_inode, new_dentry);
exit6:
mnt_drop_write(oldnd.path.mnt);
exit5:
dput(new_dentry);
exit4:
dput(old_dentry);
exit3:
unlock_rename(new_dir, old_dir);
exit2:
path_put(&newnd.path);
putname(to);
exit1:
path_put(&oldnd.path);
putname(from);
exit:
return error;
}
SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
{
return sys_renameat(AT_FDCWD, oldname, AT_FDCWD, newname);
}
int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen, const char *link)
{
int len;
len = PTR_ERR(link);
if (IS_ERR(link))
goto out;
len = strlen(link);
if (len > (unsigned) buflen)
len = buflen;
if (copy_to_user(buffer, link, len))
len = -EFAULT;
out:
return len;
}
/*
* A helper for ->readlink(). This should be used *ONLY* for symlinks that
* have ->follow_link() touching nd only in nd_set_link(). Using (or not
* using) it for any given inode is up to filesystem.
*/
int generic_readlink(struct dentry *dentry, char __user *buffer, int buflen)
{
struct nameidata nd;
void *cookie;
int res;
nd.depth = 0;
cookie = dentry->d_inode->i_op->follow_link(dentry, &nd);
if (IS_ERR(cookie))
return PTR_ERR(cookie);
res = vfs_readlink(dentry, buffer, buflen, nd_get_link(&nd));
if (dentry->d_inode->i_op->put_link)
dentry->d_inode->i_op->put_link(dentry, &nd, cookie);
return res;
}
int vfs_follow_link(struct nameidata *nd, const char *link)
{
return __vfs_follow_link(nd, link);
}
/* get the link contents into pagecache */
static char *page_getlink(struct dentry * dentry, struct page **ppage)
{
char *kaddr;
struct page *page;
struct address_space *mapping = dentry->d_inode->i_mapping;
page = read_mapping_page(mapping, 0, NULL);
if (IS_ERR(page))
return (char*)page;
*ppage = page;
kaddr = kmap(page);
nd_terminate_link(kaddr, dentry->d_inode->i_size, PAGE_SIZE - 1);
return kaddr;
}
int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
{
struct page *page = NULL;
char *s = page_getlink(dentry, &page);
int res = vfs_readlink(dentry,buffer,buflen,s);
if (page) {
kunmap(page);
page_cache_release(page);
}
return res;
}
void *page_follow_link_light(struct dentry *dentry, struct nameidata *nd)
{
struct page *page = NULL;
nd_set_link(nd, page_getlink(dentry, &page));
return page;
}
void page_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie)
{
struct page *page = cookie;
if (page) {
kunmap(page);
page_cache_release(page);
}
}
/*
* The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
*/
int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
{
struct address_space *mapping = inode->i_mapping;
struct page *page;
void *fsdata;
int err;
char *kaddr;
unsigned int flags = AOP_FLAG_UNINTERRUPTIBLE;
if (nofs)
flags |= AOP_FLAG_NOFS;
retry:
err = pagecache_write_begin(NULL, mapping, 0, len-1,
flags, &page, &fsdata);
if (err)
goto fail;
kaddr = kmap_atomic(page);
memcpy(kaddr, symname, len-1);
kunmap_atomic(kaddr);
err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
page, fsdata);
if (err < 0)
goto fail;
if (err < len-1)
goto retry;
mark_inode_dirty(inode);
return 0;
fail:
return err;
}
int page_symlink(struct inode *inode, const char *symname, int len)
{
return __page_symlink(inode, symname, len,
!(mapping_gfp_mask(inode->i_mapping) & __GFP_FS));
}
const struct inode_operations page_symlink_inode_operations = {
.readlink = generic_readlink,
.follow_link = page_follow_link_light,
.put_link = page_put_link,
};
EXPORT_SYMBOL(user_path_at);
EXPORT_SYMBOL(follow_down_one);
EXPORT_SYMBOL(follow_down);
EXPORT_SYMBOL(follow_up);
EXPORT_SYMBOL(get_write_access); /* binfmt_aout */
EXPORT_SYMBOL(getname);
EXPORT_SYMBOL(lock_rename);
EXPORT_SYMBOL(lookup_one_len);
EXPORT_SYMBOL(page_follow_link_light);
EXPORT_SYMBOL(page_put_link);
EXPORT_SYMBOL(page_readlink);
EXPORT_SYMBOL(__page_symlink);
EXPORT_SYMBOL(page_symlink);
EXPORT_SYMBOL(page_symlink_inode_operations);
EXPORT_SYMBOL(kern_path);
EXPORT_SYMBOL(vfs_path_lookup);
EXPORT_SYMBOL(inode_permission);
EXPORT_SYMBOL(unlock_rename);
EXPORT_SYMBOL(vfs_create);
EXPORT_SYMBOL(vfs_follow_link);
EXPORT_SYMBOL(vfs_link);
EXPORT_SYMBOL(vfs_mkdir);
EXPORT_SYMBOL(vfs_mknod);
EXPORT_SYMBOL(generic_permission);
EXPORT_SYMBOL(vfs_readlink);
EXPORT_SYMBOL(vfs_rename);
EXPORT_SYMBOL(vfs_rmdir);
EXPORT_SYMBOL(vfs_symlink);
EXPORT_SYMBOL(vfs_unlink);
EXPORT_SYMBOL(dentry_unhash);
EXPORT_SYMBOL(generic_readlink);
| Java |
# Puluc
language: C. Game: Puluc
I don't know if it is working well but if you have time, you can modify it.
| Java |
#ifndef Podd_THaVDCPoint_h_
#define Podd_THaVDCPoint_h_
///////////////////////////////////////////////////////////////////////////////
// //
// THaVDCPoint //
// //
// A pair of one U and one V VDC cluster in a given VDC chamber //
// //
///////////////////////////////////////////////////////////////////////////////
#include "THaCluster.h"
#include "THaVDCCluster.h"
class THaVDCChamber;
class THaTrack;
class THaVDCPoint : public THaCluster {
public:
THaVDCPoint( THaVDCCluster* u_cl, THaVDCCluster* v_cl,
THaVDCChamber* chamber );
virtual ~THaVDCPoint() {}
void CalcDetCoords();
// Get and Set Functions
THaVDCCluster* GetUCluster() const { return fUClust; }
THaVDCCluster* GetVCluster() const { return fVClust; }
THaVDCChamber* GetChamber() const { return fChamber; }
THaVDCPoint* GetPartner() const { return fPartner; }
THaTrack* GetTrack() const { return fTrack; }
Double_t GetU() const;
Double_t GetV() const;
Double_t GetX() const { return fX; }
Double_t GetY() const { return fY; }
Double_t GetTheta() const { return fTheta; }
Double_t GetPhi() const { return fPhi; }
Int_t GetTrackIndex() const;
Double_t GetZU() const;
Double_t GetZV() const;
Double_t GetZ() const { return GetZU(); }
Bool_t HasPartner() const { return (fPartner != 0); }
void CalcChisquare(Double_t &chi2, Int_t &nhits) const;
void SetTrack( THaTrack* track);
void SetPartner( THaVDCPoint* partner) { fPartner = partner;}
void SetSlopes( Double_t mu, Double_t mv );
protected:
THaVDCCluster* fUClust; // Cluster in the U plane
THaVDCCluster* fVClust; // Cluster in the V plane
THaVDCChamber* fChamber; // Chamber of this cluster pair
THaTrack* fTrack; // Track that this point is associated with
THaVDCPoint* fPartner; // Point associated with this one in
// the other chamber
// Detector system coordinates derived from fUClust and fVClust
// at the U plane (z = GetZ()). X,Y in m; theta, phi in tan(angle)
Double_t fX; // X position of point in U wire plane
Double_t fY; // Y position of point in U wire plane
Double_t fTheta; // tan(angle between z-axis and track proj onto xz plane)
Double_t fPhi; // tan(angle between z-axis and track proj onto yz plane)
void Set( Double_t x, Double_t y, Double_t theta, Double_t phi )
{ fX = x; fY = y; fTheta = theta; fPhi = phi; }
private:
// Hide copy ctor and op=
THaVDCPoint( const THaVDCPoint& );
THaVDCPoint& operator=( const THaVDCPoint& );
ClassDef(THaVDCPoint,0) // Pair of one U and one V cluster in a VDC chamber
};
//-------------------- inlines ------------------------------------------------
inline
Double_t THaVDCPoint::GetU() const
{
// Return intercept of u cluster
return fUClust->GetIntercept();
}
//_____________________________________________________________________________
inline
Double_t THaVDCPoint::GetV() const
{
// Return intercept of v cluster
return fVClust->GetIntercept();
}
///////////////////////////////////////////////////////////////////////////////
#endif
| Java |
import os, socket, sys, urllib
from wx.lib.embeddedimage import PyEmbeddedImage
ldc_name = "Live Debian Creator"
ldc_cli_version = "1.4.0"
ldc_gui_version = "1.11.0"
if (sys.platform == "win32"):
slash = "\\"
if os.path.isfile(sys.path[0]): #fix for compiled binaries
homepath = os.path.dirname(sys.path[0]) + slash
else:
homepath = sys.path[0] + slash
else:
slash = "/"
#socket.setdefaulttimeout(10)
def defineBrowserAgent(uiname, uiversion):
class AppURLopener(urllib.FancyURLopener):
version = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
#version = uiname + " " + uiversion + " / " + sys.platform
urllib._urlopener = AppURLopener()
bookico = PyEmbeddedImage(
"iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAABPZJ"
"REFUWIWtl09sFFUcxz/iYN+YTZyNxewiTWiV6FZQtqhkN3pgGw6UW6unJVxEDtaThJMc9WLg"
"oj1hwJhANURqQkw9NGwTla0c6JqArELSMVCzi63uKJX5UR7Bw8x0Z2d3yxJ5yctM3vu93/f7"
"+ztv4CGPqamp9A/nL2Q6lTceBqht26pw7kL+7K+10S/tJ9OpBBPASCdnH/k/wFNTU+nzc/+M"
"2v925a2N21Sq1yKJg/wxV7XWyIHBnYPjD53A9PS0mrv+e/6yw6gT60+72iK7AVJJSBoCBihD"
"AVC6WK7O3bx3+thFyY30ycSH7+w5FNXXcQgymUzaei49+vHMX/kq/SqpYGiDRbYHlBFoigMu"
"gklxHsZ1NlG4yygvKiruWauV3vsS2L59e+qZVwfHqsnB3G8LkI2ZHHzdImGBaZi+BgVaqIhi"
"sqo4uQBlrQDPI2jx5gMQUFu39A3veW3ru9leMmO19aQ2JDm8C5SCuDJBgUJRM6DkKE5WFYUF"
"cLSAxgOnNeiqBHZt6z2wO2UdSvXGrfimFNYrIzhHbca/LlOcTzL0coJsj8IRKC4pJhfAXvKB"
"dKBFQu+AdjsnsG/AOpzc+RZWKkc8FgcFGDYApas1SgtAUjxXJOK+a1XUgRHrzc4JlMslqB5C"
"ZYbg+Sws2rAYByPlSQcntNQtNSLaNGCoxv07HRJAQ63ioM6MI2fGPdt6DngKDbVK1kS9IKBV"
"PQmN6P4qBNAgGlw/jqJp9vKKBtVILrA4nA+GegAPBCT8Z0P6RF0dvAfgwdRRIu2rYfU+sLKr"
"mtcCq3UIPGyABmupzIBRoOIkuXzF7oyACq2KDne5FmQC2fC+UyWtZxmIlchtseg1sti2yzf2"
"z8n8559kdmzbYW/evLnalgAGmLr+Lp00aw3WYomUUaDfKpNJphmIDWEZXvd1N9m80HNj+Fs5"
"Pvx0TY0AE6sQUGB45SOA0m0kwyWnHfLdh8nGd5NJDGMqEwyXoi5QXJrAltmVsNxabq2mrWVi"
"qHoitkpCBJwKp6uTVDbaVGKziK5wWWaQoAOGu2IbO5pGkLfuKocD5WrJwVRQXirjXC+DAdY6"
"1ZSYCng8cnxNk8K1fukF/eA+FqAFpIaiMT0VXgIr5fcohUfosca23EzgTh3cDep5taFdcCN1"
"bviAMTB98OZqakfAH65vx4rqKBlNm2+8grUeWGCrGW5S9yWwti7ofW5Ucx9rIBK6bIRB2lVN"
"Y29tQcBonG4Ta6k/NSBeDkSH2Sp0GoiUYYsQ+AB+0rTt4hov/lpQ0lrKDT/F66y3IjLN9rmh"
"VQVo1b4StHgkWhAIEjioKBFfx91GFzR5wJ5HRINpem3YQfzyklAihgCjxDT1SvLvLLLkR0rA"
"jdzOmjxwotbVf656+/20YmS9wrIfvSdO8p53A0UAM0RihVqIjNSB/WXRIFpwXVhebgxCkwdu"
"/33b/kXY94VD/KWPjvY9lduVvaWxCVzYYipxW1eKFhwRajcdat9RemP+vd2jbx6cCIt19Gf0"
"6fETw28fKR6jf9Ci24LuuFeuMWC2IIlLXxVl70+5ZDckuxWuFuIxqIjgTDOjzvV9UC7OTbbS"
"3fGvmW3bauyzE/nCFXe4dIMsy45tVX889oT+83RXV5d5bf21MXIyZD3re2WGgnyfOFK9VG0J"
"/MAEOhmnTp1KXF28mlsXWzezf+/+1legyPgPTicVRBS2XfsAAAAASUVORK5CYII=")
getbookicoIcon = bookico.GetIcon | Java |
<?php
namespace Connections_Directory\Content_Blocks\Entry\Related;
use Connections_Directory\Content_Blocks\Entry\Related;
/**
* Class Last_Name
*
* @package Connections_Directory\Content_Blocks\Entry
*/
class Last_Name extends Related {
/**
* @since 9.8
* @var string
*/
const ID = 'entry-related-last_name';
/**
* @since 9.7
* @var array
*/
private $properties = array(
'relation' => 'last_name',
);
/**
* Related constructor.
*
* @since 9.8
*
* @param $id
*/
public function __construct( $id ) {
$atts = array(
'context' => 'single',
'name' => __( 'Related Entries by Last Name', 'connections' ),
'permission_callback' => '__return_true',
'heading' => __( 'Related by Last Name', 'connections' ),
'script_handle' => 'Connections_Directory/Block/Carousel/Script',
'style_handle' => 'Connections_Directory/Block/Carousel/Style',
);
parent::__construct( $id, $atts );
$this->setProperties( $this->properties );
$this->hooks();
}
/**
* Add hooks.
*
* @since 9.8
*/
private function hooks() {
// Add the last name to the Content Block heading.
add_filter(
'Connections_Directory/Entry/Related/Query_Parameters',
function( $queryParameters ) {
if ( is_array( $queryParameters ) && array_key_exists( 'last_name', $queryParameters ) ) {
$this->set(
'heading',
/* translators: A surname, family name, or last name. */
sprintf( __( 'Related by Last Name - %s', 'connections' ), $queryParameters['last_name'] )
);
}
return $queryParameters;
}
);
}
}
| Java |
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>schrodinger.application.desmond.enhsamp.Series</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="schrodinger-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
>Suite 2012 Schrodinger Python API</th>
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="schrodinger-module.html">Package schrodinger</a> ::
<a href="schrodinger.application-module.html">Package application</a> ::
<a href="schrodinger.application.desmond-module.html">Package desmond</a> ::
<a href="schrodinger.application.desmond.enhsamp-module.html">Module enhsamp</a> ::
Class Series
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="schrodinger.application.desmond.enhsamp.Series-class.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== CLASS DESCRIPTION ==================== -->
<h1 class="epydoc">Class Series</h1><p class="nomargin-top"></p>
<pre class="base-tree">
object --+
|
<a href="schrodinger.application.desmond.enhsamp.Node-class.html">Node</a> --+
|
<strong class="uidshort">Series</strong>
</pre>
<hr />
<!-- ==================== INSTANCE METHODS ==================== -->
<a name="section-InstanceMethods"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Instance Methods</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-InstanceMethods"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.application.desmond.enhsamp.Series-class.html#__init__" class="summary-sig-name">__init__</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">env</span>,
<span class="summary-sig-arg">iters</span>,
<span class="summary-sig-arg">value</span>)</span><br />
x.__init__(...) initializes x; see help(type(x)) for signature</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.application.desmond.enhsamp.Series-class.html#get_type" class="summary-sig-name">get_type</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">env</span>)</span></td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.application.desmond.enhsamp.Series-class.html#__str__" class="summary-sig-name">__str__</a>(<span class="summary-sig-arg">self</span>)</span><br />
str(x)</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.application.desmond.enhsamp.Node-class.html">Node</a></code></b>:
<code><a href="schrodinger.application.desmond.enhsamp.Node-class.html#constant_fold">constant_fold</a></code>,
<code><a href="schrodinger.application.desmond.enhsamp.Node-class.html#resolve_atomsel">resolve_atomsel</a></code>
</p>
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__delattr__</code>,
<code>__format__</code>,
<code>__getattribute__</code>,
<code>__hash__</code>,
<code>__new__</code>,
<code>__reduce__</code>,
<code>__reduce_ex__</code>,
<code>__repr__</code>,
<code>__setattr__</code>,
<code>__sizeof__</code>,
<code>__subclasshook__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== PROPERTIES ==================== -->
<a name="section-Properties"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Properties</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Properties"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__class__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== METHOD DETAILS ==================== -->
<a name="section-MethodDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Method Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-MethodDetails"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="__init__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__init__</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">env</span>,
<span class="sig-arg">iters</span>,
<span class="sig-arg">value</span>)</span>
<br /><em class="fname">(Constructor)</em>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>x.__init__(...) initializes x; see help(type(x)) for signature</p>
<dl class="fields">
<dt>Overrides:
object.__init__
<dd><em class="note">(inherited documentation)</em></dd>
</dt>
</dl>
</td></tr></table>
</div>
<a name="get_type"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">get_type</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">env</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<dl class="fields">
<dt>Overrides:
<a href="schrodinger.application.desmond.enhsamp.Node-class.html#get_type">Node.get_type</a>
</dt>
</dl>
</td></tr></table>
</div>
<a name="__str__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__str__</span>(<span class="sig-arg">self</span>)</span>
<br /><em class="fname">(Informal representation operator)</em>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>str(x)</p>
<dl class="fields">
<dt>Overrides:
object.__str__
<dd><em class="note">(inherited documentation)</em></dd>
</dt>
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="schrodinger-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
>Suite 2012 Schrodinger Python API</th>
</tr></table></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Tue Sep 25 02:22:59 2012
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
| Java |
/* This file is part of the KDevelop PHP Documentation Plugin
Copyright 2012 Milian Wolff <mail@milianw.de>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License or (at your option) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
by the membership of KDE e.V.), which shall act as a proxy
defined in Section 14 of version 3 of the license.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "phpdocsconfig.h"
#include <KLocalizedString>
#include <KPluginFactory>
#include <KPluginLoader>
#include <KConfigGroup>
#include <KUrlRequester>
#include <KAboutData>
#include <KFile>
#include <ksettings/Dispatcher>
#include "phpdocssettings.h"
#include "ui_phpdocsconfig.h"
K_PLUGIN_FACTORY_WITH_JSON(PhpDocsConfigFactory, "kcm_kdevphpdocs.json", registerPlugin<PhpDocsConfig>();)
PhpDocsConfig::PhpDocsConfig(QWidget *parent, const QVariantList &args)
: KCModule(KAboutData::pluginData(QStringLiteral("kcm_kdevphpdocs")), parent, args)
{
QVBoxLayout * l = new QVBoxLayout( this );
QWidget* w = new QWidget;
m_configWidget = new Ui::PhpDocsConfigUI;
m_configWidget->setupUi( w );
m_configWidget->kcfg_phpDocLocation->setMode( KFile::Directory | KFile::ExistingOnly );
l->addWidget( w );
addConfig( PhpDocsSettings::self(), w );
load();
}
void PhpDocsConfig::save()
{
KCModule::save();
// looks like we have to force a write so readConfig() can get the new values
PhpDocsSettings::self()->save();
KSettings::Dispatcher::reparseConfiguration( componentData().componentName() );
}
PhpDocsConfig::~PhpDocsConfig()
{
delete m_configWidget;
}
#include "phpdocsconfig.moc"
| Java |
<?php $st_buttons_p = ot_get_option('st_buttons_p'); ?>
<?php $sidebar_checkbox = get_post_meta($post->ID, 'sidebar_checkbox', true);?>
<?php $full_width = get_post_meta($post->ID, 'portfolio_options_full', true);?>
<?php $details = get_post_meta($post->ID, 'portfolio_options_repeatable', true); if($details){$details = array_filter($details);};?>
<?php $terms = get_the_terms($post->ID, 'portfolio_tags' ); ?>
<?php $share = get_post_meta($post->ID, 'portfolio_options_share', true);?>
<?php get_header(); ?>
<?php //get_template_part('includes/title-breadcrumb' ) ?>
<div id="main" class="inner-page <?php if ($sidebar_checkbox){?>left-sidebar-template<?php }?>">
<div class="container">
<div class="row">
<div class="<?php if ($full_width){?>col-md-12<?php }else{?>col-md-9<?php }?> page-content">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php get_template_part('includes/single-portfolio-post' );?>
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.', GETTEXT_DOMAIN) ?></p>
<?php endif; ?>
</div>
<?php if (!$full_width){?>
<div class="col-md-3">
<?php if ( is_active_sidebar(4)||!empty($details) || $terms || !$share ){?>
<div class="sidebar">
<?php if ( !empty($details) || $terms || !$share ){?>
<div class="widget portfolio-info-widget">
<ul>
<?php if($details){ ?>
<?php $separator = "%%";
$output = '';
foreach ($details as $item) {
if($item){
list($item_text1, $item_text2) = explode($separator, trim($item));
$output .= '<li><strong>' . $item_text1 . ':</strong> ' . do_shortcode($item_text2) . '</li>';
}
}
echo $output;?>
<?php } ?>
<?php if($terms){?>
<li class="tags">
<?php if($terms) : foreach ($terms as $term) { ?>
<?php echo '<a title="'.$term->name.'" href="'.get_term_link($term->slug, 'portfolio_tags').'">'.$term->name.'</a>'?>
<?php } endif;?>
<div class="clearfix"></div>
</li>
<?php }?>
<?php if(!$share&&$st_buttons_p){?>
<li class="st-share-portfolio"><strong><?php _e( 'Share', GETTEXT_DOMAIN);?>:</strong>
<?php echo $st_buttons_p;?>
</li>
<?php }?>
</ul>
</div>
<?php }?>
<?php if ( !function_exists( 'dynamic_sidebar' ) || !dynamic_sidebar('Portfolio Post Sidebar') ) ?>
</div>
<?php } ?>
</div>
<?php }?>
</div>
</div>
</div>
<?php get_footer(); ?> | Java |
/* Table of relaxations for Xtensa assembly.
Copyright 2003, 2004 Free Software Foundation, Inc.
This file is part of GAS, the GNU Assembler.
GAS is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GAS 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 GAS; see the file COPYING. If not, write to
the Free Software Foundation, 51 Franklin Street - Fifth Floor, Boston,
MA 02110-1301, USA. */
#ifndef XTENSA_RELAX_H
#define XTENSA_RELAX_H
#include "xtensa-isa.h"
/* Data structures for the table-driven relaxations for Xtensa processors.
See xtensa-relax.c for details. */
typedef struct transition_list TransitionList;
typedef struct transition_table TransitionTable;
typedef struct transition_rule TransitionRule;
typedef struct precondition_list PreconditionList;
typedef struct precondition Precondition;
typedef struct req_or_option_list ReqOrOptionList;
typedef struct req_or_option_list ReqOrOption;
typedef struct req_option_list ReqOptionList;
typedef struct req_option_list ReqOption;
struct transition_table
{
int num_opcodes;
TransitionList **table; /* Possible transitions for each opcode. */
};
struct transition_list
{
TransitionRule *rule;
TransitionList *next;
};
struct precondition_list
{
Precondition *precond;
PreconditionList *next;
};
/* The required options for a rule are represented with a two-level
structure, with leaf expressions combined by logical ORs at the
lower level, and the results then combined by logical ANDs at the
top level. The AND terms are linked in a list, and each one can
contain a reference to a list of OR terms. The leaf expressions,
i.e., the OR options, can be negated by setting the is_true field
to FALSE. There are two classes of leaf expressions: (1) those
that are properties of the Xtensa configuration and can be
evaluated once when building the tables, and (2) those that depend
of the state of directives or other settings that may vary during
the assembly. The following expressions may be used in group (1):
IsaUse*: Xtensa configuration settings.
realnop: TRUE if the instruction set includes a NOP instruction.
There are currently no expressions in group (2), but they are still
supported since there is a good chance they'll be needed again for
something. */
struct req_option_list
{
ReqOrOptionList *or_option_terms;
ReqOptionList *next;
};
struct req_or_option_list
{
char *option_name;
bfd_boolean is_true;
ReqOrOptionList *next;
};
/* Operand types and constraints on operands: */
typedef enum op_type OpType;
typedef enum cmp_op CmpOp;
enum op_type
{
OP_CONSTANT,
OP_OPERAND,
OP_OPERAND_LOW8, /* Sign-extended low 8 bits of immed. */
OP_OPERAND_HI24S, /* High 24 bits of immed,
plus 0x100 if low 8 bits are signed. */
OP_OPERAND_F32MINUS, /* 32 - immed. */
OP_OPERAND_LOW16U, /* Low 16 bits of immed. */
OP_OPERAND_HI16U, /* High 16 bits of immed. */
OP_LITERAL,
OP_LABEL
};
enum cmp_op
{
OP_EQUAL,
OP_NOTEQUAL,
};
struct precondition
{
CmpOp cmp;
int op_num;
OpType typ; /* CONSTANT: op_data is a constant.
OPERAND: operand op_num must equal op_data.
Cannot be LITERAL or LABEL. */
int op_data;
};
typedef struct build_op BuildOp;
struct build_op
{
int op_num;
OpType typ;
unsigned op_data; /* CONSTANT: op_data is the value to encode.
OPERAND: op_data is the field in the
source instruction to take the value from
and encode in the op_num field here.
LITERAL or LABEL: op_data is the ordinal
that identifies the appropriate one, i.e.,
there can be more than one literal or
label in an expansion. */
BuildOp *next;
};
typedef struct build_instr BuildInstr;
typedef enum instr_type InstrType;
enum instr_type
{
INSTR_INSTR,
INSTR_LITERAL_DEF,
INSTR_LABEL_DEF
};
struct build_instr
{
InstrType typ;
unsigned id; /* LITERAL_DEF or LABEL_DEF: an ordinal to
identify which one. */
xtensa_opcode opcode; /* Unused for LITERAL_DEF or LABEL_DEF. */
BuildOp *ops;
BuildInstr *next;
};
struct transition_rule
{
xtensa_opcode opcode;
PreconditionList *conditions;
ReqOptionList *options;
BuildInstr *to_instr;
};
typedef int (*transition_cmp_fn) (const TransitionRule *,
const TransitionRule *);
extern TransitionTable *xg_build_simplify_table (transition_cmp_fn);
extern TransitionTable *xg_build_widen_table (transition_cmp_fn);
extern bfd_boolean xg_has_userdef_op_fn (OpType);
extern long xg_apply_userdef_op_fn (OpType, long);
#endif /* !XTENSA_RELAX_H */
| Java |
<?php
/**
* template_lite upper modifier plugin
*
* Type: modifier
* Name: upper
* Purpose: Wrapper for the PHP 'strtoupper' function
*/
function tpl_modifier_upper($string) {
return strtoupper($string);
}
?> | Java |
.redux-container-switch {
/*disable text selection*/
}
.redux-container-switch .switch-options {
min-height: 30px;
margin-right: 10px;
}
.redux-container-switch .switch-options label {
cursor: pointer;
}
.redux-container-switch .switch-options input {
display: none;
}
.redux-container-switch .cb-enable span,
.redux-container-switch .cb-disable span {
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
-ms-user-select: none;
user-select: none;
}
.redux-container-switch .cb-enable,
.redux-container-switch .cb-disable,
.redux-container-switch .cb-enable span,
.redux-container-switch .cb-disable span {
display: block;
float: left;
}
.redux-container-switch .cb-enable span,
.redux-container-switch .cb-disable span {
line-height: 30px;
display: block;
font-weight: 700;
}
.redux-container-switch .cb-enable,
.redux-container-switch .cb-disable {
padding: 0 10px;
border-width: 1px;
border-style: solid;
-webkit-appearance: none;
professional-space: nowrap;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.redux-container-switch .cb-enable {
border-right: 0;
border-radius: 3px 0px 0px 3px;
-moz-border-radius: 3px 0px 0px 3px;
-webkit-border-radius: 3px 0px 0px 3px;
}
.redux-container-switch .cb-disable {
border-left: 0;
border-radius: 0px 3px 3px 0px;
-moz-border-radius: 0px 3px 3px 0px;
-webkit-border-radius: 0px 3px 3px 0px;
}
.redux-container-switch .cb-disable.selected {
color: #fff;
}
.redux-container-switch .cb-enable.selected {
color: #fff;
}
| Java |
# encoding: utf-8
# module PyKDE4.kdeui
# from /usr/lib/python3/dist-packages/PyKDE4/kdeui.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import PyKDE4.kdecore as __PyKDE4_kdecore
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtGui as __PyQt4_QtGui
import PyQt4.QtSvg as __PyQt4_QtSvg
class KPassivePopupMessageHandler(__PyQt4_QtCore.QObject, __PyKDE4_kdecore.KMessageHandler):
# no doc
def message(self, *args, **kwargs): # real signature unknown
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
| Java |
/*
* This is free software, licensed under the GNU General Public License v2.
* See /LICENSE for more information.
*
* Copyright (C) 2015 Álvaro Fernández Rojas <noltari@gmail.com>
*/
#ifndef _NAND_H
#define _NAND_H
#define NAND_PAGE_DEF 2048
#define NAND_OOB_DEF 64
#define NAND_CHECK_ENTRIES 1
#define DEBUG_DEF 0
#define DEBUG_PROG 5
#define pr_info(...) printf(__VA_ARGS__)
#define pr_err(...) fprintf(stderr, __VA_ARGS__)
enum errors {
NO_ERROR = 0,
ERROR_ARGS,
ERROR_PTR,
ERROR_FILE,
ERROR_SEEK,
ERROR_READ,
ERROR_WRITE,
ERROR_ENTRIES
};
int nand_clean_oob(int debug, int ifd, int ofd, ssize_t size, int nand_page, int nand_oob, int nand_entries);
void nand_tools_version(void);
#endif /* _NAND_H */
| Java |
/*
* Copyright (C) 2005-2014 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <ace/Message_Block.h>
#include <ace/OS_NS_string.h>
#include <ace/OS_NS_unistd.h>
#include <ace/os_include/arpa/os_inet.h>
#include <ace/os_include/netinet/os_tcp.h>
#include <ace/os_include/sys/os_types.h>
#include <ace/os_include/sys/os_socket.h>
#include <ace/OS_NS_string.h>
#include <ace/Reactor.h>
#include <ace/Auto_Ptr.h>
#include "WorldSocket.h"
#include "Common.h"
#include "Player.h"
#include "Util.h"
#include "World.h"
#include "WorldPacket.h"
#include "SharedDefines.h"
#include "ByteBuffer.h"
#include "Opcodes.h"
#include "DatabaseEnv.h"
#include "BigNumber.h"
#include "SHA1.h"
#include "WorldSession.h"
#include "WorldSocketMgr.h"
#include "Log.h"
#include "PacketLog.h"
#include "ScriptMgr.h"
#include "AccountMgr.h"
#if defined(__GNUC__)
#pragma pack(1)
#else
#pragma pack(push, 1)
#endif
struct ServerPktHeader
{
ServerPktHeader(uint32 size, uint32 cmd, AuthCrypt* _authCrypt) : size(size)
{
if (_authCrypt->IsInitialized())
{
uint32 data = (size << 13) | cmd & MAX_OPCODE;
memcpy(&header[0], &data, 4);
_authCrypt->EncryptSend((uint8*)&header[0], getHeaderLength());
}
else
{
// Dynamic header size is not needed anymore, we are using not encrypted part for only the first few packets
memcpy(&header[0], &size, 2);
memcpy(&header[2], &cmd, 2);
}
}
uint8 getHeaderLength()
{
return 4;
}
const uint32 size;
uint8 header[4];
};
struct AuthClientPktHeader
{
uint16 size;
uint32 cmd;
};
struct WorldClientPktHeader
{
uint16 size;
uint16 cmd;
};
#if defined(__GNUC__)
#pragma pack()
#else
#pragma pack(pop)
#endif
WorldSocket::WorldSocket (void): WorldHandler(),
m_LastPingTime(ACE_Time_Value::zero), m_OverSpeedPings(0), m_Session(0),
m_RecvWPct(0), m_RecvPct(), m_Header(sizeof(AuthClientPktHeader)),
m_WorldHeader(sizeof(WorldClientPktHeader)), m_OutBuffer(0),
m_OutBufferSize(65536), m_OutActive(false),
m_Seed(static_cast<uint32> (rand32()))
{
reference_counting_policy().value (ACE_Event_Handler::Reference_Counting_Policy::ENABLED);
msg_queue()->high_water_mark(8 * 1024 * 1024);
msg_queue()->low_water_mark(8 * 1024 * 1024);
}
WorldSocket::~WorldSocket (void)
{
delete m_RecvWPct;
if (m_OutBuffer)
m_OutBuffer->release();
closing_ = true;
peer().close();
}
bool WorldSocket::IsClosed (void) const
{
return closing_;
}
void WorldSocket::CloseSocket (void)
{
{
ACE_GUARD (LockType, Guard, m_OutBufferLock);
if (closing_)
return;
closing_ = true;
peer().close_writer();
}
{
ACE_GUARD (LockType, Guard, m_SessionLock);
m_Session = NULL;
}
}
const std::string& WorldSocket::GetRemoteAddress (void) const
{
return m_Address;
}
int WorldSocket::SendPacket(WorldPacket const& pct)
{
ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, -1);
if (closing_)
return -1;
// Dump outgoing packet
if (sPacketLog->CanLogPacket())
sPacketLog->LogPacket(pct, SERVER_TO_CLIENT);
WorldPacket const* pkt = &pct;
// Empty buffer used in case packet should be compressed
// Disable compression for now :)
/* WorldPacket buff;
if (m_Session && pkt->size() > 0x400)
{
buff.Compress(m_Session->GetCompressionStream(), pkt);
pkt = &buff;
}*/
uint16 opcodeNumber = serveurOpcodeTable[pkt->GetOpcode()]->OpcodeNumber;
if (m_Session)
TC_LOG_TRACE("network.opcode", "S->C: %s %s", m_Session->GetPlayerInfo().c_str(), GetOpcodeNameForLogging(pkt->GetOpcode(), true).c_str());
sScriptMgr->OnPacketSend(this, *pkt);
ServerPktHeader header(!m_Crypt.IsInitialized() ? pkt->size() + 2 : pct.size(), opcodeNumber, &m_Crypt);
if (m_OutBuffer->space() >= pkt->size() + header.getHeaderLength() && msg_queue()->is_empty())
{
// Put the packet on the buffer.
if (m_OutBuffer->copy((char*) header.header, header.getHeaderLength()) == -1)
ACE_ASSERT (false);
if (!pkt->empty())
if (m_OutBuffer->copy((char*) pkt->contents(), pkt->size()) == -1)
ACE_ASSERT (false);
}
else
{
// Enqueue the packet.
ACE_Message_Block* mb;
ACE_NEW_RETURN(mb, ACE_Message_Block(pkt->size() + header.getHeaderLength()), -1);
mb->copy((char*) header.header, header.getHeaderLength());
if (!pkt->empty())
mb->copy((const char*)pkt->contents(), pkt->size());
if (msg_queue()->enqueue_tail(mb, (ACE_Time_Value*)&ACE_Time_Value::zero) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::SendPacket enqueue_tail failed");
mb->release();
return -1;
}
}
return 0;
}
long WorldSocket::AddReference (void)
{
return static_cast<long> (add_reference());
}
long WorldSocket::RemoveReference (void)
{
return static_cast<long> (remove_reference());
}
int WorldSocket::open (void *a)
{
ACE_UNUSED_ARG (a);
// Prevent double call to this func.
if (m_OutBuffer)
return -1;
// This will also prevent the socket from being Updated
// while we are initializing it.
m_OutActive = true;
// Hook for the manager.
if (sWorldSocketMgr->OnSocketOpen(this) == -1)
return -1;
// Allocate the buffer.
ACE_NEW_RETURN (m_OutBuffer, ACE_Message_Block (m_OutBufferSize), -1);
// Store peer address.
ACE_INET_Addr remote_addr;
if (peer().get_remote_addr(remote_addr) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::open: peer().get_remote_addr errno = %s", ACE_OS::strerror (errno));
return -1;
}
m_Address = remote_addr.get_host_addr();
// not an opcode. this packet sends raw string WORLD OF WARCRAFT CONNECTION - SERVER TO CLIENT"
// because of our implementation, bytes "WO" become the opcode
WorldPacket packet(MSG_VERIFY_CONNECTIVITY);
packet << std::string("RLD OF WARCRAFT CONNECTION - SERVER TO CLIENT");
if (SendPacket(packet) == -1)
return -1;
// Register with ACE Reactor
if (reactor()->register_handler(this, ACE_Event_Handler::READ_MASK | ACE_Event_Handler::WRITE_MASK) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::open: unable to register client handler errno = %s", ACE_OS::strerror (errno));
return -1;
}
// reactor takes care of the socket from now on
remove_reference();
return 0;
}
int WorldSocket::close (u_long)
{
shutdown();
closing_ = true;
remove_reference();
return 0;
}
int WorldSocket::handle_input (ACE_HANDLE)
{
if (closing_)
return -1;
switch (handle_input_missing_data())
{
case -1 :
{
if ((errno == EWOULDBLOCK) ||
(errno == EAGAIN))
{
return Update(); // interesting line, isn't it ?
}
TC_LOG_DEBUG("network", "WorldSocket::handle_input: Peer error closing connection errno = %s", ACE_OS::strerror (errno));
errno = ECONNRESET;
return -1;
}
case 0:
{
TC_LOG_DEBUG("network", "WorldSocket::handle_input: Peer has closed connection");
errno = ECONNRESET;
return -1;
}
case 1:
return 1;
default:
return Update(); // another interesting line ;)
}
ACE_NOTREACHED(return -1);
}
int WorldSocket::handle_output (ACE_HANDLE)
{
ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, -1);
if (closing_)
return -1;
size_t send_len = m_OutBuffer->length();
if (send_len == 0)
return handle_output_queue(Guard);
#ifdef MSG_NOSIGNAL
ssize_t n = peer().send (m_OutBuffer->rd_ptr(), send_len, MSG_NOSIGNAL);
#else
ssize_t n = peer().send (m_OutBuffer->rd_ptr(), send_len);
#endif // MSG_NOSIGNAL
if (n == 0)
return -1;
else if (n == -1)
{
if (errno == EWOULDBLOCK || errno == EAGAIN)
return schedule_wakeup_output (Guard);
return -1;
}
else if (n < (ssize_t)send_len) //now n > 0
{
m_OutBuffer->rd_ptr (static_cast<size_t> (n));
// move the data to the base of the buffer
m_OutBuffer->crunch();
return schedule_wakeup_output (Guard);
}
else //now n == send_len
{
m_OutBuffer->reset();
return handle_output_queue (Guard);
}
ACE_NOTREACHED (return 0);
}
int WorldSocket::handle_output_queue (GuardType& g)
{
if (msg_queue()->is_empty())
return cancel_wakeup_output(g);
ACE_Message_Block* mblk;
if (msg_queue()->dequeue_head(mblk, (ACE_Time_Value*)&ACE_Time_Value::zero) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::handle_output_queue dequeue_head");
return -1;
}
const size_t send_len = mblk->length();
#ifdef MSG_NOSIGNAL
ssize_t n = peer().send(mblk->rd_ptr(), send_len, MSG_NOSIGNAL);
#else
ssize_t n = peer().send(mblk->rd_ptr(), send_len);
#endif // MSG_NOSIGNAL
if (n == 0)
{
mblk->release();
return -1;
}
else if (n == -1)
{
if (errno == EWOULDBLOCK || errno == EAGAIN)
{
msg_queue()->enqueue_head(mblk, (ACE_Time_Value*) &ACE_Time_Value::zero);
return schedule_wakeup_output (g);
}
mblk->release();
return -1;
}
else if (n < (ssize_t)send_len) //now n > 0
{
mblk->rd_ptr(static_cast<size_t> (n));
if (msg_queue()->enqueue_head(mblk, (ACE_Time_Value*) &ACE_Time_Value::zero) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::handle_output_queue enqueue_head");
mblk->release();
return -1;
}
return schedule_wakeup_output (g);
}
else //now n == send_len
{
mblk->release();
return msg_queue()->is_empty() ? cancel_wakeup_output(g) : ACE_Event_Handler::WRITE_MASK;
}
ACE_NOTREACHED(return -1);
}
int WorldSocket::handle_close (ACE_HANDLE h, ACE_Reactor_Mask)
{
// Critical section
{
ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, -1);
closing_ = true;
if (h == ACE_INVALID_HANDLE)
peer().close_writer();
}
// Critical section
{
ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1);
m_Session = NULL;
}
reactor()->remove_handler(this, ACE_Event_Handler::DONT_CALL | ACE_Event_Handler::ALL_EVENTS_MASK);
return 0;
}
int WorldSocket::Update (void)
{
if (closing_)
return -1;
if (m_OutActive)
return 0;
{
ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, 0);
if (m_OutBuffer->length() == 0 && msg_queue()->is_empty())
return 0;
}
int ret;
do
ret = handle_output(get_handle());
while (ret > 0);
return ret;
}
int WorldSocket::handle_input_header (void)
{
ACE_ASSERT(m_RecvWPct == NULL);
if (m_Crypt.IsInitialized())
{
ACE_ASSERT(m_WorldHeader.length() == sizeof(WorldClientPktHeader));
uint8* uintHeader = (uint8*)m_WorldHeader.rd_ptr();
m_Crypt.DecryptRecv(uintHeader, sizeof(WorldClientPktHeader));
WorldClientPktHeader& header = *(WorldClientPktHeader*)uintHeader;
uint32 value = *(uint32*)uintHeader;
header.cmd = value & 0x1FFF;
header.size = ((value & ~(uint32)0x1FFF) >> 13);
if (header.size > 10236)
{
Player* _player = m_Session ? m_Session->GetPlayer() : NULL;
TC_LOG_ERROR("network", "WorldSocket::handle_input_header(): client (account: %u, char [GUID: %u, name: %s]) sent malformed packet (size: %d, cmd: %d)",
m_Session ? m_Session->GetAccountId() : 0,
_player ? _player->GetGUIDLow() : 0,
_player ? _player->GetName().c_str() : "<none>",
header.size, header.cmd);
errno = EINVAL;
return -1;
}
uint16 opcodeNumber = PacketFilter::DropHighBytes(header.cmd);
ACE_NEW_RETURN(m_RecvWPct, WorldPacket(clientOpcodeTable.GetOpcodeByNumber(opcodeNumber), header.size), -1);
m_RecvWPct->SetReceivedOpcode(opcodeNumber);
if (header.size > 0)
{
m_RecvWPct->resize(header.size);
m_RecvPct.base ((char*) m_RecvWPct->contents(), m_RecvWPct->size());
}
else
ACE_ASSERT(m_RecvPct.space() == 0);
}
else
{
ACE_ASSERT(m_Header.length() == sizeof(AuthClientPktHeader));
uint8* uintHeader = (uint8*)m_Header.rd_ptr();
AuthClientPktHeader& header = *((AuthClientPktHeader*)uintHeader);
if ((header.size < 4) || (header.size > 10240))
{
Player* _player = m_Session ? m_Session->GetPlayer() : NULL;
TC_LOG_ERROR("network", "WorldSocket::handle_input_header(): client (account: %u, char [GUID: %u, name: %s]) sent malformed packet (size: %d, cmd: %d)",
m_Session ? m_Session->GetAccountId() : 0,
_player ? _player->GetGUIDLow() : 0,
_player ? _player->GetName().c_str() : "<none>",
header.size, header.cmd);
errno = EINVAL;
return -1;
}
header.size -= 4;
uint16 opcodeNumber = PacketFilter::DropHighBytes(header.cmd);
ACE_NEW_RETURN(m_RecvWPct, WorldPacket(clientOpcodeTable.GetOpcodeByNumber(opcodeNumber), header.size), -1);
m_RecvWPct->SetReceivedOpcode(opcodeNumber);
if (header.size > 0)
{
m_RecvWPct->resize(header.size);
m_RecvPct.base ((char*) m_RecvWPct->contents(), m_RecvWPct->size());
}
else
ACE_ASSERT(m_RecvPct.space() == 0);
}
return 0;
}
int WorldSocket::handle_input_payload (void)
{
// set errno properly here on error !!!
// now have a header and payload
if (m_Crypt.IsInitialized())
{
ACE_ASSERT (m_RecvPct.space() == 0);
ACE_ASSERT (m_WorldHeader.space() == 0);
ACE_ASSERT (m_RecvWPct != NULL);
const int ret = ProcessIncoming (m_RecvWPct);
m_RecvPct.base (NULL, 0);
m_RecvPct.reset();
m_RecvWPct = NULL;
m_WorldHeader.reset();
if (ret == -1)
errno = EINVAL;
return ret;
}
else
{
ACE_ASSERT(m_RecvPct.space() == 0);
ACE_ASSERT(m_Header.space() == 0);
ACE_ASSERT(m_RecvWPct != NULL);
const int ret = ProcessIncoming(m_RecvWPct);
m_RecvPct.base(NULL, 0);
m_RecvPct.reset();
m_RecvWPct = NULL;
m_Header.reset();
if (ret == -1)
errno = EINVAL;
return ret;
}
}
int WorldSocket::handle_input_missing_data (void)
{
char buf [4096];
ACE_Data_Block db (sizeof (buf),
ACE_Message_Block::MB_DATA,
buf,
0,
0,
ACE_Message_Block::DONT_DELETE,
0);
ACE_Message_Block message_block(&db,
ACE_Message_Block::DONT_DELETE,
0);
const size_t recv_size = message_block.space();
const ssize_t n = peer().recv (message_block.wr_ptr(),
recv_size);
if (n <= 0)
return int(n);
message_block.wr_ptr (n);
while (message_block.length() > 0)
{
if (m_Crypt.IsInitialized())
{
if (m_WorldHeader.space() > 0)
{
//need to receive the header
const size_t to_header = (message_block.length() > m_WorldHeader.space() ? m_WorldHeader.space() : message_block.length());
m_WorldHeader.copy (message_block.rd_ptr(), to_header);
message_block.rd_ptr (to_header);
if (m_WorldHeader.space() > 0)
{
// Couldn't receive the whole header this time.
ACE_ASSERT (message_block.length() == 0);
errno = EWOULDBLOCK;
return -1;
}
// We just received nice new header
if (handle_input_header() == -1)
{
ACE_ASSERT ((errno != EWOULDBLOCK) && (errno != EAGAIN));
return -1;
}
}
}
else
{
if (m_Header.space() > 0)
{
//need to receive the header
const size_t to_header = (message_block.length() > m_Header.space() ? m_Header.space() : message_block.length());
m_Header.copy (message_block.rd_ptr(), to_header);
message_block.rd_ptr (to_header);
if (m_Header.space() > 0)
{
// Couldn't receive the whole header this time.
ACE_ASSERT (message_block.length() == 0);
errno = EWOULDBLOCK;
return -1;
}
// We just received nice new header
if (handle_input_header() == -1)
{
ACE_ASSERT ((errno != EWOULDBLOCK) && (errno != EAGAIN));
return -1;
}
}
}
// Its possible on some error situations that this happens
// for example on closing when epoll receives more chunked data and stuff
// hope this is not hack, as proper m_RecvWPct is asserted around
if (!m_RecvWPct)
{
TC_LOG_ERROR("network", "Forcing close on input m_RecvWPct = NULL");
errno = EINVAL;
return -1;
}
// We have full read header, now check the data payload
if (m_RecvPct.space() > 0)
{
//need more data in the payload
const size_t to_data = (message_block.length() > m_RecvPct.space() ? m_RecvPct.space() : message_block.length());
m_RecvPct.copy (message_block.rd_ptr(), to_data);
message_block.rd_ptr (to_data);
if (m_RecvPct.space() > 0)
{
// Couldn't receive the whole data this time.
ACE_ASSERT (message_block.length() == 0);
errno = EWOULDBLOCK;
return -1;
}
}
//just received fresh new payload
if (handle_input_payload() == -1)
{
ACE_ASSERT ((errno != EWOULDBLOCK) && (errno != EAGAIN));
return -1;
}
}
return size_t(n) == recv_size ? 1 : 2;
}
int WorldSocket::cancel_wakeup_output (GuardType& g)
{
if (!m_OutActive)
return 0;
m_OutActive = false;
g.release();
if (reactor()->cancel_wakeup
(this, ACE_Event_Handler::WRITE_MASK) == -1)
{
// would be good to store errno from reactor with errno guard
TC_LOG_ERROR("network", "WorldSocket::cancel_wakeup_output");
return -1;
}
return 0;
}
int WorldSocket::schedule_wakeup_output (GuardType& g)
{
if (m_OutActive)
return 0;
m_OutActive = true;
g.release();
if (reactor()->schedule_wakeup
(this, ACE_Event_Handler::WRITE_MASK) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::schedule_wakeup_output");
return -1;
}
return 0;
}
int WorldSocket::ProcessIncoming(WorldPacket* new_pct)
{
ACE_ASSERT (new_pct);
// manage memory ;)
ACE_Auto_Ptr<WorldPacket> aptr(new_pct);
Opcodes opcode = new_pct->GetOpcode();
if (closing_)
return -1;
// Dump received packet.
if (sPacketLog->CanLogPacket())
sPacketLog->LogPacket(*new_pct, CLIENT_TO_SERVER);
std::string opcodeName = GetOpcodeNameForLogging(opcode, false);
if (m_Session)
TC_LOG_TRACE("network.opcode", "C->S: %s %s", m_Session->GetPlayerInfo().c_str(), opcodeName.c_str());
try
{
switch (opcode)
{
case CMSG_PING:
return HandlePing(*new_pct);
case CMSG_AUTH_SESSION:
if (m_Session)
{
TC_LOG_ERROR("network", "WorldSocket::ProcessIncoming: received duplicate CMSG_AUTH_SESSION from %s", m_Session->GetPlayerInfo().c_str());
return -1;
}
sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct));
return HandleAuthSession(*new_pct);
//case CMSG_KEEP_ALIVE:
// sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct));
// return 0;
case CMSG_LOG_DISCONNECT:
new_pct->rfinish(); // contains uint32 disconnectReason;
sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct));
return 0;
// not an opcode, client sends string "WORLD OF WARCRAFT CONNECTION - CLIENT TO SERVER" without opcode
// first 4 bytes become the opcode (2 dropped)
case MSG_VERIFY_CONNECTIVITY:
{
sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct));
std::string str;
*new_pct >> str;
if (str != "D OF WARCRAFT CONNECTION - CLIENT TO SERVER")
return -1;
return HandleSendAuthSession();
}
/*case CMSG_ENABLE_NAGLE:
{
TC_LOG_DEBUG("network", "%s", opcodeName.c_str());
sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct));
return m_Session ? m_Session->HandleEnableNagleAlgorithm() : -1;
}*/
default:
{
ACE_GUARD_RETURN(LockType, Guard, m_SessionLock, -1);
if (!m_Session)
{
TC_LOG_ERROR("network.opcode", "ProcessIncoming: Client not authed opcode = %u", uint32(opcode));
return -1;
}
// prevent invalid memory access/crash with custom opcodes
if (opcode >= NUM_OPCODES)
return 0;
OpcodeHandler const* handler = clientOpcodeTable[opcode];
if (!handler || handler->Status == STATUS_UNHANDLED)
{
TC_LOG_ERROR("network.opcode", "No defined handler for opcode %s sent by %s", GetOpcodeNameForLogging(new_pct->GetOpcode(), false, new_pct->GetReceivedOpcode()).c_str(), m_Session->GetPlayerInfo().c_str());
return 0;
}
// Our Idle timer will reset on any non PING opcodes.
// Catches people idling on the login screen and any lingering ingame connections.
m_Session->ResetTimeOutTime();
// OK, give the packet to WorldSession
aptr.release();
// WARNING here we call it with locks held.
// Its possible to cause deadlock if QueuePacket calls back
m_Session->QueuePacket(new_pct);
return 0;
}
}
}
catch (ByteBufferException &)
{
TC_LOG_ERROR("network", "WorldSocket::ProcessIncoming ByteBufferException occured while parsing an instant handled packet %s from client %s, accountid=%i. Disconnected client.",
opcodeName.c_str(), GetRemoteAddress().c_str(), m_Session ? int32(m_Session->GetAccountId()) : -1);
new_pct->hexlike();
return -1;
}
ACE_NOTREACHED (return 0);
}
int WorldSocket::HandleSendAuthSession()
{
WorldPacket packet(SMSG_AUTH_CHALLENGE, 37);
packet << uint16(0);
for (int i = 0; i < 8; i++)
packet << uint32(0);
packet << uint8(1);
packet << uint32(m_Seed);
return SendPacket(packet);
}
int WorldSocket::HandleAuthSession(WorldPacket& recvPacket)
{
uint8 digest[20];
uint32 clientSeed;
uint8 security;
uint16 clientBuild;
uint32 id;
uint32 addonSize;
LocaleConstant locale;
std::string account;
SHA1Hash sha;
BigNumber k;
WorldPacket addonsData;
recvPacket.read_skip<uint32>();
recvPacket.read_skip<uint32>();
recvPacket >> digest[18];
recvPacket >> digest[14];
recvPacket >> digest[3];
recvPacket >> digest[4];
recvPacket >> digest[0];
recvPacket.read_skip<uint32>();
recvPacket >> digest[11];
recvPacket >> clientSeed;
recvPacket >> digest[19];
recvPacket.read_skip<uint8>();
recvPacket.read_skip<uint8>();
recvPacket >> digest[2];
recvPacket >> digest[9];
recvPacket >> digest[12];
recvPacket.read_skip<uint64>();
recvPacket.read_skip<uint32>();
recvPacket >> digest[16];
recvPacket >> digest[5];
recvPacket >> digest[6];
recvPacket >> digest[8];
recvPacket >> clientBuild;
recvPacket >> digest[17];
recvPacket >> digest[7];
recvPacket >> digest[13];
recvPacket >> digest[15];
recvPacket >> digest[1];
recvPacket >> digest[10];
recvPacket >> addonSize;
addonsData.resize(addonSize);
recvPacket.read((uint8*)addonsData.contents(), addonSize);
recvPacket.ReadBit();
uint32 accountNameLength = recvPacket.ReadBits(11);
account = recvPacket.ReadString(accountNameLength);
if (sWorld->IsClosed())
{
SendAuthResponseError(AUTH_REJECT);
TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: World closed, denying client (%s).", GetRemoteAddress().c_str());
return -1;
}
// Get the account information from the realmd database
// 0 1 2 3 4 5 6 7 8
// SELECT id, sessionkey, last_ip, locked, expansion, mutetime, locale, recruiter, os FROM account WHERE username = ?
PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_INFO_BY_NAME);
stmt->setString(0, account);
PreparedQueryResult result = LoginDatabase.Query(stmt);
// Stop if the account is not found
if (!result)
{
SendAuthResponseError(AUTH_UNKNOWN_ACCOUNT);
TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Sent Auth Response (unknown account).");
return -1;
}
Field* fields = result->Fetch();
uint8 expansion = fields[4].GetUInt8();
uint32 world_expansion = sWorld->getIntConfig(CONFIG_EXPANSION);
if (expansion > world_expansion)
expansion = world_expansion;
///- Re-check ip locking (same check as in realmd).
if (fields[3].GetUInt8() == 1) // if ip is locked
{
if (strcmp (fields[2].GetCString(), GetRemoteAddress().c_str()))
{
SendAuthResponseError(AUTH_FAILED);
TC_LOG_DEBUG("network", "WorldSocket::HandleAuthSession: Sent Auth Response (Account IP differs).");
return -1;
}
}
id = fields[0].GetUInt32();
k.SetHexStr(fields[1].GetCString());
int64 mutetime = fields[5].GetInt64();
//! Negative mutetime indicates amount of seconds to be muted effective on next login - which is now.
if (mutetime < 0)
{
mutetime = time(NULL) + llabs(mutetime);
PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_MUTE_TIME_LOGIN);
stmt->setInt64(0, mutetime);
stmt->setUInt32(1, id);
LoginDatabase.Execute(stmt);
}
locale = LocaleConstant (fields[6].GetUInt8());
if (locale >= TOTAL_LOCALES)
locale = LOCALE_enUS;
uint32 recruiter = fields[7].GetUInt32();
std::string os = fields[8].GetString();
// Must be done before WorldSession is created
if (sWorld->getBoolConfig(CONFIG_WARDEN_ENABLED) && os != "Win" && os != "OSX")
{
SendAuthResponseError(AUTH_REJECT);
TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Client %s attempted to log in using invalid client OS (%s).", GetRemoteAddress().c_str(), os.c_str());
return -1;
}
// Checks gmlevel per Realm
stmt = LoginDatabase.GetPreparedStatement(LOGIN_GET_GMLEVEL_BY_REALMID);
stmt->setUInt32(0, id);
stmt->setInt32(1, int32(realmID));
result = LoginDatabase.Query(stmt);
if (!result)
security = 0;
else
{
fields = result->Fetch();
security = fields[0].GetUInt8();
}
// Re-check account ban (same check as in realmd)
stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_BANS);
stmt->setUInt32(0, id);
stmt->setString(1, GetRemoteAddress());
PreparedQueryResult banresult = LoginDatabase.Query(stmt);
if (banresult) // if account banned
{
SendAuthResponseError(AUTH_BANNED);
TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Sent Auth Response (Account banned).");
return -1;
}
// Check locked state for serveur
AccountTypes allowedAccountType = sWorld->GetPlayerSecurityLimit();
TC_LOG_DEBUG("network", "Allowed Level: %u Player Level %u", allowedAccountType, AccountTypes(security));
if (allowedAccountType > SEC_PLAYER && AccountTypes(security) < allowedAccountType)
{
SendAuthResponseError(AUTH_UNAVAILABLE);
TC_LOG_INFO("network", "WorldSocket::HandleAuthSession: User tries to login but his security level is not enough");
return -1;
}
// Check that Key and account name are the same on client and serveur
uint32 t = 0;
uint32 seed = m_Seed;
sha.UpdateData(account);
sha.UpdateData((uint8*)&t, 4);
sha.UpdateData((uint8*)&clientSeed, 4);
sha.UpdateData((uint8*)&seed, 4);
sha.UpdateBigNumbers(&k, NULL);
sha.Finalize();
std::string address = GetRemoteAddress();
if (memcmp(sha.GetDigest(), digest, 20))
{
SendAuthResponseError(AUTH_FAILED);
TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Authentication failed for account: %u ('%s') address: %s", id, account.c_str(), address.c_str());
return -1;
}
TC_LOG_DEBUG("network", "WorldSocket::HandleAuthSession: Client '%s' authenticated successfully from %s.",
account.c_str(),
address.c_str());
// Check if this user is by any chance a recruiter
stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_RECRUITER);
stmt->setUInt32(0, id);
result = LoginDatabase.Query(stmt);
bool isRecruiter = false;
if (result)
isRecruiter = true;
// Update the last_ip in the database
stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_LAST_IP);
stmt->setString(0, address);
stmt->setString(1, account);
LoginDatabase.Execute(stmt);
// NOTE ATM the socket is single-threaded, have this in mind ...
ACE_NEW_RETURN(m_Session, WorldSession(id, this, AccountTypes(security), expansion, mutetime, locale, recruiter, isRecruiter), -1);
m_Crypt.Init(&k);
m_Session->LoadGlobalAccountData();
m_Session->LoadTutorialsData();
m_Session->ReadAddonsInfo(addonsData);
m_Session->LoadPermissions();
// Initialize Warden system only if it is enabled by config
if (sWorld->getBoolConfig(CONFIG_WARDEN_ENABLED))
m_Session->InitWarden(&k, os);
// Sleep this Network thread for
uint32 sleepTime = sWorld->getIntConfig(CONFIG_SESSION_ADD_DELAY);
ACE_OS::sleep(ACE_Time_Value(0, sleepTime));
sWorld->AddSession(m_Session);
return 0;
}
int WorldSocket::HandlePing (WorldPacket& recvPacket)
{
uint32 ping;
uint32 latency;
// Get the ping packet content
recvPacket >> latency;
recvPacket >> ping;
if (m_LastPingTime == ACE_Time_Value::zero)
m_LastPingTime = ACE_OS::gettimeofday(); // for 1st ping
else
{
ACE_Time_Value cur_time = ACE_OS::gettimeofday();
ACE_Time_Value diff_time (cur_time);
diff_time -= m_LastPingTime;
m_LastPingTime = cur_time;
if (diff_time < ACE_Time_Value (27))
{
++m_OverSpeedPings;
uint32 max_count = sWorld->getIntConfig (CONFIG_MAX_OVERSPEED_PINGS);
if (max_count && m_OverSpeedPings > max_count)
{
ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1);
if (m_Session && !m_Session->HasPermission(rbac::RBAC_PERM_SKIP_CHECK_OVERSPEED_PING))
{
TC_LOG_ERROR("network", "WorldSocket::HandlePing: %s kicked for over-speed pings (address: %s)",
m_Session->GetPlayerInfo().c_str(), GetRemoteAddress().c_str());
return -1;
}
}
}
else
m_OverSpeedPings = 0;
}
// critical section
{
ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1);
if (m_Session)
{
m_Session->SetLatency (latency);
m_Session->ResetClientTimeDelay();
}
else
{
TC_LOG_ERROR("network", "WorldSocket::HandlePing: peer sent CMSG_PING, "
"but is not authenticated or got recently kicked, "
" address = %s",
GetRemoteAddress().c_str());
return -1;
}
}
WorldPacket packet(SMSG_PONG, 4);
packet << ping;
return SendPacket(packet);
}
void WorldSocket::SendAuthResponseError(uint8 code)
{
WorldPacket packet(SMSG_AUTH_RESPONSE, 1);
packet.WriteBit(0); // has account info
packet.WriteBit(0); // has queue info
packet << uint8(code);
SendPacket(packet);
}
| Java |
<HTML> <HEAD> <TITLE>Jan Kerouac Biography</TITLE> </HEAD>
<BODY BACKGROUND="" BGCOLOR="#e7e7ff" TEXT="#000000"
LINK="#004fcf" ALINK="#ffff00" VLINK="#006faf">
<H3><IMG ALIGN=MIDDLE SRC="images/jan.jpg">About Jan Kerouac </H3>
Jan Kerouac, daughter of Beat Generation novelist Jack Kerouac,
was born in 1952 in Albany, New York. Raised on the Lower East
Side of New York, she traveled extensively in Mexico and South
America in her teenage years and early twenties. Returning to
live with her mother Joan Haverty Stuart in Washington State in
the late 1970's, she completed her first novel BABY DRIVER, which
was published in 1981 by St. Martin's.
<P>
Her second novel TRAIN SONG was published by Henry Holt in 1988.
She has also published and read her poetry at a wide variety
of places, and she has taken part in a number of the symposiums
on the Beat writers, including the Amsterdam Poetry Festival in
1983, the ON THE ROAD celebration at the Naropa Institute in 1982
and the dedication of the Jack Kerouac Memorial in Lowell in 1988.
She was a featured speaker at the international Beat Generation
conference at NYU in May, 1994, and she continues to speak out,
despite her bad health, about the need to preserve her father's
entire archive in a library or a museum.
<P>
She is currently working on her third novel, PARROT FEVER. A
I 10,000-word excerpt is available as a collector's chapbook, signed
and numbered, in an edition of 135, for $50 each plus $3 postage
and handling. Make checks payable to Jan Kerouac Benefit Fund,
11 Palm Ave., Corte Madera, CA 94925.<P>
<A HREF="../LitKicks.html">Literary Kicks</A><BR>
<I><A HREF="../IKL/IKL.html">Inside the Kerouac Legacy</A></I><BR>
A Special Section Maintained by
<A HREF="../IKL/RalphVirgo.html">Ralph Virgo</A> = rvirgo@ix.netcom.com<P>
</BODY></HTML>
| Java |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CompanyDirectoryDF.Models
{
using System;
using System.Collections.Generic;
public partial class Directory
{
public Directory()
{
this.Addresses = new HashSet<Address>();
this.Departments = new HashSet<Department>();
this.DirectoryEmployees = new HashSet<DirectoryEmployee>();
this.PhoneLists = new HashSet<PhoneList>();
this.WebURLWebLocations = new HashSet<WebURLWebLocation>();
}
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
public virtual ICollection<Department> Departments { get; set; }
public virtual ICollection<DirectoryEmployee> DirectoryEmployees { get; set; }
public virtual ICollection<PhoneList> PhoneLists { get; set; }
public virtual ICollection<WebURLWebLocation> WebURLWebLocations { get; set; }
}
}
| Java |
<?php
/**
* The admin-specific functionality of the plugin.
*
* @link kjhuer.com
* @since 1.0.0
*
* @package Za_Collect
* @subpackage Za_Collect/admin
*/
/**
* The admin-specific functionality of the plugin.
*
* Defines the plugin name, version, and two examples hooks for how to
* enqueue the admin-specific stylesheet and JavaScript.
*
* @package Za_Collect
* @subpackage Za_Collect/admin
* @author Kevin J Huer <kjhuer@gmail.com>
*/
class Za_Collect_Admin {
/**
* The ID of this plugin.
*
* @since 1.0.0
* @access private
* @var string $plugin_name The ID of this plugin.
*/
private $plugin_name;
/**
* The version of this plugin.
*
* @since 1.0.0
* @access private
* @var string $version The current version of this plugin.
*/
private $version;
/**
* Initialize the class and set its properties.
*
* @since 1.0.0
* @param string $plugin_name The name of this plugin.
* @param string $version The version of this plugin.
*/
public function __construct( $plugin_name, $version ) {
$this->plugin_name = $plugin_name;
$this->version = $version;
}
/**
* Register the stylesheets for the admin area.
*
* @since 1.0.0
*/
public function enqueue_styles() {
wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/za-collect-admin.css', array(), $this->version, 'all' );
}
/**
* Register the JavaScript for the admin area.
*
* @since 1.0.0
*/
public function enqueue_scripts() {
wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/za-collect-admin.js', array( 'jquery' ), $this->version, false );
}
/**
* Add options page for zaCollect
*
* @since 1.0.0
*/
public function add_plugin_admin_menu(){
add_options_page('zaCollect','zaCollect','manage_options',$this->plugin_name,array($this,'display_plugin_setup_page'));
}
public function add_action_links( $links ) {
/*
* Documentation : https://codex.wordpress.org/Plugin_API/Filter_Reference/plugin_action_links_(plugin_file_name)
*/
$settings_link = array(
'<a href="' . admin_url( 'options-general.php?page=' . $this->plugin_name ) . '">' . __('Settings', $this->plugin_name) . '</a>',
);
return array_merge( $settings_link, $links );
}
/**
* Render the settings page for this plugin.
*
* @since 1.0.0
*/
public function display_plugin_setup_page() {
include_once( 'partials/za-collect-admin-display.php' );
}
public function options_update() {
register_setting($this->plugin_name, $this->plugin_name, array($this, 'validate'));
}
public function validate( $input ){
$valid = array();
$valid['referral_id'] = (isset($input['referral_id']) && !empty($input['referral_id']) && preg_match( '/^[0-9]{18}$/', $input['referral_id'] ) ) ? sanitize_text_field($input['referral_id']) : '';
if ( empty($valid['referral_id']) && !empty($input['referral_id']) ) {
add_settings_error(
'referral_id', // Setting title
'referral_id_texterror', // Error ID
'Please enter a valid referral ID (18 numbers, no spaces or extra characters)', // Error message
'error' // Type of message
);
}
$valid['buy_button_text'] =(isset($input['buy_button_text']) && !empty($input['buy_button_text'])) ? sanitize_text_field($input['buy_button_text']) : '';
$valid['accent_color'] = (isset($input['accent_color']) && !empty($input['accent_color'])) ? sanitize_text_field($input['accent_color']) : '';
if ( !empty($valid['accent_color']) && !preg_match( '/^#[a-f0-9]{6}$/i', $valid['accent_color'] ) ) { // if user insert a HEX color with #
add_settings_error(
'accent_color', // Setting title
'accent_color_texterror', // Error ID
'Please enter a valid hex value color for accent color', // Error message
'error' // Type of message
);
}
$valid['accent_text_color'] = (isset($input['accent_text_color']) && !empty($input['accent_text_color'])) ? sanitize_text_field($input['accent_text_color']) : '';
if ( !empty($valid['accent_text_color']) && !preg_match( '/^#[a-f0-9]{6}$/i', $valid['accent_text_color'] ) ) { // if user insert a HEX color with #
add_settings_error(
'accent_text_color', // Setting title
'accent_text_color_texterror', // Error ID
'Please enter a valid hex value color for accent text color', // Error message
'error' // Type of message
);
}
$valid['new_window'] = (isset($input['new_window']) && !empty($input['new_window'])) ? 1 : 0;
return $valid;
}
}
| Java |
/* a10 513
* Copyright (c) 2001-2012 Nicolas Léveillé <knos.free.fr>
*
* You should have received this file ('src/lib/cokus.c') with a license
* agreement. ('LICENSE' file)
*
* Copying, using, modifying and distributing this file are rights
* covered under this licensing agreement and are conditioned by its
* full acceptance and understanding.
* e 513 */
// This is the ``Mersenne Twister'' random number generator MT19937, which
// generates pseudorandom integers uniformly distributed in 0..(2^32 - 1)
// starting from any odd seed in 0..(2^32 - 1). This version is a recode
// by Shawn Cokus (Cokus@math.washington.edu) on March 8, 1998 of a version by
// Takuji Nishimura (who had suggestions from Topher Cooper and Marc Rieffel in
// July-August 1997).
//
// Effectiveness of the recoding (on Goedel2.math.washington.edu, a DEC Alpha
// running OSF/1) using GCC -O3 as a compiler: before recoding: 51.6 sec. to
// generate 300 million random numbers; after recoding: 24.0 sec. for the same
// (i.e., 46.5% of original time), so speed is now about 12.5 million random
// number generations per second on this machine.
//
// According to the URL <http://www.math.keio.ac.jp/~matumoto/emt.html>
// (and paraphrasing a bit in places), the Mersenne Twister is ``designed
// with consideration of the flaws of various existing generators,'' has
// a period of 2^19937 - 1, gives a sequence that is 623-dimensionally
// equidistributed, and ``has passed many stringent tests, including the
// die-hard test of G. Marsaglia and the load test of P. Hellekalek and
// S. Wegenkittl.'' It is efficient in memory usage (typically using 2506
// to 5012 bytes of static data, depending on data type sizes, and the code
// is quite short as well). It generates random numbers in batches of 624
// at a time, so the caching and pipelining of modern systems is exploited.
// It is also divide- and mod-free.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Library General Public License as published by
// the Free Software Foundation (either version 2 of the License or, at your
// option, any later version). This library is distributed in the hope that
// it will be useful, but WITHOUT ANY WARRANTY, without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
// the GNU Library General Public License for more details. You should have
// received a copy of the GNU Library General Public License along with this
// library; if not, write to the Free Software Foundation, Inc., 59 Temple
// Place, Suite 330, Boston, MA 02111-1307, USA.
//
// The code as Shawn received it included the following notice:
//
// Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. When
// you use this, send an e-mail to <matumoto@math.keio.ac.jp> with
// an appropriate reference to your work.
//
// It would be nice to CC: <Cokus@math.washington.edu> when you write.
//
#include <libc/stdio.h>
#include <libc/stdlib.h>
#include <libc/stdint.h>
//
// uint32_t must be an unsigned integer type capable of holding at least 32
// bits; exactly 32 should be fastest, but 64 is better on an Alpha with
// GCC at -O3 optimization so try your options and see what's best for you
//
#define N (624) // length of state vector
#define M (397) // a period parameter
#define K (0x9908B0DFU) // a magic constant
#define hiBit(u) ((u)&0x80000000U) // mask all but highest bit of u
#define loBit(u) ((u)&0x00000001U) // mask all but lowest bit of u
#define loBits(u) ((u)&0x7FFFFFFFU) // mask the highest bit of u
#define mixBits(u, v) (hiBit(u) | loBits(v)) // move hi bit of u to hi bit of v
static uint32_t state[N + 1]; // state vector + 1 extra to not violate ANSI C
static uint32_t *next; // next random value is computed from here
static int left = -1; // can *next++ this many times before reloading
extern void seedMT(uint32_t seed)
{
//
// We initialize state[0..(N-1)] via the generator
//
// x_new = (69069 * x_old) mod 2^32
//
// from Line 15 of Table 1, p. 106, Sec. 3.3.4 of Knuth's
// _The Art of Computer Programming_, Volume 2, 3rd ed.
//
// Notes (SJC): I do not know what the initial state requirements
// of the Mersenne Twister are, but it seems this seeding generator
// could be better. It achieves the maximum period for its modulus
// (2^30) iff x_initial is odd (p. 20-21, Sec. 3.2.1.2, Knuth); if
// x_initial can be even, you have sequences like 0, 0, 0, ...;
// 2^31, 2^31, 2^31, ...; 2^30, 2^30, 2^30, ...; 2^29, 2^29 + 2^31,
// 2^29, 2^29 + 2^31, ..., etc. so I force seed to be odd below.
//
// Even if x_initial is odd, if x_initial is 1 mod 4 then
//
// the lowest bit of x is always 1,
// the next-to-lowest bit of x is always 0,
// the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... ,
// the 3rd-from-lowest bit of x 4-cycles ... 0 1 1 0 0 1 1 0 ... ,
// the 4th-from-lowest bit of x has the 8-cycle ... 0 0 0 1 1 1 1 0 ... ,
// ...
//
// and if x_initial is 3 mod 4 then
//
// the lowest bit of x is always 1,
// the next-to-lowest bit of x is always 1,
// the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... ,
// the 3rd-from-lowest bit of x 4-cycles ... 0 0 1 1 0 0 1 1 ... ,
// the 4th-from-lowest bit of x has the 8-cycle ... 0 0 1 1 1 1 0 0 ... ,
// ...
//
// The generator's potency (min. s>=0 with (69069-1)^s = 0 mod 2^32) is
// 16, which seems to be alright by p. 25, Sec. 3.2.1.3 of Knuth. It
// also does well in the dimension 2..5 spectral tests, but it could be
// better in dimension 6 (Line 15, Table 1, p. 106, Sec. 3.3.4, Knuth).
//
// Note that the random number user does not see the values generated
// here directly since reloadMT() will always munge them first, so maybe
// none of all of this matters. In fact, the seed values made here could
// even be extra-special desirable if the Mersenne Twister theory says
// so-- that's why the only change I made is to restrict to odd seeds.
//
register uint32_t x = (seed | 1U) & 0xFFFFFFFFU, *s = state;
register int j;
for (left = 0, *s++ = x, j = N; --j; *s++ = (x *= 69069U) & 0xFFFFFFFFU)
;
}
extern uint32_t reloadMT(void)
{
register uint32_t *p0 = state, *p2 = state + 2, *pM = state + M, s0, s1;
register int j;
if (left < -1)
seedMT(4357U);
left = N - 1, next = state + 1;
for (s0 = state[0], s1 = state[1], j = N - M + 1; --j; s0 = s1, s1 = *p2++)
*p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
for (pM = state, j = M; --j; s0 = s1, s1 = *p2++)
*p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
s1 = state[0], *p0 = *pM ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
s1 ^= (s1 >> 11);
s1 ^= (s1 << 7) & 0x9D2C5680U;
s1 ^= (s1 << 15) & 0xEFC60000U;
return (s1 ^ (s1 >> 18));
}
extern uint32_t randomMT(void)
{
uint32_t y;
if (--left < 0)
return (reloadMT());
y = *next++;
y ^= (y >> 11);
y ^= (y << 7) & 0x9D2C5680U;
y ^= (y << 15) & 0xEFC60000U;
return (y ^ (y >> 18));
}
#if 0
int main(void)
{
int j;
// you can seed with any uint32_t, but the best are odds in 0..(2^32 - 1)
seedMT(4357U);
// print the first 2,002 random numbers seven to a line as an example
for(j=0; j<2002; j++)
printf(" %10lu%s", (unsigned long) randomMT(), (j%7)==6 ? "\n" : "");
return(EXIT_SUCCESS);
}
#endif
| Java |
/*
* Copyright (C) ST-Ericsson SA 2010,2011
*
* Author: Chris Blair <chris.blair@stericsson.com> for ST-Ericsson
*
* License terms: GNU General Public License (GPL) version 2
*
* U9500 <-> M6718 IPC protocol implementation using SPI.
* state machine definition and functionality.
*/
#include <linux/modem/m6718_spi/modem_driver.h>
#include "modem_statemachine.h"
#include "modem_util.h"
#include "modem_netlink.h"
#include "modem_debug.h"
#include "modem_queue.h"
#include "modem_protocol.h"
#ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_MODEM_STATE
#include "modem_state.h"
#endif
#define CMD_BOOTREQ (1)
#define CMD_BOOTRESP (2)
#define CMD_WRITE (3)
#define CMD_READ (4)
static u8 sm_init_enter(u8 event, struct ipc_link_context *context)
{
#ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_MODEM_STATE
/* if modem is off un-configure the IPC GPIO pins for low-power */
if (modem_state_get_state() == MODEM_STATE_OFF) {
dev_info(&context->sdev->dev,
"link %d: modem is off, un-configuring GPIO\n",
context->link->id);
ipc_util_link_gpio_unconfig(context);
}
#endif
/* nothing more to do until an event happens */
return IPC_SM_RUN_NONE;
}
static const struct ipc_sm_state *sm_init_exit(u8 event,
struct ipc_link_context *context)
{
bool int_active = false;
/*
* For reset event just re-enter init in case the modem has
* powered off - we need to reconfigure our GPIO pins
*/
if (event == IPC_SM_RUN_RESET)
return ipc_sm_state(IPC_SM_INIT);
/* re-sample link INT pin */
int_active = ipc_util_int_is_active(context);
atomic_set(&context->state_int, int_active);
dev_info(&context->sdev->dev,
"link %d: link initialised; SS:INACTIVE(%d) INT:%s(%d)\n",
context->link->id,
ipc_util_ss_level_inactive(context),
int_active ? "ACTIVE" : "INACTIVE",
int_active ? ipc_util_int_level_active(context) :
ipc_util_int_level_inactive(context));
/* handshake is only on link 0 */
if (context->link->id == 0) {
if (!int_active) {
dev_info(&context->sdev->dev,
"link %d: slave INT signal is inactive\n",
context->link->id);
/* start boot handshake */
return ipc_sm_state(IPC_SM_SLW_TX_BOOTREQ);
} else {
/* wait for slave INT signal to stabilise inactive */
return ipc_sm_state(IPC_SM_WAIT_SLAVE_STABLE);
}
} else {
dev_info(&context->sdev->dev,
"link %d: boot sync not needed, going idle\n",
context->link->id);
return ipc_sm_state(IPC_SM_IDL);
}
}
static const struct ipc_sm_state *sm_init_aud_exit(u8 event,
struct ipc_link_context *context)
{
bool int_active = false;
/*
* For reset event just re-enter init in case the modem has
* powered off - we need to reconfigure our GPIO pins
*/
if (event == IPC_SM_RUN_RESET)
return ipc_sm_state(IPC_SM_INIT_AUD);
/* re-sample link INT pin */
int_active = ipc_util_int_is_active(context);
atomic_set(&context->state_int, int_active);
dev_info(&context->sdev->dev,
"link %d: link initialised; SS:INACTIVE(%d) INT:%s(%d)\n",
context->link->id,
ipc_util_ss_level_inactive(context),
int_active ? "ACTIVE" : "INACTIVE",
int_active ? ipc_util_int_level_active(context) :
ipc_util_int_level_inactive(context));
dev_info(&context->sdev->dev,
"link %d: boot sync not needed, going idle\n",
context->link->id);
return ipc_sm_state(IPC_SM_IDL_AUD);
}
static u8 sm_wait_slave_stable_enter(u8 event, struct ipc_link_context *context)
{
static unsigned long printk_warn_time;
if (printk_timed_ratelimit(&printk_warn_time, 60 * 1000))
dev_info(&context->sdev->dev,
"link %d: waiting for stable inactive slave INT\n",
context->link->id);
ipc_util_start_slave_stable_timer(context);
return IPC_SM_RUN_NONE;
}
static const struct ipc_sm_state *sm_wait_slave_stable_exit(u8 event,
struct ipc_link_context *context)
{
if (!ipc_util_int_is_active(context)) {
dev_info(&context->sdev->dev,
"link %d: slave INT signal is stable inactive\n",
context->link->id);
return ipc_sm_state(IPC_SM_SLW_TX_BOOTREQ);
} else {
return ipc_sm_state(IPC_SM_WAIT_SLAVE_STABLE);
}
}
static u8 sm_wait_handshake_inactive_enter(u8 event,
struct ipc_link_context *context)
{
dev_info(&context->sdev->dev,
"link %d: waiting for stable inactive slave INT\n",
context->link->id);
ipc_util_start_slave_stable_timer(context);
return IPC_SM_RUN_NONE;
}
static const struct ipc_sm_state *sm_wait_handshake_inactive_exit(u8 event,
struct ipc_link_context *context)
{
int i;
if (!ipc_util_int_is_active(context)) {
dev_info(&context->sdev->dev,
"link %d: slave INT signal is inactive, going idle\n",
context->link->id);
/* modem sync is done */
atomic_inc(&l1_context.boot_sync_done);
ipc_broadcast_modem_online(context);
/*
* Kick the state machine for any initialised links - skip link0
* since this link has just completed handshake
*/
for (i = 1; i < IPC_NBR_SUPPORTED_SPI_LINKS; i++)
if (l1_context.device_context[i].state != NULL) {
dev_dbg(&context->sdev->dev,
"link %d has already been probed, "
"kicking state machine\n", i);
ipc_sm_kick(IPC_SM_RUN_INIT,
&l1_context.device_context[i]);
}
return ipc_sm_state(IPC_SM_IDL);
} else {
return ipc_sm_state(IPC_SM_WAIT_HANDSHAKE_INACTIVE);
}
}
static u8 sm_idl_enter(u8 event, struct ipc_link_context *context)
{
ipc_util_deactivate_ss(context);
ipc_dbg_enter_idle(context);
/* check if tx queue contains items */
if (atomic_read(&context->tx_q_count) > 0) {
dev_dbg(&context->sdev->dev,
"link %d: tx queue contains items\n",
context->link->id);
return IPC_SM_RUN_TX_REQ;
}
/* check if modem has already requested transaction start */
if (atomic_read(&context->state_int)) {
dev_dbg(&context->sdev->dev,
"link %d: slave has already signalled ready\n",
context->link->id);
return IPC_SM_RUN_SLAVE_IRQ;
}
dev_dbg(&context->sdev->dev,
"link %d: going idle\n", context->link->id);
return IPC_SM_RUN_NONE;
}
static const struct ipc_sm_state *sm_idl_exit(u8 event,
struct ipc_link_context *context)
{
ipc_dbg_exit_idle(context);
if (event == IPC_SM_RUN_RESET)
return ipc_sm_state(IPC_SM_RESET);
else if (event == IPC_SM_RUN_TX_REQ)
return ipc_sm_state(IPC_SM_SLW_TX_WR_CMD);
else if (event == IPC_SM_RUN_SLAVE_IRQ)
return ipc_sm_state(IPC_SM_SLW_TX_RD_CMD);
else
return ipc_sm_state(IPC_SM_HALT);
}
static const struct ipc_sm_state *sm_idl_aud_exit(u8 event,
struct ipc_link_context *context)
{
ipc_dbg_exit_idle(context);
if (event == IPC_SM_RUN_RESET)
return ipc_sm_state(IPC_SM_RESET_AUD);
/* always transmit data first */
return ipc_sm_state(IPC_SM_SLW_TX_WR_DAT_AUD);
}
static u8 sm_slw_tx_wr_cmd_enter(u8 event, struct ipc_link_context *context)
{
struct ipc_tx_queue *frame;
/* get the frame from the head of the tx queue */
if (ipc_queue_is_empty(context)) {
dev_err(&context->sdev->dev,
"link %d error: tx queue is empty!\n",
context->link->id);
return IPC_SM_RUN_ABORT;
}
frame = ipc_queue_get_frame(context);
ipc_dbg_dump_frame(&context->sdev->dev, context->link->id, frame, true);
context->cmd = ipc_util_make_l1_header(CMD_WRITE, frame->counter,
frame->len);
dev_dbg(&context->sdev->dev,
"link %d: TX FRAME cmd %08x (type %d counter %d len %d)\n",
context->link->id,
context->cmd,
ipc_util_get_l1_cmd(context->cmd),
ipc_util_get_l1_counter(context->cmd),
ipc_util_get_l1_length(context->cmd));
ipc_util_spi_message_prepare(context, &context->cmd,
NULL, IPC_L1_HDR_SIZE);
context->frame = frame;
/* slave might already have signalled ready to transmit */
if (atomic_read(&context->state_int)) {
dev_dbg(&context->sdev->dev,
"link %d: slave has already signalled ready\n",
context->link->id);
ipc_util_activate_ss(context);
return IPC_SM_RUN_SLAVE_IRQ;
} else {
ipc_util_activate_ss_with_tmo(context);
return IPC_SM_RUN_NONE;
}
}
static const struct ipc_sm_state *sm_slw_tx_wr_cmd_exit(u8 event,
struct ipc_link_context *context)
{
if (event == IPC_SM_RUN_RESET)
return ipc_sm_state(IPC_SM_RESET);
else if (event == IPC_SM_RUN_COMMS_TMO)
return ipc_sm_state(IPC_SM_HALT);
else
return ipc_sm_state(IPC_SM_ACT_TX_WR_CMD);
}
static u8 sm_act_tx_wr_cmd_enter(u8 event, struct ipc_link_context *context)
{
int err;
/* slave is ready - start the spi transfer */
dev_dbg(&context->sdev->dev,
"link %d: starting spi tfr\n", context->link->id);
err = spi_async(context->sdev, &context->spi_message);
if (err < 0) {
dev_err(&context->sdev->dev,
"link %d error: spi tfr start failed, error %d\n",
context->link->id, err);
return IPC_SM_RUN_ABORT;
}
return IPC_SM_RUN_NONE;
}
static const struct ipc_sm_state *sm_act_tx_wr_cmd_exit(u8 event,
struct ipc_link_context *context)
{
if (event == IPC_SM_RUN_RESET)
return ipc_sm_state(IPC_SM_RESET);
else
return ipc_sm_state(IPC_SM_SLW_TX_WR_DAT);
}
static u8 sm_slw_tx_wr_dat_enter(u8 event, struct ipc_link_context *context)
{
/* prepare to transfer the frame tx data */
ipc_util_spi_message_prepare(context, context->frame->data,
NULL, context->frame->len);
/* slave might already have signalled ready to transmit */
if (atomic_read(&context->state_int)) {
dev_dbg(&context->sdev->dev,
"link %d: slave has already signalled ready\n",
context->link->id);
ipc_util_activate_ss(context);
return IPC_SM_RUN_SLAVE_IRQ;
} else {
ipc_util_activate_ss_with_tmo(context);
return IPC_SM_RUN_NONE;
}
}
static u8 sm_slw_tx_wr_dat_aud_enter(u8 event, struct ipc_link_context *context)
{
struct ipc_tx_queue *frame = NULL;
/* check if there is a frame to be sent */
if (!ipc_queue_is_empty(context)) {
frame = ipc_queue_get_frame(context);
} else {
/* no frame to send, create an empty one */
dev_dbg(&context->sdev->dev,
"link %d: no frame to send, allocating dummy\n",
context->link->id);
frame = ipc_queue_new_frame(context, 0);
if (frame == NULL)
return IPC_SM_RUN_ABORT;
}
ipc_dbg_dump_frame(&context->sdev->dev, context->link->id, frame, true);
/* prepare to transfer the frame tx data */
context->frame = frame;
ipc_util_spi_message_prepare(context, context->frame->data,
NULL, context->frame->len);
/* slave might already have signalled ready to transmit */
if (event == IPC_SM_RUN_SLAVE_IRQ || atomic_read(&context->state_int)) {
dev_dbg(&context->sdev->dev,
"link %d: slave has already signalled ready\n",
context->link->id);
ipc_util_activate_ss(context);
return IPC_SM_RUN_SLAVE_IRQ;
} else {
ipc_util_activate_ss_with_tmo(context);
return IPC_SM_RUN_NONE;
}
}
static const struct ipc_sm_state *sm_slw_tx_wr_dat_exit(u8 event,
struct ipc_link_context *context)
{
if (event == IPC_SM_RUN_RESET)
return ipc_sm_state(IPC_SM_RESET);
else if (event == IPC_SM_RUN_COMMS_TMO)
return ipc_sm_state(IPC_SM_HALT);
else
return ipc_sm_state(IPC_SM_ACT_TX_WR_DAT);
}
static const struct ipc_sm_state *sm_slw_tx_wr_dat_aud_exit(u8 event,
struct ipc_link_context *context)
{
if (event == IPC_SM_RUN_RESET)
return ipc_sm_state(IPC_SM_RESET_AUD);
else if (event == IPC_SM_RUN_COMMS_TMO)
return ipc_sm_state(IPC_SM_HALT_AUD);
else
return ipc_sm_state(IPC_SM_ACT_TX_WR_DAT_AUD);
}
static u8 sm_act_tx_wr_dat_enter(u8 event, struct ipc_link_context *context)
{
int err;
/* slave is ready - start the spi transfer */
dev_dbg(&context->sdev->dev,
"link %d: starting spi tfr\n", context->link->id);
err = spi_async(context->sdev, &context->spi_message);
if (err < 0) {
dev_err(&context->sdev->dev,
"link %d error: spi tfr start failed, error %d\n",
context->link->id, err);
return IPC_SM_RUN_ABORT;
}
return IPC_SM_RUN_NONE;
}
static const struct ipc_sm_state *sm_act_tx_wr_dat_exit(u8 event,
struct ipc_link_context *context)
{
if (event == IPC_SM_RUN_RESET)
return ipc_sm_state(IPC_SM_RESET);
#ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_THROUGHPUT_MEASUREMENT
/* frame is sent, increment link tx counter */
context->tx_bytes += context->frame->actual_len;
#endif
#ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_VERIFY_FRAMES
{
u8 channel;
channel = ipc_util_get_l2_channel(*(u32 *)context->frame->data);
if (ipc_util_channel_is_loopback(channel)) {
context->last_frame = context->frame;
} else {
ipc_queue_delete_frame(context->frame);
context->frame = NULL;
}
}
#else
/* free the sent frame */
ipc_queue_delete_frame(context->frame);
context->frame = NULL;
#endif
return ipc_sm_state(IPC_SM_SLW_TX_RD_CMD);
}
static const struct ipc_sm_state *sm_act_tx_wr_dat_aud_exit(u8 event,
struct ipc_link_context *context)
{
if (event == IPC_SM_RUN_RESET)
return ipc_sm_state(IPC_SM_RESET_AUD);
#ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_THROUGHPUT_MEASUREMENT
/* frame is sent, increment link tx counter */
context->tx_bytes += context->frame->actual_len;
#endif
#ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_VERIFY_FRAMES
{
u8 channel;
channel = ipc_util_get_l2_channel(*(u32 *)context->frame->data);
if (ipc_util_channel_is_loopback(channel)) {
/* create a copy of the frame */
context->last_frame = ipc_queue_new_frame(context,
context->frame->actual_len);
memcpy(context->last_frame->data,
context->frame->data,
context->frame->actual_len);
}
}
#endif
return ipc_sm_state(IPC_SM_SLW_RX_WR_DAT_AUD);
}
static u8 sm_slw_tx_rd_cmd_enter(u8 event, struct ipc_link_context *context)
{
context->cmd = ipc_util_make_l1_header(CMD_READ, 0, 0);
dev_dbg(&context->sdev->dev,
"link %d: cmd %08x (type %d)\n",
context->link->id,
context->cmd,
ipc_util_get_l1_cmd(context->cmd));
/* prepare the spi message to transfer */
ipc_util_spi_message_prepare(context, &context->cmd,
NULL, IPC_L1_HDR_SIZE);
/* check if the slave requested this transaction */
if (event == IPC_SM_RUN_SLAVE_IRQ) {
dev_dbg(&context->sdev->dev,
"link %d: slave initiated transaction, continue\n",
context->link->id);
ipc_util_activate_ss(context);
return IPC_SM_RUN_SLAVE_IRQ;
} else {
/* slave might already have signalled ready to transmit */
if (atomic_read(&context->state_int)) {
dev_dbg(&context->sdev->dev,
"link %d: slave has already signalled ready\n",
context->link->id);
ipc_util_activate_ss(context);
return IPC_SM_RUN_SLAVE_IRQ;
} else {
ipc_util_activate_ss_with_tmo(context);
return IPC_SM_RUN_NONE;
}
}
}
static const struct ipc_sm_state *sm_slw_tx_rd_cmd_exit(u8 event,
struct ipc_link_context *context)
{
if (event == IPC_SM_RUN_RESET)
return ipc_sm_state(IPC_SM_RESET);
else if (event == IPC_SM_RUN_COMMS_TMO)
return ipc_sm_state(IPC_SM_HALT);
else
return ipc_sm_state(IPC_SM_ACT_TX_RD_CMD);
}
static u8 sm_act_tx_rd_cmd_enter(u8 event, struct ipc_link_context *context)
{
int err;
/* slave is ready - start the spi transfer */
dev_dbg(&context->sdev->dev,
"link %d: starting spi tfr\n", context->link->id);
err = spi_async(context->sdev, &context->spi_message);
if (err < 0) {
dev_err(&context->sdev->dev,
"link %d error: spi tfr start failed, error %d\n",
context->link->id, err);
return IPC_SM_RUN_ABORT;
}
return IPC_SM_RUN_NONE;
}
static const struct ipc_sm_state *sm_act_tx_rd_cmd_exit(u8 event,
struct ipc_link_context *context)
{
if (event == IPC_SM_RUN_RESET)
return ipc_sm_state(IPC_SM_RESET);
else
return ipc_sm_state(IPC_SM_SLW_RX_WR_CMD);
}
static u8 sm_slw_rx_wr_cmd_enter(u8 event, struct ipc_link_context *context)
{
/* prepare to receive MESSAGE WRITE frame header */
ipc_util_spi_message_prepare(context, NULL,
&context->cmd, IPC_L1_HDR_SIZE);
/* slave might already have signalled ready to transmit */
if (atomic_read(&context->state_int)) {
dev_dbg(&context->sdev->dev,
"link %d: slave has already signalled ready\n",
context->link->id);
ipc_util_activate_ss(context);
return IPC_SM_RUN_SLAVE_IRQ;
} else {
ipc_util_activate_ss_with_tmo(context);
return IPC_SM_RUN_NONE;
}
}
static const struct ipc_sm_state *sm_slw_rx_wr_cmd_exit(u8 event,
struct ipc_link_context *context)
{
if (event == IPC_SM_RUN_RESET)
return ipc_sm_state(IPC_SM_RESET);
else if (event == IPC_SM_RUN_COMMS_TMO)
return ipc_sm_state(IPC_SM_HALT);
else
return ipc_sm_state(IPC_SM_ACT_RX_WR_CMD);
}
static u8 sm_act_rx_wr_cmd_enter(u8 event, struct ipc_link_context *context)
{
int err;
/* slave is ready - start the spi transfer */
dev_dbg(&context->sdev->dev,
"link %d: starting spi tfr\n", context->link->id);
err = spi_async(context->sdev, &context->spi_message);
if (err < 0) {
dev_err(&context->sdev->dev,
"link %d error: spi tfr start failed, error %d\n",
context->link->id, err);
return IPC_SM_RUN_ABORT;
}
return IPC_SM_RUN_NONE;
}
static const struct ipc_sm_state *sm_act_rx_wr_cmd_exit(u8 event,
struct ipc_link_context *context)
{
u8 cmd_type = ipc_util_get_l1_cmd(context->cmd);
int counter = ipc_util_get_l1_counter(context->cmd);
int length = ipc_util_get_l1_length(context->cmd);
dev_dbg(&context->sdev->dev,
"link %d: RX HEADER %08x (type %d counter %d length %d)\n",
context->link->id,
context->cmd,
cmd_type,
counter,
length);
if (event == IPC_SM_RUN_RESET)
return ipc_sm_state(IPC_SM_RESET);
if (cmd_type == CMD_WRITE) {
/* slave has data to send - allocate a frame to hold it */
context->frame = ipc_queue_new_frame(context, length);
if (context->frame == NULL)
return ipc_sm_state(IPC_SM_IDL);
context->frame->counter = counter;
ipc_util_spi_message_prepare(context, NULL,
context->frame->data, context->frame->len);
return ipc_sm_state(IPC_SM_ACT_RX_WR_DAT);
} else {
if (cmd_type != 0)
dev_err(&context->sdev->dev,
"link %d error: received invalid frame type %x "
"(%08x)! assuming TRANSACTION_END...\n",
context->link->id,
cmd_type,
context->cmd);
/* slave has no data to send */
dev_dbg(&context->sdev->dev,
"link %d: slave has no data to send\n",
context->link->id);
return ipc_sm_state(IPC_SM_IDL);
}
}
static u8 sm_slw_rx_wr_dat_aud_enter(u8 event, struct ipc_link_context *context)
{
/*
* We're using the same frame buffer we just sent, so no need for a
* new allocation here, just prepare the spi message
*/
ipc_util_spi_message_prepare(context, NULL,
context->frame->data, context->frame->len);
/* slave might already have signalled ready to transmit */
if (atomic_read(&context->state_int)) {
dev_dbg(&context->sdev->dev,
"link %d: slave has already signalled ready\n",
context->link->id);
ipc_util_activate_ss(context);
return IPC_SM_RUN_SLAVE_IRQ;
} else {
ipc_util_activate_ss_with_tmo(context);
return IPC_SM_RUN_NONE;
}
}
static const struct ipc_sm_state *sm_slw_rx_wr_dat_aud_exit(u8 event,
struct ipc_link_context *context)
{
if (event == IPC_SM_RUN_RESET)
return ipc_sm_state(IPC_SM_RESET_AUD);
else if (event == IPC_SM_RUN_COMMS_TMO)
return ipc_sm_state(IPC_SM_HALT_AUD);
else
return ipc_sm_state(IPC_SM_ACT_RX_WR_DAT_AUD);
}
static u8 sm_act_rx_wr_dat_enter(u8 event, struct ipc_link_context *context)
{
int err;
/* assume slave is still ready - prepare and start the spi transfer */
ipc_util_spi_message_prepare(context, NULL,
context->frame->data, context->frame->len);
dev_dbg(&context->sdev->dev,
"link %d: starting spi tfr\n", context->link->id);
err = spi_async(context->sdev, &context->spi_message);
if (err < 0) {
dev_err(&context->sdev->dev,
"link %d error: spi tfr start failed, error %d\n",
context->link->id, err);
return IPC_SM_RUN_ABORT;
}
return IPC_SM_RUN_NONE;
}
static u8 sm_act_rx_wr_dat_aud_enter(u8 event, struct ipc_link_context *context)
{
int err;
dev_dbg(&context->sdev->dev,
"link %d: starting spi tfr\n", context->link->id);
err = spi_async(context->sdev, &context->spi_message);
if (err < 0) {
dev_err(&context->sdev->dev,
"link %d error: spi tfr start failed, error %d\n",
context->link->id, err);
return IPC_SM_RUN_ABORT;
}
return IPC_SM_RUN_NONE;
}
static const struct ipc_sm_state *sm_act_rx_wr_dat_exit(u8 event,
struct ipc_link_context *context)
{
u32 frame_hdr;
unsigned char l2_header;
unsigned int l2_length;
u8 *l2_data;
if (event == IPC_SM_RUN_RESET)
return ipc_sm_state(IPC_SM_RESET);
dev_dbg(&context->sdev->dev,
"link %d: RX PAYLOAD %d bytes\n",
context->link->id, context->frame->len);
#ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_THROUGHPUT_MEASUREMENT
/* frame is received, increment link rx counter */
context->rx_bytes += context->frame->len;
#endif
/* decode L2 header */
frame_hdr = *(u32 *)context->frame->data;
l2_header = ipc_util_get_l2_channel(frame_hdr);
l2_length = ipc_util_get_l2_length(frame_hdr);
l2_data = (u8 *)context->frame->data + IPC_L2_HDR_SIZE;
context->frame->actual_len = l2_length + IPC_L2_HDR_SIZE;
ipc_dbg_dump_frame(&context->sdev->dev, context->link->id,
context->frame, false);
if (l2_length > (context->frame->len - 4)) {
dev_err(&context->sdev->dev,
"link %d: suspicious frame: L1 len %d L2 len %d\n",
context->link->id, context->frame->len, l2_length);
}
dev_dbg(&context->sdev->dev,
"link %d: L2 PDU decode: header 0x%08x channel %d length %d "
"data[%02x%02x%02x...]\n",
context->link->id, frame_hdr, l2_header, l2_length,
l2_data[0], l2_data[1], l2_data[2]);
if (ipc_util_channel_is_loopback(l2_header))
ipc_dbg_verify_rx_frame(context);
/* pass received frame up to L2mux layer */
if (!modem_protocol_channel_is_open(l2_header)) {
dev_err(&context->sdev->dev,
"link %d error: received frame on invalid channel %d, "
"frame discarded\n",
context->link->id, l2_header);
} else {
#ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_THROUGHPUT_MEASUREMENT
/*
* Discard loopback frames if we are taking throughput
* measurements - we'll be loading the links and so will likely
* overload the buffers.
*/
if (!ipc_util_channel_is_loopback(l2_header))
#endif
modem_m6718_spi_receive(context->sdev,
l2_header, l2_length, l2_data);
}
/* data is copied by L2mux so free the frame here */
ipc_queue_delete_frame(context->frame);
context->frame = NULL;
/* check tx queue for content */
if (!ipc_queue_is_empty(context)) {
dev_dbg(&context->sdev->dev,
"link %d: tx queue not empty\n", context->link->id);
return ipc_sm_state(IPC_SM_SLW_TX_WR_CMD);
} else {
dev_dbg(&context->sdev->dev,
"link %d: tx queue empty\n", context->link->id);
return ipc_sm_state(IPC_SM_SLW_TX_RD_CMD);
}
}
static const struct ipc_sm_state *sm_act_rx_wr_dat_aud_exit(u8 event,
struct ipc_link_context *context)
{
u32 frame_hdr;
unsigned char l2_header;
unsigned int l2_length;
u8 *l2_data;
if (event == IPC_SM_RUN_RESET)
return ipc_sm_state(IPC_SM_RESET_AUD);
dev_dbg(&context->sdev->dev,
"link %d: RX PAYLOAD %d bytes\n",
context->link->id, context->frame->len);
/* decode L2 header */
frame_hdr = *(u32 *)context->frame->data;
l2_header = ipc_util_get_l2_channel(frame_hdr);
l2_length = ipc_util_get_l2_length(frame_hdr);
l2_data = (u8 *)context->frame->data + IPC_L2_HDR_SIZE;
#ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_THROUGHPUT_MEASUREMENT
/* frame is received, increment link rx counter */
context->rx_bytes += l2_length;
#endif
if (frame_hdr != 0)
context->frame->actual_len = l2_length + IPC_L2_HDR_SIZE;
else
context->frame->actual_len = 0;
ipc_dbg_dump_frame(&context->sdev->dev, context->link->id,
context->frame, false);
if (l2_length > (context->frame->len - 4))
dev_err(&context->sdev->dev,
"link %d: suspicious frame: L1 len %d L2 len %d\n",
context->link->id, context->frame->len, l2_length);
dev_dbg(&context->sdev->dev,
"link %d: L2 PDU decode: header 0x%08x channel %d length %d "
"data[%02x%02x%02x...]\n",
context->link->id, frame_hdr, l2_header, l2_length,
l2_data[0], l2_data[1], l2_data[2]);
if (ipc_util_channel_is_loopback(l2_header))
ipc_dbg_verify_rx_frame(context);
/* did the slave actually have anything to send? */
if (frame_hdr != 0) {
/* pass received frame up to L2mux layer */
if (!modem_protocol_channel_is_open(l2_header)) {
dev_err(&context->sdev->dev,
"link %d error: received frame on invalid "
"channel %d, frame discarded\n",
context->link->id, l2_header);
} else {
#ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_THROUGHPUT_MEASUREMENT
/*
* Discard loopback frames if we are taking throughput
* measurements - we'll be loading the links and so will
* likely overload the buffers.
*/
if (!ipc_util_channel_is_loopback(l2_header))
#endif
modem_m6718_spi_receive(context->sdev,
l2_header, l2_length, l2_data);
}
} else {
dev_dbg(&context->sdev->dev,
"link %d: received dummy frame, discarding\n",
context->link->id);
}
/* data is copied by L2mux so free the frame here */
ipc_queue_delete_frame(context->frame);
context->frame = NULL;
/* audio link goes idle ready for next transaction */
return ipc_sm_state(IPC_SM_IDL_AUD);
}
static u8 sm_halt_enter(u8 event, struct ipc_link_context *context)
{
dev_err(&context->sdev->dev,
"link %d error: HALTED\n", context->link->id);
#ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_MODEM_STATE
/*
* Force modem reset, this will cause a reset event from the modemstate
* driver which will reset the links. If debugfs is enabled then there
* is a userspace file which controls whether MSR is enabled or not.
*/
#ifdef CONFIG_DEBUG_FS
if (l1_context.msr_disable) {
dev_info(&context->sdev->dev,
"link %d: MSR is disabled by user, "
"not requesting modem reset\n", context->link->id);
return IPC_SM_RUN_RESET;
}
#endif
modem_state_force_reset();
#endif
return IPC_SM_RUN_RESET;
}
static const struct ipc_sm_state *sm_halt_exit(u8 event,
struct ipc_link_context *context)
{
return ipc_sm_state(IPC_SM_RESET);
}
static const struct ipc_sm_state *sm_halt_aud_exit(u8 event,
struct ipc_link_context *context)
{
return ipc_sm_state(IPC_SM_RESET_AUD);
}
static u8 sm_reset_enter(u8 event, struct ipc_link_context *context)
{
dev_err(&context->sdev->dev,
"link %d resetting\n", context->link->id);
if (context->link->id == 0)
ipc_broadcast_modem_reset(context);
ipc_util_deactivate_ss(context);
ipc_queue_reset(context);
if (context->frame != NULL) {
ipc_queue_delete_frame(context->frame);
context->frame = NULL;
}
#ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_VERIFY_FRAMES
if (context->last_frame != NULL) {
ipc_queue_delete_frame(context->last_frame);
context->last_frame = NULL;
}
#endif
dev_dbg(&context->sdev->dev,
"link %d reset completed\n", context->link->id);
return IPC_SM_RUN_RESET;
}
static const struct ipc_sm_state *sm_reset_exit(u8 event,
struct ipc_link_context *context)
{
return ipc_sm_state(IPC_SM_INIT);
}
static const struct ipc_sm_state *sm_reset_aud_exit(u8 event,
struct ipc_link_context *context)
{
return ipc_sm_state(IPC_SM_INIT_AUD);
}
static u8 sm_slw_tx_bootreq_enter(u8 event, struct ipc_link_context *context)
{
dev_info(&context->sdev->dev,
"link %d: waiting for boot sync\n", context->link->id);
ipc_util_activate_ss(context);
context->cmd = ipc_util_make_l1_header(CMD_BOOTREQ, 0,
IPC_DRIVER_VERSION);
dev_dbg(&context->sdev->dev,
"link %d: TX HEADER cmd %08x (type %x)\n",
context->link->id,
context->cmd,
ipc_util_get_l1_cmd(context->cmd));
ipc_util_spi_message_prepare(context, &context->cmd,
NULL, IPC_L1_HDR_SIZE);
/* wait now for the slave to indicate ready... */
return IPC_SM_RUN_NONE;
}
static const struct ipc_sm_state *sm_slw_tx_bootreq_exit(u8 event,
struct ipc_link_context *context)
{
return ipc_sm_state(IPC_SM_ACT_TX_BOOTREQ);
}
static u8 sm_act_tx_bootreq_enter(u8 event, struct ipc_link_context *context)
{
int err;
/* slave is ready - start the spi transfer */
dev_dbg(&context->sdev->dev,
"link %d: starting spi tfr\n", context->link->id);
err = spi_async(context->sdev, &context->spi_message);
if (err < 0) {
dev_err(&context->sdev->dev,
"link %d error: spi tfr start failed, error %d\n",
context->link->id, err);
return IPC_SM_RUN_ABORT;
}
return IPC_SM_RUN_NONE;
}
static const struct ipc_sm_state *sm_act_tx_bootreq_exit(u8 event,
struct ipc_link_context *context)
{
return ipc_sm_state(IPC_SM_SLW_RX_BOOTRESP);
}
static u8 sm_slw_rx_bootresp_enter(u8 event, struct ipc_link_context *context)
{
/* prepare to receive BOOTRESP frame header */
ipc_util_spi_message_prepare(context, NULL,
&context->cmd, IPC_L1_HDR_SIZE);
/* slave might already have signalled ready to transmit */
if (atomic_read(&context->state_int)) {
dev_dbg(&context->sdev->dev,
"link %d: slave has already signalled ready\n",
context->link->id);
ipc_util_activate_ss(context);
return IPC_SM_RUN_SLAVE_IRQ;
} else {
ipc_util_activate_ss_with_tmo(context);
return IPC_SM_RUN_NONE;
}
}
static const struct ipc_sm_state *sm_slw_rx_bootresp_exit(u8 event,
struct ipc_link_context *context)
{
if (event == IPC_SM_RUN_COMMS_TMO) {
/*
* Modem timeout: was it really ready or just noise?
* Revert to waiting for handshake to start.
*/
ipc_util_deactivate_ss(context);
return ipc_sm_state(IPC_SM_SLW_TX_BOOTREQ);
} else {
return ipc_sm_state(IPC_SM_ACT_RX_BOOTRESP);
}
}
static u8 sm_act_rx_bootresp_enter(u8 event, struct ipc_link_context *context)
{
int err;
/* slave is ready - start the spi transfer */
dev_dbg(&context->sdev->dev,
"link %d: starting spi tfr\n", context->link->id);
err = spi_async(context->sdev, &context->spi_message);
if (err < 0) {
dev_err(&context->sdev->dev,
"link %d error: spi tfr start failed, error %d\n",
context->link->id, err);
return IPC_SM_RUN_ABORT;
}
return IPC_SM_RUN_NONE;
}
static const struct ipc_sm_state *sm_act_rx_bootresp_exit(u8 event,
struct ipc_link_context *context)
{
u8 cmd_type = ipc_util_get_l1_cmd(context->cmd);
u8 modem_ver;
dev_dbg(&context->sdev->dev,
"link %d: RX HEADER %08x (type %d)\n",
context->link->id, context->cmd, cmd_type);
if (cmd_type == CMD_BOOTRESP) {
modem_ver = ipc_util_get_l1_bootresp_ver(context->cmd);
dev_info(&context->sdev->dev,
"link %d: boot sync done; "
"APE version %02x, MODEM version %02x\n",
context->link->id, IPC_DRIVER_VERSION, modem_ver);
/* check for minimum required modem version */
if (modem_ver < IPC_DRIVER_MODEM_MIN_VER) {
dev_warn(&context->sdev->dev,
"link %d warning: modem version mismatch! "
"minimum required version is %02x\n",
context->link->id,
IPC_DRIVER_MODEM_MIN_VER);
}
return ipc_sm_state(IPC_SM_WAIT_HANDSHAKE_INACTIVE);
} else {
/* invalid response... this is not our slave */
dev_err(&context->sdev->dev,
"link %d error: expected %x (BOOTRESP), received %x.\n",
context->link->id,
CMD_BOOTRESP,
cmd_type);
return ipc_sm_state(IPC_SM_HALT);
}
}
/* the driver protocol state machine */
static const struct ipc_sm_state state_machine[IPC_SM_STATE_ID_NBR] = {
[IPC_SM_INIT] = {
.id = IPC_SM_INIT,
.enter = sm_init_enter,
.exit = sm_init_exit,
.events = IPC_SM_RUN_INIT | IPC_SM_RUN_RESET
},
[IPC_SM_HALT] = {
.id = IPC_SM_HALT,
.enter = sm_halt_enter,
.exit = sm_halt_exit,
.events = IPC_SM_RUN_RESET
},
[IPC_SM_RESET] = {
.id = IPC_SM_RESET,
.enter = sm_reset_enter,
.exit = sm_reset_exit,
.events = IPC_SM_RUN_RESET
},
[IPC_SM_WAIT_SLAVE_STABLE] = {
.id = IPC_SM_WAIT_SLAVE_STABLE,
.enter = sm_wait_slave_stable_enter,
.exit = sm_wait_slave_stable_exit,
.events = IPC_SM_RUN_STABLE_TMO
},
[IPC_SM_WAIT_HANDSHAKE_INACTIVE] = {
.id = IPC_SM_WAIT_HANDSHAKE_INACTIVE,
.enter = sm_wait_handshake_inactive_enter,
.exit = sm_wait_handshake_inactive_exit,
.events = IPC_SM_RUN_STABLE_TMO
},
[IPC_SM_SLW_TX_BOOTREQ] = {
.id = IPC_SM_SLW_TX_BOOTREQ,
.enter = sm_slw_tx_bootreq_enter,
.exit = sm_slw_tx_bootreq_exit,
.events = IPC_SM_RUN_SLAVE_IRQ
},
[IPC_SM_ACT_TX_BOOTREQ] = {
.id = IPC_SM_ACT_TX_BOOTREQ,
.enter = sm_act_tx_bootreq_enter,
.exit = sm_act_tx_bootreq_exit,
.events = IPC_SM_RUN_TFR_COMPLETE
},
[IPC_SM_SLW_RX_BOOTRESP] = {
.id = IPC_SM_SLW_RX_BOOTRESP,
.enter = sm_slw_rx_bootresp_enter,
.exit = sm_slw_rx_bootresp_exit,
.events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_COMMS_TMO
},
[IPC_SM_ACT_RX_BOOTRESP] = {
.id = IPC_SM_ACT_RX_BOOTRESP,
.enter = sm_act_rx_bootresp_enter,
.exit = sm_act_rx_bootresp_exit,
.events = IPC_SM_RUN_TFR_COMPLETE
},
[IPC_SM_IDL] = {
.id = IPC_SM_IDL,
.enter = sm_idl_enter,
.exit = sm_idl_exit,
.events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_TX_REQ |
IPC_SM_RUN_RESET
},
[IPC_SM_SLW_TX_WR_CMD] = {
.id = IPC_SM_SLW_TX_WR_CMD,
.enter = sm_slw_tx_wr_cmd_enter,
.exit = sm_slw_tx_wr_cmd_exit,
.events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_COMMS_TMO |
IPC_SM_RUN_RESET
},
[IPC_SM_ACT_TX_WR_CMD] = {
.id = IPC_SM_ACT_TX_WR_CMD,
.enter = sm_act_tx_wr_cmd_enter,
.exit = sm_act_tx_wr_cmd_exit,
.events = IPC_SM_RUN_TFR_COMPLETE | IPC_SM_RUN_RESET
},
[IPC_SM_SLW_TX_WR_DAT] = {
.id = IPC_SM_SLW_TX_WR_DAT,
.enter = sm_slw_tx_wr_dat_enter,
.exit = sm_slw_tx_wr_dat_exit,
.events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_COMMS_TMO |
IPC_SM_RUN_RESET
},
[IPC_SM_ACT_TX_WR_DAT] = {
.id = IPC_SM_ACT_TX_WR_DAT,
.enter = sm_act_tx_wr_dat_enter,
.exit = sm_act_tx_wr_dat_exit,
.events = IPC_SM_RUN_TFR_COMPLETE | IPC_SM_RUN_RESET
},
[IPC_SM_SLW_TX_RD_CMD] = {
.id = IPC_SM_SLW_TX_RD_CMD,
.enter = sm_slw_tx_rd_cmd_enter,
.exit = sm_slw_tx_rd_cmd_exit,
.events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_COMMS_TMO |
IPC_SM_RUN_RESET
},
[IPC_SM_ACT_TX_RD_CMD] = {
.id = IPC_SM_ACT_TX_RD_CMD,
.enter = sm_act_tx_rd_cmd_enter,
.exit = sm_act_tx_rd_cmd_exit,
.events = IPC_SM_RUN_TFR_COMPLETE | IPC_SM_RUN_RESET
},
[IPC_SM_SLW_RX_WR_CMD] = {
.id = IPC_SM_SLW_RX_WR_CMD,
.enter = sm_slw_rx_wr_cmd_enter,
.exit = sm_slw_rx_wr_cmd_exit,
.events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_COMMS_TMO |
IPC_SM_RUN_RESET
},
[IPC_SM_ACT_RX_WR_CMD] = {
.id = IPC_SM_ACT_RX_WR_CMD,
.enter = sm_act_rx_wr_cmd_enter,
.exit = sm_act_rx_wr_cmd_exit,
.events = IPC_SM_RUN_TFR_COMPLETE | IPC_SM_RUN_RESET
},
[IPC_SM_ACT_RX_WR_DAT] = {
.id = IPC_SM_ACT_RX_WR_DAT,
.enter = sm_act_rx_wr_dat_enter,
.exit = sm_act_rx_wr_dat_exit,
.events = IPC_SM_RUN_TFR_COMPLETE | IPC_SM_RUN_RESET
},
/* audio link states below */
[IPC_SM_INIT_AUD] = {
.id = IPC_SM_INIT_AUD,
.enter = sm_init_enter,
.exit = sm_init_aud_exit,
.events = IPC_SM_RUN_INIT | IPC_SM_RUN_RESET
},
[IPC_SM_HALT_AUD] = {
.id = IPC_SM_HALT_AUD,
.enter = sm_halt_enter,
.exit = sm_halt_aud_exit,
.events = IPC_SM_RUN_RESET
},
[IPC_SM_RESET_AUD] = {
.id = IPC_SM_RESET_AUD,
.enter = sm_reset_enter,
.exit = sm_reset_aud_exit,
.events = IPC_SM_RUN_RESET
},
[IPC_SM_IDL_AUD] = {
.id = IPC_SM_IDL_AUD,
.enter = sm_idl_enter,
.exit = sm_idl_aud_exit,
.events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_TX_REQ |
IPC_SM_RUN_RESET
},
[IPC_SM_SLW_TX_WR_DAT_AUD] = {
.id = IPC_SM_SLW_TX_WR_DAT_AUD,
.enter = sm_slw_tx_wr_dat_aud_enter,
.exit = sm_slw_tx_wr_dat_aud_exit,
.events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_COMMS_TMO |
IPC_SM_RUN_RESET
},
[IPC_SM_ACT_TX_WR_DAT_AUD] = {
.id = IPC_SM_ACT_TX_WR_DAT_AUD,
.enter = sm_act_tx_wr_dat_enter,
.exit = sm_act_tx_wr_dat_aud_exit,
.events = IPC_SM_RUN_TFR_COMPLETE | IPC_SM_RUN_RESET
},
[IPC_SM_SLW_RX_WR_DAT_AUD] = {
.id = IPC_SM_SLW_RX_WR_DAT_AUD,
.enter = sm_slw_rx_wr_dat_aud_enter,
.exit = sm_slw_rx_wr_dat_aud_exit,
.events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_COMMS_TMO |
IPC_SM_RUN_RESET
},
[IPC_SM_ACT_RX_WR_DAT_AUD] = {
.id = IPC_SM_ACT_RX_WR_DAT_AUD,
.enter = sm_act_rx_wr_dat_aud_enter,
.exit = sm_act_rx_wr_dat_aud_exit,
.events = IPC_SM_RUN_TFR_COMPLETE | IPC_SM_RUN_RESET
}
};
const struct ipc_sm_state *ipc_sm_idle_state(struct ipc_link_context *context)
{
if (context->link->id == IPC_LINK_AUDIO)
return ipc_sm_state(IPC_SM_IDL_AUD);
else
return ipc_sm_state(IPC_SM_IDL);
}
const struct ipc_sm_state *ipc_sm_init_state(struct ipc_link_context *context)
{
if (context->link->id == IPC_LINK_AUDIO)
return ipc_sm_state(IPC_SM_INIT_AUD);
else
return ipc_sm_state(IPC_SM_INIT);
}
const struct ipc_sm_state *ipc_sm_state(u8 id)
{
BUG_ON(id >= IPC_SM_STATE_ID_NBR);
return &state_machine[id];
}
bool ipc_sm_valid_for_state(u8 event, const struct ipc_sm_state *state)
{
return (state->events & event) == event;
}
static void state_machine_run(struct ipc_link_context *context, u8 event)
{
struct modem_m6718_spi_link_platform_data *link = context->link;
struct spi_device *sdev = context->sdev;
const struct ipc_sm_state *cur_state = context->state;
/* some sanity checking */
if (context == NULL || link == NULL || cur_state == NULL) {
pr_err("M6718 IPC protocol error: "
"inconsistent driver state, ignoring event\n");
return;
}
dev_dbg(&sdev->dev, "link %d: RUNNING in %s (%s)\n", link->id,
ipc_dbg_state_id(cur_state), ipc_dbg_event(event));
/* valid trigger event for current state? */
if (!ipc_sm_valid_for_state(event, cur_state)) {
dev_dbg(&sdev->dev,
"link %d: ignoring invalid event\n", link->id);
ipc_dbg_ignoring_event(context, event);
return;
}
ipc_dbg_handling_event(context, event);
/* run machine while state entry functions trigger new changes */
do {
if (event == IPC_SM_RUN_SLAVE_IRQ &&
!ipc_util_int_is_active(context)) {
dev_err(&sdev->dev,
"link %d error: slave is not ready! (%s)",
link->id,
ipc_dbg_state_id(cur_state));
}
if (event == IPC_SM_RUN_ABORT) {
dev_err(&sdev->dev,
"link %d error: abort event\n", link->id);
/* reset state to idle */
context->state = ipc_sm_idle_state(context);
break;
} else {
/* exit current state */
dev_dbg(&sdev->dev, "link %d: exit %s (%s)\n",
link->id, ipc_dbg_state_id(cur_state),
ipc_dbg_event(event));
cur_state = cur_state->exit(event, context);
context->state = cur_state;
}
/* reset state of slave irq to prepare for next event */
if (event == IPC_SM_RUN_SLAVE_IRQ)
atomic_set(&context->state_int, 0);
/* enter new state */
dev_dbg(&sdev->dev, "link %d: enter %s (%s)\n", link->id,
ipc_dbg_state_id(cur_state), ipc_dbg_event(event));
event = context->state->enter(event, context);
ipc_dbg_entering_state(context);
} while (event != IPC_SM_RUN_NONE);
dev_dbg(&sdev->dev, "link %d: STOPPED in %s\n", link->id,
ipc_dbg_state_id(cur_state));
}
void ipc_sm_kick(u8 event, struct ipc_link_context *context)
{
unsigned long flags;
struct modem_m6718_spi_link_platform_data *link = context->link;
struct spi_device *sdev = context->sdev;
struct spi_message *msg = &context->spi_message;
u8 i;
spin_lock_irqsave(&context->sm_lock, flags);
switch (event) {
case IPC_SM_RUN_SLAVE_IRQ:
dev_dbg(&sdev->dev,
"link %d EVENT: slave-ready irq\n", link->id);
del_timer(&context->comms_timer);
atomic_set(&context->state_int,
ipc_util_int_is_active(context));
break;
case IPC_SM_RUN_TFR_COMPLETE:
dev_dbg(&sdev->dev,
"link %d EVENT: spi tfr complete (status %d len %d)\n",
link->id, msg->status, msg->actual_length);
ipc_dbg_dump_spi_tfr(context);
break;
case IPC_SM_RUN_COMMS_TMO:
{
char *statestr;
struct ipc_link_context *contexts = l1_context.device_context;
statestr = ipc_dbg_link_state_str(context);
dev_err(&sdev->dev,
"link %d EVENT: modem comms timeout (%s)!\n",
link->id, ipc_dbg_state_id(context->state));
if (statestr != NULL) {
dev_err(&sdev->dev, "%s", statestr);
kfree(statestr);
}
/* cancel all link timeout timers except this one */
for (i = 0; i < IPC_NBR_SUPPORTED_SPI_LINKS; i++)
if (contexts[i].link->id != link->id)
del_timer(&contexts[i].comms_timer);
break;
}
case IPC_SM_RUN_STABLE_TMO:
dev_dbg(&sdev->dev,
"link %d EVENT: slave-stable timeout\n", link->id);
break;
case IPC_SM_RUN_RESET:
dev_dbg(&sdev->dev,
"link %d EVENT: reset\n", link->id);
del_timer(&context->comms_timer);
break;
default:
break;
}
if (!ipc_util_link_is_suspended(context))
state_machine_run(context, event);
else
dev_dbg(&sdev->dev,
"link %d is suspended, waiting for resume\n", link->id);
spin_unlock_irqrestore(&context->sm_lock, flags);
}
| Java |
/*
** tr2latex - troff to LaTeX converter
** $Id: setups.h,v 1.1.1.1 1992/04/27 15:20:56 teuben Exp $
** COPYRIGHT (C) 1987 Kamal Al-Yahya, 1991,1992 Christian Engel
**
** Module: setups.h
**
** setup file
*/
#ifdef __TURBOC__
# ifndef __COMPACT__
# error "The COMPACT model is needed"
# endif
#endif
#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#include <stdlib.h>
#include <time.h>
#if defined(__TURBOC__) | defined(MSC)
# include <io.h> /* for type declarations */
#endif
#ifdef UCB
# include <strings.h>
#else
# include <string.h>
#endif
#ifdef VMS
# define GOOD 1
#else
# define GOOD 0
#endif
#ifdef __TURBOC__
/*--- ONE MEGABYTE for EACH BUFFER? Really? - not for a brain-dead cpu
like the 8086 or 80286. Would my account on the VAX let me have
this much?
Maybe, one day when we all have an 80386+, or a SPARC, or a real
cpu.... ---*/
#define MAXLEN (0xfff0) /* maximum length of document */
/* A segment is 64k bytes! */
#else
/* ... but no problem on virtual operating systems */
#define MAXLEN (1024*1024) /* maximum length of document */
#endif
#define MAXWORD 250 /* maximum word length */
#define MAXLINE 500 /* maximum line length */
#define MAXDEF 200 /* maximum number of defines */
#define MAXARGS 128 /* maximal number of arguments */
#define EOS '\0' /* end of string */
#if defined(__TURBOC__) | defined (VAXC)
# define index strchr
#endif
#ifdef MAIN /* can only declare globals once */
# define GLOBAL
#else
# define GLOBAL extern
#endif
GLOBAL int math_mode, /* math mode status */
de_arg, /* .de argument */
IP_stat, /* IP status */
QP_stat, /* QP status */
TP_stat; /* TP status */
#ifdef DEBUG
GLOBAL int debug_o;
GLOBAL int debug_v;
#endif
GLOBAL struct defs {
char *def_macro;
char *replace;
int illegal;
} def[MAXDEF];
GLOBAL struct mydefs {
char *def_macro;
char *replace;
int illegal;
int arg_no;
int par; /* if it impiles (or contains) a par break */
} mydef[MAXDEF];
GLOBAL struct measure {
char old_units[MAXWORD]; float old_value;
char units[MAXWORD]; float value;
char def_units[MAXWORD]; /* default units */
int def_value; /* default value: 0 means take last one */
} linespacing, indent, tmpind, space, vspace;
typedef unsigned char bool;
extern int errno;
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/js.cookie.js"></script>
<title>BenchmarkTest00250</title>
</head>
<body>
<form action="/benchmark/BenchmarkTest00250" method="POST" id="FormBenchmarkTest00250">
<div><label>Please explain your answer:</label></div>
<br/>
<div><textarea rows="4" cols="50" id="vectorArea" name="vectorArea" value=""></textarea></div>
<div><label>Any additional note for the reviewer:</label></div>
<div><input type="text" id="answer" name="answer"></input></div>
<br/>
<div><label>An AJAX request will be sent with a header named vector and value:</label>
<input type="text" id="vector" name="vector" value="color" class="safe"></input></div>
<div><input type="button" id="login-btn" value="Login" /></div>
</form>
<div id="ajax-form-msg1"><pre><code class="prettyprint" id="code"></code></pre></div>
<script>
$('.safe').keypress(function (e) {
if (e.which == 13) {
$('#login-btn').trigger('click');
return false;
}
});
$("#login-btn").click(function(){
var formData = $("#FormBenchmarkTest00250").serializeArray();
var URL = $("#FormBenchmarkTest00250").attr("action");
var text = $("#FormBenchmarkTest00250 input[id=vector]").val();
$.ajax({
beforeSend: function (request){
request.setRequestHeader($("#FormBenchmarkTest00250 input[id=vector]").val(), 'vector');
},
url : URL,
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR){
$("#code").text(data);
},
error: function (jqXHR, textStatus, errorThrown){ console.error(errorThrown);}
});
});
</script>
</body>
</html>
| Java |
#!/usr/bin/python
#CHANGE ONLY, IF YOU KNOW, WHAT YOU DO!
#OPKMANAGER WILL CRASH IF YOUR OUTPUT IS INVALID!
import subprocess
import argparse
import time
import calendar
import string
import sys
class RegisterAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
print "Official Repository" # Name
print "web" # Type (maybe web for web, or anything else for usb)
print "http://www.gcw-zero.com/files/upload/opk/" #URL
print "official.py --update" #Call for updating the list
print "O" #letter to show
class UpdateAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
process = subprocess.Popen('wget --timeout='+str(values[0])+' -qO- http://ziz.gp2x.de/gcw-repos/count.php',stdout=subprocess.PIPE,shell=True)
process = subprocess.Popen('wget --timeout='+str(values[0])+' -qO- http://www.gcw-zero.com/downloads',stdout=subprocess.PIPE,shell=True)
#process = subprocess.Popen('wget --timeout='+str(values[0])+' -qO- http://ziz.gp2x.de/temp/test.htm',stdout=subprocess.PIPE,shell=True)
#process = subprocess.Popen('cat downloads',stdout=subprocess.PIPE,shell=True)
output = process.stdout.read().split('<div class="downloads_overview">')
for output_part in output:
part = output_part.split('\n')
line_number = 0;
not_found = 1;
while (line_number < len(part)):
if (part[line_number].strip().startswith('<span class="downloads_title">')):
not_found = 0;
break;
line_number += 1;
if not_found:
continue;
program_name_description = part[line_number];
name = program_name_description.split('>')[1].split('<')[0];
if (name == ""):
continue
line_number = 0;
not_found = 1;
while (line_number < len(part)):
if (part[line_number].strip().startswith('<a class="downloads_link"')):
not_found = 0;
break;
line_number += 1;
if not_found:
continue;
filename = part[line_number].split('href="file.php?file=')[1].split('">')[0];
print "["+name+"]"
description = program_name_description.split('>')[3];
print "description: "+description
print "filename: " + filename
l = len(part)
found_version = 0
found_image = 0
found_long = 0;
for i in range(0,l-1):
if string.find(part[i],'Publication Date') != -1:
version = part[i+1]
version = version.split('>')[1]
version = version.split('<')[0]
t = time.strptime(version,"%A, %d %b %Y")
print "version: " + str(calendar.timegm(t)) #NEEDED!
found_version = 1
if string.find(part[i],'<div class="downloads_preview"') != -1:
image = part[i];
image = image.split("background-image: url('")[1].split("');")[0];
print "image_url: http://www.gcw-zero.com/" + image
if string.find(part[i],'<p class="more fade">') != -1:
long_description = part[i];
long_description = long_description.split('<p class="more fade">')[1].split("</p>")[0];
long_description = long_description.replace('<br /> ','\\n')
long_description = long_description.split('>')
sys.stdout.write("long_description: ")
for long_description_part in long_description:
sys.stdout.write(long_description_part.split('<')[0])
sys.stdout.write('\n')
found_long = 1
if (found_version and found_image and found_long):
break
print ""
def main():
parser = argparse.ArgumentParser(description="Ziz's Repository script")
parser.add_argument('--register', nargs=0, action=RegisterAction)
parser.add_argument('--update', nargs=1, action=UpdateAction)
args = parser.parse_args()
if __name__ == "__main__":
main()
| Java |
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log: CMAny.hpp,v $
* Revision 1.2 2001/05/11 13:27:14 tng
* Copyright update.
*
* Revision 1.1 2001/02/27 14:48:46 tng
* Schema: Add CMAny and ContentLeafNameTypeVector, by Pei Yong Zhang
*
*/
#if !defined(CMANY_HPP)
#define CMANY_HPP
#include <util/XercesDefs.hpp>
#include <validators/common/CMNode.hpp>
class CMStateSet;
class CMAny : public CMNode
{
public :
// -----------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------
CMAny
(
const ContentSpecNode::NodeTypes type
, const unsigned int URI
, const unsigned int position
);
~CMAny();
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
unsigned int getURI() const;
unsigned int getPosition() const;
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
void setPosition(const unsigned int newPosition);
// -----------------------------------------------------------------------
// Implementation of the public CMNode virtual interface
// -----------------------------------------------------------------------
bool isNullable() const;
protected :
// -----------------------------------------------------------------------
// Implementation of the protected CMNode virtual interface
// -----------------------------------------------------------------------
void calcFirstPos(CMStateSet& toSet) const;
void calcLastPos(CMStateSet& toSet) const;
private :
// -----------------------------------------------------------------------
// Private data members
//
// fURI;
// URI of the any content model. This value is set if the type is
// of the following:
// XMLContentSpec.CONTENTSPECNODE_ANY,
// XMLContentSpec.CONTENTSPECNODE_ANY_OTHER.
//
// fPosition
// Part of the algorithm to convert a regex directly to a DFA
// numbers each leaf sequentially. If its -1, that means its an
// epsilon node. Zero and greater are non-epsilon positions.
// -----------------------------------------------------------------------
unsigned int fURI;
unsigned int fPosition;
};
#endif
| Java |
<?php // $Id: report.php,v 1.29 2008/11/30 21:33:58 skodak Exp $
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
$courses = get_courses('all','c.shortname','c.id,c.shortname,c.fullname');
$courseoptions = array();
foreach ($courses as $c) {
$context = get_context_instance(CONTEXT_COURSE, $c->id);
if (has_capability('coursereport/stats:view', $context)) {
$courseoptions[$c->id] = $c->shortname;
}
}
$reportoptions = stats_get_report_options($course->id, $mode);
$timeoptions = report_stats_timeoptions($mode);
if (empty($timeoptions)) {
print_error('nostatstodisplay', '', $CFG->wwwroot.'/course/view.php?id='.$course->id);
}
$table->width = 'auto';
if ($mode == STATS_MODE_DETAILED) {
$param = stats_get_parameters($time,null,$course->id,$mode); // we only care about the table and the time string (if we have time)
//TODO: lceanup this ugly mess
$sql = 'SELECT DISTINCT s.userid, u.firstname, u.lastname, u.idnumber
FROM {stats_user_'.$param->table.'} s
JOIN {user} u ON u.id = s.userid
WHERE courseid = '.$course->id
. ((!empty($param->stattype)) ? ' AND stattype = \''.$param->stattype.'\'' : '')
. ((!empty($time)) ? ' AND timeend >= '.$param->timeafter : '')
.' ORDER BY u.lastname, u.firstname ASC';
if (!$us = $DB->get_records_sql($sql, $param->params)) {
print_error('nousers');
}
foreach ($us as $u) {
$users[$u->userid] = fullname($u, true);
}
$table->align = array('left','left','left','left','left','left','left','left');
$table->data[] = array(get_string('course'),choose_from_menu($courseoptions,'course',$course->id,'','','',true),
get_string('users'),choose_from_menu($users,'userid',$userid,'','','',true),
get_string('statsreporttype'),choose_from_menu($reportoptions,'report',($report == 5) ? $report.$roleid : $report,'','','',true),
get_string('statstimeperiod'),choose_from_menu($timeoptions,'time',$time,'','','',true),
'<input type="submit" value="'.get_string('view').'" />') ;
} else if ($mode == STATS_MODE_RANKED) {
$table->align = array('left','left','left','left','left','left');
$table->data[] = array(get_string('statsreporttype'),choose_from_menu($reportoptions,'report',($report == 5) ? $report.$roleid : $report,'','','',true),
get_string('statstimeperiod'),choose_from_menu($timeoptions,'time',$time,'','','',true),
'<input type="submit" value="'.get_string('view').'" />') ;
} else if ($mode == STATS_MODE_GENERAL) {
$table->align = array('left','left','left','left','left','left','left');
$table->data[] = array(get_string('course'),choose_from_menu($courseoptions,'course',$course->id,'','','',true),
get_string('statsreporttype'),choose_from_menu($reportoptions,'report',($report == 5) ? $report.$roleid : $report,'','','',true),
get_string('statstimeperiod'),choose_from_menu($timeoptions,'time',$time,'','','',true),
'<input type="submit" value="'.get_string('view').'" />') ;
}
echo '<form action="index.php" method="post">'."\n"
.'<div>'."\n"
.'<input type="hidden" name="mode" value="'.$mode.'" />'."\n";
print_table($table);
echo '</div>';
echo '</form>';
if (!empty($report) && !empty($time)) {
if ($report == STATS_REPORT_LOGINS && $course->id != SITEID) {
print_error('reportnotavailable');
}
$param = stats_get_parameters($time,$report,$course->id,$mode);
if ($mode == STATS_MODE_DETAILED) {
$param->table = 'user_'.$param->table;
}
if (!empty($param->sql)) {
$sql = $param->sql;
} else {
//TODO: lceanup this ugly mess
$sql = 'SELECT '.((empty($param->fieldscomplete)) ? 'id,roleid,timeend,' : '').$param->fields
.' FROM {stats_'.$param->table.'} WHERE '
.(($course->id == SITEID) ? '' : ' courseid = '.$course->id.' AND ')
.((!empty($userid)) ? ' userid = '.$userid.' AND ' : '')
.((!empty($roleid)) ? ' roleid = '.$roleid.' AND ' : '')
. ((!empty($param->stattype)) ? ' stattype = \''.$param->stattype.'\' AND ' : '')
.' timeend >= '.$param->timeafter
.' '.$param->extras
.' ORDER BY timeend DESC';
}
$stats = $DB->get_records_sql($sql, $params);
if (empty($stats)) {
notify(get_string('statsnodata'));
} else {
$stats = stats_fix_zeros($stats,$param->timeafter,$param->table,(!empty($param->line2)));
print_heading(format_string($course->shortname).' - '.get_string('statsreport'.$report)
.((!empty($user)) ? ' '.get_string('statsreportforuser').' ' .fullname($user,true) : '')
.((!empty($roleid)) ? ' '.$DB->get_field('role','name', array('id'=>$roleid)) : ''));
if (empty($CFG->gdversion)) {
echo "(".get_string("gdneed").")";
} else {
if ($mode == STATS_MODE_DETAILED) {
echo '<div class="graph"><img src="'.$CFG->wwwroot.'/course/report/stats/graph.php?mode='.$mode.'&course='.$course->id.'&time='.$time.'&report='.$report.'&userid='.$userid.'" alt="'.get_string('statisticsgraph').'" /></div';
} else {
echo '<div class="graph"><img src="'.$CFG->wwwroot.'/course/report/stats/graph.php?mode='.$mode.'&course='.$course->id.'&time='.$time.'&report='.$report.'&roleid='.$roleid.'" alt="'.get_string('statisticsgraph').'" /></div>';
}
}
$table = new StdClass;
$table->align = array('left','center','center','center');
$param->table = str_replace('user_','',$param->table);
switch ($param->table) {
case 'daily' : $period = get_string('day'); break;
case 'weekly' : $period = get_string('week'); break;
case 'monthly': $period = get_string('month', 'form'); break;
default : $period = '';
}
$table->head = array(get_string('periodending','moodle',$period));
if (empty($param->crosstab)) {
$table->head[] = $param->line1;
if (!empty($param->line2)) {
$table->head[] = $param->line2;
}
}
if (empty($param->crosstab)) {
foreach ($stats as $stat) {
$a = array(userdate($stat->timeend-(60*60*24),get_string('strftimedate'),$CFG->timezone),$stat->line1);
if (isset($stat->line2)) {
$a[] = $stat->line2;
}
if (empty($CFG->loglifetime) || ($stat->timeend-(60*60*24)) >= (time()-60*60*24*$CFG->loglifetime)) {
if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE, $course->id))) {
$a[] = '<a href="'.$CFG->wwwroot.'/course/report/log/index.php?id='.
$course->id.'&chooselog=1&showusers=1&showcourses=1&user='
.$userid.'&date='.usergetmidnight($stat->timeend-(60*60*24)).'">'
.get_string('course').' ' .get_string('logs').'</a> ';
} else {
$a[] = '';
}
}
$table->data[] = $a;
}
} else {
$data = array();
$roles = array();
$times = array();
$missedlines = array();
$rolenames = get_all_roles();
foreach ($rolenames as $r) {
$rolenames[$r->id] = $r->name;
}
$rolenames = role_fix_names($rolenames, get_context_instance(CONTEXT_COURSE, $course->id));
foreach ($stats as $stat) {
if (!empty($stat->zerofixed)) {
$missedlines[] = $stat->timeend;
}
$data[$stat->timeend][$stat->roleid] = $stat->line1;
if ($stat->roleid != 0) {
if (!array_key_exists($stat->roleid,$roles)) {
$roles[$stat->roleid] = $rolenames[$stat->roleid];
}
} else {
if (!array_key_exists($stat->roleid,$roles)) {
$roles[$stat->roleid] = get_string('all');
}
}
if (!array_key_exists($stat->timeend,$times)) {
$times[$stat->timeend] = userdate($stat->timeend,get_string('strftimedate'),$CFG->timezone);
}
}
foreach ($data as $time => $rolesdata) {
if (in_array($time,$missedlines)) {
$rolesdata = array();
foreach ($roles as $roleid => $guff) {
$rolesdata[$roleid] = 0;
}
}
else {
foreach (array_keys($roles) as $r) {
if (!array_key_exists($r, $rolesdata)) {
$rolesdata[$r] = 0;
}
}
}
krsort($rolesdata);
$row = array_merge(array($times[$time]),$rolesdata);
if (empty($CFG->loglifetime) || ($stat->timeend-(60*60*24)) >= (time()-60*60*24*$CFG->loglifetime)) {
if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE, $course->id))) {
$row[] = '<a href="'.$CFG->wwwroot.'/course/report/log/index.php?id='
.$course->id.'&chooselog=1&showusers=1&showcourses=1&user='.$userid
.'&date='.usergetmidnight($time-(60*60*24)).'">'
.get_string('course').' ' .get_string('logs').'</a> ';
} else {
$row[] = '';
}
}
$table->data[] = $row;
}
krsort($roles);
$table->head = array_merge($table->head,$roles);
}
$table->head[] = get_string('logs');
if (!empty($lastrecord)) {
$lastrecord[] = $lastlink;
$table->data[] = $lastrecord;
}
print_table($table);
}
}
?>
| Java |
module Actions
module Pulp3
module Repository
class CreatePublication < Pulp3::AbstractAsyncTask
middleware.use Actions::Middleware::ExecuteIfContentsChanged
def plan(repository, smart_proxy, options)
sequence do
action = plan_self(:repository_id => repository.id, :smart_proxy_id => smart_proxy.id, :contents_changed => options[:contents_changed], :options => options)
plan_action(SavePublication, repository, action.output, :contents_changed => options[:contents_changed])
end
end
def invoke_external_task
repository = ::Katello::Repository.find(input[:repository_id])
smart_proxy = ::SmartProxy.find(input[:smart_proxy_id])
if repository.publication_href.nil? || input[:options][:force]
output[:response] = repository.backend_service(smart_proxy).create_publication
else
[]
end
end
end
end
end
end
| Java |
'use strict';
app.controller('orderController', ['$scope', '$rootScope', 'toastrService', 'orderService',
function ($scope, $rootScope, toastrService, orderService) {
$scope.paging = 1;
$scope.disabledMore = false;
$scope.data = [];
$scope.getOrders = function () {
orderService.get($scope.paging).then(function (data) {
if (data.length > 0) {
$scope.data.push.apply($scope.data, data);
} else {
$scope.disabledMore = true;
}
});
}
$scope.more = function () {
$scope.paging++;
$scope.getOrders();
};
$scope.refresh = function () {
$scope.paging = 1;
$scope.data = [];
$scope.getOrders();
};
$scope.getOrders();
$scope.openOrder = function (item, $index) {
$scope.order = item;
$scope.order.$index = $index;
$('#modal-order').modal({
backdrop: true
});
};
}
]); | Java |
obj-$(CONFIG_ICDTCP3_ITD) += itddrv.o
obj-$(CONFIG_ICDTCP3_LCD) += hd44780drv.o
obj-$(CONFIG_ICDTCP3) += icdcommon.o
| Java |
#!/usr/bin/env python
####################################
#
# --- TEXTPATGEN TEMPLATE ---
#
# Users can change the output by editing
# this file directly.
#
####################################
import sys
sys.stdout.write('####################################\n')
sys.stdout.write('#\n')
sys.stdout.write('# -- TEXTPATGEN GENERATED FILE --\n')
sys.stdout.write('#\n')
sys.stdout.write('# -- Created from a Python script.\n')
sys.stdout.write('#\n')
sys.stdout.write("####################################\n")
num=0
for length in range(0, 16):
for width in range(0, 15):
sys.stdout.write('X-%04X ' % num)
num=num+1
width=width+1
length=length+1
sys.stdout.write('X-%04X\n' % num)
num=num+1
sys.stdout.write('# -- End of file.\n');
sys.stdout.flush()
| Java |
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<title><?php
/*
* Print the <title> tag based on what is being viewed.
*/
global $page, $paged;
wp_title( '|', true, 'right' );
// Add the blog name.
bloginfo( 'name' );
// Add the blog description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
echo " | $site_description";
// Add a page number if necessary:
if ( $paged >= 2 || $page >= 2 )
echo ' | ' . sprintf( __( 'Page %s', 'twentyten' ), max( $paged, $page ) );
?></title>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" />
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo('template_url'); ?>/css/skin.css" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<?php
/* We add some JavaScript to pages with the comment form
* to support sites with threaded comments (when in use).
*/
if ( is_singular() && get_option( 'thread_comments' ) )
wp_enqueue_script( 'comment-reply' );
/* Always have wp_head() just before the closing </head>
* tag of your theme, or you will break many plugins, which
* generally use this hook to add elements to <head> such
* as styles, scripts, and meta tags.
*/
wp_head();
?>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/javascript/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/javascript/jquery.jcarousel.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#mycarousel').jcarousel({
scroll:3,
auto:5,
wrap:"both"
});
});
</script>
</head>
<a name="menu"></a>
<body <?php body_class(); ?>>
<div class="centralizarCorpo content">
<div class="header">
<div class='img_header_detalhe img_header_detalhe_size'>
<div class="img_header_logo_jzconsultoria img_header_logo_jzconsultoria_size"></div>
<div class="img_header_consultoria_treinamento img_header_consultoria_treinamento_size"></div>
</div>
<div class="img_header_menu img_header_menu_size"></div>
<div class="img_header_line img_header_line_size"></div>
<div class="menu">
<a class="bt_empresa" href="#empresa"><div class="img_header_bt1 img_header_bt1_size"></div></a>
<a class="bt_consultoria" href="#consultoria"><div class="img_header_bt2 img_header_bt2_size"></div></a>
<a class="bt_treinamentos" href="#treinamento"><div class="img_header_bt3 img_header_bt3_size"></div></a>
<a class="bt_clientes" href="#clientes"><div class="img_header_bt4 img_header_bt4_size"></div></a>
<a class="bt_contato" href="#contato"><div class="img_header_bt5 img_header_bt5_size"></div></a>
</div>
</div> | Java |
from .. import config
from .. import fixtures
from ..assertions import eq_
from ..assertions import in_
from ..schema import Column
from ..schema import Table
from ... import bindparam
from ... import case
from ... import Computed
from ... import exists
from ... import false
from ... import func
from ... import Integer
from ... import literal
from ... import literal_column
from ... import null
from ... import select
from ... import String
from ... import testing
from ... import text
from ... import true
from ... import tuple_
from ... import union
from ... import util
class CollateTest(fixtures.TablesTest):
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String(100)),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.some_table.insert(),
[
{"id": 1, "data": "collate data1"},
{"id": 2, "data": "collate data2"},
],
)
def _assert_result(self, select, result):
eq_(config.db.execute(select).fetchall(), result)
@testing.requires.order_by_collation
def test_collate_order_by(self):
collation = testing.requires.get_order_by_collation(testing.config)
self._assert_result(
select([self.tables.some_table]).order_by(
self.tables.some_table.c.data.collate(collation).asc()
),
[(1, "collate data1"), (2, "collate data2")],
)
class OrderByLabelTest(fixtures.TablesTest):
"""Test the dialect sends appropriate ORDER BY expressions when
labels are used.
This essentially exercises the "supports_simple_order_by_label"
setting.
"""
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
Column("x", Integer),
Column("y", Integer),
Column("q", String(50)),
Column("p", String(50)),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.some_table.insert(),
[
{"id": 1, "x": 1, "y": 2, "q": "q1", "p": "p3"},
{"id": 2, "x": 2, "y": 3, "q": "q2", "p": "p2"},
{"id": 3, "x": 3, "y": 4, "q": "q3", "p": "p1"},
],
)
def _assert_result(self, select, result):
eq_(config.db.execute(select).fetchall(), result)
def test_plain(self):
table = self.tables.some_table
lx = table.c.x.label("lx")
self._assert_result(select([lx]).order_by(lx), [(1,), (2,), (3,)])
def test_composed_int(self):
table = self.tables.some_table
lx = (table.c.x + table.c.y).label("lx")
self._assert_result(select([lx]).order_by(lx), [(3,), (5,), (7,)])
def test_composed_multiple(self):
table = self.tables.some_table
lx = (table.c.x + table.c.y).label("lx")
ly = (func.lower(table.c.q) + table.c.p).label("ly")
self._assert_result(
select([lx, ly]).order_by(lx, ly.desc()),
[(3, util.u("q1p3")), (5, util.u("q2p2")), (7, util.u("q3p1"))],
)
def test_plain_desc(self):
table = self.tables.some_table
lx = table.c.x.label("lx")
self._assert_result(
select([lx]).order_by(lx.desc()), [(3,), (2,), (1,)]
)
def test_composed_int_desc(self):
table = self.tables.some_table
lx = (table.c.x + table.c.y).label("lx")
self._assert_result(
select([lx]).order_by(lx.desc()), [(7,), (5,), (3,)]
)
@testing.requires.group_by_complex_expression
def test_group_by_composed(self):
table = self.tables.some_table
expr = (table.c.x + table.c.y).label("lx")
stmt = (
select([func.count(table.c.id), expr])
.group_by(expr)
.order_by(expr)
)
self._assert_result(stmt, [(1, 3), (1, 5), (1, 7)])
class LimitOffsetTest(fixtures.TablesTest):
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
Column("x", Integer),
Column("y", Integer),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.some_table.insert(),
[
{"id": 1, "x": 1, "y": 2},
{"id": 2, "x": 2, "y": 3},
{"id": 3, "x": 3, "y": 4},
{"id": 4, "x": 4, "y": 5},
],
)
def _assert_result(self, select, result, params=()):
eq_(config.db.execute(select, params).fetchall(), result)
def test_simple_limit(self):
table = self.tables.some_table
self._assert_result(
select([table]).order_by(table.c.id).limit(2),
[(1, 1, 2), (2, 2, 3)],
)
@testing.requires.offset
def test_simple_offset(self):
table = self.tables.some_table
self._assert_result(
select([table]).order_by(table.c.id).offset(2),
[(3, 3, 4), (4, 4, 5)],
)
@testing.requires.offset
def test_simple_limit_offset(self):
table = self.tables.some_table
self._assert_result(
select([table]).order_by(table.c.id).limit(2).offset(1),
[(2, 2, 3), (3, 3, 4)],
)
@testing.requires.offset
def test_limit_offset_nobinds(self):
"""test that 'literal binds' mode works - no bound params."""
table = self.tables.some_table
stmt = select([table]).order_by(table.c.id).limit(2).offset(1)
sql = stmt.compile(
dialect=config.db.dialect, compile_kwargs={"literal_binds": True}
)
sql = str(sql)
self._assert_result(sql, [(2, 2, 3), (3, 3, 4)])
@testing.requires.bound_limit_offset
def test_bound_limit(self):
table = self.tables.some_table
self._assert_result(
select([table]).order_by(table.c.id).limit(bindparam("l")),
[(1, 1, 2), (2, 2, 3)],
params={"l": 2},
)
@testing.requires.bound_limit_offset
def test_bound_offset(self):
table = self.tables.some_table
self._assert_result(
select([table]).order_by(table.c.id).offset(bindparam("o")),
[(3, 3, 4), (4, 4, 5)],
params={"o": 2},
)
@testing.requires.bound_limit_offset
def test_bound_limit_offset(self):
table = self.tables.some_table
self._assert_result(
select([table])
.order_by(table.c.id)
.limit(bindparam("l"))
.offset(bindparam("o")),
[(2, 2, 3), (3, 3, 4)],
params={"l": 2, "o": 1},
)
class CompoundSelectTest(fixtures.TablesTest):
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
Column("x", Integer),
Column("y", Integer),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.some_table.insert(),
[
{"id": 1, "x": 1, "y": 2},
{"id": 2, "x": 2, "y": 3},
{"id": 3, "x": 3, "y": 4},
{"id": 4, "x": 4, "y": 5},
],
)
def _assert_result(self, select, result, params=()):
eq_(config.db.execute(select, params).fetchall(), result)
def test_plain_union(self):
table = self.tables.some_table
s1 = select([table]).where(table.c.id == 2)
s2 = select([table]).where(table.c.id == 3)
u1 = union(s1, s2)
self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)])
def test_select_from_plain_union(self):
table = self.tables.some_table
s1 = select([table]).where(table.c.id == 2)
s2 = select([table]).where(table.c.id == 3)
u1 = union(s1, s2).alias().select()
self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)])
@testing.requires.order_by_col_from_union
@testing.requires.parens_in_union_contained_select_w_limit_offset
def test_limit_offset_selectable_in_unions(self):
table = self.tables.some_table
s1 = (
select([table])
.where(table.c.id == 2)
.limit(1)
.order_by(table.c.id)
)
s2 = (
select([table])
.where(table.c.id == 3)
.limit(1)
.order_by(table.c.id)
)
u1 = union(s1, s2).limit(2)
self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)])
@testing.requires.parens_in_union_contained_select_wo_limit_offset
def test_order_by_selectable_in_unions(self):
table = self.tables.some_table
s1 = select([table]).where(table.c.id == 2).order_by(table.c.id)
s2 = select([table]).where(table.c.id == 3).order_by(table.c.id)
u1 = union(s1, s2).limit(2)
self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)])
def test_distinct_selectable_in_unions(self):
table = self.tables.some_table
s1 = select([table]).where(table.c.id == 2).distinct()
s2 = select([table]).where(table.c.id == 3).distinct()
u1 = union(s1, s2).limit(2)
self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)])
@testing.requires.parens_in_union_contained_select_w_limit_offset
def test_limit_offset_in_unions_from_alias(self):
table = self.tables.some_table
s1 = (
select([table])
.where(table.c.id == 2)
.limit(1)
.order_by(table.c.id)
)
s2 = (
select([table])
.where(table.c.id == 3)
.limit(1)
.order_by(table.c.id)
)
# this necessarily has double parens
u1 = union(s1, s2).alias()
self._assert_result(
u1.select().limit(2).order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)]
)
def test_limit_offset_aliased_selectable_in_unions(self):
table = self.tables.some_table
s1 = (
select([table])
.where(table.c.id == 2)
.limit(1)
.order_by(table.c.id)
.alias()
.select()
)
s2 = (
select([table])
.where(table.c.id == 3)
.limit(1)
.order_by(table.c.id)
.alias()
.select()
)
u1 = union(s1, s2).limit(2)
self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)])
class ExpandingBoundInTest(fixtures.TablesTest):
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
Column("x", Integer),
Column("y", Integer),
Column("z", String(50)),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.some_table.insert(),
[
{"id": 1, "x": 1, "y": 2, "z": "z1"},
{"id": 2, "x": 2, "y": 3, "z": "z2"},
{"id": 3, "x": 3, "y": 4, "z": "z3"},
{"id": 4, "x": 4, "y": 5, "z": "z4"},
],
)
def _assert_result(self, select, result, params=()):
eq_(config.db.execute(select, params).fetchall(), result)
def test_multiple_empty_sets(self):
# test that any anonymous aliasing used by the dialect
# is fine with duplicates
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(table.c.x.in_(bindparam("q", expanding=True)))
.where(table.c.y.in_(bindparam("p", expanding=True)))
.order_by(table.c.id)
)
self._assert_result(stmt, [], params={"q": [], "p": []})
@testing.requires.tuple_in
def test_empty_heterogeneous_tuples(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(
tuple_(table.c.x, table.c.z).in_(
bindparam("q", expanding=True)
)
)
.order_by(table.c.id)
)
self._assert_result(stmt, [], params={"q": []})
@testing.requires.tuple_in
def test_empty_homogeneous_tuples(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(
tuple_(table.c.x, table.c.y).in_(
bindparam("q", expanding=True)
)
)
.order_by(table.c.id)
)
self._assert_result(stmt, [], params={"q": []})
def test_bound_in_scalar(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(table.c.x.in_(bindparam("q", expanding=True)))
.order_by(table.c.id)
)
self._assert_result(stmt, [(2,), (3,), (4,)], params={"q": [2, 3, 4]})
@testing.requires.tuple_in
def test_bound_in_two_tuple(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(
tuple_(table.c.x, table.c.y).in_(
bindparam("q", expanding=True)
)
)
.order_by(table.c.id)
)
self._assert_result(
stmt, [(2,), (3,), (4,)], params={"q": [(2, 3), (3, 4), (4, 5)]}
)
@testing.requires.tuple_in
def test_bound_in_heterogeneous_two_tuple(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(
tuple_(table.c.x, table.c.z).in_(
bindparam("q", expanding=True)
)
)
.order_by(table.c.id)
)
self._assert_result(
stmt,
[(2,), (3,), (4,)],
params={"q": [(2, "z2"), (3, "z3"), (4, "z4")]},
)
def test_empty_set_against_integer(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(table.c.x.in_(bindparam("q", expanding=True)))
.order_by(table.c.id)
)
self._assert_result(stmt, [], params={"q": []})
def test_empty_set_against_integer_negation(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(table.c.x.notin_(bindparam("q", expanding=True)))
.order_by(table.c.id)
)
self._assert_result(stmt, [(1,), (2,), (3,), (4,)], params={"q": []})
def test_empty_set_against_string(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(table.c.z.in_(bindparam("q", expanding=True)))
.order_by(table.c.id)
)
self._assert_result(stmt, [], params={"q": []})
def test_empty_set_against_string_negation(self):
table = self.tables.some_table
stmt = (
select([table.c.id])
.where(table.c.z.notin_(bindparam("q", expanding=True)))
.order_by(table.c.id)
)
self._assert_result(stmt, [(1,), (2,), (3,), (4,)], params={"q": []})
def test_null_in_empty_set_is_false(self):
stmt = select(
[
case(
[
(
null().in_(
bindparam("foo", value=(), expanding=True)
),
true(),
)
],
else_=false(),
)
]
)
in_(config.db.execute(stmt).fetchone()[0], (False, 0))
class LikeFunctionsTest(fixtures.TablesTest):
__backend__ = True
run_inserts = "once"
run_deletes = None
@classmethod
def define_tables(cls, metadata):
Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String(50)),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.some_table.insert(),
[
{"id": 1, "data": "abcdefg"},
{"id": 2, "data": "ab/cdefg"},
{"id": 3, "data": "ab%cdefg"},
{"id": 4, "data": "ab_cdefg"},
{"id": 5, "data": "abcde/fg"},
{"id": 6, "data": "abcde%fg"},
{"id": 7, "data": "ab#cdefg"},
{"id": 8, "data": "ab9cdefg"},
{"id": 9, "data": "abcde#fg"},
{"id": 10, "data": "abcd9fg"},
],
)
def _test(self, expr, expected):
some_table = self.tables.some_table
with config.db.connect() as conn:
rows = {
value
for value, in conn.execute(
select([some_table.c.id]).where(expr)
)
}
eq_(rows, expected)
def test_startswith_unescaped(self):
col = self.tables.some_table.c.data
self._test(col.startswith("ab%c"), {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
def test_startswith_autoescape(self):
col = self.tables.some_table.c.data
self._test(col.startswith("ab%c", autoescape=True), {3})
def test_startswith_sqlexpr(self):
col = self.tables.some_table.c.data
self._test(
col.startswith(literal_column("'ab%c'")),
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
)
def test_startswith_escape(self):
col = self.tables.some_table.c.data
self._test(col.startswith("ab##c", escape="#"), {7})
def test_startswith_autoescape_escape(self):
col = self.tables.some_table.c.data
self._test(col.startswith("ab%c", autoescape=True, escape="#"), {3})
self._test(col.startswith("ab#c", autoescape=True, escape="#"), {7})
def test_endswith_unescaped(self):
col = self.tables.some_table.c.data
self._test(col.endswith("e%fg"), {1, 2, 3, 4, 5, 6, 7, 8, 9})
def test_endswith_sqlexpr(self):
col = self.tables.some_table.c.data
self._test(
col.endswith(literal_column("'e%fg'")), {1, 2, 3, 4, 5, 6, 7, 8, 9}
)
def test_endswith_autoescape(self):
col = self.tables.some_table.c.data
self._test(col.endswith("e%fg", autoescape=True), {6})
def test_endswith_escape(self):
col = self.tables.some_table.c.data
self._test(col.endswith("e##fg", escape="#"), {9})
def test_endswith_autoescape_escape(self):
col = self.tables.some_table.c.data
self._test(col.endswith("e%fg", autoescape=True, escape="#"), {6})
self._test(col.endswith("e#fg", autoescape=True, escape="#"), {9})
def test_contains_unescaped(self):
col = self.tables.some_table.c.data
self._test(col.contains("b%cde"), {1, 2, 3, 4, 5, 6, 7, 8, 9})
def test_contains_autoescape(self):
col = self.tables.some_table.c.data
self._test(col.contains("b%cde", autoescape=True), {3})
def test_contains_escape(self):
col = self.tables.some_table.c.data
self._test(col.contains("b##cde", escape="#"), {7})
def test_contains_autoescape_escape(self):
col = self.tables.some_table.c.data
self._test(col.contains("b%cd", autoescape=True, escape="#"), {3})
self._test(col.contains("b#cd", autoescape=True, escape="#"), {7})
class ComputedColumnTest(fixtures.TablesTest):
__backend__ = True
__requires__ = ("computed_columns",)
@classmethod
def define_tables(cls, metadata):
Table(
"square",
metadata,
Column("id", Integer, primary_key=True),
Column("side", Integer),
Column("area", Integer, Computed("side * side")),
Column("perimeter", Integer, Computed("4 * side")),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.square.insert(),
[{"id": 1, "side": 10}, {"id": 10, "side": 42}],
)
def test_select_all(self):
with config.db.connect() as conn:
res = conn.execute(
select([text("*")])
.select_from(self.tables.square)
.order_by(self.tables.square.c.id)
).fetchall()
eq_(res, [(1, 10, 100, 40), (10, 42, 1764, 168)])
def test_select_columns(self):
with config.db.connect() as conn:
res = conn.execute(
select(
[self.tables.square.c.area, self.tables.square.c.perimeter]
)
.select_from(self.tables.square)
.order_by(self.tables.square.c.id)
).fetchall()
eq_(res, [(100, 40), (1764, 168)])
class ExistsTest(fixtures.TablesTest):
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"stuff",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String(50)),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.stuff.insert(),
[
{"id": 1, "data": "some data"},
{"id": 2, "data": "some data"},
{"id": 3, "data": "some data"},
{"id": 4, "data": "some other data"},
],
)
def test_select_exists(self, connection):
stuff = self.tables.stuff
eq_(
connection.execute(
select([literal(1)]).where(
exists().where(stuff.c.data == "some data")
)
).fetchall(),
[(1,)],
)
def test_select_exists_false(self, connection):
stuff = self.tables.stuff
eq_(
connection.execute(
select([literal(1)]).where(
exists().where(stuff.c.data == "no data")
)
).fetchall(),
[],
)
class IsOrIsNotDistinctFromTest(fixtures.TablesTest):
__backend__ = True
__requires__ = ("supports_is_distinct_from",)
@classmethod
def define_tables(cls, metadata):
Table(
"is_distinct_test",
metadata,
Column("id", Integer, primary_key=True),
Column("col_a", Integer, nullable=True),
Column("col_b", Integer, nullable=True),
)
@testing.combinations(
("both_int_different", 0, 1, 1),
("both_int_same", 1, 1, 0),
("one_null_first", None, 1, 1),
("one_null_second", 0, None, 1),
("both_null", None, None, 0),
id_="iaaa",
argnames="col_a_value, col_b_value, expected_row_count_for_is",
)
def test_is_or_isnot_distinct_from(
self, col_a_value, col_b_value, expected_row_count_for_is, connection
):
tbl = self.tables.is_distinct_test
connection.execute(
tbl.insert(),
[{"id": 1, "col_a": col_a_value, "col_b": col_b_value}],
)
result = connection.execute(
tbl.select(tbl.c.col_a.is_distinct_from(tbl.c.col_b))
).fetchall()
eq_(
len(result),
expected_row_count_for_is,
)
expected_row_count_for_isnot = (
1 if expected_row_count_for_is == 0 else 0
)
result = connection.execute(
tbl.select(tbl.c.col_a.isnot_distinct_from(tbl.c.col_b))
).fetchall()
eq_(
len(result),
expected_row_count_for_isnot,
)
| Java |
// **********************************************************************
//
// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
#ifndef ICE_INTERFACE_BY_VALUE_H
#define ICE_INTERFACE_BY_VALUE_H
#include <Ice/Value.h>
#include <Ice/OutputStream.h>
#include <Ice/InputStream.h>
#ifdef ICE_CPP11_MAPPING
namespace Ice
{
template<typename T>
class InterfaceByValue : public ValueHelper<InterfaceByValue<T>, Value>
{
public:
virtual std::string ice_id() const
{
return T::ice_staticId();
}
static const std::string& ice_staticId()
{
return T::ice_staticId();
}
std::tuple<> ice_tuple() const
{
return std::tie();
}
};
}
#endif
#endif
| Java |
<?lsmb FILTER latex -?>
\documentclass{scrartcl}
\usepackage{xltxtra}
\setmainfont{Verdana}
\usepackage{tabularx}
\usepackage[letterpaper,top=2cm,bottom=1.5cm,left=1.1cm,right=1.5cm]{geometry}
\usepackage{graphicx}
\setlength{\parindent}{0pt}
\begin{document}
\pagestyle{myheadings}
\thispagestyle{empty}
<?lsmb INCLUDE letterhead.tex ?>
\centerline{\MakeUppercase{\textbf{<?lsmb text('AP Transaction') ?>}}}
\vspace*{0.5cm}
\parbox[t]{.5\textwidth}{
<?lsmb name ?>
<?lsmb address1 ?>
<?lsmb address2 ?>
<?lsmb city ?>
<?lsmb IF state ?>
\hspace{-0.1cm}, <?lsmb state ?>
<?lsmb END ?> <?lsmb zipcode ?>
<?lsmb country ?>
\vspace{0.3cm}
<?lsmb IF contact ?>
<?lsmb contact ?>
\vspace{0.2cm}
<?lsmb END ?>
<?lsmb IF vendorphone ?>
Tel: <?lsmb vendorphone ?>
<?lsmb END ?>
<?lsmb IF vendorfax ?>
Fax: <?lsmb vendorfax ?>
<?lsmb END ?>
<?lsmb email ?>
<?lsmb IF vendortaxnumber ?>
Tax Number: <?lsmb vendortaxnumber ?>
<?lsmb END ?>
}
\hfill
\begin{tabular}[t]{ll}
\textbf{<?lsmb text('Invoice #') ?>} & <?lsmb invnumber ?> \\
\textbf{<?lsmb text('Date') ?>} & <?lsmb invdate ?> \\
\textbf{<?lsmb text('Due') ?>} & <?lsmb duedate ?> \\
<?lsmb IF ponumber ?>
\textbf{<?lsmb text('PO #') ?>} & <?lsmb ponumber ?> \\
<?lsmb END ?>
<?lsmb IF ordnumber ?>
\textbf{<?lsmb text('Order #') ?>} & <?lsmb ordnumber ?> \\
<?lsmb END ?>
\textbf{<?lsmb text('Employee') ?>} & <?lsmb employee ?> \\
\end{tabular}
\vspace{1cm}
\begin{tabularx}{\textwidth}[t]{@{}llrX@{\hspace{1cm}}l@{}}
<?lsmb FOREACH amount ?>
<?lsmb lc = loop.count - 1 ?>
<?lsmb accno.${lc} ?> &
<?lsmb account.${lc} ?> &
<?lsmb amount.${lc} ?> &
<?lsmb description.${lc} ?> &
<?lsmb projectnumber.${lc} ?> \\
<?lsmb END ?>
\multicolumn{2}{r}{\textbf{Subtotal}} & <?lsmb subtotal ?> & \\
<?lsmb FOREACH tax ?>
<?lsmb lc = loop.count - 1 ?>
\multicolumn{2}{r}{\textbf{<?lsmb taxdescription.${lc} ?> @ <?lsmb taxrate.${lc} ?> \%}} & <?lsmb tax.${lc} ?> & \\
<?lsmb END ?>
\multicolumn{2}{r}{\textbf{Total}} & <?lsmb invtotal ?> & \\
\end{tabularx}
\vspace{0.3cm}
<?lsmb text_amount ?> ***** <?lsmb decimal ?>/100 <?lsmb currency ?>
<?lsmb IF notes ?>
\vspace{0.3cm}
<?lsmb FOREACH P IN notes.split('\n\n') ?>
<?lsmb P ?>\medskip
<?lsmb END ?>
<?lsmb END ?>
\vspace{0.3cm}
<?lsmb IF paid_1 ?>
\begin{tabular}{@{}llllr@{}}
\multicolumn{5}{c}{\textbf{<?lsmb text('Payments') ?>}} \\
\hline
\textbf{<?lsmb text('Date') ?>} & & \textbf{<?lsmb text('Source') ?>} & \textbf{<?lsmb text('Memo') ?>} & \textbf{<?lsmb text('Amount') ?>} \\
<?lsmb END ?>
<?lsmb FOREACH payment ?>
<?lsmb lc = loop.count - 1 ?>
<?lsmb paymentdate.${lc} ?> & <?lsmb paymentaccount.${lc} ?> & <?lsmb paymentsource.${lc} ?> & <?lsmb paymentmemo.${lc} ?> & <?lsmb payment.${lc} ?> \\
<?lsmb END ?>
<?lsmb IF paid_1 ?>
\end{tabular}
<?lsmb END ?>
\end{document}
<?lsmb END ?>
| Java |
<?php
/**
* @Project NUKEVIET 4.x
* @Author VINADES.,JSC (contact@vinades.vn)
* @Copyright (C) 2014 VINADES.,JSC. All rights reserved
* @License GNU/GPL version 2 or any later version
* @Createdate 9/9/2010, 6:38
*/
if (! defined('NV_IS_FILE_WEBTOOLS')) {
die('Stop!!!');
}
$contents = 'Error Access!!!';
$checksess = $nv_Request->get_title('checksess', 'get', '');
if ($checksess == md5($global_config['sitekey'] . session_id()) and file_exists(NV_ROOTDIR . '/install/update_data.php')) {
$contents = '';
$list_file_docs = nv_scandir(NV_ROOTDIR . '/install', '/^update_docs_([a-z]{2})\.html$/');
// Xoa cac file docs
foreach ($list_file_docs as $docsfile) {
$check_del = nv_deletefile(NV_ROOTDIR . '/install/' . $docsfile);
if ($check_del[0] == 0) {
$contents .= $check_del[1] . ' ' . $lang_module['update_manual_delete'];
}
}
// Xoa file du lieu nang cap
$check_delete_file = nv_deletefile(NV_ROOTDIR . '/install/update_data.php');
if ($check_delete_file[0] == 0) {
$contents .= $check_delete_file[1] . ' ' . $lang_module['update_manual_delete'];
}
// Xoa thu muc file thay doi
if (file_exists(NV_ROOTDIR . '/install/update')) {
$check_delete_dir = nv_deletefile(NV_ROOTDIR . '/install/update', true);
if ($check_delete_dir[0] == 0) {
$contents .= $check_delete_dir[1] . ' ' . $lang_module['update_manual_delete'];
}
}
// Xoa file log
$list_file_logs = nv_scandir(NV_ROOTDIR . '/' . NV_DATADIR, '/^config_update_NVUD([A-Z0-9]+)\.php$/');
foreach ($list_file_logs as $logsfile) {
$check_del = nv_deletefile(NV_ROOTDIR . '/' . NV_DATADIR . '/' . $logsfile);
if ($check_del[0] == 0) {
$contents .= $check_del[1] . ' ' . $lang_module['update_manual_delete'];
}
}
clearstatcache();
}
if ($contents == '') {
$contents = 'OK';
}
include NV_ROOTDIR . '/includes/header.php';
echo $contents;
include NV_ROOTDIR . '/includes/footer.php';
| Java |
/*
Theme Name: Hughes Benefits Site
Theme URI: http://coverwaco.com
Description: A custom WordPress theme for Hughes Benefits.
Author: Heath Hughes
Author URI: http://heathwhughes.com
Version: 1.0
Tags: responsive, insurance, simple
License: GNU General Public License v2.0
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
@import url(http://fonts.googleapis.com/css?family=Quicksand:400,700|Paytone+One|Montserrat+Alternates:400,700|Josefin+Sans:400,600,700,400italic|Wendy+One|Fredoka+One|Raleway:400,600,500,700|Righteous|Passion+One:700,400,900|Comfortaa:700,400|Open+Sans:700,400);
/* VARIABLES */
/* navy */
/* bright light blue #7ECEFD */
/* muted blue (darker) */
/* light muted blue */
/* orange #D57E01 #ED8C01 */
/* muted yellow */
/* light orange */
/* white - the background-color for the header, body, and footer */
/* grey - the main text on the site */
/* */
/* super light blue */
/* FONT */
/********************************
GENERAL
********************************/
html {
height: 100%;
font-size: 1.2em; }
html, body, button, input, select, textarea {
font-family: "Josefin Sans", san-seriff; }
body {
height: 100%;
background-color: #fff;
color: #7A7A7A; }
a {
text-decoration: none;
color: #71B9E4; }
div#wrapper, div#header-wrapper {
max-width: 1200px;
margin: 0 auto;
padding: 0 5%;
height: 100%; }
h2 {
color: #346098;
margin: .75em 0;
font-size: 2em; }
h3 {
color: #71B9E4;
margin: .5em 0;
font-size: 1.4em; }
h4 {
font-size: 1.2em;
margin: .75em 0; }
p {
margin: .35em 0; }
ul {
margin: .5em 0; }
img {
width: 100%; }
/********************************
HEADING
********************************/
header {
float: left;
margin: 0 0 1.6em 0;
padding: 5px 0 0 0;
width: 100%;
background-color: #346098; }
#logo {
text-align: center;
margin: 0; }
h1 {
font-family: "Josefin Sans", san-seriff;
margin: 15px 0;
font-size: 2.2em;
font-weight: bold;
line-height: 0.8em; }
h1 .logo-1 {
color: #FFA347; }
h1 .logo-2 {
color: #F5C149; }
h1 .logo-3 {
color: #ACACAC;
font-size: .75em;
/* for the ".com" */ }
p#slogan {
color: #ACACAC;
font-style: italic;
position: relative;
top: -15px;
left: 5px;
margin: 0; }
/*********************************
NAVIGATION
********************************/
nav {
text-align: center;
padding: 10px 0 0 0;
margin: 0;
/* end ul */
/* end li */
/* end a */ }
nav ul {
list-style: none;
margin: 0 10px;
padding: 0; }
nav li {
display: inline-block;
margin-bottom: 10px; }
nav li.current_page_item {
border-bottom: 3px solid #F5C149; }
nav a {
font-size: 1em;
font-weight: 600;
padding: 0 10px;
font-family: "Josefin Sans", san-seriff;
text-transform: uppercase; }
nav a:hover {
border-bottom: 3px solid #F5C149; }
/* end nav */
/********************************
FOOTER
********************************/
footer {
font-size: 0.75em;
text-align: center;
clear: both;
padding-top: 50px;
color: #7A7A7A;
margin-bottom: 30px; }
footer hr {
position: relative;
top: 25px; }
footer p {
line-height: 50px;
/* this should match the max-height of the image */
border-top: solid #7A7A7A 1.9px; }
footer img {
max-height: 50px;
position: relative;
top: 30px;
padding: 5px;
width: auto; }
/*******************************
PAGE: HOME
********************************/
#home-2 h3, #home-3 h3 {
margin-top: 0; }
h2.cta {
margin: 0 0 .75em 0; }
section#home-1 {
clear: left;
position: relative;
top: -1.6em; }
/*
section#home-2 {
margin-top: 56px;;
}*/
img#home-img {
width: 100%;
height: 250px;
display: none;
/* this default will be overridden when the screen get's wider than 480px */ }
section#home-4:after {
content: "";
visibility: hidden;
display: block;
height: 0;
clear: both; }
section#home-4 {
margin-bottom: 1em; }
section#home-4 div {
margin: 12px; }
section#home-4 div span {
margin-left: 5em; }
.btn, .button-orange {
-moz-box-shadow: inset 0px 1px 0px 0px #fce2c1;
-webkit-box-shadow: inset 0px 1px 0px 0px #fce2c1;
box-shadow: inset 0px 1px 0px 0px #fce2c1;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #ffc477), color-stop(1, #FFA347));
background: -moz-linear-gradient(center top, #ffc477 5%, #ffa347 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc477', endColorstr='#ffa347');
background-color: #ffc477;
-webkit-border-top-left-radius: 13px;
-moz-border-radius-topleft: 13px;
border-top-left-radius: 13px;
-webkit-border-top-right-radius: 13px;
-moz-border-radius-topright: 13px;
border-top-right-radius: 13px;
-webkit-border-bottom-right-radius: 13px;
-moz-border-radius-bottomright: 13px;
border-bottom-right-radius: 13px;
-webkit-border-bottom-left-radius: 13px;
-moz-border-radius-bottomleft: 13px;
border-bottom-left-radius: 13px;
text-indent: 0px;
border: 1px solid #eeb44f;
display: inline-block;
color: #ffffff;
/*font-family:Trebuchet MS;*/
font-size: 20px;
font-weight: bold;
font-style: normal;
height: 39px;
line-height: 39px;
width: 250px;
text-decoration: none;
text-align: center;
text-shadow: 1px 1px 0px #cc9f52; }
.button-orange:hover {
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #FFA347), color-stop(1, #ffc477));
background: -moz-linear-gradient(center top, #FFA347 5%, #ffc477 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffa347', endColorstr='#ffc477');
background-color: #FFA347; }
.button-1:active {
position: relative;
top: 1px; }
/* This button was generated using CSSButtonGenerator.com */
.button-yellow {
-moz-box-shadow: inset 0px 1px 0px 0px #fae7c0;
-webkit-box-shadow: inset 0px 1px 0px 0px #fae7c0;
box-shadow: inset 0px 1px 0px 0px #fae7c0;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #f8d480), color-stop(1, #F5C149));
background: -moz-linear-gradient(center top, #f8d480 5%, #F5C149 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f8d480', endColorstr='#f5c149');
background-color: #f8d480;
/*-webkit-border-top-left-radius:13px;
-moz-border-radius-topleft:13px;
border-top-left-radius:13px;
-webkit-border-top-right-radius:13px;
-moz-border-radius-topright:13px;
border-top-right-radius:13px;
-webkit-border-bottom-right-radius:13px;
-moz-border-radius-bottomright:13px;
border-bottom-right-radius:13px;
-webkit-border-bottom-left-radius:13px;
-moz-border-radius-bottomleft:13px;
border-bottom-left-radius:13px;
text-indent:0px;*/
border: 1px solid #edc651;
/*display:inline-block;
color:#ffffff;
font-family:Trebuchet MS;
font-size:15px;
font-weight:bold;
font-style:normal;
height:39px;
line-height:39px;
width:200px;
text-decoration:none;
text-align:center;*/
text-shadow: 1px 1px 0px #cc9f52; }
.button-yellow:hover {
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #F5C149), color-stop(1, #f8d480));
background: -moz-linear-gradient(center top, #F5C149 5%, #f8d480 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f5c149', endColorstr='#f8d480');
background-color: #F5C149; }
.button-yellow:active {
/*position:relative;
top:1px;*/ }
h4.cta {
clear: both; }
html, body {
overflow-x: hidden; }
/********************************
PAGE: CONTACT
********************************/
/* keep the help boxes from being huge */
img.ninja-forms-help-text {
/* "width: auto is the fallback for IE not supporting width: initial" */
width: auto;
width: initial; }
/* for smaller widths - the meeting time drop down shoudln't be wider than the viewport */
select#ninja_forms_field_8 {
max-width: 100%; }
.ninja-forms-required-items {
display: none; }
#contact-2 h3 {
margin: 0 0 .5em 0; }
div#gmap {
width: 100% !important;
/*260px*/ }
/********************************
PAGE: OPTIONS/SERVICES
********************************/
/* Styles for the income thresholds table */
.CSSTableGenerator {
margin: 0px;
padding: 0px;
width: 100%;
border: 1px solid #000000;
-moz-border-radius-bottomleft: 0px;
-webkit-border-bottom-left-radius: 0px;
border-bottom-left-radius: 0px;
-moz-border-radius-bottomright: 0px;
-webkit-border-bottom-right-radius: 0px;
border-bottom-right-radius: 0px;
-moz-border-radius-topright: 0px;
-webkit-border-top-right-radius: 0px;
border-top-right-radius: 0px;
-moz-border-radius-topleft: 0px;
-webkit-border-top-left-radius: 0px;
border-top-left-radius: 0px; }
.CSSTableGenerator table {
border-collapse: collapse;
border-spacing: 0;
width: 100%;
height: 100%;
margin: 0px;
padding: 0px; }
.CSSTableGenerator tr:last-child td:last-child {
-moz-border-radius-bottomright: 0px;
-webkit-border-bottom-right-radius: 0px;
border-bottom-right-radius: 0px; }
.CSSTableGenerator table tr:first-child td:first-child {
-moz-border-radius-topleft: 0px;
-webkit-border-top-left-radius: 0px;
border-top-left-radius: 0px; }
.CSSTableGenerator table tr:first-child td:last-child {
-moz-border-radius-topright: 0px;
-webkit-border-top-right-radius: 0px;
border-top-right-radius: 0px; }
.CSSTableGenerator tr:last-child td:first-child {
-moz-border-radius-bottomleft: 0px;
-webkit-border-bottom-left-radius: 0px;
border-bottom-left-radius: 0px; }
.CSSTableGenerator tr:hover td {
background-color: #ffffff; }
.CSSTableGenerator td {
vertical-align: middle;
background-color: #fcfcfc;
border: 1px solid #000000;
border-width: 0px 1px 1px 0px;
text-align: center;
padding: 7px;
/*font-size:10px;
font-family:Arial;
font-weight:bold;
color:#000000;*/ }
.CSSTableGenerator tr:last-child td {
border-width: 0px 1px 0px 0px; }
.CSSTableGenerator tr td:last-child {
border-width: 0px 0px 1px 0px; }
.CSSTableGenerator tr:last-child td:last-child {
border-width: 0px 0px 0px 0px; }
.CSSTableGenerator tr:first-child td {
background: -o-linear-gradient(bottom, #ffa347 5%, #ffa347 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #ffa347), color-stop(1, #ffa347));
background: -moz-linear-gradient(center top, #ffa347 5%, #ffa347 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ffa347", endColorstr="#ffa347");
background: -o-linear-gradient(top, #ffa347, ffa347);
background-color: #ffa347;
border: 0px solid #000000;
text-align: center;
border-width: 0px 0px 1px 1px;
/*font-size:14px;
font-family:Arial;
font-weight:bold;
color:#ffffff;*/ }
.CSSTableGenerator tr:first-child:hover td {
background: -o-linear-gradient(bottom, #ffa347 5%, #ffa347 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #ffa347), color-stop(1, #ffa347));
background: -moz-linear-gradient(center top, #ffa347 5%, #ffa347 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ffa347", endColorstr="#ffa347");
background: -o-linear-gradient(top, #ffa347, ffa347);
background-color: #ffa347; }
.CSSTableGenerator tr:first-child td:first-child {
border-width: 0px 0px 1px 0px; }
.CSSTableGenerator tr:first-child td:last-child {
border-width: 0px 0px 1px 1px; }
.CSSTableGenerator {
max-width: 800px; }
table#income_chart {
font-size: .88em; }
/*# sourceMappingURL=style.css.map */
| Java |
<?php
/**
* Project: Securimage: A PHP class for creating and managing form CAPTCHA images<br />
* File: securimage_show_example2.php<br />
*
* Copyright (c) 2011, Drew Phillips
* 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 HOLDER 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.
*
* Any modifications to the library should be indicated clearly in the source code
* to inform users that the changes are not a part of the original software.<br /><br />
*
* If you found this script useful, please take a quick moment to rate it.<br />
* http://www.hotscripts.com/rate/49400.html Thanks.
*
* @link http://www.phpcaptcha.org Securimage PHP CAPTCHA
* @link http://www.phpcaptcha.org/latest.zip Download Latest Version
* @link http://www.phpcaptcha.org/Securimage_Docs/ Online Documentation
* @copyright 2011 Drew Phillips
* @author Drew Phillips <drew@drew-phillips.com>
* @version 3.0 (October 2011)
* @package Securimage
*
*/
require_once dirname(__FILE__) . '/securimage.php';
$img = new Securimage();
//Change some settings
$img->image_width = 280;
$img->image_height = 100;
$img->perturbation = 0.9; // high level of distortion
$img->code_length = rand(5,6); // random code length
$img->image_bg_color = new Securimage_Color("#ffffff");
$img->num_lines = 12;
$img->noise_level = 5;
$img->text_color = new Securimage_Color("#000000");
$img->noise_color = $img->text_color;
$img->line_color = new Securimage_Color("#cccccc");
$img->show(); | Java |
#ifndef FILEZILLA_INTERFACE_CLEARPRIVATEDATA_HEADER
#define FILEZILLA_INTERFACE_CLEARPRIVATEDATA_HEADER
#include "dialogex.h"
#include <wx/timer.h>
class CMainFrame;
class CClearPrivateDataDialog final : public wxDialogEx
{
public:
static CClearPrivateDataDialog* Create(CMainFrame* pMainFrame) { return new CClearPrivateDataDialog(pMainFrame); }
void Run();
void Delete();
protected:
CClearPrivateDataDialog(CMainFrame* pMainFrame);
virtual ~CClearPrivateDataDialog() = default;
bool ClearReconnect();
void RemoveXmlFile(const wxString& name);
CMainFrame* const m_pMainFrame;
wxTimer m_timer;
DECLARE_EVENT_TABLE()
void OnTimer(wxTimerEvent& event);
};
#endif
| Java |
# encoding: utf-8
#
# Copyright 2017 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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.
#
# Cerebrum 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 Cerebrum; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
""" An abstract event that can be stored in the database. """
from __future__ import absolute_import
import datetime
import itertools
import mx.DateTime
import pytz
import cereconf
class _VerbSingleton(type):
""" A metaclass that makes each EventType verb a singleton. """
verbs = {}
def __call__(cls, verb, *args):
if verb not in cls.verbs:
cls.verbs[verb] = super(_VerbSingleton, cls).__call__(verb, *args)
return cls.verbs[verb]
def get_verb(cls, verb):
return cls.verbs.get(verb)
class EventType(_VerbSingleton('EventTypeSingleton', (object,), {})):
"""Holds an event type."""
__slots__ = ['verb', 'description', ]
def __init__(self, verb, description):
""" Initialize EventType.
:verb: Scim verb
:description: HR description text
"""
self.verb = verb
self.description = description
def __repr__(self):
return '<{0.__class__.__name__!s} {0.verb}>'.format(self)
def __eq__(self, other):
"""Equality."""
return isinstance(other, EventType) and other.verb == self.verb
def __hash__(self):
"""Hash."""
return hash(self.verb)
# Define event types:
ADD = EventType('add', 'Add an object to subject')
CREATE = EventType('create', 'Create a new subject')
ACTIVATE = EventType('activate', 'Subject has no longer quarantines in system')
MODIFY = EventType('modify', 'Attributes has changed')
DEACTIVATE = EventType('deactivate', 'Quarantine is activated')
DELETE = EventType('delete', 'Subject is deleted')
REMOVE = EventType('remove', 'Remove an object from subject')
PASSWORD = EventType('password', 'Subject has changed password')
JOIN = EventType('join', 'Join two objects')
class EntityRef(object):
""" Representation of a single entity.
The entity_id can be used internally to identify which object we reference
The entity_type and ident is used to generate a reference to the object
that other systems can use.
"""
__slots__ = ['ident', 'entity_type', 'entity_id', ]
def __init__(self, entity_id, entity_type, ident):
self.entity_id = int(entity_id)
self.entity_type = entity_type
self.ident = ident
def __repr__(self):
return ("<{0.__class__.__name__}"
" id={0.entity_id!r}"
" type={0.entity_type!r}"
" ident={0.ident!r}>").format(self)
def __eq__(self, other):
return (isinstance(other, EntityRef) and
self.entity_id == other.entity_id)
def to_dict(self):
return {
'ident': self.ident,
'entity_id': self.entity_id,
'entity_type': self.entity_type, }
class DateTimeDescriptor(object):
""" Datetime descriptor that handles timezones.
When setting the datetime, this method will try to localize it with the
default_timezone in the following ways:
- mx.DateTime.DateTimeType: Naive datetime, assume in default_timezone
- datetime.datetime: Assume in default_timezone if naive
- integer: Assume timestamp in UTC
The returned object will always be a localized datetime.datetime
"""
default_timezone = pytz.timezone(cereconf.TIMEZONE)
def __init__(self, slot):
""" Creates a new datetime descriptor.
:param str slot:
The attribute name where the actual value is stored.
"""
self.slot = slot
def __repr__(self):
return '{0.__class__.__name__}({0.slot!r})'.format(self)
def __get__(self, obj, cls=None):
if not obj:
return self
return getattr(obj, self.slot, None)
def __set__(self, obj, value):
if value is None:
self.__delete__(obj)
return
if isinstance(value, (int, long, )):
# UTC timestamp
value = pytz.utc.localize(
datetime.datetime.fromtimestamp(value))
elif isinstance(value, mx.DateTime.DateTimeType):
# Naive datetime in default_timezone
value = self.default_timezone.localize(value.pydatetime())
elif isinstance(value, datetime.datetime):
if value.tzinfo is None:
value = self.default_timezone.localize(value)
else:
raise TypeError('Invalid datetime {0} ({1})'.format(type(value),
repr(value)))
setattr(obj, self.slot, value)
def __delete__(self, obj):
if hasattr(obj, self.slot):
delattr(obj, self.slot)
class Event(object):
""" Event abstraction.
Contains all the neccessary data to serialize an event.
"""
DEFAULT_TIMEZONE = 'Europe/Oslo'
__slots__ = ['event_type', 'subject', 'objects', 'context', 'attributes',
'_timestamp', '_scheduled', ]
timestamp = DateTimeDescriptor('_timestamp')
scheduled = DateTimeDescriptor('_scheduled')
def __init__(self, event_type,
subject=None,
objects=None,
context=None,
attributes=None,
timestamp=None,
scheduled=None):
"""
:param EventType event: the type of event
:param EntityRef subject: reference to the affected entity
:param list objects: sequence of other affected objects (EntityRef)
:param list context: sequence of affected systems (str)
:param list attributes: sequence of affected attributes (str)
:param datetime timestamp: when the event originated
:param datetime schedule: when the event should be issued
"""
self.event_type = event_type
self.subject = subject
self.timestamp = timestamp
self.scheduled = scheduled
self.objects = set(objects or [])
self.context = set(context or [])
self.attributes = set(attributes or [])
def __repr__(self):
return ('<{0.__class__.__name__}'
' event={0.event_type!r}'
' subject={0.subject!r}>').format(self)
def mergeable(self, other):
"""Can this event be merged with other."""
if self.scheduled is not None:
return False
if self.subject != other.subject:
return False
if self.event_type == CREATE:
return other.event_type not in (DEACTIVATE, REMOVE)
if self.event_type == DELETE:
return other.event_type in (REMOVE, DEACTIVATE, ADD, ACTIVATE,
MODIFY, PASSWORD)
if (self.event_type == other.event_type and
self.event_type in (ADD, REMOVE, ACTIVATE, DEACTIVATE)):
return True
if self.context != other.context:
return False
return True
def merge(self, other):
"""Merge messages."""
def ret_self():
self.objects.update(other.objects)
return [self]
if not self.mergeable(other):
return [self, other]
if self.event_type == CREATE:
if other.event_type == DELETE:
return []
if other.event_type == ADD:
self.context.update(other.context)
return ret_self()
if other.event_type == ACTIVATE:
return ret_self() # TODO: if quarantine is an attr, delete it
if other.event_type == MODIFY:
self.attributes.update(other.attributes)
return ret_self()
if other.event_type == PASSWORD:
self.attributes.add('password')
return ret_self()
elif self.event_type == DELETE:
return ret_self()
elif other.event_type == DELETE:
return [other]
elif (ACTIVATE == self.event_type and
DEACTIVATE == other.event_type and
self.context == other.context):
return []
elif (ADD == self.event_type and
REMOVE == other.event_type and
self.context == other.context):
return []
elif self.event_type == other.event_type:
if self.event_type in (ADD, REMOVE, ACTIVATE, DEACTIVATE):
self.context.update(other.context)
return ret_self()
if self.context != other.context:
return [self, other]
self.attributes.update(other.attributes)
return ret_self()
return [self, other]
def merge_events(events):
"""Merge events with similarities.
As long as subject is the same:
* create + add/activate/modify/password = create with attributes merged
* create + deactivate/remove is untouched
* create + delete should be removed
* delete + remove/deactivate/add/activate/modify/password = delete
* x + x = x
* activate + deactivate = noop (careful with aud)
Sort into canonical order:
#. create
#. delete
#. add
#. activate
#. modify
#. password
#. deactivate
#. remove
"""
order = (CREATE, DELETE, ADD, ACTIVATE, MODIFY, PASSWORD, DEACTIVATE,
REMOVE, JOIN)
ps = [[] for x in order]
for pl in events:
pltype = pl.event_type
idx = order.index(pltype)
ps[idx].append(pl)
result = {}
for idx, tp, pl in zip(range(len(order)), order, ps):
for p in pl:
if p.subject not in result:
result[p.subject] = [p]
else:
result[p.subject].append(p)
def merge_list(finished, merged, current, rest):
while rest or merged:
if rest:
new = current.merge(rest[0])
if not new:
rest.pop(0)
merged.extend(rest)
rest = merged
if not rest:
return finished
merged = []
current = rest.pop(0)
elif len(new) == 1:
if new[0] is not current:
merged.extend(rest)
rest = merged
current = rest.pop(0)
merged = []
else:
rest.pop(0)
else:
merged.append(rest.pop(0))
else: # merged is not empty
finished.append(current)
rest = merged
merged = []
current = rest.pop(0)
finished.append(current)
return finished
for sub, lst in result.items():
result[sub] = merge_list([], [], lst[0], lst[1:])
return list(itertools.chain(*result.values()))
| Java |
# -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.4.2_05) on Fri Aug 13 10:55:24 CDT 2004 -->
<TITLE>
Uses of Class javazoom.jl.decoder.OutputChannels
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Class javazoom.jl.decoder.OutputChannels";
}
</SCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="OutputChannels.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>javazoom.jl.decoder.OutputChannels</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Packages that use <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#javazoom.jl.decoder"><B>javazoom.jl.decoder</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="javazoom.jl.decoder"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Uses of <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A> in <A HREF="../../../../javazoom/jl/decoder/package-summary.html">javazoom.jl.decoder</A></FONT></TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Fields in <A HREF="../../../../javazoom/jl/decoder/package-summary.html">javazoom.jl.decoder</A> declared as <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></CODE></FONT></TD>
<TD><CODE><B>OutputChannels.</B><B><A HREF="../../../../javazoom/jl/decoder/OutputChannels.html#LEFT">LEFT</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></CODE></FONT></TD>
<TD><CODE><B>OutputChannels.</B><B><A HREF="../../../../javazoom/jl/decoder/OutputChannels.html#RIGHT">RIGHT</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></CODE></FONT></TD>
<TD><CODE><B>OutputChannels.</B><B><A HREF="../../../../javazoom/jl/decoder/OutputChannels.html#BOTH">BOTH</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></CODE></FONT></TD>
<TD><CODE><B>OutputChannels.</B><B><A HREF="../../../../javazoom/jl/decoder/OutputChannels.html#DOWNMIX">DOWNMIX</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Methods in <A HREF="../../../../javazoom/jl/decoder/package-summary.html">javazoom.jl.decoder</A> that return <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></CODE></FONT></TD>
<TD><CODE><B>OutputChannels.</B><B><A HREF="../../../../javazoom/jl/decoder/OutputChannels.html#fromInt(int)">fromInt</A></B>(int code)</CODE>
<BR>
Creates an <code>OutputChannels</code> instance
corresponding to the given channel code.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></CODE></FONT></TD>
<TD><CODE><B>Decoder.Params.</B><B><A HREF="../../../../javazoom/jl/decoder/Decoder.Params.html#getOutputChannels()">getOutputChannels</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Methods in <A HREF="../../../../javazoom/jl/decoder/package-summary.html">javazoom.jl.decoder</A> with parameters of type <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>Decoder.Params.</B><B><A HREF="../../../../javazoom/jl/decoder/Decoder.Params.html#setOutputChannels(javazoom.jl.decoder.OutputChannels)">setOutputChannels</A></B>(<A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A> out)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="OutputChannels.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| Java |
/*
* Flocking Debugging Unit Generators
* http://github.com/colinbdclark/flocking
*
* Copyright 2011-2014, Colin Clark
* Dual licensed under the MIT and GPL Version 2 licenses.
*/
/*global require*/
/*jshint white: false, newcap: true, regexp: true, browser: true,
forin: false, nomen: true, bitwise: false, maxerr: 100,
indent: 4, plusplus: false, curly: true, eqeqeq: true,
freeze: true, latedef: true, noarg: true, nonew: true, quotmark: double, undef: true,
unused: true, strict: true, asi: false, boss: false, evil: false, expr: false,
funcscope: false*/
var fluid = fluid || require("infusion"),
flock = fluid.registerNamespace("flock");
(function () {
"use strict";
// TODO: Unit tests.
flock.ugen.print = function (input, output, options) {
var that = flock.ugen(input, output, options);
that.gen = function (numSamps) {
var inputs = that.inputs,
out = that.output,
m = that.model,
label = m.label,
chan = inputs.channel,
// Basic multichannel support. This should be inproved
// by factoring the multichannel input code out of flock.ugen.out.
source = chan ? inputs.source.output[chan.output[0]] : inputs.source.output,
trig = inputs.trigger.output[0],
freq = inputs.freq.output[0],
i,
j,
val;
if (trig > 0.0 && m.prevTrig <= 0.0) {
fluid.log(fluid.logLevel.IMPORTANT, label + source);
}
if (m.freq !== freq) {
m.sampInterval = Math.round(m.sampleRate / freq);
m.freq = freq;
m.counter = m.sampInterval;
}
for (i = 0, j = 0 ; i < numSamps; i++, j += m.strides.source) {
if (m.counter >= m.sampInterval) {
fluid.log(fluid.logLevel.IMPORTANT, label + source[j]);
m.counter = 0;
}
m.counter++;
out[i] = val = source[i];
}
m.value = m.unscaledValue = val;
};
that.init = function () {
var o = that.options;
that.model.label = o.label ? o.label + ": " : "";
that.onInputChanged();
};
that.init();
return that;
};
flock.ugenDefaults("flock.ugen.print", {
rate: "audio",
inputs: {
source: null,
trigger: 0.0,
freq: 1.0
},
ugenOptions: {
model: {
unscaledValue: 0.0,
value: 0.0,
counter: 0
},
strideInputs: ["source"]
}
});
}());
| Java |
-- Copyright (c) 2012 Roland Yonaba
--[[
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
--]]
local insert = table.insert
local require = require
local pcall = pcall
local loadstring = loadstring
local print = print
local tests = {}
local aborted = {}
local function addTest (test)
test.n = #tests+1
insert(tests,test)
end
local function runTests(listOfTests,output)
local output = output or io.stdout
local status,err,fails
for i,test in ipairs(listOfTests) do
output:write(i..'/ TOPIC : '..test.topic..'\n')
output:write('COMMENTS : '..test.comments..'\n')
output:write('Sample Code :\n'..test.sample..'\n')
output:write('Output\n')
status,err = pcall(loadstring(test.sample))
if not status then
output:write('Error occured\n')
insert(aborted,{test = test, error = err})
end
output:write('\nEnd of Test '..i..'\n\n')
end
fails = #aborted
if fails > 0 then
output:write(fails..' test'..(fails>1 and 's' or '')..' aborted..\n')
for i in ipairs(aborted) do
output:write('Test '..aborted[i].test.n..' : '..aborted[i].error..'\n')
end
else
output:write('All tests runned successfully\n')
output:close()
end
end
addTest(
{
topic = 'Class Creation',
comments = 'We will cover various ways to create classes using LCS',
sample = [[
local LCS = require "LCS"
local myClass = LCS.class()
local myClass2 = LCS.class {var1 = 0, var2 = nil}
print(myClass2.var1)
print(myClass2.var2)
print(myClass2.var3)
print(LCS.is_A(myClass,'class'))
print(LCS.is_A(myClass))
]],
}
)
addTest(
{
topic = 'Instantiation (1/2)',
comments = 'We will cover differents ways to instantiate objects from a class',
sample = [[
local LCS = require 'LCS'
local Animal = LCS.class {name = 'Animal'}
function Animal:yell()
print('I am a '..self.name)
end
local kitty = Animal()
print(kitty.name)
kitty.name = 'kitty'
kitty:yell()
local doggy = Animal:new()
print(doggy.name)
doggy.name = 'doggy'
doggy:yell()
]],
}
)
addTest(
{
topic = 'Instantiation (2/2)',
comments = 'We will cover how to instantiante objects and init them with parameters',
sample = [[
local LCS = require 'LCS'
local Animal = LCS.class {name = 'Animal', weight = nil}
function Animal:init(name,weight)
self.name = name
self.weight = weight
end
function Animal:yell()
print('I am a ',self.name,', I weight ',self.weight)
end
local kitty = Animal('kitty',10)
local doggy = Animal:new('doggy',20)
kitty:yell()
doggy:yell()
]],
}
)
addTest(
{
topic = 'Inheritance ',
comments = 'We will learn how to use inheritance feature in LCS',
sample = [[
local LCS = require 'LCS'
local Animal = LCS.class {name = 'Animal'}
function Animal:init(name)
self.name = name
end
function Animal:yell()
print('I am a ',self.name)
end
local Cat = Animal:extends()
local Dog = Animal:extends()
function Cat:speak()
print('Meeoow')
end
function Dog:speak()
print('Ouah Ouah!')
end
local kitty = Cat('kitty')
local doggy = Dog('Doggy')
kitty:yell()
doggy:yell()
kitty:speak()
doggy:speak()
]],
}
)
addTest(
{
topic = 'Super Call ',
comments = 'We will learn how to call methods defined within a superclass from a derived class',
sample = [[
local LCS = require 'LCS'
local Animal = LCS.class {name = 'Animal'}
function Animal:init(name)
self.name = name
end
function Animal:yell()
print('I am a ',self.name)
end
local Cat = Animal:extends()
function Cat:yell()
print('Meeoow')
end
local kitty = Cat('kitty')
kitty:yell()
kitty:super('yell')
]],
}
)
addTest(
{
topic = 'Final and static classes ',
comments = 'We will learn how to create final and static classes.\nThis test will have no output.',
sample = [[
local LCS = require 'LCS'
local FinalAnimal = LCS.class.final {name = 'Animal'}
local StaticAnimal = LCS.class.static {name = 'Animal'}
-- This will throw an error
-- local FinalDog = FinalAnimal:extends()
-- This will throw an error
-- staticKitty = StaticAnimal()
]],
}
)
addTest(
{
topic = 'Full Api review ',
comments = 'We will learn the use of the whole api functions',
sample = [[
local LCS = require 'LCS'
local Animal = LCS.class {name = 'Animal'}
function Animal:init(name)
self.name = name
end
local Cat = Animal:extends()
function Cat:yell()
print('Meeoow')
end
local thing = Animal('thing')
local kitty = Cat('kitty')
print(kitty:getClass() == Cat)
print(Cat:getClass() == Animal)
print(thing:getClass() == Animal)
print(Animal:getClass() == nil)
print(kitty:is_A(Cat))
print(thing:is_A(Animal))
print(LCS.is_A(kitty,'object'))
print(LCS.is_A(thing))
print(LCS.is_A(Cat,'class'))
print(LCS.is_A(Animal))
print((Animal:getSubClasses())[Cat])
]],
}
)
runTests(tests)
| Java |
/*
This file is part of the KDE project
* Copyright (C) 2009 Pierre Stirnweiss <pstirnweiss@googlemail.com>
* Copyright (C) 2011 Boudewijn Rempt <boud@kde.org>
*
* 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 "TextPasteCommand.h"
#include <KoTextEditor.h>
#include <KoTextDocument.h>
#include <KoTextPaste.h>
#include <KoChangeTracker.h>
#include <KoShapeController.h>
#include <klocale.h>
#include <kdebug.h>
#include <kaction.h>
#include <QTextDocument>
#include <QApplication>
#include <QMimeData>
#include "ChangeTrackedDeleteCommand.h"
#include "DeleteCommand.h"
#include "KoDocumentRdfBase.h"
#ifdef SHOULD_BUILD_RDF
#include <Soprano/Soprano>
#else
namespace Soprano
{
class Model
{
};
}
#endif
TextPasteCommand::TextPasteCommand(const QMimeData *mimeData,
QTextDocument *document,
KoShapeController *shapeController,
KoCanvasBase *canvas, KUndo2Command *parent, bool pasteAsText)
: KUndo2Command (parent),
m_mimeData(mimeData),
m_document(document),
m_rdf(0),
m_shapeController(shapeController),
m_canvas(canvas),
m_pasteAsText(pasteAsText),
m_first(true)
{
m_rdf = qobject_cast<KoDocumentRdfBase*>(shapeController->resourceManager()->resource(KoText::DocumentRdf).value<QObject*>());
if (m_pasteAsText)
setText(i18nc("(qtundo-format)", "Paste As Text"));
else
setText(i18nc("(qtundo-format)", "Paste"));
}
void TextPasteCommand::undo()
{
KUndo2Command::undo();
}
void TextPasteCommand::redo()
{
if (m_document.isNull()) return;
KoTextDocument textDocument(m_document);
KoTextEditor *editor = textDocument.textEditor();
if (!m_first) {
KUndo2Command::redo();
} else {
editor->beginEditBlock(); //this is needed so Qt does not merge successive paste actions together
m_first = false;
if (editor->hasSelection()) { //TODO
editor->addCommand(new DeleteCommand(DeleteCommand::NextChar, m_document.data(), m_shapeController, this));
}
// check for mime type
if (m_mimeData->hasFormat(KoOdf::mimeType(KoOdf::Text))
|| m_mimeData->hasFormat(KoOdf::mimeType(KoOdf::OpenOfficeClipboard)) ) {
KoOdf::DocumentType odfType = KoOdf::Text;
if (!m_mimeData->hasFormat(KoOdf::mimeType(odfType))) {
odfType = KoOdf::OpenOfficeClipboard;
}
if (m_pasteAsText) {
editor->insertText(m_mimeData->text());
} else {
QSharedPointer<Soprano::Model> rdfModel;
#ifdef SHOULD_BUILD_RDF
if(!m_rdf) {
rdfModel = QSharedPointer<Soprano::Model>(Soprano::createModel());
} else {
rdfModel = m_rdf->model();
}
#endif
KoTextPaste paste(editor, m_shapeController, rdfModel, m_canvas, this);
paste.paste(odfType, m_mimeData);
#ifdef SHOULD_BUILD_RDF
if (m_rdf) {
m_rdf->updateInlineRdfStatements(editor->document());
}
#endif
}
} else if (!m_pasteAsText && m_mimeData->hasHtml()) {
editor->insertHtml(m_mimeData->html());
} else if (m_pasteAsText || m_mimeData->hasText()) {
editor->insertText(m_mimeData->text());
}
editor->endEditBlock(); //see above beginEditBlock
}
}
| Java |
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 2.4
# Default target executed when no arguments are given to make.
default_target: all
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canoncical targets will work.
.SUFFIXES:
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /opt/local/bin/cmake
# The command to remove a file.
RM = /opt/local/bin/cmake -E remove -f
# The program to use to edit the cache.
CMAKE_EDIT_COMMAND = /opt/local/bin/ccmake
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /Users/paul/Estelle-ruby/ext/taglib
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /Users/paul/Estelle-ruby/ext/taglib
# Include the progress variables for this target.
include CMakeFiles/progress.make
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake cache editor..."
cd /Users/paul/Estelle-ruby/ext/taglib/taglib/ape && /opt/local/bin/ccmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
# Special rule for the target install
install: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..."
cd /Users/paul/Estelle-ruby/ext/taglib/taglib/ape && /opt/local/bin/cmake -P cmake_install.cmake
# Special rule for the target install
install/fast: preinstall/fast
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..."
cd /Users/paul/Estelle-ruby/ext/taglib/taglib/ape && /opt/local/bin/cmake -P cmake_install.cmake
# Special rule for the target install/local
install/local: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..."
cd /Users/paul/Estelle-ruby/ext/taglib/taglib/ape && /opt/local/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake
# Special rule for the target install/local
install/local/fast: install/local
# Special rule for the target list_install_components
list_install_components:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Only default component available"
# Special rule for the target list_install_components
list_install_components/fast: list_install_components
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
cd /Users/paul/Estelle-ruby/ext/taglib/taglib/ape && /opt/local/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
# The main all target
all: cmake_check_build_system
cd /Users/paul/Estelle-ruby/ext/taglib && $(CMAKE_COMMAND) -E cmake_progress_start /Users/paul/Estelle-ruby/ext/taglib/CMakeFiles $(CMAKE_ALL_PROGRESS)
cd /Users/paul/Estelle-ruby/ext/taglib && $(MAKE) -f CMakeFiles/Makefile2 taglib/ape/all
$(CMAKE_COMMAND) -E cmake_progress_start /Users/paul/Estelle-ruby/ext/taglib/CMakeFiles 0
# The main clean target
clean:
cd /Users/paul/Estelle-ruby/ext/taglib && $(MAKE) -f CMakeFiles/Makefile2 taglib/ape/clean
# The main clean target
clean/fast: clean
# Prepare targets for installation.
preinstall: all
cd /Users/paul/Estelle-ruby/ext/taglib && $(MAKE) -f CMakeFiles/Makefile2 taglib/ape/preinstall
# Prepare targets for installation.
preinstall/fast:
cd /Users/paul/Estelle-ruby/ext/taglib && $(MAKE) -f CMakeFiles/Makefile2 taglib/ape/preinstall
# clear depends
depend:
$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
# Help Target
help::
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... edit_cache"
@echo "... install"
@echo "... install/local"
@echo "... list_install_components"
@echo "... rebuild_cache"
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
cd /Users/paul/Estelle-ruby/ext/taglib && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
| Java |
/*
* Virtual Raw MIDI client on Sequencer
*
* Copyright (c) 2000 by Takashi Iwai <tiwai@suse.de>,
* Jaroslav Kysela <perex@perex.cz>
*
* 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
*
*/
/*
* Virtual Raw MIDI client
*
* The virtual rawmidi client is a sequencer client which associate
* a rawmidi device file. The created rawmidi device file can be
* accessed as a normal raw midi, but its MIDI source and destination
* are arbitrary. For example, a user-client software synth connected
* to this port can be used as a normal midi device as well.
*
* The virtual rawmidi device accepts also multiple opens. Each file
* has its own input buffer, so that no conflict would occur. The drain
* of input/output buffer acts only to the local buffer.
*
*/
#include <linux/init.h>
#include <linux/wait.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/rawmidi.h>
#include <sound/info.h>
#include <sound/control.h>
#include <sound/minors.h>
#include <sound/seq_kernel.h>
#include <sound/seq_midi_event.h>
#include <sound/seq_virmidi.h>
MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>");
MODULE_DESCRIPTION("Virtual Raw MIDI client on Sequencer");
MODULE_LICENSE("GPL");
/*
* initialize an event record
*/
static void snd_virmidi_init_event(struct snd_virmidi *vmidi,
struct snd_seq_event *ev)
{
memset(ev, 0, sizeof(*ev));
ev->source.port = vmidi->port;
switch (vmidi->seq_mode) {
case SNDRV_VIRMIDI_SEQ_DISPATCH:
ev->dest.client = SNDRV_SEQ_ADDRESS_SUBSCRIBERS;
break;
case SNDRV_VIRMIDI_SEQ_ATTACH:
/* FIXME: source and destination are same - not good.. */
ev->dest.client = vmidi->client;
ev->dest.port = vmidi->port;
break;
}
ev->type = SNDRV_SEQ_EVENT_NONE;
}
/*
* decode input event and put to read buffer of each opened file
*/
static int snd_virmidi_dev_receive_event(struct snd_virmidi_dev *rdev,
struct snd_seq_event *ev)
{
struct snd_virmidi *vmidi;
unsigned char msg[4];
int len;
read_lock(&rdev->filelist_lock);
list_for_each_entry(vmidi, &rdev->filelist, list) {
if (!vmidi->trigger)
continue;
if (ev->type == SNDRV_SEQ_EVENT_SYSEX) {
if ((ev->flags & SNDRV_SEQ_EVENT_LENGTH_MASK) != SNDRV_SEQ_EVENT_LENGTH_VARIABLE)
continue;
snd_seq_dump_var_event(ev, (snd_seq_dump_func_t)snd_rawmidi_receive, vmidi->substream);
} else {
len = snd_midi_event_decode(vmidi->parser, msg, sizeof(msg), ev);
if (len > 0)
snd_rawmidi_receive(vmidi->substream, msg, len);
}
}
read_unlock(&rdev->filelist_lock);
return 0;
}
/*
* receive an event from the remote virmidi port
*
* for rawmidi inputs, you can call this function from the event
* handler of a remote port which is attached to the virmidi via
* SNDRV_VIRMIDI_SEQ_ATTACH.
*/
#if 0
int snd_virmidi_receive(struct snd_rawmidi *rmidi, struct snd_seq_event *ev)
{
struct snd_virmidi_dev *rdev;
rdev = rmidi->private_data;
return snd_virmidi_dev_receive_event(rdev, ev);
}
#endif /* 0 */
/*
* event handler of virmidi port
*/
static int snd_virmidi_event_input(struct snd_seq_event *ev, int direct,
void *private_data, int atomic, int hop)
{
struct snd_virmidi_dev *rdev;
rdev = private_data;
if (!(rdev->flags & SNDRV_VIRMIDI_USE))
return 0; /* ignored */
return snd_virmidi_dev_receive_event(rdev, ev);
}
/*
* trigger rawmidi stream for input
*/
static void snd_virmidi_input_trigger(struct snd_rawmidi_substream *substream, int up)
{
struct snd_virmidi *vmidi = substream->runtime->private_data;
if (up) {
vmidi->trigger = 1;
} else {
vmidi->trigger = 0;
}
}
/*
* trigger rawmidi stream for output
*/
static void snd_virmidi_output_trigger(struct snd_rawmidi_substream *substream, int up)
{
struct snd_virmidi *vmidi = substream->runtime->private_data;
int count, res;
unsigned char buf[32], *pbuf;
if (up) {
vmidi->trigger = 1;
if (vmidi->seq_mode == SNDRV_VIRMIDI_SEQ_DISPATCH &&
!(vmidi->rdev->flags & SNDRV_VIRMIDI_SUBSCRIBE)) {
snd_rawmidi_transmit_ack(substream, substream->runtime->buffer_size - substream->runtime->avail);
return; /* ignored */
}
if (vmidi->event.type != SNDRV_SEQ_EVENT_NONE) {
if (snd_seq_kernel_client_dispatch(vmidi->client, &vmidi->event, in_atomic(), 0) < 0)
return;
vmidi->event.type = SNDRV_SEQ_EVENT_NONE;
}
while (1) {
count = snd_rawmidi_transmit_peek(substream, buf, sizeof(buf));
if (count <= 0)
break;
pbuf = buf;
while (count > 0) {
res = snd_midi_event_encode(vmidi->parser, pbuf, count, &vmidi->event);
if (res < 0) {
snd_midi_event_reset_encode(vmidi->parser);
continue;
}
snd_rawmidi_transmit_ack(substream, res);
pbuf += res;
count -= res;
if (vmidi->event.type != SNDRV_SEQ_EVENT_NONE) {
if (snd_seq_kernel_client_dispatch(vmidi->client, &vmidi->event, in_atomic(), 0) < 0)
return;
vmidi->event.type = SNDRV_SEQ_EVENT_NONE;
}
}
}
} else {
vmidi->trigger = 0;
}
}
/*
* open rawmidi handle for input
*/
static int snd_virmidi_input_open(struct snd_rawmidi_substream *substream)
{
struct snd_virmidi_dev *rdev = substream->rmidi->private_data;
struct snd_rawmidi_runtime *runtime = substream->runtime;
struct snd_virmidi *vmidi;
unsigned long flags;
vmidi = kzalloc(sizeof(*vmidi), GFP_KERNEL);
if (vmidi == NULL)
return -ENOMEM;
vmidi->substream = substream;
if (snd_midi_event_new(0, &vmidi->parser) < 0) {
kfree(vmidi);
return -ENOMEM;
}
vmidi->seq_mode = rdev->seq_mode;
vmidi->client = rdev->client;
vmidi->port = rdev->port;
runtime->private_data = vmidi;
write_lock_irqsave(&rdev->filelist_lock, flags);
list_add_tail(&vmidi->list, &rdev->filelist);
write_unlock_irqrestore(&rdev->filelist_lock, flags);
vmidi->rdev = rdev;
return 0;
}
/*
* open rawmidi handle for output
*/
static int snd_virmidi_output_open(struct snd_rawmidi_substream *substream)
{
struct snd_virmidi_dev *rdev = substream->rmidi->private_data;
struct snd_rawmidi_runtime *runtime = substream->runtime;
struct snd_virmidi *vmidi;
vmidi = kzalloc(sizeof(*vmidi), GFP_KERNEL);
if (vmidi == NULL)
return -ENOMEM;
vmidi->substream = substream;
if (snd_midi_event_new(MAX_MIDI_EVENT_BUF, &vmidi->parser) < 0) {
kfree(vmidi);
return -ENOMEM;
}
vmidi->seq_mode = rdev->seq_mode;
vmidi->client = rdev->client;
vmidi->port = rdev->port;
snd_virmidi_init_event(vmidi, &vmidi->event);
vmidi->rdev = rdev;
runtime->private_data = vmidi;
return 0;
}
/*
* close rawmidi handle for input
*/
static int snd_virmidi_input_close(struct snd_rawmidi_substream *substream)
{
struct snd_virmidi *vmidi = substream->runtime->private_data;
snd_midi_event_free(vmidi->parser);
list_del(&vmidi->list);
substream->runtime->private_data = NULL;
kfree(vmidi);
return 0;
}
/*
* close rawmidi handle for output
*/
static int snd_virmidi_output_close(struct snd_rawmidi_substream *substream)
{
struct snd_virmidi *vmidi = substream->runtime->private_data;
snd_midi_event_free(vmidi->parser);
substream->runtime->private_data = NULL;
kfree(vmidi);
return 0;
}
/*
* subscribe callback - allow output to rawmidi device
*/
static int snd_virmidi_subscribe(void *private_data,
struct snd_seq_port_subscribe *info)
{
struct snd_virmidi_dev *rdev;
rdev = private_data;
if (!try_module_get(rdev->card->module))
return -EFAULT;
rdev->flags |= SNDRV_VIRMIDI_SUBSCRIBE;
return 0;
}
/*
* unsubscribe callback - disallow output to rawmidi device
*/
static int snd_virmidi_unsubscribe(void *private_data,
struct snd_seq_port_subscribe *info)
{
struct snd_virmidi_dev *rdev;
rdev = private_data;
rdev->flags &= ~SNDRV_VIRMIDI_SUBSCRIBE;
module_put(rdev->card->module);
return 0;
}
/*
* use callback - allow input to rawmidi device
*/
static int snd_virmidi_use(void *private_data,
struct snd_seq_port_subscribe *info)
{
struct snd_virmidi_dev *rdev;
rdev = private_data;
if (!try_module_get(rdev->card->module))
return -EFAULT;
rdev->flags |= SNDRV_VIRMIDI_USE;
return 0;
}
/*
* unuse callback - disallow input to rawmidi device
*/
static int snd_virmidi_unuse(void *private_data,
struct snd_seq_port_subscribe *info)
{
struct snd_virmidi_dev *rdev;
rdev = private_data;
rdev->flags &= ~SNDRV_VIRMIDI_USE;
module_put(rdev->card->module);
return 0;
}
/*
* Register functions
*/
static struct snd_rawmidi_ops snd_virmidi_input_ops = {
.open = snd_virmidi_input_open,
.close = snd_virmidi_input_close,
.trigger = snd_virmidi_input_trigger,
};
static struct snd_rawmidi_ops snd_virmidi_output_ops = {
.open = snd_virmidi_output_open,
.close = snd_virmidi_output_close,
.trigger = snd_virmidi_output_trigger,
};
/*
* create a sequencer client and a port
*/
static int snd_virmidi_dev_attach_seq(struct snd_virmidi_dev *rdev)
{
int client;
struct snd_seq_port_callback pcallbacks;
struct snd_seq_port_info *pinfo;
int err;
if (rdev->client >= 0)
return 0;
pinfo = kzalloc(sizeof(*pinfo), GFP_KERNEL);
if (!pinfo) {
err = -ENOMEM;
goto __error;
}
client = snd_seq_create_kernel_client(rdev->card, rdev->device,
"%s %d-%d", rdev->rmidi->name,
rdev->card->number,
rdev->device);
if (client < 0) {
err = client;
goto __error;
}
rdev->client = client;
/* create a port */
pinfo->addr.client = client;
sprintf(pinfo->name, "VirMIDI %d-%d", rdev->card->number, rdev->device);
/* set all capabilities */
pinfo->capability |= SNDRV_SEQ_PORT_CAP_WRITE | SNDRV_SEQ_PORT_CAP_SYNC_WRITE | SNDRV_SEQ_PORT_CAP_SUBS_WRITE;
pinfo->capability |= SNDRV_SEQ_PORT_CAP_READ | SNDRV_SEQ_PORT_CAP_SYNC_READ | SNDRV_SEQ_PORT_CAP_SUBS_READ;
pinfo->capability |= SNDRV_SEQ_PORT_CAP_DUPLEX;
pinfo->type = SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC
| SNDRV_SEQ_PORT_TYPE_SOFTWARE
| SNDRV_SEQ_PORT_TYPE_PORT;
pinfo->midi_channels = 16;
memset(&pcallbacks, 0, sizeof(pcallbacks));
pcallbacks.owner = THIS_MODULE;
pcallbacks.private_data = rdev;
pcallbacks.subscribe = snd_virmidi_subscribe;
pcallbacks.unsubscribe = snd_virmidi_unsubscribe;
pcallbacks.use = snd_virmidi_use;
pcallbacks.unuse = snd_virmidi_unuse;
pcallbacks.event_input = snd_virmidi_event_input;
pinfo->kernel = &pcallbacks;
err = snd_seq_kernel_client_ctl(client, SNDRV_SEQ_IOCTL_CREATE_PORT, pinfo);
if (err < 0) {
snd_seq_delete_kernel_client(client);
rdev->client = -1;
goto __error;
}
rdev->port = pinfo->addr.port;
err = 0; /* success */
__error:
kfree(pinfo);
return err;
}
/*
* release the sequencer client
*/
static void snd_virmidi_dev_detach_seq(struct snd_virmidi_dev *rdev)
{
if (rdev->client >= 0) {
snd_seq_delete_kernel_client(rdev->client);
rdev->client = -1;
}
}
/*
* register the device
*/
static int snd_virmidi_dev_register(struct snd_rawmidi *rmidi)
{
struct snd_virmidi_dev *rdev = rmidi->private_data;
int err;
switch (rdev->seq_mode) {
case SNDRV_VIRMIDI_SEQ_DISPATCH:
err = snd_virmidi_dev_attach_seq(rdev);
if (err < 0)
return err;
break;
case SNDRV_VIRMIDI_SEQ_ATTACH:
if (rdev->client == 0)
return -EINVAL;
/* should check presence of port more strictly.. */
break;
default:
snd_printk(KERN_ERR "seq_mode is not set: %d\n", rdev->seq_mode);
return -EINVAL;
}
return 0;
}
/*
* unregister the device
*/
static int snd_virmidi_dev_unregister(struct snd_rawmidi *rmidi)
{
struct snd_virmidi_dev *rdev = rmidi->private_data;
if (rdev->seq_mode == SNDRV_VIRMIDI_SEQ_DISPATCH)
snd_virmidi_dev_detach_seq(rdev);
return 0;
}
/*
*
*/
static struct snd_rawmidi_global_ops snd_virmidi_global_ops = {
.dev_register = snd_virmidi_dev_register,
.dev_unregister = snd_virmidi_dev_unregister,
};
/*
* free device
*/
static void snd_virmidi_free(struct snd_rawmidi *rmidi)
{
struct snd_virmidi_dev *rdev = rmidi->private_data;
kfree(rdev);
}
/*
* create a new device
*
*/
/* exported */
int snd_virmidi_new(struct snd_card *card, int device, struct snd_rawmidi **rrmidi)
{
struct snd_rawmidi *rmidi;
struct snd_virmidi_dev *rdev;
int err;
*rrmidi = NULL;
if ((err = snd_rawmidi_new(card, "VirMidi", device,
16, /* may be configurable */
16, /* may be configurable */
&rmidi)) < 0)
return err;
strcpy(rmidi->name, rmidi->id);
rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
if (rdev == NULL) {
snd_device_free(card, rmidi);
return -ENOMEM;
}
rdev->card = card;
rdev->rmidi = rmidi;
rdev->device = device;
rdev->client = -1;
rwlock_init(&rdev->filelist_lock);
INIT_LIST_HEAD(&rdev->filelist);
rdev->seq_mode = SNDRV_VIRMIDI_SEQ_DISPATCH;
rmidi->private_data = rdev;
rmidi->private_free = snd_virmidi_free;
rmidi->ops = &snd_virmidi_global_ops;
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &snd_virmidi_input_ops);
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &snd_virmidi_output_ops);
rmidi->info_flags = SNDRV_RAWMIDI_INFO_INPUT |
SNDRV_RAWMIDI_INFO_OUTPUT |
SNDRV_RAWMIDI_INFO_DUPLEX;
*rrmidi = rmidi;
return 0;
}
/*
* ENTRY functions
*/
static int __init alsa_virmidi_init(void)
{
return 0;
}
static void __exit alsa_virmidi_exit(void)
{
}
module_init(alsa_virmidi_init)
module_exit(alsa_virmidi_exit)
EXPORT_SYMBOL(snd_virmidi_new);
| Java |
@echo off
taskkill /f /im paraengineclient.exe
taskkill /f /im cmd.exe | Java |
// External imports
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import javax.imageio.ImageIO;
import javax.swing.*;
// Local imports
import org.j3d.renderer.aviatrix3d.texture.TextureCreateUtils;
/**
* Example application that demonstrates how to use the loader interface
* to load a file into the scene graph.
* <p>
*
* @author Justin Couch
* @version $Revision: 1.1 $
*/
public class NormalMapDemo extends JFrame
implements ActionListener
{
private JFileChooser openDialog;
/** Renderer for the basic image */
private ImageIcon srcIcon;
private JLabel srcLabel;
/** Renderer for the normal map version */
private ImageIcon mapIcon;
private JLabel mapLabel;
/** Utility for munging textures to power of 2 size */
private TextureCreateUtils textureUtils;
public NormalMapDemo()
{
super("Normal map conversion demo");
setSize(1280, 1024);
setLocation(0, 0);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textureUtils = new TextureCreateUtils();
JPanel p1 = new JPanel(new BorderLayout());
srcIcon = new ImageIcon();
srcLabel = new JLabel();
srcLabel.setVerticalTextPosition(SwingConstants.BOTTOM);
srcLabel.setText("Source Image");
mapIcon = new ImageIcon();
mapLabel = new JLabel();
mapLabel.setVerticalTextPosition(SwingConstants.BOTTOM);
mapLabel.setText("NormalMap Image");
JButton b = new JButton("Open A file");
b.addActionListener(this);
p1.add(b, BorderLayout.SOUTH);
p1.add(srcLabel, BorderLayout.WEST);
p1.add(mapLabel, BorderLayout.EAST);
getContentPane().add(p1);
}
//---------------------------------------------------------------
// Methods defined by WindowListener
//---------------------------------------------------------------
/**
* Process the action event from the open button
*/
public void actionPerformed(ActionEvent evt)
{
if(openDialog == null)
openDialog = new JFileChooser();
int ret_val = openDialog.showOpenDialog(this);
if(ret_val != JFileChooser.APPROVE_OPTION)
return;
File file = openDialog.getSelectedFile();
try
{
System.out.println("Loading external file: " + file);
FileInputStream is = new FileInputStream(file);
BufferedInputStream stream = new BufferedInputStream(is);
BufferedImage img = ImageIO.read(stream);
if(img == null)
{
System.out.println("Image load barfed");
return;
}
srcIcon.setImage(img);
srcLabel.setIcon(srcIcon);
BufferedImage map_img = textureUtils.createNormalMap(img, null);
mapIcon.setImage(map_img);
mapLabel.setIcon(mapIcon);
}
catch(IOException ioe)
{
System.out.println("crashed " + ioe.getMessage());
ioe.printStackTrace();
}
}
//---------------------------------------------------------------
// Local methods
//---------------------------------------------------------------
public static void main(String[] args)
{
NormalMapDemo demo = new NormalMapDemo();
demo.setVisible(true);
}
}
| Java |
# tps23861
Linux driver for TPS23861 IEEE 802.3at Quad Port Power-over-Ethernet PSE Controller.
Tested with kernel version 3.19.0
Bindings example:
tps23861: tps23861@20 {
compatible = "ti,tps23861";
reg = <0x20>;
irq-gpio = <84>;
port0@0 {
enable = <1>;
mode = "auto";
power = <1>;
};
port1@1 {
enable = <1>;
mode = "manual";
power = <0>;
};
port2@2 {
enable = <0>;
};
port3@3 {
enable = <0>;
};
};
| Java |
<?php get_header() ?>
archive
<!--/nav-->
<?php
$banner_image = get_field('banner_image');
$bannerUrl = wp_get_attachment_image_src($banner_image, 'large');
$bannerImg = aq_resize($bannerUrl[0], 974, 312, true);
if ($bannerImg == '') {
$bannerImg = get_template_directory_uri() . '/images/the-authors-banner.jpg';
}
?>
<section id="banner">
<div class="container" style="background-image:url('<?php echo $bannerImg; ?>');">
</div>
</section>
<!--main-->
<div id="main" role="main">
<div class="container">
<section id="archive-news">
<header class="section-header left"><h1>Latest News</h1></header>
<?php if (have_posts()):
while (have_posts()) : the_post();
?>
<?php
$feat_image = get_post_thumbnail_id($post->ID);
$featureUrl = wp_get_attachment_image_src($feat_image, 'large');
$featureImage = aq_resize($featureUrl[0], 309, 206, true);
?>
<article class="has-feature">
<div class="wrap">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<div class="alpha">
<small><time datetime="2014-11-21"><?php echo get_the_date(); ?></time></small>
<?php the_content(); ?>
</div>
<div class="beta"><figure><a href="<?php the_permalink(); ?>"><img src="<?php echo $featureImage; ?>" /></a></figure></div>
</div>
<div class="divide"><div></div></div>
</article>
<?php
endwhile;
endif;
?>
</section>
</div> <!-- /container -->
</div>
<!-- testimonials slider -->
<!-- /testimonials slider -->
<?php get_footer() ?> | Java |
/*
* The TiLib: wavelet based lossy image compression library
* Copyright (C) 1998-2004 Alexander Simakov
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* QuikInfo:
*
* Top-level compression & decompression functions.
*
*/
#ifndef TILIB_H
#define TILIB_H
#ifdef __cplusplus
extern "C" {
#endif
#define GRAYSCALE (0)
#define TRUECOLOR (1)
#define BUTTERWORTH (0)
#define DAUB97 (1)
int TiCompress(unsigned char *image,
unsigned char *stream,
int img_width,
int img_height,
int wavelet,
int img_type,
int desired_size,
int *actual_size,
int lum_ratio,
int cb_ratio,
int cr_ratio,
int scales);
int TiCheckHeader(unsigned char *stream,
int *img_width,
int *img_height,
int *img_type,
int stream_size);
int TiDecompress(unsigned char *stream,
unsigned char *image,
int img_width,
int img_height,
int img_type,
int stream_size);
#ifdef __cplusplus
}
#endif
#endif /* TILIB_H */
| Java |
<?php
/**
* Created by PhpStorm.
* User: Anh Tuan
* Date: 4/22/14
* Time: 12:26 AM
*/
//////////////////////////////////////////////////////////////////
// Dropcap shortcode
//////////////////////////////////////////////////////////////////
add_shortcode( 'dropcap', 'shortcode_dropcap' );
function shortcode_dropcap( $atts, $content = null ) {
extract( shortcode_atts( array(
'text' => '',
'el_class' => ''
), $atts ) );
return '<span class="dropcap '.$el_class.'">' . $content . '</span>';
} | Java |
/*
* $RCSfile: OrCRIF.java,v $
*
* Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
*
* Use is subject to license terms.
*
* $Revision: 1.1 $
* $Date: 2005/02/11 04:56:38 $
* $State: Exp $
*/
package com.sun.media.jai.opimage;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.RenderContext;
import java.awt.image.renderable.ParameterBlock;
import java.awt.image.renderable.RenderableImage;
import javax.media.jai.CRIFImpl;
import javax.media.jai.ImageLayout;
import java.util.Map;
/**
* A <code>CRIF</code> supporting the "Or" operation in the
* rendered and renderable image layers.
*
* @since EA2
* @see javax.media.jai.operator.OrDescriptor
* @see OrOpImage
*
*/
public class OrCRIF extends CRIFImpl {
/** Constructor. */
public OrCRIF() {
super("or");
}
/**
* Creates a new instance of <code>OrOpImage</code> in the
* rendered layer. This method satisifies the implementation of RIF.
*
* @param paramBlock The two source images to be "Ored" together.
* @param renderHints Optionally contains destination image layout.
*/
public RenderedImage create(ParameterBlock paramBlock,
RenderingHints renderHints) {
// Get ImageLayout from renderHints if any.
ImageLayout layout = RIFUtil.getImageLayoutHint(renderHints);
return new OrOpImage(paramBlock.getRenderedSource(0),
paramBlock.getRenderedSource(1),
renderHints,
layout);
}
}
| Java |
using BlueBit.CarsEvidence.Commons.Templates;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.Contracts;
namespace BlueBit.CarsEvidence.BL.Entities
{
public class Person :
EntityBase,
IObjectWithGetCode,
IObjectWithGetInfo
{
[Required]
[MaxLength(Configuration.Consts.LengthCode)]
public virtual string Code { get; set; }
[MaxLength(Configuration.Consts.LengthInfo)]
public virtual string Info { get; set; }
[Required]
[MaxLength(Configuration.Consts.LengthText)]
public virtual string FirstName { get; set; }
[Required]
[MaxLength(Configuration.Consts.LengthText)]
public virtual string LastName { get; set; }
public virtual ISet<PeriodRouteEntry> PeriodRouteEntries { get; set; }
public virtual ISet<PeriodFuelEntry> PeriodFuelEntries { get; set; }
public override void Init()
{
PeriodRouteEntries = PeriodRouteEntries ?? new HashSet<PeriodRouteEntry>();
PeriodFuelEntries = PeriodFuelEntries ?? new HashSet<PeriodFuelEntry>();
}
}
public static class PersonExtensions
{
public static PeriodRouteEntry AddPeriodRouteEntry(this Person @this, PeriodRouteEntry entry)
{
Contract.Assert(@this != null);
Contract.Assert(entry != null);
Contract.Assert(entry.Person == null);
entry.Person = @this;
@this.PeriodRouteEntries.Add(entry);
return entry;
}
public static PeriodFuelEntry AddPeriodFuelEntry(this Person @this, PeriodFuelEntry entry)
{
Contract.Assert(@this != null);
Contract.Assert(entry != null);
Contract.Assert(entry.Person == null);
entry.Person = @this;
@this.PeriodFuelEntries.Add(entry);
return entry;
}
}
}
| Java |
/*
* Created by Rolando Abarca 2012.
* Copyright (c) 2012 Rolando Abarca. All rights reserved.
* Copyright (c) 2013 Zynga Inc. All rights reserved.
* Copyright (c) 2013-2014 Chukong Technologies Inc.
*
* Heavy based on: https://github.com/funkaster/FakeWebGL/blob/master/FakeWebGL/WebGL/XMLHTTPRequest.h
*
* 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.
*/
#ifndef __FAKE_XMLHTTPREQUEST_H__
#define __FAKE_XMLHTTPREQUEST_H__
#include "jsapi.h"
#include "jsfriendapi.h"
#include "network/HttpClient.h"
#include "js_bindings_config.h"
#include "ScriptingCore.h"
#include "jsb_helper.h"
class MinXmlHttpRequest : public cocos2d::Ref
{
public:
enum class ResponseType
{
STRING,
ARRAY_BUFFER,
BLOB,
DOCUMENT,
JSON
};
// Ready States (http://www.w3.org/TR/XMLHttpRequest/#interface-xmlhttprequest)
static const unsigned short UNSENT = 0;
static const unsigned short OPENED = 1;
static const unsigned short HEADERS_RECEIVED = 2;
static const unsigned short LOADING = 3;
static const unsigned short DONE = 4;
MinXmlHttpRequest();
~MinXmlHttpRequest();
JS_BINDED_CLASS_GLUE(MinXmlHttpRequest);
JS_BINDED_CONSTRUCTOR(MinXmlHttpRequest);
JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, onreadystatechange);
JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, responseType);
JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, withCredentials);
JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, upload);
JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, timeout);
JS_BINDED_PROP_GET(MinXmlHttpRequest, readyState);
JS_BINDED_PROP_GET(MinXmlHttpRequest, status);
JS_BINDED_PROP_GET(MinXmlHttpRequest, statusText);
JS_BINDED_PROP_GET(MinXmlHttpRequest, responseText);
JS_BINDED_PROP_GET(MinXmlHttpRequest, response);
JS_BINDED_PROP_GET(MinXmlHttpRequest, responseXML);
JS_BINDED_FUNC(MinXmlHttpRequest, open);
JS_BINDED_FUNC(MinXmlHttpRequest, send);
JS_BINDED_FUNC(MinXmlHttpRequest, abort);
JS_BINDED_FUNC(MinXmlHttpRequest, getAllResponseHeaders);
JS_BINDED_FUNC(MinXmlHttpRequest, getResponseHeader);
JS_BINDED_FUNC(MinXmlHttpRequest, setRequestHeader);
JS_BINDED_FUNC(MinXmlHttpRequest, overrideMimeType);
void handle_requestResponse(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response);
private:
void _gotHeader(std::string header);
void _setRequestHeader(const char* field, const char* value);
void _setHttpRequestHeader();
void _sendRequest(JSContext *cx);
std::string _url;
JSContext* _cx;
std::string _meth;
std::string _type;
char* _data;
uint32_t _dataSize;
JSObject* _onreadystateCallback;
int _readyState;
int _status;
std::string _statusText;
ResponseType _responseType;
unsigned _timeout;
bool _isAsync;
cocos2d::network::HttpRequest* _httpRequest;
bool _isNetwork;
bool _withCredentialsValue;
bool _errorFlag;
std::unordered_map<std::string, std::string> _httpHeader;
std::unordered_map<std::string, std::string> _requestHeader;
};
#endif
| Java |
<?php
/**
Admin Page Framework v3.5.6 by Michael Uno
Generated by PHP Class Files Script Generator <https://github.com/michaeluno/PHP-Class-Files-Script-Generator>
<http://en.michaeluno.jp/admin-page-framework>
Copyright (c) 2013-2015, Michael Uno; Licensed under MIT <http://opensource.org/licenses/MIT>
*/
abstract class SeamlessDonationsAdminPageFramework_TaxonomyField_View extends SeamlessDonationsAdminPageFramework_TaxonomyField_Model {
public function _replyToPrintFieldsWOTableRows($oTerm) {
echo $this->_getFieldsOutput(isset($oTerm->term_id) ? $oTerm->term_id : null, false);
}
public function _replyToPrintFieldsWithTableRows($oTerm) {
echo $this->_getFieldsOutput(isset($oTerm->term_id) ? $oTerm->term_id : null, true);
}
private function _getFieldsOutput($iTermID, $bRenderTableRow) {
$_aOutput = array();
$_aOutput[] = wp_nonce_field($this->oProp->sClassHash, $this->oProp->sClassHash, true, false);
$this->_setOptionArray($iTermID, $this->oProp->sOptionKey);
$this->oForm->format();
$_oFieldsTable = new SeamlessDonationsAdminPageFramework_FormTable($this->oProp->aFieldTypeDefinitions, $this->_getFieldErrors(), $this->oMsg);
$_aOutput[] = $bRenderTableRow ? $_oFieldsTable->getFieldRows($this->oForm->aFields['_default'], array($this, '_replyToGetFieldOutput')) : $_oFieldsTable->getFields($this->oForm->aFields['_default'], array($this, '_replyToGetFieldOutput'));
$_sOutput = $this->oUtil->addAndApplyFilters($this, 'content_' . $this->oProp->sClassName, implode(PHP_EOL, $_aOutput));
$this->oUtil->addAndDoActions($this, 'do_' . $this->oProp->sClassName, $this);
return $_sOutput;
}
public function _replyToPrintColumnCell($vValue, $sColumnSlug, $sTermID) {
$_sCellHTML = '';
if (isset($_GET['taxonomy']) && $_GET['taxonomy']) {
$_sCellHTML = $this->oUtil->addAndApplyFilter($this, "cell_{$_GET['taxonomy']}", $vValue, $sColumnSlug, $sTermID);
}
$_sCellHTML = $this->oUtil->addAndApplyFilter($this, "cell_{$this->oProp->sClassName}", $_sCellHTML, $sColumnSlug, $sTermID);
$_sCellHTML = $this->oUtil->addAndApplyFilter($this, "cell_{$this->oProp->sClassName}_{$sColumnSlug}", $_sCellHTML, $sTermID);
echo $_sCellHTML;
}
} | Java |
<?php
/**
* Created by PhpStorm.
* User: udit
* Date: 12/9/14
* Time: 10:43 AM
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'WM_Revision' ) ) {
/**
* Class WM_Revision
*
* Handles all the functionality to track custom fields
*
* @since 0.4
*/
class WM_Revision {
/**
* @since 0.4
*/
function __construct() {
/**
* This hook filters the number of revisions to keep for a specific post.
*/
add_filter( 'wp_revisions_to_keep', array( $this, 'filter_revisions_to_keep' ), 999, 2 );
/**
* This hooks gets fired once a revision is stored in WP_Post table in DB.
*
* This gives us $revision_id. So we can make use of that and store our stuff into post meta for that particular revision.
* E.g., Taxonomy diff, meta diff., featured image diff, etc.
*
*/
add_action( '_wp_put_post_revision', array( $this, 'post_revision_process' ), 10, 1 );
/**
* Filter whether the post has changed since the last revision.
*
* By default a revision is saved only if one of the revisioned fields has changed.
* This filter can override that so a revision is saved even if nothing has changed.
*
* We will take care of our own fields and pass on the flag.
*/
add_filter( 'wp_save_post_revision_post_has_changed', array( $this, 'check_for_changes' ), 10, 3 );
/**
* We may have to call this dynamically within a for loop. depending upon how many custom fields that we are supporting.
*/
foreach ( array_keys( $this->get_custom_revision_fields() ) as $field ) {
add_filter( '_wp_post_revision_field_'.$field, array( $this, 'revision_field_content' ), 10, 4 );
}
/**
* This adds custom diff ui for custom revision fields
*/
add_filter( 'wp_get_revision_ui_diff', array( $this, 'revision_ui_diff' ), 10, 3 );
}
/**
* @param $num
* @param $post
*
* @return int
* @since 0.1
*/
function filter_revisions_to_keep( $num, $post ) {
// Check individual Post Limit
$revision_limit = get_post_meta( $post->ID, WM_Admin::$wm_revision_limit_meta_key, true );
if ( '' !== $revision_limit ) {
if ( ! is_numeric( $revision_limit ) ) {
$num = - 1;
} else {
$num = intval( $revision_limit );
}
} else {
$post_type = get_post_type( $post );
$revision_limit = get_option( WM_Settings::$revision_limit_key . $post_type, false );
if ( '' === $revision_limit || ! is_numeric( $revision_limit ) ) {
$num = - 1;
} else {
$num = intval( $revision_limit );
}
}
return $num;
}
/**
* @return array $revision_fields
* @since 0.5
*/
function get_custom_revision_fields() {
$revision_fields = array(
'post_author' => array(
'label' => __( 'Post Author', WM_TEXT_DOMAIN ),
'meta_key' => '_wm_post_author',
'meta_value' => function( $post ) {
$author = new WP_User( $post->post_author );
return $author->display_name . ' (' . $post->post_author . ')';
},
),
'post_status' => array(
'label' => __( 'Post Status', WM_TEXT_DOMAIN ),
'meta_key' => '_wm_post_status',
'meta_value' => function( $post ) {
$post_status = get_post_status_object( $post->post_status );
return $post_status->label;
},
),
'post_date' => array(
'label' => __( 'Post Date', WM_TEXT_DOMAIN ),
'meta_key' => '_wm_post_date',
'meta_value' => function( $post ) {
$datef = 'M j, Y @ H:i';
return date_i18n( $datef, strtotime( $post->post_date ) );
},
),
);
return $revision_fields;
}
/**
* @param $revision_id
* @since 0.4
*/
function post_revision_process( $revision_id ) {
$revision = get_post( $revision_id );
$post = get_post( $revision->post_parent );
foreach ( $this->get_custom_revision_fields() as $field => $fieldmeta ) {
update_post_meta( $post->ID, $fieldmeta['meta_key'] . '_' . $revision_id , call_user_func( $fieldmeta['meta_value'], $post ) );
}
}
/**
* @param $post_has_changed
* @param $last_revision
* @param $post
*
* @return mixed
* @since 0.4
*/
function check_for_changes( $post_has_changed, $last_revision, $post ) {
foreach ( $this->get_custom_revision_fields() as $field => $fieldmeta ) {
$post_value = normalize_whitespace( call_user_func( $fieldmeta['meta_value'], $post ) );
$revision_value = normalize_whitespace( apply_filters( "_wp_post_revision_field_$field", $last_revision->$field, $field, $last_revision, 'from' ) );
if ( $post_value != $revision_value ) {
$post_has_changed = true;
break;
}
}
return $post_has_changed;
}
/**
* Contextually filter a post revision field.
*
* The dynamic portion of the hook name, $field, corresponds to each of the post
* fields of the revision object being iterated over in a foreach statement.
*
* @param string $value The current revision field to compare to or from.
* @param string $field The current revision field.
* @param WP_Post $post The revision post object to compare to or from.
* @param string $context The context of whether the current revision is the old or the new one. Values are 'to' or 'from'.
*
* @return string $value
* @since 0.4
*/
function revision_field_content( $value, $field, $post, $context ) {
$revision_fields = $this->get_custom_revision_fields();
if ( array_key_exists( $field, $revision_fields ) ) {
$value = get_post_meta( $post->post_parent, $revision_fields[ $field ]['meta_key'] . '_' . $post->ID, true );
}
return $value;
}
/**
* Filter the fields displayed in the post revision diff UI.
*
* @since 4.1.0
*
* @param array $return Revision UI fields. Each item is an array of id, name and diff.
* @param WP_Post $compare_from The revision post to compare from.
* @param WP_Post $compare_to The revision post to compare to.
*
* @return array $return
* @since 0.5
*/
function revision_ui_diff( $return, $compare_from, $compare_to ) {
foreach ( $this->get_custom_revision_fields() as $field => $fieldmeta ) {
/**
* Contextually filter a post revision field.
*
* The dynamic portion of the hook name, `$field`, corresponds to each of the post
* fields of the revision object being iterated over in a foreach statement.
*
* @since 3.6.0
*
* @param string $compare_from->$field The current revision field to compare to or from.
* @param string $field The current revision field.
* @param WP_Post $compare_from The revision post object to compare to or from.
* @param string null The context of whether the current revision is the old
* or the new one. Values are 'to' or 'from'.
*/
$content_from = $compare_from ? apply_filters( "_wp_post_revision_field_$field", $compare_from->$field, $field, $compare_from, 'from' ) : '';
/** This filter is documented in wp-admin/includes/revision.php */
$content_to = apply_filters( "_wp_post_revision_field_$field", $compare_to->$field, $field, $compare_to, 'to' );
$args = array(
'show_split_view' => true,
);
/**
* Filter revisions text diff options.
*
* Filter the options passed to {@see wp_text_diff()} when viewing a post revision.
*
* @since 4.1.0
*
* @param array $args {
* Associative array of options to pass to {@see wp_text_diff()}.
*
* @type bool $show_split_view True for split view (two columns), false for
* un-split view (single column). Default true.
* }
* @param string $field The current revision field.
* @param WP_Post $compare_from The revision post to compare from.
* @param WP_Post $compare_to The revision post to compare to.
*/
$args = apply_filters( 'revision_text_diff_options', $args, $field, $compare_from, $compare_to );
$diff = wp_text_diff( $content_from, $content_to, $args );
if ( $diff ) {
$return[] = array(
'id' => $field,
'name' => $fieldmeta['label'],
'diff' => $diff,
);
}
}
return $return;
}
}
}
| Java |
<?php
/**
* The main template file.
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package morrisseys_catering
*/
get_header(); ?>
<?php if ( have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
/* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'content', get_post_format() );
?>
<?php endwhile; ?>
<?php morrisseys_catering_content_nav( 'nav-below' ); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
<div id="food-content">
<h1>image</h1>
<div id="inner-box">
<p>Fresh. Local. Family Owned.</p>
<a class="button" href="#">
<h1>Icon menu </h1>
<p>Browse Menus</p>
</a>
</div>
</div>
<div class="wrapper">
<blockquote id="feedback">
<p> Thank you for providing us each delicious food and service for the St. Mary's
50th Anniversary Celebration! The food was excellent and you are all the best to work with! We are grateful for you, thank you.<br>
<span>-Siobhan </span>
</p>
<div class="splitter">
</div>
<br>
<br>
<p>Many thanks for your kindness during such a sad time for us - you were so helpful. Everyone enjoyed your wonderful food at the church reception. <br> <span>-Mrs. Showalter</span></p>
</blockquote>
<div id="contact-info">
<div id="contact-box">
<img src="wp-content/themes/morrisseys_catering/images/icon_phone.png" alt="phone.icon"> <p> (804) 592-2188</p>
</div>
<br>
<br>
<div class="address-info">
<p> 8901 Three Chopt Road, Suite A, Richmond, Va 23229 </p>
<p> Located in the Westbury Pharmacy Center</p>
</div> <!--address-info -->
</div> <!-- contact-info" -->
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
| Java |
<?php
/* --------------------------------------------------------------
$Id: customer_memo.php 10395 2016-11-07 13:18:38Z GTB $
modified eCommerce Shopsoftware
http://www.modified-shop.org
Copyright (c) 2009 - 2013 [www.modified-shop.org]
--------------------------------------------------------------
Released under the GNU General Public License
--------------------------------------------------------------
Third Party contribution:
(c) 2003 XT-Commerce
(c) 2003 nextcommerce (customer_memo.php,v 1.6 2003/08/18); www.nextcommerce.org
--------------------------------------------------------------*/
defined( '_VALID_XTC' ) or die( 'Direct Access to this location is not allowed.' );
?>
<td class="dataTableConfig col-left" style="vertical-align:top;"><?php echo ENTRY_MEMO; ?></td>
<td class="dataTableConfig col-single-right">
<?php
$memo_query = xtc_db_query("SELECT *
FROM " . TABLE_CUSTOMERS_MEMO . "
WHERE customers_id = '" . (int)$_GET['cID'] . "'
ORDER BY memo_date DESC");
if (xtc_db_num_rows($memo_query) > 0) {
while ($memo_values = xtc_db_fetch_array($memo_query)) {
$poster_query = xtc_db_query("SELECT customers_firstname, customers_lastname FROM " . TABLE_CUSTOMERS . " WHERE customers_id = '" . $memo_values['poster_id'] . "'");
$poster_values = xtc_db_fetch_array($poster_query);
?>
<div style="margin:2px; padding:2px; border: 1px solid; border-color: #cccccc;">
<table style="width:100%">
<tr>
<td class="main" style="width:120px; border:none; padding:2px;"><strong><?php echo TEXT_DATE; ?></strong>:</td>
<td class="main" style="border:none; padding:2px;"><?php echo xtc_date_short($memo_values['memo_date']); ?></td>
</tr>
<tr>
<td class="main" style="border:none; padding:2px;"><strong><?php echo TEXT_TITLE; ?></strong>:</td>
<td class="main" style="border:none; padding:2px;"><?php echo $memo_values['memo_title']; ?></td>
</tr>
<tr>
<td class="main" style="border:none; padding:2px;"><strong><?php echo TEXT_POSTER; ?></strong>:</td>
<td class="main" style="border:none; padding:2px;"><?php echo $poster_values['customers_lastname'] . ' ' . $poster_values['customers_firstname']; ?></td>
</tr>
<tr>
<td class="main" style="border:none; padding:2px; vertical-align:top;"><strong><?php echo ENTRY_MEMO; ?></strong>:</td>
<td class="main" style="border:none; padding:2px;"><?php echo $memo_values['memo_text']; ?></td>
</tr>
<tr>
<td class="txta-r" colspan="2" style="border:none; padding:2px;"><a style="text-decoration:none;" href="<?php echo xtc_href_link(basename($PHP_SELF), 'cID=' . (int)$_GET['cID'] . '&action=edit&special=remove_memo&mID=' . $memo_values['memo_id']); ?>" class="button" onclick="return confirmLink('<?php echo DELETE_ENTRY; ?>', '', this)"><?php echo BUTTON_DELETE; ?></a></td>
</tr>
</table>
</div>
<?php
}
echo '<br/>';
}
?>
<div style="margin:2px; padding:2px; border: 1px solid; border-color: #cccccc;">
<table style="width:100%">
<tr>
<td class="main" style="width:80px; border:none; padding:2px;"><strong><?php echo TEXT_TITLE; ?></strong>:</td>
<td class="main" style="border:none; padding:2px;"><?php echo xtc_draw_input_field('memo_title', ((isset($cInfo->memo_title)) ? $cInfo->memo_title : ''), 'style="width:100%; max-width:676px;"'); ?></td>
</tr>
<tr>
<td class="main" style="border:none; padding:2px; vertical-align:top;"><strong><?php echo ENTRY_MEMO; ?></strong>:</td>
<td class="main" style="border:none; padding:2px;"><?php echo xtc_draw_textarea_field('memo_text', 'soft', '80', '8', ((isset($cInfo->memo_text)) ? $cInfo->memo_text : ''), 'style="width:99%; max-width:676px;"'); ?></td>
</tr>
<tr>
<td class="txta-r" colspan="2" style="border:none; padding:2px;"><input type="submit" class="button" value="<?php echo BUTTON_INSERT; ?>"></td>
</tr>
</table>
</div>
</td> | Java |
<?php
/* Icinga Web 2 | (c) 2013-2015 Icinga Development Team | GPLv2+ */
use Icinga\Web\Controller;
use Icinga\Web\Url;
use Icinga\Web\Widget\Tabextension\DashboardAction;
use Icinga\Web\Widget\Tabextension\OutputFormat;
use Icinga\Application\Config;
use Icinga\Application\Logger;
use Icinga\Data\ConfigObject;
use Icinga\Protocol\File\FileReader;
use \Zend_Controller_Action_Exception as ActionError;
/**
* Class ListController
*
* Application wide controller for various listing actions
*/
class ListController extends Controller
{
/**
* Add title tab
*
* @param string $action
*/
protected function addTitleTab($action)
{
$this->getTabs()->add($action, array(
'label' => ucfirst($action),
'url' => Url::fromPath(
'list/'
. str_replace(' ', '', $action)
)
))->extend(new OutputFormat())->extend(new DashboardAction())->activate($action);
}
/**
* Display the application log
*/
public function applicationlogAction()
{
if (! Logger::writesToFile()) {
throw new ActionError('Site not found', 404);
}
$this->addTitleTab('application log');
$resource = new FileReader(new ConfigObject(array(
'filename' => Config::app()->get('logging', 'file'),
'fields' => '/(?<!.)(?<datetime>[0-9]{4}(?:-[0-9]{2}){2}' // date
. 'T[0-9]{2}(?::[0-9]{2}){2}(?:[\+\-][0-9]{2}:[0-9]{2})?)' // time
. ' - (?<loglevel>[A-Za-z]+) - (?<message>.*)(?!.)/msS' // loglevel, message
)));
$this->view->logData = $resource->select()->order('DESC');
$this->setupLimitControl();
$this->setupPaginationControl($this->view->logData);
}
}
| Java |
SHELL = /bin/sh
# V=0 quiet, V=1 verbose. other values don't work.
V = 0
Q1 = $(V:1=)
Q = $(Q1:0=@)
ECHO1 = $(V:1=@ :)
ECHO = $(ECHO1:0=@ echo)
NULLCMD = :
#### Start of system configuration section. ####
srcdir = .
topdir = /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/include/ruby-2.6.0
hdrdir = $(topdir)
arch_hdrdir = /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/include/ruby-2.6.0/universal-darwin19
PATH_SEPARATOR = :
VPATH = $(srcdir):$(arch_hdrdir)/ruby:$(hdrdir)/ruby
prefix = $(DESTDIR)/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr
rubysitearchprefix = $(rubylibprefix)/$(sitearch)
rubyarchprefix = $(rubylibprefix)/$(arch)
rubylibprefix = $(libdir)/$(RUBY_BASE_NAME)
exec_prefix = $(prefix)
vendorarchhdrdir = $(vendorhdrdir)/$(sitearch)
sitearchhdrdir = $(sitehdrdir)/$(sitearch)
rubyarchhdrdir = $(rubyhdrdir)/$(arch)
vendorhdrdir = $(rubyhdrdir)/vendor_ruby
sitehdrdir = $(rubyhdrdir)/site_ruby
rubyhdrdir = $(includedir)/$(RUBY_VERSION_NAME)
vendorarchdir = $(vendorlibdir)/$(sitearch)
vendorlibdir = $(vendordir)/$(ruby_version)
vendordir = $(rubylibprefix)/vendor_ruby
sitearchdir = $(DESTDIR)./.gem.20200512-39687-o0q90e
sitelibdir = $(DESTDIR)./.gem.20200512-39687-o0q90e
sitedir = $(DESTDIR)/Library/Ruby/Site
rubyarchdir = $(rubylibdir)/$(arch)
rubylibdir = $(rubylibprefix)/$(ruby_version)
sitearchincludedir = $(includedir)/$(sitearch)
archincludedir = $(includedir)/$(arch)
sitearchlibdir = $(libdir)/$(sitearch)
archlibdir = $(libdir)/$(arch)
ridir = $(datarootdir)/$(RI_BASE_NAME)
mandir = $(DESTDIR)/usr/share/man
localedir = $(datarootdir)/locale
libdir = $(exec_prefix)/lib
psdir = $(docdir)
pdfdir = $(docdir)
dvidir = $(docdir)
htmldir = $(docdir)
infodir = $(DESTDIR)/usr/share/info
docdir = $(datarootdir)/doc/$(PACKAGE)
oldincludedir = $(DESTDIR)/usr/include
includedir = $(DESTDIR)/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk$(prefix)/include
localstatedir = $(prefix)/var
sharedstatedir = $(prefix)/com
sysconfdir = $(DESTDIR)/Library/Ruby/Site
datadir = $(datarootdir)
datarootdir = $(prefix)/share
libexecdir = $(exec_prefix)/libexec
sbindir = $(exec_prefix)/sbin
bindir = $(exec_prefix)/bin
archdir = $(rubyarchdir)
CC_WRAPPER =
CC = xcrun clang
CXX = xcrun clang++
LIBRUBY = $(LIBRUBY_SO)
LIBRUBY_A = lib$(RUBY_SO_NAME)-static.a
LIBRUBYARG_SHARED = -l$(RUBY_SO_NAME)
LIBRUBYARG_STATIC = -l$(RUBY_SO_NAME)-static -framework Security -framework Foundation $(MAINLIBS)
empty =
OUTFLAG = -o $(empty)
COUTFLAG = -o $(empty)
CSRCFLAG = $(empty)
RUBY_EXTCONF_H = extconf.h
cflags = $(optflags) $(debugflags) $(warnflags)
cxxflags = $(optflags) $(debugflags) $(warnflags)
optflags =
debugflags = -g
warnflags =
cppflags =
CCDLFLAGS =
CFLAGS = $(CCDLFLAGS) -g -Os -pipe -DHAVE_GCC_ATOMIC_BUILTINS $(ARCH_FLAG)
INCFLAGS = -I. -I$(arch_hdrdir) -I$(hdrdir)/ruby/backward -I$(hdrdir) -I$(srcdir) -I/opt/local/lib/libffi-3.2.1/include
DEFS =
CPPFLAGS = -DRUBY_EXTCONF_H=\"$(RUBY_EXTCONF_H)\" -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT $(DEFS) $(cppflags)
CXXFLAGS = $(CCDLFLAGS) -g -Os -pipe $(ARCH_FLAG)
ldflags = -L. -L/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.Internal.sdk/usr/local/lib -L/opt/local/lib
dldflags = -arch x86_64 -undefined dynamic_lookup -multiply_defined suppress
ARCH_FLAG = -arch x86_64
DLDFLAGS = $(ldflags) $(dldflags) $(ARCH_FLAG)
LDSHARED = $(CC) -dynamic -bundle
LDSHAREDXX = $(CXX) -dynamic -bundle
AR = libtool -static
EXEEXT =
RUBY_INSTALL_NAME = $(RUBY_BASE_NAME)
RUBY_SO_NAME = ruby.2.6
RUBYW_INSTALL_NAME =
RUBY_VERSION_NAME = $(RUBY_BASE_NAME)-$(ruby_version)
RUBYW_BASE_NAME = rubyw
RUBY_BASE_NAME = ruby
arch = universal-darwin19
sitearch = $(arch)
ruby_version = 2.6.0
ruby = $(bindir)/$(RUBY_BASE_NAME)
RUBY = $(ruby)
ruby_headers = $(hdrdir)/ruby.h $(hdrdir)/ruby/backward.h $(hdrdir)/ruby/ruby.h $(hdrdir)/ruby/defines.h $(hdrdir)/ruby/missing.h $(hdrdir)/ruby/intern.h $(hdrdir)/ruby/st.h $(hdrdir)/ruby/subst.h $(arch_hdrdir)/ruby/config.h $(RUBY_EXTCONF_H)
RM = rm -f
RM_RF = $(RUBY) -run -e rm -- -rf
RMDIRS = rmdir -p
MAKEDIRS = mkdir -p
INSTALL = /usr/bin/install -c
INSTALL_PROG = $(INSTALL) -m 0755
INSTALL_DATA = $(INSTALL) -m 644
COPY = cp
TOUCH = exit >
#### End of system configuration section. ####
preload =
libpath = . $(libdir)
LIBPATH = -L. -L$(libdir)
DEFFILE =
CLEANFILES = mkmf.log
DISTCLEANFILES =
DISTCLEANDIRS =
extout =
extout_prefix =
target_prefix =
LOCAL_LIBS =
LIBS = $(LIBRUBYARG_SHARED) -lffi -lffi
ORIG_SRCS = AbstractMemory.c ArrayType.c Buffer.c Call.c ClosurePool.c DynamicLibrary.c Function.c FunctionInfo.c LastError.c LongDouble.c MappedType.c MemoryPointer.c MethodHandle.c Platform.c Pointer.c Struct.c StructByValue.c StructLayout.c Thread.c Type.c Types.c Variadic.c ffi.c
SRCS = $(ORIG_SRCS)
OBJS = AbstractMemory.o ArrayType.o Buffer.o Call.o ClosurePool.o DynamicLibrary.o Function.o FunctionInfo.o LastError.o LongDouble.o MappedType.o MemoryPointer.o MethodHandle.o Platform.o Pointer.o Struct.o StructByValue.o StructLayout.o Thread.o Type.o Types.o Variadic.o ffi.o
HDRS = $(srcdir)/Type.h $(srcdir)/rbffi_endian.h $(srcdir)/MappedType.h $(srcdir)/Types.h $(srcdir)/LastError.h $(srcdir)/ArrayType.h $(srcdir)/extconf.h $(srcdir)/StructByValue.h $(srcdir)/AbstractMemory.h $(srcdir)/ClosurePool.h $(srcdir)/Call.h $(srcdir)/MethodHandle.h $(srcdir)/Struct.h $(srcdir)/rbffi.h $(srcdir)/Thread.h $(srcdir)/compat.h $(srcdir)/DynamicLibrary.h $(srcdir)/Platform.h $(srcdir)/Function.h $(srcdir)/LongDouble.h $(srcdir)/MemoryPointer.h $(srcdir)/Pointer.h
LOCAL_HDRS =
TARGET = ffi_c
TARGET_NAME = ffi_c
TARGET_ENTRY = Init_$(TARGET_NAME)
DLLIB = $(TARGET).bundle
EXTSTATIC =
STATIC_LIB =
TIMESTAMP_DIR = .
BINDIR = $(bindir)
RUBYCOMMONDIR = $(sitedir)$(target_prefix)
RUBYLIBDIR = $(sitelibdir)$(target_prefix)
RUBYARCHDIR = $(sitearchdir)$(target_prefix)
HDRDIR = $(rubyhdrdir)/ruby$(target_prefix)
ARCHHDRDIR = $(rubyhdrdir)/$(arch)/ruby$(target_prefix)
TARGET_SO_DIR =
TARGET_SO = $(TARGET_SO_DIR)$(DLLIB)
CLEANLIBS = $(TARGET_SO)
CLEANOBJS = *.o *.bak
all: $(DLLIB)
static: $(STATIC_LIB)
.PHONY: all install static install-so install-rb
.PHONY: clean clean-so clean-static clean-rb
clean-static::
clean-rb-default::
clean-rb::
clean-so::
clean: clean-so clean-static clean-rb-default clean-rb
-$(Q)$(RM) $(CLEANLIBS) $(CLEANOBJS) $(CLEANFILES) .*.time
distclean-rb-default::
distclean-rb::
distclean-so::
distclean-static::
distclean: clean distclean-so distclean-static distclean-rb-default distclean-rb
-$(Q)$(RM) Makefile $(RUBY_EXTCONF_H) conftest.* mkmf.log
-$(Q)$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES)
-$(Q)$(RMDIRS) $(DISTCLEANDIRS) 2> /dev/null || true
realclean: distclean
install: install-so install-rb
install-so: $(DLLIB) $(TIMESTAMP_DIR)/.sitearchdir.time
$(INSTALL_PROG) $(DLLIB) $(RUBYARCHDIR)
clean-static::
-$(Q)$(RM) $(STATIC_LIB)
install-rb: pre-install-rb do-install-rb install-rb-default
install-rb-default: pre-install-rb-default do-install-rb-default
pre-install-rb: Makefile
pre-install-rb-default: Makefile
do-install-rb:
do-install-rb-default:
pre-install-rb-default:
@$(NULLCMD)
$(TIMESTAMP_DIR)/.sitearchdir.time:
$(Q) $(MAKEDIRS) $(@D) $(RUBYARCHDIR)
$(Q) $(TOUCH) $@
site-install: site-install-so site-install-rb
site-install-so: install-so
site-install-rb: install-rb
.SUFFIXES: .c .m .cc .mm .cxx .cpp .o .S
.cc.o:
$(ECHO) compiling $(<)
$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$<
.cc.S:
$(ECHO) translating $(<)
$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$<
.mm.o:
$(ECHO) compiling $(<)
$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$<
.mm.S:
$(ECHO) translating $(<)
$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$<
.cxx.o:
$(ECHO) compiling $(<)
$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$<
.cxx.S:
$(ECHO) translating $(<)
$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$<
.cpp.o:
$(ECHO) compiling $(<)
$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$<
.cpp.S:
$(ECHO) translating $(<)
$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$<
.c.o:
$(ECHO) compiling $(<)
$(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$<
.c.S:
$(ECHO) translating $(<)
$(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$<
.m.o:
$(ECHO) compiling $(<)
$(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$<
.m.S:
$(ECHO) translating $(<)
$(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$<
$(TARGET_SO): $(OBJS) Makefile
$(ECHO) linking shared-object $(DLLIB)
-$(Q)$(RM) $(@)
$(Q) $(LDSHARED) -o $@ $(OBJS) $(LIBPATH) $(DLDFLAGS) $(LOCAL_LIBS) $(LIBS)
$(Q) $(POSTLINK)
$(OBJS): $(HDRS) $(ruby_headers)
| Java |
/*
neutrino bouquet editor - channel selection
Copyright (C) 2001 Steffen Hehn 'McClean'
Copyright (C) 2017 Sven Hoefer
License: GPL
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <unistd.h>
#include <global.h>
#include <neutrino.h>
#include <driver/fontrenderer.h>
#include <driver/screen_max.h>
#include <gui/widget/icons.h>
#include <zapit/getservices.h>
#include <zapit/zapit.h>
#include "bouqueteditor_chanselect.h"
extern CBouquetManager *g_bouquetManager;
CBEChannelSelectWidget::CBEChannelSelectWidget(const std::string & Caption, CZapitBouquet* Bouquet, CZapitClient::channelsMode Mode)
{
caption = Caption;
bouquet = Bouquet;
mode = Mode;
selected = 0;
liststart = 0;
channellist_sort_mode = SORT_ALPHA;
bouquetChannels = NULL;
int iw, ih;
action_icon_width = 0;
frameBuffer->getIconSize(NEUTRINO_ICON_BUTTON_DUMMY_SMALL, &action_icon_width, &ih);
status_icon_width = 0;
frameBuffer->getIconSize(NEUTRINO_ICON_MARKER_SCRAMBLED, &iw, &ih);
status_icon_width = std::max(status_icon_width, iw);
frameBuffer->getIconSize(NEUTRINO_ICON_MARKER_STREAMING, &iw, &ih);
status_icon_width = std::max(status_icon_width, iw);
}
CBEChannelSelectWidget::~CBEChannelSelectWidget()
{
}
void CBEChannelSelectWidget::paintItem(int pos)
{
int ypos = y + header_height + pos*item_height;
unsigned int current = liststart + pos;
bool i_selected = current == selected;
int i_radius = RADIUS_NONE;
fb_pixel_t color;
fb_pixel_t bgcolor;
getItemColors(color, bgcolor, i_selected);
if (i_selected)
{
if (current < Channels.size() || Channels.empty())
paintDetails(pos, current);
i_radius = RADIUS_LARGE;
}
else
{
if (current < Channels.size() && (Channels[current]->flags & CZapitChannel::NOT_PRESENT))
color = COL_MENUCONTENTINACTIVE_TEXT;
}
if (i_radius)
frameBuffer->paintBoxRel(x, ypos, width - SCROLLBAR_WIDTH, item_height, COL_MENUCONTENT_PLUS_0);
frameBuffer->paintBoxRel(x, ypos, width - SCROLLBAR_WIDTH, item_height, bgcolor, i_radius);
if (current < Channels.size())
{
if (isChannelInBouquet(current))
frameBuffer->paintIcon(NEUTRINO_ICON_BUTTON_GREEN, x + OFFSET_INNER_MID, ypos, item_height);
else
frameBuffer->paintIcon(NEUTRINO_ICON_BUTTON_DUMMY_SMALL, x + OFFSET_INNER_MID, ypos, item_height);
int text_offset = 2*OFFSET_INNER_MID + action_icon_width;
item_font->RenderString(x + text_offset, ypos + item_height, width - text_offset - SCROLLBAR_WIDTH - 2*OFFSET_INNER_MID - status_icon_width, Channels[current]->getName(), color);
if (Channels[current]->scrambled)
frameBuffer->paintIcon(NEUTRINO_ICON_MARKER_SCRAMBLED, x + width - SCROLLBAR_WIDTH - OFFSET_INNER_MID - status_icon_width, ypos, item_height);
else if (!Channels[current]->getUrl().empty())
frameBuffer->paintIcon(NEUTRINO_ICON_MARKER_STREAMING, x + width - SCROLLBAR_WIDTH - OFFSET_INNER_MID - status_icon_width, ypos, item_height);
}
frameBuffer->blit();
}
void CBEChannelSelectWidget::paintItems()
{
liststart = (selected/items_count)*items_count;
for(unsigned int count = 0; count < items_count; count++)
paintItem(count);
int total_pages;
int current_page;
getScrollBarData(&total_pages, ¤t_page, Channels.size(), items_count, selected);
paintScrollBar(x + width - SCROLLBAR_WIDTH, y + header_height, SCROLLBAR_WIDTH, body_height, total_pages, current_page);
}
void CBEChannelSelectWidget::paintHead()
{
CBEGlobals::paintHead(caption + (mode == CZapitClient::MODE_TV ? " - TV" : " - Radio"),
mode == CZapitClient::MODE_TV ? NEUTRINO_ICON_VIDEO : NEUTRINO_ICON_AUDIO);
}
struct button_label CBEChannelSelectButtons[] =
{
{ NEUTRINO_ICON_BUTTON_RED, LOCALE_CHANNELLIST_FOOT_SORT_ALPHA },
{ NEUTRINO_ICON_BUTTON_OKAY, LOCALE_BOUQUETEDITOR_SWITCH },
{ NEUTRINO_ICON_BUTTON_HOME, LOCALE_BOUQUETEDITOR_RETURN }
};
void CBEChannelSelectWidget::paintFoot()
{
switch (channellist_sort_mode)
{
case SORT_FREQ:
{
CBEChannelSelectButtons[0].locale = LOCALE_CHANNELLIST_FOOT_SORT_FREQ;
break;
}
case SORT_SAT:
{
CBEChannelSelectButtons[0].locale = LOCALE_CHANNELLIST_FOOT_SORT_SAT;
break;
}
case SORT_CH_NUMBER:
{
CBEChannelSelectButtons[0].locale = LOCALE_CHANNELLIST_FOOT_SORT_CHNUM;
break;
}
case SORT_ALPHA:
default:
{
CBEChannelSelectButtons[0].locale = LOCALE_CHANNELLIST_FOOT_SORT_ALPHA;
break;
}
}
const short numbuttons = sizeof(CBEChannelSelectButtons)/sizeof(CBEChannelSelectButtons[0]);
CBEGlobals::paintFoot(numbuttons, CBEChannelSelectButtons);
}
std::string CBEChannelSelectWidget::getInfoText(int index)
{
std::string res = "";
if (Channels.empty())
return res;
std::string satname = CServiceManager::getInstance()->GetSatelliteName(Channels[index]->getSatellitePosition());
if (IS_WEBCHAN(Channels[index]->getChannelID()))
satname = "Web-Channel"; // TODO split into WebTV/WebRadio
transponder t;
CServiceManager::getInstance()->GetTransponder(Channels[index]->getTransponderId(), t);
std::string desc = t.description();
if (Channels[index]->pname)
{
if (desc.empty())
desc = std::string(Channels[index]->pname);
else
desc += " (" + std::string(Channels[index]->pname) + ")";
}
if (!Channels[index]->getDesc().empty())
desc += "\n" + Channels[index]->getDesc();
res = satname + " - " + desc;
return res;
}
void CBEChannelSelectWidget::updateSelection(unsigned int newpos)
{
if (newpos == selected || newpos == (unsigned int)-1)
return;
unsigned int prev_selected = selected;
selected = newpos;
unsigned int oldliststart = liststart;
liststart = (selected/items_count)*items_count;
if (oldliststart != liststart)
{
paintItems();
}
else
{
paintItem(prev_selected - liststart);
paintItem(selected - liststart);
}
}
int CBEChannelSelectWidget::exec(CMenuTarget* parent, const std::string & /*actionKey*/)
{
neutrino_msg_t msg;
neutrino_msg_data_t data;
int res = menu_return::RETURN_REPAINT;
selected = 0;
if (parent)
parent->hide();
bouquetChannels = mode == CZapitClient::MODE_TV ? &(bouquet->tvChannels) : &(bouquet->radioChannels);
Channels.clear();
if (mode == CZapitClient::MODE_RADIO)
CServiceManager::getInstance()->GetAllRadioChannels(Channels);
else
CServiceManager::getInstance()->GetAllTvChannels(Channels);
sort(Channels.begin(), Channels.end(), CmpChannelByChName());
paintHead();
paintBody();
paintFoot();
paintItems();
uint64_t timeoutEnd = CRCInput::calcTimeoutEnd(*timeout_ptr);
channelChanged = false;
bool loop = true;
while (loop)
{
g_RCInput->getMsgAbsoluteTimeout(&msg, &data, &timeoutEnd);
if (msg <= CRCInput::RC_MaxRC)
timeoutEnd = CRCInput::calcTimeoutEnd(*timeout_ptr);
if ((msg == CRCInput::RC_timeout) || (msg == CRCInput::RC_home))
{
loop = false;
}
else if (msg == CRCInput::RC_up || msg == (neutrino_msg_t)g_settings.key_pageup ||
msg == CRCInput::RC_down || msg == (neutrino_msg_t)g_settings.key_pagedown)
{
int new_selected = UpDownKey(Channels, msg, items_count, selected);
updateSelection(new_selected);
}
else if (msg == (neutrino_msg_t) g_settings.key_list_start || msg == (neutrino_msg_t) g_settings.key_list_end)
{
if (!Channels.empty())
{
int new_selected = msg == (neutrino_msg_t) g_settings.key_list_start ? 0 : Channels.size() - 1;
updateSelection(new_selected);
}
}
else if (msg == CRCInput::RC_ok || msg == CRCInput::RC_green)
{
if (selected < Channels.size())
selectChannel();
}
else if (msg == CRCInput::RC_red)
{
if (selected < Channels.size())
sortChannels();
}
else if (CNeutrinoApp::getInstance()->listModeKey(msg))
{
// do nothing
}
else
{
CNeutrinoApp::getInstance()->handleMsg(msg, data);
}
}
hide();
return res;
}
void CBEChannelSelectWidget::sortChannels()
{
channellist_sort_mode++;
if (channellist_sort_mode >= SORT_END)
channellist_sort_mode = SORT_ALPHA;
switch (channellist_sort_mode)
{
case SORT_FREQ:
{
sort(Channels.begin(), Channels.end(), CmpChannelByFreq());
break;
}
case SORT_SAT:
{
sort(Channels.begin(), Channels.end(), CmpChannelBySat());
break;
}
case SORT_CH_NUMBER:
{
sort(Channels.begin(), Channels.end(), CmpChannelByChNum());
break;
}
case SORT_ALPHA:
default:
{
sort(Channels.begin(), Channels.end(), CmpChannelByChName());
break;
}
}
paintFoot();
paintItems();
}
void CBEChannelSelectWidget::selectChannel()
{
channelChanged = true;
if (isChannelInBouquet(selected))
bouquet->removeService(Channels[selected]);
else
bouquet->addService(Channels[selected]);
bouquetChannels = mode == CZapitClient::MODE_TV ? &(bouquet->tvChannels) : &(bouquet->radioChannels);
paintItem(selected - liststart);
g_RCInput->postMsg(CRCInput::RC_down, 0);
}
bool CBEChannelSelectWidget::isChannelInBouquet(int index)
{
for (unsigned int i=0; i< bouquetChannels->size(); i++)
{
if ((*bouquetChannels)[i]->getChannelID() == Channels[index]->getChannelID())
return true;
}
return false;
}
bool CBEChannelSelectWidget::hasChanged()
{
return channelChanged;
}
| Java |
/*
* Copyright (C) 2014 Fraunhofer ITWM
*
* 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.
*
* Written by:
* Phoebe Buckheister <phoebe.buckheister@itwm.fraunhofer.de>
*/
#include <linux/err.h>
#include <linux/bug.h>
#include <linux/completion.h>
#include <net/ieee802154.h>
#include <crypto/algapi.h>
#include "mac802154.h"
#include "llsec.h"
static void llsec_key_put(struct mac802154_llsec_key *key);
static bool llsec_key_id_equal(const struct ieee802154_llsec_key_id *a,
const struct ieee802154_llsec_key_id *b);
static void llsec_dev_free(struct mac802154_llsec_device *dev);
void mac802154_llsec_init(struct mac802154_llsec *sec)
{
memset(sec, 0, sizeof(*sec));
memset(&sec->params.default_key_source, 0xFF, IEEE802154_ADDR_LEN);
INIT_LIST_HEAD(&sec->table.security_levels);
INIT_LIST_HEAD(&sec->table.devices);
INIT_LIST_HEAD(&sec->table.keys);
hash_init(sec->devices_short);
hash_init(sec->devices_hw);
rwlock_init(&sec->lock);
}
void mac802154_llsec_destroy(struct mac802154_llsec *sec)
{
struct ieee802154_llsec_seclevel *sl, *sn;
struct ieee802154_llsec_device *dev, *dn;
struct ieee802154_llsec_key_entry *key, *kn;
list_for_each_entry_safe(sl, sn, &sec->table.security_levels, list) {
struct mac802154_llsec_seclevel *msl;
msl = container_of(sl, struct mac802154_llsec_seclevel, level);
list_del(&sl->list);
kfree(msl);
}
list_for_each_entry_safe(dev, dn, &sec->table.devices, list) {
struct mac802154_llsec_device *mdev;
mdev = container_of(dev, struct mac802154_llsec_device, dev);
list_del(&dev->list);
llsec_dev_free(mdev);
}
list_for_each_entry_safe(key, kn, &sec->table.keys, list) {
struct mac802154_llsec_key *mkey;
mkey = container_of(key->key, struct mac802154_llsec_key, key);
list_del(&key->list);
llsec_key_put(mkey);
kfree(key);
}
}
int mac802154_llsec_get_params(struct mac802154_llsec *sec,
struct ieee802154_llsec_params *params)
{
read_lock_bh(&sec->lock);
*params = sec->params;
read_unlock_bh(&sec->lock);
return 0;
}
int mac802154_llsec_set_params(struct mac802154_llsec *sec,
const struct ieee802154_llsec_params *params,
int changed)
{
write_lock_bh(&sec->lock);
if (changed & IEEE802154_LLSEC_PARAM_ENABLED)
sec->params.enabled = params->enabled;
if (changed & IEEE802154_LLSEC_PARAM_FRAME_COUNTER)
sec->params.frame_counter = params->frame_counter;
if (changed & IEEE802154_LLSEC_PARAM_OUT_LEVEL)
sec->params.out_level = params->out_level;
if (changed & IEEE802154_LLSEC_PARAM_OUT_KEY)
sec->params.out_key = params->out_key;
if (changed & IEEE802154_LLSEC_PARAM_KEY_SOURCE)
sec->params.default_key_source = params->default_key_source;
if (changed & IEEE802154_LLSEC_PARAM_PAN_ID)
sec->params.pan_id = params->pan_id;
if (changed & IEEE802154_LLSEC_PARAM_HWADDR)
sec->params.hwaddr = params->hwaddr;
if (changed & IEEE802154_LLSEC_PARAM_COORD_HWADDR)
sec->params.coord_hwaddr = params->coord_hwaddr;
if (changed & IEEE802154_LLSEC_PARAM_COORD_SHORTADDR)
sec->params.coord_shortaddr = params->coord_shortaddr;
write_unlock_bh(&sec->lock);
return 0;
}
static struct mac802154_llsec_key*
llsec_key_alloc(const struct ieee802154_llsec_key *template)
{
const int authsizes[3] = { 4, 8, 16 };
struct mac802154_llsec_key *key;
int i;
key = kzalloc(sizeof(*key), GFP_KERNEL);
if (!key)
return NULL;
kref_init(&key->ref);
key->key = *template;
BUILD_BUG_ON(ARRAY_SIZE(authsizes) != ARRAY_SIZE(key->tfm));
for (i = 0; i < ARRAY_SIZE(key->tfm); i++) {
key->tfm[i] = crypto_alloc_aead("ccm(aes)", 0,
CRYPTO_ALG_ASYNC);
if (!key->tfm[i])
goto err_tfm;
if (crypto_aead_setkey(key->tfm[i], template->key,
IEEE802154_LLSEC_KEY_SIZE))
goto err_tfm;
if (crypto_aead_setauthsize(key->tfm[i], authsizes[i]))
goto err_tfm;
}
key->tfm0 = crypto_alloc_blkcipher("ctr(aes)", 0, CRYPTO_ALG_ASYNC);
if (!key->tfm0)
goto err_tfm;
if (crypto_blkcipher_setkey(key->tfm0, template->key,
IEEE802154_LLSEC_KEY_SIZE))
goto err_tfm0;
return key;
err_tfm0:
crypto_free_blkcipher(key->tfm0);
err_tfm:
for (i = 0; i < ARRAY_SIZE(key->tfm); i++)
if (key->tfm[i])
crypto_free_aead(key->tfm[i]);
kfree(key);
return NULL;
}
static void llsec_key_release(struct kref *ref)
{
struct mac802154_llsec_key *key;
int i;
key = container_of(ref, struct mac802154_llsec_key, ref);
for (i = 0; i < ARRAY_SIZE(key->tfm); i++)
crypto_free_aead(key->tfm[i]);
crypto_free_blkcipher(key->tfm0);
kfree(key);
}
static struct mac802154_llsec_key*
llsec_key_get(struct mac802154_llsec_key *key)
{
kref_get(&key->ref);
return key;
}
static void llsec_key_put(struct mac802154_llsec_key *key)
{
kref_put(&key->ref, llsec_key_release);
}
static bool llsec_key_id_equal(const struct ieee802154_llsec_key_id *a,
const struct ieee802154_llsec_key_id *b)
{
if (a->mode != b->mode)
return false;
if (a->mode == IEEE802154_SCF_KEY_IMPLICIT)
return ieee802154_addr_equal(&a->device_addr, &b->device_addr);
if (a->id != b->id)
return false;
switch (a->mode) {
case IEEE802154_SCF_KEY_INDEX:
return true;
case IEEE802154_SCF_KEY_SHORT_INDEX:
return a->short_source == b->short_source;
case IEEE802154_SCF_KEY_HW_INDEX:
return a->extended_source == b->extended_source;
}
return false;
}
int mac802154_llsec_key_add(struct mac802154_llsec *sec,
const struct ieee802154_llsec_key_id *id,
const struct ieee802154_llsec_key *key)
{
struct mac802154_llsec_key *mkey = NULL;
struct ieee802154_llsec_key_entry *pos, *new;
if (!(key->frame_types & (1 << IEEE802154_FC_TYPE_MAC_CMD)) &&
key->cmd_frame_ids)
return -EINVAL;
list_for_each_entry(pos, &sec->table.keys, list) {
if (llsec_key_id_equal(&pos->id, id))
return -EEXIST;
if (memcmp(pos->key->key, key->key,
IEEE802154_LLSEC_KEY_SIZE))
continue;
mkey = container_of(pos->key, struct mac802154_llsec_key, key);
/* Don't allow multiple instances of the same AES key to have
* different allowed frame types/command frame ids, as this is
* not possible in the 802.15.4 PIB.
*/
if (pos->key->frame_types != key->frame_types ||
pos->key->cmd_frame_ids != key->cmd_frame_ids)
return -EEXIST;
break;
}
new = kzalloc(sizeof(*new), GFP_KERNEL);
if (!new)
return -ENOMEM;
if (!mkey)
mkey = llsec_key_alloc(key);
else
mkey = llsec_key_get(mkey);
if (!mkey)
goto fail;
new->id = *id;
new->key = &mkey->key;
list_add_rcu(&new->list, &sec->table.keys);
return 0;
fail:
kfree(new);
return -ENOMEM;
}
int mac802154_llsec_key_del(struct mac802154_llsec *sec,
const struct ieee802154_llsec_key_id *key)
{
struct ieee802154_llsec_key_entry *pos;
list_for_each_entry(pos, &sec->table.keys, list) {
struct mac802154_llsec_key *mkey;
mkey = container_of(pos->key, struct mac802154_llsec_key, key);
if (llsec_key_id_equal(&pos->id, key)) {
list_del_rcu(&pos->list);
llsec_key_put(mkey);
return 0;
}
}
return -ENOENT;
}
static bool llsec_dev_use_shortaddr(__le16 short_addr)
{
return short_addr != cpu_to_le16(IEEE802154_ADDR_UNDEF) &&
short_addr != cpu_to_le16(0xffff);
}
static u32 llsec_dev_hash_short(__le16 short_addr, __le16 pan_id)
{
return ((__force u16) short_addr) << 16 | (__force u16) pan_id;
}
static u64 llsec_dev_hash_long(__le64 hwaddr)
{
return (__force u64) hwaddr;
}
static struct mac802154_llsec_device*
llsec_dev_find_short(struct mac802154_llsec *sec, __le16 short_addr,
__le16 pan_id)
{
struct mac802154_llsec_device *dev;
u32 key = llsec_dev_hash_short(short_addr, pan_id);
hash_for_each_possible_rcu(sec->devices_short, dev, bucket_s, key) {
if (dev->dev.short_addr == short_addr &&
dev->dev.pan_id == pan_id)
return dev;
}
return NULL;
}
static struct mac802154_llsec_device*
llsec_dev_find_long(struct mac802154_llsec *sec, __le64 hwaddr)
{
struct mac802154_llsec_device *dev;
u64 key = llsec_dev_hash_long(hwaddr);
hash_for_each_possible_rcu(sec->devices_hw, dev, bucket_hw, key) {
if (dev->dev.hwaddr == hwaddr)
return dev;
}
return NULL;
}
static void llsec_dev_free(struct mac802154_llsec_device *dev)
{
struct ieee802154_llsec_device_key *pos, *pn;
struct mac802154_llsec_device_key *devkey;
list_for_each_entry_safe(pos, pn, &dev->dev.keys, list) {
devkey = container_of(pos, struct mac802154_llsec_device_key,
devkey);
list_del(&pos->list);
kfree(devkey);
}
kfree(dev);
}
int mac802154_llsec_dev_add(struct mac802154_llsec *sec,
const struct ieee802154_llsec_device *dev)
{
struct mac802154_llsec_device *entry;
u32 skey = llsec_dev_hash_short(dev->short_addr, dev->pan_id);
u64 hwkey = llsec_dev_hash_long(dev->hwaddr);
BUILD_BUG_ON(sizeof(hwkey) != IEEE802154_ADDR_LEN);
if ((llsec_dev_use_shortaddr(dev->short_addr) &&
llsec_dev_find_short(sec, dev->short_addr, dev->pan_id)) ||
llsec_dev_find_long(sec, dev->hwaddr))
return -EEXIST;
entry = kmalloc(sizeof(*entry), GFP_KERNEL);
if (!entry)
return -ENOMEM;
entry->dev = *dev;
spin_lock_init(&entry->lock);
INIT_LIST_HEAD(&entry->dev.keys);
if (llsec_dev_use_shortaddr(dev->short_addr))
hash_add_rcu(sec->devices_short, &entry->bucket_s, skey);
else
INIT_HLIST_NODE(&entry->bucket_s);
hash_add_rcu(sec->devices_hw, &entry->bucket_hw, hwkey);
list_add_tail_rcu(&entry->dev.list, &sec->table.devices);
return 0;
}
static void llsec_dev_free_rcu(struct rcu_head *rcu)
{
llsec_dev_free(container_of(rcu, struct mac802154_llsec_device, rcu));
}
int mac802154_llsec_dev_del(struct mac802154_llsec *sec, __le64 device_addr)
{
struct mac802154_llsec_device *pos;
pos = llsec_dev_find_long(sec, device_addr);
if (!pos)
return -ENOENT;
hash_del_rcu(&pos->bucket_s);
hash_del_rcu(&pos->bucket_hw);
call_rcu(&pos->rcu, llsec_dev_free_rcu);
return 0;
}
static struct mac802154_llsec_device_key*
llsec_devkey_find(struct mac802154_llsec_device *dev,
const struct ieee802154_llsec_key_id *key)
{
struct ieee802154_llsec_device_key *devkey;
list_for_each_entry_rcu(devkey, &dev->dev.keys, list) {
if (!llsec_key_id_equal(key, &devkey->key_id))
continue;
return container_of(devkey, struct mac802154_llsec_device_key,
devkey);
}
return NULL;
}
int mac802154_llsec_devkey_add(struct mac802154_llsec *sec,
__le64 dev_addr,
const struct ieee802154_llsec_device_key *key)
{
struct mac802154_llsec_device *dev;
struct mac802154_llsec_device_key *devkey;
dev = llsec_dev_find_long(sec, dev_addr);
if (!dev)
return -ENOENT;
if (llsec_devkey_find(dev, &key->key_id))
return -EEXIST;
devkey = kmalloc(sizeof(*devkey), GFP_KERNEL);
if (!devkey)
return -ENOMEM;
devkey->devkey = *key;
list_add_tail_rcu(&devkey->devkey.list, &dev->dev.keys);
return 0;
}
int mac802154_llsec_devkey_del(struct mac802154_llsec *sec,
__le64 dev_addr,
const struct ieee802154_llsec_device_key *key)
{
struct mac802154_llsec_device *dev;
struct mac802154_llsec_device_key *devkey;
dev = llsec_dev_find_long(sec, dev_addr);
if (!dev)
return -ENOENT;
devkey = llsec_devkey_find(dev, &key->key_id);
if (!devkey)
return -ENOENT;
list_del_rcu(&devkey->devkey.list);
kfree_rcu(devkey, rcu);
return 0;
}
static struct mac802154_llsec_seclevel*
llsec_find_seclevel(const struct mac802154_llsec *sec,
const struct ieee802154_llsec_seclevel *sl)
{
struct ieee802154_llsec_seclevel *pos;
list_for_each_entry(pos, &sec->table.security_levels, list) {
if (pos->frame_type != sl->frame_type ||
(pos->frame_type == IEEE802154_FC_TYPE_MAC_CMD &&
pos->cmd_frame_id != sl->cmd_frame_id) ||
pos->device_override != sl->device_override ||
pos->sec_levels != sl->sec_levels)
continue;
return container_of(pos, struct mac802154_llsec_seclevel,
level);
}
return NULL;
}
int mac802154_llsec_seclevel_add(struct mac802154_llsec *sec,
const struct ieee802154_llsec_seclevel *sl)
{
struct mac802154_llsec_seclevel *entry;
if (llsec_find_seclevel(sec, sl))
return -EEXIST;
entry = kmalloc(sizeof(*entry), GFP_KERNEL);
if (!entry)
return -ENOMEM;
entry->level = *sl;
list_add_tail_rcu(&entry->level.list, &sec->table.security_levels);
return 0;
}
int mac802154_llsec_seclevel_del(struct mac802154_llsec *sec,
const struct ieee802154_llsec_seclevel *sl)
{
struct mac802154_llsec_seclevel *pos;
pos = llsec_find_seclevel(sec, sl);
if (!pos)
return -ENOENT;
list_del_rcu(&pos->level.list);
kfree_rcu(pos, rcu);
return 0;
}
static int llsec_recover_addr(struct mac802154_llsec *sec,
struct ieee802154_addr *addr)
{
__le16 caddr = sec->params.coord_shortaddr;
addr->pan_id = sec->params.pan_id;
if (caddr == cpu_to_le16(IEEE802154_ADDR_BROADCAST)) {
return -EINVAL;
} else if (caddr == cpu_to_le16(IEEE802154_ADDR_UNDEF)) {
addr->extended_addr = sec->params.coord_hwaddr;
addr->mode = IEEE802154_ADDR_LONG;
} else {
addr->short_addr = sec->params.coord_shortaddr;
addr->mode = IEEE802154_ADDR_SHORT;
}
return 0;
}
static struct mac802154_llsec_key*
llsec_lookup_key(struct mac802154_llsec *sec,
const struct ieee802154_hdr *hdr,
const struct ieee802154_addr *addr,
struct ieee802154_llsec_key_id *key_id)
{
struct ieee802154_addr devaddr = *addr;
u8 key_id_mode = hdr->sec.key_id_mode;
struct ieee802154_llsec_key_entry *key_entry;
struct mac802154_llsec_key *key;
if (key_id_mode == IEEE802154_SCF_KEY_IMPLICIT &&
devaddr.mode == IEEE802154_ADDR_NONE) {
if (hdr->fc.type == IEEE802154_FC_TYPE_BEACON) {
devaddr.extended_addr = sec->params.coord_hwaddr;
devaddr.mode = IEEE802154_ADDR_LONG;
} else if (llsec_recover_addr(sec, &devaddr) < 0) {
return NULL;
}
}
list_for_each_entry_rcu(key_entry, &sec->table.keys, list) {
const struct ieee802154_llsec_key_id *id = &key_entry->id;
if (!(key_entry->key->frame_types & BIT(hdr->fc.type)))
continue;
if (id->mode != key_id_mode)
continue;
if (key_id_mode == IEEE802154_SCF_KEY_IMPLICIT) {
if (ieee802154_addr_equal(&devaddr, &id->device_addr))
goto found;
} else {
if (id->id != hdr->sec.key_id)
continue;
if ((key_id_mode == IEEE802154_SCF_KEY_INDEX) ||
(key_id_mode == IEEE802154_SCF_KEY_SHORT_INDEX &&
id->short_source == hdr->sec.short_src) ||
(key_id_mode == IEEE802154_SCF_KEY_HW_INDEX &&
id->extended_source == hdr->sec.extended_src))
goto found;
}
}
return NULL;
found:
key = container_of(key_entry->key, struct mac802154_llsec_key, key);
if (key_id)
*key_id = key_entry->id;
return llsec_key_get(key);
}
static void llsec_geniv(u8 iv[16], __le64 addr,
const struct ieee802154_sechdr *sec)
{
__be64 addr_bytes = (__force __be64) swab64((__force u64) addr);
__be32 frame_counter = (__force __be32) swab32((__force u32) sec->frame_counter);
iv[0] = 1; /* L' = L - 1 = 1 */
memcpy(iv + 1, &addr_bytes, sizeof(addr_bytes));
memcpy(iv + 9, &frame_counter, sizeof(frame_counter));
iv[13] = sec->level;
iv[14] = 0;
iv[15] = 1;
}
static int
llsec_do_encrypt_unauth(struct sk_buff *skb, const struct mac802154_llsec *sec,
const struct ieee802154_hdr *hdr,
struct mac802154_llsec_key *key)
{
u8 iv[16];
struct scatterlist src;
struct blkcipher_desc req = {
.tfm = key->tfm0,
.info = iv,
.flags = 0,
};
llsec_geniv(iv, sec->params.hwaddr, &hdr->sec);
sg_init_one(&src, skb->data, skb->len);
return crypto_blkcipher_encrypt_iv(&req, &src, &src, skb->len);
}
static struct crypto_aead*
llsec_tfm_by_len(struct mac802154_llsec_key *key, int authlen)
{
int i;
for (i = 0; i < ARRAY_SIZE(key->tfm); i++)
if (crypto_aead_authsize(key->tfm[i]) == authlen)
return key->tfm[i];
BUG();
}
static int
llsec_do_encrypt_auth(struct sk_buff *skb, const struct mac802154_llsec *sec,
const struct ieee802154_hdr *hdr,
struct mac802154_llsec_key *key)
{
u8 iv[16];
unsigned char *data;
int authlen, assoclen, datalen, rc;
struct scatterlist src, assoc[2], dst[2];
struct aead_request *req;
authlen = ieee802154_sechdr_authtag_len(&hdr->sec);
llsec_geniv(iv, sec->params.hwaddr, &hdr->sec);
req = aead_request_alloc(llsec_tfm_by_len(key, authlen), GFP_ATOMIC);
if (!req)
return -ENOMEM;
sg_init_table(assoc, 2);
sg_set_buf(&assoc[0], skb_mac_header(skb), skb->mac_len);
assoclen = skb->mac_len;
data = skb_mac_header(skb) + skb->mac_len;
datalen = skb_tail_pointer(skb) - data;
if (hdr->sec.level & IEEE802154_SCF_SECLEVEL_ENC) {
sg_set_buf(&assoc[1], data, 0);
} else {
sg_set_buf(&assoc[1], data, datalen);
assoclen += datalen;
datalen = 0;
}
sg_init_one(&src, data, datalen);
sg_init_table(dst, 2);
sg_set_buf(&dst[0], data, datalen);
sg_set_buf(&dst[1], skb_put(skb, authlen), authlen);
aead_request_set_callback(req, 0, NULL, NULL);
aead_request_set_assoc(req, assoc, assoclen);
aead_request_set_crypt(req, &src, dst, datalen, iv);
rc = crypto_aead_encrypt(req);
kfree(req);
return rc;
}
static int llsec_do_encrypt(struct sk_buff *skb,
const struct mac802154_llsec *sec,
const struct ieee802154_hdr *hdr,
struct mac802154_llsec_key *key)
{
if (hdr->sec.level == IEEE802154_SCF_SECLEVEL_ENC)
return llsec_do_encrypt_unauth(skb, sec, hdr, key);
else
return llsec_do_encrypt_auth(skb, sec, hdr, key);
}
int mac802154_llsec_encrypt(struct mac802154_llsec *sec, struct sk_buff *skb)
{
struct ieee802154_hdr hdr;
int rc, authlen, hlen;
struct mac802154_llsec_key *key;
u32 frame_ctr;
hlen = ieee802154_hdr_pull(skb, &hdr);
if (hlen < 0 || hdr.fc.type != IEEE802154_FC_TYPE_DATA)
return -EINVAL;
if (!hdr.fc.security_enabled || hdr.sec.level == 0) {
skb_push(skb, hlen);
return 0;
}
authlen = ieee802154_sechdr_authtag_len(&hdr.sec);
if (skb->len + hlen + authlen + IEEE802154_MFR_SIZE > IEEE802154_MTU)
return -EMSGSIZE;
rcu_read_lock();
read_lock_bh(&sec->lock);
if (!sec->params.enabled) {
rc = -EINVAL;
goto fail_read;
}
key = llsec_lookup_key(sec, &hdr, &hdr.dest, NULL);
if (!key) {
rc = -ENOKEY;
goto fail_read;
}
read_unlock_bh(&sec->lock);
write_lock_bh(&sec->lock);
frame_ctr = be32_to_cpu(sec->params.frame_counter);
hdr.sec.frame_counter = cpu_to_le32(frame_ctr);
if (frame_ctr == 0xFFFFFFFF) {
write_unlock_bh(&sec->lock);
llsec_key_put(key);
rc = -EOVERFLOW;
goto fail;
}
sec->params.frame_counter = cpu_to_be32(frame_ctr + 1);
write_unlock_bh(&sec->lock);
rcu_read_unlock();
skb->mac_len = ieee802154_hdr_push(skb, &hdr);
skb_reset_mac_header(skb);
rc = llsec_do_encrypt(skb, sec, &hdr, key);
llsec_key_put(key);
return rc;
fail_read:
read_unlock_bh(&sec->lock);
fail:
rcu_read_unlock();
return rc;
}
static struct mac802154_llsec_device*
llsec_lookup_dev(struct mac802154_llsec *sec,
const struct ieee802154_addr *addr)
{
struct ieee802154_addr devaddr = *addr;
struct mac802154_llsec_device *dev = NULL;
if (devaddr.mode == IEEE802154_ADDR_NONE &&
llsec_recover_addr(sec, &devaddr) < 0)
return NULL;
if (devaddr.mode == IEEE802154_ADDR_SHORT) {
u32 key = llsec_dev_hash_short(devaddr.short_addr,
devaddr.pan_id);
hash_for_each_possible_rcu(sec->devices_short, dev,
bucket_s, key) {
if (dev->dev.pan_id == devaddr.pan_id &&
dev->dev.short_addr == devaddr.short_addr)
return dev;
}
} else {
u64 key = llsec_dev_hash_long(devaddr.extended_addr);
hash_for_each_possible_rcu(sec->devices_hw, dev,
bucket_hw, key) {
if (dev->dev.hwaddr == devaddr.extended_addr)
return dev;
}
}
return NULL;
}
static int
llsec_lookup_seclevel(const struct mac802154_llsec *sec,
u8 frame_type, u8 cmd_frame_id,
struct ieee802154_llsec_seclevel *rlevel)
{
struct ieee802154_llsec_seclevel *level;
list_for_each_entry_rcu(level, &sec->table.security_levels, list) {
if (level->frame_type == frame_type &&
(frame_type != IEEE802154_FC_TYPE_MAC_CMD ||
level->cmd_frame_id == cmd_frame_id)) {
*rlevel = *level;
return 0;
}
}
return -EINVAL;
}
static int
llsec_do_decrypt_unauth(struct sk_buff *skb, const struct mac802154_llsec *sec,
const struct ieee802154_hdr *hdr,
struct mac802154_llsec_key *key, __le64 dev_addr)
{
u8 iv[16];
unsigned char *data;
int datalen;
struct scatterlist src;
struct blkcipher_desc req = {
.tfm = key->tfm0,
.info = iv,
.flags = 0,
};
llsec_geniv(iv, dev_addr, &hdr->sec);
data = skb_mac_header(skb) + skb->mac_len;
datalen = skb_tail_pointer(skb) - data;
sg_init_one(&src, data, datalen);
return crypto_blkcipher_decrypt_iv(&req, &src, &src, datalen);
}
static int
llsec_do_decrypt_auth(struct sk_buff *skb, const struct mac802154_llsec *sec,
const struct ieee802154_hdr *hdr,
struct mac802154_llsec_key *key, __le64 dev_addr)
{
u8 iv[16];
unsigned char *data;
int authlen, datalen, assoclen, rc;
struct scatterlist src, assoc[2];
struct aead_request *req;
authlen = ieee802154_sechdr_authtag_len(&hdr->sec);
llsec_geniv(iv, dev_addr, &hdr->sec);
req = aead_request_alloc(llsec_tfm_by_len(key, authlen), GFP_ATOMIC);
if (!req)
return -ENOMEM;
sg_init_table(assoc, 2);
sg_set_buf(&assoc[0], skb_mac_header(skb), skb->mac_len);
assoclen = skb->mac_len;
data = skb_mac_header(skb) + skb->mac_len;
datalen = skb_tail_pointer(skb) - data;
if (hdr->sec.level & IEEE802154_SCF_SECLEVEL_ENC) {
sg_set_buf(&assoc[1], data, 0);
} else {
sg_set_buf(&assoc[1], data, datalen - authlen);
assoclen += datalen - authlen;
data += datalen - authlen;
datalen = authlen;
}
sg_init_one(&src, data, datalen);
aead_request_set_callback(req, 0, NULL, NULL);
aead_request_set_assoc(req, assoc, assoclen);
aead_request_set_crypt(req, &src, &src, datalen, iv);
rc = crypto_aead_decrypt(req);
kfree(req);
skb_trim(skb, skb->len - authlen);
return rc;
}
static int
llsec_do_decrypt(struct sk_buff *skb, const struct mac802154_llsec *sec,
const struct ieee802154_hdr *hdr,
struct mac802154_llsec_key *key, __le64 dev_addr)
{
if (hdr->sec.level == IEEE802154_SCF_SECLEVEL_ENC)
return llsec_do_decrypt_unauth(skb, sec, hdr, key, dev_addr);
else
return llsec_do_decrypt_auth(skb, sec, hdr, key, dev_addr);
}
static int
llsec_update_devkey_info(struct mac802154_llsec_device *dev,
const struct ieee802154_llsec_key_id *in_key,
u32 frame_counter)
{
struct mac802154_llsec_device_key *devkey = NULL;
if (dev->dev.key_mode == IEEE802154_LLSEC_DEVKEY_RESTRICT) {
devkey = llsec_devkey_find(dev, in_key);
if (!devkey)
return -ENOENT;
}
spin_lock_bh(&dev->lock);
if ((!devkey && frame_counter < dev->dev.frame_counter) ||
(devkey && frame_counter < devkey->devkey.frame_counter)) {
spin_unlock_bh(&dev->lock);
return -EINVAL;
}
if (devkey)
devkey->devkey.frame_counter = frame_counter + 1;
else
dev->dev.frame_counter = frame_counter + 1;
spin_unlock_bh(&dev->lock);
return 0;
}
int mac802154_llsec_decrypt(struct mac802154_llsec *sec, struct sk_buff *skb)
{
struct ieee802154_hdr hdr;
struct mac802154_llsec_key *key;
struct ieee802154_llsec_key_id key_id;
struct mac802154_llsec_device *dev;
struct ieee802154_llsec_seclevel seclevel;
int err;
__le64 dev_addr;
u32 frame_ctr;
if (ieee802154_hdr_peek(skb, &hdr) < 0)
return -EINVAL;
if (!hdr.fc.security_enabled)
return 0;
if (hdr.fc.version == 0)
return -EINVAL;
read_lock_bh(&sec->lock);
if (!sec->params.enabled) {
read_unlock_bh(&sec->lock);
return -EINVAL;
}
read_unlock_bh(&sec->lock);
rcu_read_lock();
key = llsec_lookup_key(sec, &hdr, &hdr.source, &key_id);
if (!key) {
err = -ENOKEY;
goto fail;
}
dev = llsec_lookup_dev(sec, &hdr.source);
if (!dev) {
err = -EINVAL;
goto fail_dev;
}
if (llsec_lookup_seclevel(sec, hdr.fc.type, 0, &seclevel) < 0) {
err = -EINVAL;
goto fail_dev;
}
if (!(seclevel.sec_levels & BIT(hdr.sec.level)) &&
(hdr.sec.level == 0 && seclevel.device_override &&
!dev->dev.seclevel_exempt)) {
err = -EINVAL;
goto fail_dev;
}
frame_ctr = le32_to_cpu(hdr.sec.frame_counter);
if (frame_ctr == 0xffffffff) {
err = -EOVERFLOW;
goto fail_dev;
}
err = llsec_update_devkey_info(dev, &key_id, frame_ctr);
if (err)
goto fail_dev;
dev_addr = dev->dev.hwaddr;
rcu_read_unlock();
err = llsec_do_decrypt(skb, sec, &hdr, key, dev_addr);
llsec_key_put(key);
return err;
fail_dev:
llsec_key_put(key);
fail:
rcu_read_unlock();
return err;
}
| Java |
vti_encoding:SR|utf8-nl
vti_timelastmodified:TR|08 Nov 2012 23:29:31 -0000
vti_extenderversion:SR|5.0.2.6790
vti_lineageid:SR|{44761BDF-1053-4E8B-8B42-2966A30F18D2}
vti_cacheddtm:TX|08 Nov 2012 23:29:31 -0000
vti_filesize:IR|2149
vti_backlinkinfo:VX|
| Java |
# gonads
A Go-style CSP channel implementation for Haskell Monads.
Get it?
| Java |
package org.janelia.alignment.match;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* List of {@link CanvasMatches} with associated tileIds mapped for fast lookup.
*
* @author Eric Trautman
*/
public class TileIdsWithMatches {
private final Set<String> tileIds;
private final List<CanvasMatches> canvasMatchesList;
public TileIdsWithMatches() {
this.canvasMatchesList = new ArrayList<>();
this.tileIds = new HashSet<>();
}
/**
*
* @param canvasMatchesList list of matches for section (could include tiles not in stack).
* @param stackTileIds set of tile ids in stack.
* To be kept, match pair must have both tiles in stack.
*/
public void addMatches(final List<CanvasMatches> canvasMatchesList,
final Set<String> stackTileIds) {
for (final CanvasMatches canvasMatches : canvasMatchesList) {
final String pId = canvasMatches.getpId();
final String qId = canvasMatches.getqId();
if (stackTileIds.contains(pId) && stackTileIds.contains(qId)) {
this.canvasMatchesList.add(canvasMatches);
this.tileIds.add(pId);
this.tileIds.add(qId);
}
}
}
public boolean contains(final String tileId) {
return tileIds.contains(tileId);
}
public List<CanvasMatches> getCanvasMatchesList() {
return canvasMatchesList;
}
}
| Java |
/* Pin Tool for
* calculation of the Stack Reuse Distance Histogram
*
* (C) 2015, Josef Weidendorfer / LRR-TUM
* GPLv2+ (see COPYING)
*/
#include "pin.H"
#include <stdio.h>
#include <cassert>
#include <cstring>
#include <cmath>
#include <unistd.h>
#include "dist.cpp"
// Consistency checks?
#define DEBUG 0
// 2: Huge amount of debug output, 1: checks, 0: silent
#define VERBOSE 0
// uses INS_IsStackRead/Write: misleading with -fomit-frame-pointer
#define IGNORE_STACK 1
// collect addresses in chunk buffer before? (always worse)
#define MERGE_CHUNK 0
#define CHUNKSIZE 4096
// must be a power-of-two
#define MEMBLOCKLEN 64
unsigned long stackAccesses;
unsigned long ignoredReads, ignoredWrites;
/* ===================================================================== */
/* Command line options */
/* ===================================================================== */
KNOB<int> KnobMinDist(KNOB_MODE_WRITEONCE, "pintool",
"m", "4096", "minimum bucket distance");
KNOB<int> KnobDoubleSteps(KNOB_MODE_WRITEONCE, "pintool",
"s", "1", "number of buckets for doubling distance");
KNOB<bool> KnobPIDPrefix(KNOB_MODE_WRITEONCE, "pintool",
"p", "0", "prepend output by --PID--");
/* ===================================================================== */
/* Handle Memory block access (aligned at multiple of MEMBLOCKLEN) */
/* ===================================================================== */
#if MERGE_CHUNK
void accessMerging(Addr a)
{
static Addr mergeBuffer[CHUNKSIZE];
static int ptr = 0;
if (ptr < CHUNKSIZE) {
mergeBuffer[ptr++] = a;
return;
}
sort(mergeBuffer,mergeBuffer+CHUNKSIZE);
for(ptr=0; ptr<CHUNKSIZE; ptr++) {
RD_accessBlock(mergeBuffer[ptr]);
}
ptr = 0;
}
#define RD_accessBlock accessMerging
#endif
/* ===================================================================== */
/* Direct Callbacks */
/* ===================================================================== */
void memAccess(ADDRINT addr, UINT32 size)
{
Addr a1 = (void*) (addr & ~(MEMBLOCKLEN-1));
Addr a2 = (void*) ((addr+size-1) & ~(MEMBLOCKLEN-1));
if (a1 == a2) {
if (VERBOSE >1)
fprintf(stderr," => %p\n", a1);
RD_accessBlock(a1);
}
else {
if (VERBOSE >1)
fprintf(stderr," => CROSS %p/%p\n", a1, a2);
RD_accessBlock(a1);
RD_accessBlock(a2);
}
}
VOID memRead(THREADID t, ADDRINT addr, UINT32 size)
{
if (t > 0) {
// we are NOT thread-safe, ignore access
ignoredReads++;
return;
}
if (VERBOSE >1)
fprintf(stderr,"R %p/%d", (void*)addr, size);
memAccess(addr, size);
}
VOID memWrite(THREADID t, ADDRINT addr, UINT32 size)
{
if (t > 0) {
// we are NOT thread-safe, ignore access
ignoredWrites++;
return;
}
if (VERBOSE >1)
fprintf(stderr,"W %p/%d", (void*)addr, size);
memAccess(addr, size);
}
VOID stackAccess()
{
stackAccesses++;
}
/* ===================================================================== */
/* Instrumentation */
/* ===================================================================== */
VOID Instruction(INS ins, VOID* v)
{
if (IGNORE_STACK && (INS_IsStackRead(ins) || INS_IsStackWrite(ins))) {
INS_InsertPredicatedCall( ins, IPOINT_BEFORE, (AFUNPTR)stackAccess,
IARG_END);
return;
}
UINT32 memOperands = INS_MemoryOperandCount(ins);
for (UINT32 memOp = 0; memOp < memOperands; memOp++) {
if (INS_MemoryOperandIsRead(ins, memOp))
INS_InsertPredicatedCall( ins, IPOINT_BEFORE, (AFUNPTR)memRead,
IARG_THREAD_ID,
IARG_MEMORYOP_EA, memOp,
IARG_UINT32, INS_MemoryOperandSize(ins, memOp),
IARG_END);
if (INS_MemoryOperandIsWritten(ins, memOp))
INS_InsertPredicatedCall( ins, IPOINT_BEFORE, (AFUNPTR)memWrite,
IARG_THREAD_ID,
IARG_MEMORYOP_EA, memOp,
IARG_UINT32, INS_MemoryOperandSize(ins, memOp),
IARG_END);
}
}
/* ===================================================================== */
/* Callbacks from Pin */
/* ===================================================================== */
VOID ThreadStart(THREADID t, CONTEXT *ctxt, INT32 flags, VOID *v)
{
fprintf(stderr, "Thread %d started\n", t);
}
/* ===================================================================== */
/* Output results at exit */
/* ===================================================================== */
VOID Exit(INT32 code, VOID *v)
{
char pStr[20];
if (KnobPIDPrefix.Value())
sprintf(pStr, "--%5d-- ", getpid());
else
pStr[0] = 0;
RD_printHistogram(stderr, pStr, MEMBLOCKLEN);
fprintf(stderr,
"%s ignored stack accesses: %lu\n",
pStr, stackAccesses);
fprintf(stderr,
"%s ignored accesses by thread != 0: %lu reads, %lu writes\n",
pStr, ignoredReads, ignoredWrites);
}
/* ===================================================================== */
/* Usage/Main Function of the Pin Tool */
/* ===================================================================== */
INT32 Usage()
{
PIN_ERROR( "PinDist: Get the Stack Reuse Distance Histogram\n"
+ KNOB_BASE::StringKnobSummary() + "\n");
return -1;
}
int main (int argc, char *argv[])
{
if (PIN_Init(argc, argv)) return Usage();
// add buckets [0-1023], [1K - 2K-1], ... [1G - ]
double d = KnobMinDist.Value();
int s = KnobDoubleSteps.Value();
double f = pow(2, 1.0/s);
RD_init((int)(d / MEMBLOCKLEN));
for(d*=f; d< 1024*1024*1024; d*=f)
RD_addBucket((int)(d / MEMBLOCKLEN));
stackAccesses = 0;
PIN_InitSymbols();
INS_AddInstrumentFunction(Instruction, 0);
PIN_AddFiniFunction(Exit, 0);
PIN_AddThreadStartFunction(ThreadStart, 0);
PIN_StartProgram();
return 0;
}
| Java |
import { createSelector } from '@automattic/state-utils';
import { filter, orderBy } from 'lodash';
import 'calypso/state/comments/init';
function filterCommentsByStatus( comments, status ) {
return 'all' === status
? filter(
comments,
( comment ) => 'approved' === comment.status || 'unapproved' === comment.status
)
: filter( comments, ( comment ) => status === comment.status );
}
/**
* Returns list of loaded comments for a given site, filtered by status
*
* @param {object} state Redux state
* @param {number} siteId Site for whose comments to find
* @param {string} [status] Status to filter comments
* @param {string} [order=asc] Order in which to sort filtered comments
* @returns {Array<object>} Available comments for site, filtered by status
*/
export const getSiteComments = createSelector(
( state, siteId, status, order = 'asc' ) => {
const comments = state.comments.items ?? {};
const parsedComments = Object.keys( comments )
.filter( ( key ) => parseInt( key.split( '-', 1 ), 10 ) === siteId )
.reduce( ( list, key ) => [ ...list, ...comments[ key ] ], [] );
return status
? orderBy( filterCommentsByStatus( parsedComments, status ), 'date', order )
: orderBy( parsedComments, 'date', order );
},
( state ) => [ state.comments.items ]
);
| Java |
(function(customer_id) {
tinymce.create('tinymce.plugins.ItStream_AttachToPost', {
customer_id: customer_id,
init : function(editor, plugin_url) {
editor.addButton('player_scheduling', {
title : 'Embed ItStream Player',
cmd : 'itm_scheduling',
image : plugin_url + '/scheduling.gif'
});
// Register a new TinyMCE command
editor.addCommand('itm_scheduling', this.render_attach_to_post_interface, {
editor: editor,
plugin: editor.plugins.ItStream_AttachToPost
});
},
createControl : function(n, cm) {
return null;
},
getInfo : function() {
return {
longname : 'ItStream Scheduling Button',
author : 'It-Marketing',
authorurl : 'http://www.itmarketingsrl.it/',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/example',
version : "0.1"
};
},
wm_close_event: function() {
// Restore scrolling for the main content window when the attach to post interface is closed
jQuery('html,body').css('overflow', 'auto');
tinyMCE.activeEditor.selection.select(tinyMCE.activeEditor.dom.select('p')[0]);
tinyMCE.activeEditor.selection.collapse(0);
},
render_attach_to_post_interface: function() {
var attach_to_post_url = itstream_ajax.attach_to_post;
if (typeof(customer_id) != 'undefined') {
attach_to_post_url += "?id=" + itstream_ajax.customer_id;
}
var win = window;
while (win.parent != null && win.parent != win) {
win = win.parent;
}
win = jQuery(win);
var winWidth = win.width();
var winHeight = win.height();
var popupWidth = 680;
var popupHeight = 560;
var minWidth = 320;
var minHeight = 200;
var maxWidth = winWidth - (winWidth * 0.05);
var maxHeight = winHeight - (winHeight * 0.05);
if (maxWidth < minWidth) { maxWidth = winWidth - 10; }
if (maxHeight < minHeight) { maxHeight = winHeight - 10; }
if (popupWidth > maxWidth) { popupWidth = maxWidth; }
if (popupHeight > maxHeight) { popupHeight = maxHeight; }
// Open a window
this.editor.windowManager.open({
url: attach_to_post_url,
id: 'its_attach_to_post_dialog',
width: popupWidth,
height: popupHeight,
title: 'ItStream - Embed Player',
inline: 1
/*buttons: [{
text: 'Close',
onclick: 'close'
}]*/
});
// Ensure that the window cannot be scrolled - XXX actually allow scrolling in the main window and disable it for the inner-windows/frames/elements as to create a single scrollbar
jQuery('html,body').css('overflow', 'hidden');
jQuery('#its_attach_to_post_dialog_ifr').css('overflow-y', 'auto');
jQuery('#its_attach_to_post_dialog_ifr').css('overflow-x', 'hidden');
}
});
// Register plugin
tinymce.PluginManager.add( 'itstream', tinymce.plugins.ItStream_AttachToPost );
})(itstream_ajax.customer_id); | Java |
<?php
/**
* ExtendedEditBar extension for BlueSpice
*
* Provides additional buttons to the wiki edit field.
*
* 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.
*
* This file is part of BlueSpice for MediaWiki
* For further information visit http://www.blue-spice.org
*
* @author Markus Glaser <glaser@hallowelt.biz>
* @author MediaWiki Extension
* @version 2.22.0 stable
* @package BlueSpice_Extensions
* @subpackage ExtendedEditBar
* @copyright Copyright (C) 2010 Hallo Welt! - Medienwerkstatt GmbH, All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License v2 or later
* @filesource
*/
/* Changelog
* v1.20.0
*
* v1.0.0
* - raised to stable
* v0.1
* - initial release
*/
/**
* Base class for ExtendedEditBar extension
* @package BlueSpice_Extensions
* @subpackage ExtendedEditBar
*/
class ExtendedEditBar extends BsExtensionMW {
/**
* Constructor of ExtendedEditBar class
*/
public function __construct() {
wfProfileIn( 'BS::'.__METHOD__ );
// Base settings
$this->mExtensionFile = __FILE__;
$this->mExtensionType = EXTTYPE::OTHER; //SPECIALPAGE/OTHER/VARIABLE/PARSERHOOK
$this->mInfo = array(
EXTINFO::NAME => 'ExtendedEditBar',
EXTINFO::DESCRIPTION => wfMessage( 'bs-extendededitbar-desc' )->escaped(),
EXTINFO::AUTHOR => 'MediaWiki Extension, packaging by Markus Glaser',
EXTINFO::VERSION => 'default',
EXTINFO::STATUS => 'default',
EXTINFO::PACKAGE => 'default',
EXTINFO::URL => 'http://www.blue-spice.org',
EXTINFO::DEPS => array( 'bluespice' => '2.22.0' )
);
$this->mExtensionKey = 'MW::ExtendedEditBar';
wfProfileOut('BS::'.__METHOD__ );
}
/**
* Initialization of ExtendedEditBar extension
*/
protected function initExt() {
wfProfileIn( 'BS::'.__METHOD__ );
$this->setHook('EditPageBeforeEditToolbar');
wfProfileOut( 'BS::'.__METHOD__ );
}
/**
*
* @global type $wgStylePath
* @global type $wgContLang
* @global type $wgLang
* @global OutputPage $wgOut
* @global type $wgUseTeX
* @global type $wgEnableUploads
* @global type $wgForeignFileRepos
* @param string $toolbar
* @return boolean
*/
public function onEditPageBeforeEditToolbar( &$toolbar ) {
$this->getOutput()->addModuleStyles( 'ext.bluespice.extendeditbar.styles' );
$this->getOutput()->addModules( 'ext.bluespice.extendeditbar' );
//This is copy-code from EditPage::getEditToolbar(). Sad but neccesary
//until we suppot WikiEditor and this get's obsolete.
global $wgContLang, $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
$imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
$sNs = $this->getLanguage()->getNsText( NS_IMAGE );
$sCaption = wfMessage( 'bs-extendededitbar-gallerysamplecaption' )->plain();
$sPicture = wfMessage( 'bs-extendededitbar-gallerysamplepicture' )->plain();
$sGallery = "{$sNs}:{$sPicture}.jpg|{$sCaption}\n{$sNs}:{$sPicture}.jpg|{$sCaption}";
$sHeader = wfMessage( 'bs-extendededitbar-tablesampleheader' )->plain();
$sRow = wfMessage( 'bs-extendededitbar-tablesamplerow' )->plain();
$sCell = wfMessage( 'bs-extendededitbar-tablesamplecell' )->plain();
$sTable = "! {$sHeader} 1\n! {$sHeader} 2\n! {$sHeader} 3\n|-\n| {$sRow} 1, ".
"{$sCell} 1\n| {$sRow} 1, {$sCell} 2\n| {$sRow} 1, {$sCell} 3\n|-\n|".
" {$sRow} 2, {$sCell} 1\n| {$sRow} 2, {$sCell} 2\n| {$sRow} 2, {$sCell} 3";
$aMWButtonCfgs = array(
'mw-editbutton-bold' => array(
'open' => '\'\'\'',
'close' => '\'\'\'',
'sample' => wfMessage( 'bold_sample' )->text(),
'tip' => wfMessage( 'bold_tip' )->text(),
'key' => 'B'
),
'mw-editbutton-italic' => array(
'open' => '\'\'',
'close' => '\'\'',
'sample' => wfMessage( 'italic_sample' )->text(),
'tip' => wfMessage( 'italic_tip' )->text(),
'key' => 'I'
),
'mw-editbutton-link' => array(
'open' => '[[',
'close' => ']]',
'sample' => wfMessage( 'link_sample' )->text(),
'tip' => wfMessage( 'link_tip' )->text(),
'key' => 'L'
),
'mw-editbutton-extlink' => array(
'open' => '[',
'close' => ']',
'sample' => wfMessage( 'extlink_sample' )->text(),
'tip' => wfMessage( 'extlink_tip' )->text(),
'key' => 'X'
),
'mw-editbutton-headline' => array(
'open' => "\n== ",
'close' => " ==\n",
'sample' => wfMessage( 'headline_sample' )->text(),
'tip' => wfMessage( 'headline_tip' )->text(),
'key' => 'H'
),
'mw-editbutton-image' => $imagesAvailable ? array(
'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
'close' => ']]',
'sample' => wfMessage( 'image_sample' )->text(),
'tip' => wfMessage( 'image_tip' )->text(),
'key' => 'D',
) : false,
'mw-editbutton-media' => $imagesAvailable ? array(
'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
'close' => ']]',
'sample' => wfMessage( 'media_sample' )->text(),
'tip' => wfMessage( 'media_tip' )->text(),
'key' => 'M'
) : false,
'mw-editbutton-math' => $wgUseTeX ? array(
'open' => "<math>",
'close' => "</math>",
'sample' => wfMessage( 'math_sample' )->text(),
'tip' => wfMessage( 'math_tip' )->text(),
'key' => 'C'
) : false,
'mw-editbutton-signature' => array(
'open' => '--~~~~',
'close' => '',
'sample' => '',
'tip' => wfMessage( 'sig_tip' )->text(),
'key' => 'Y'
),
);
$aBSButtonCfgs = array(
'bs-editbutton-redirect' => array(
'tip' => wfMessage('bs-extendededitbar-redirecttip')->plain(),
'open' => "#REDIRECT [[",
'close' => "]]",
'sample' => wfMessage('bs-extendededitbar-redirectsample')->plain()
),
'bs-editbutton-strike' => array(
'tip' => wfMessage('bs-extendededitbar-striketip')->plain(),
'open' => "<s>",
'close' => "</s>",
'sample' => wfMessage('bs-extendededitbar-strikesample')->plain()
),
'bs-editbutton-linebreak' => array(
'tip' => wfMessage('bs-extendededitbar-entertip')->plain(),
'open' => "<br />\n",
'close' => "",
'sample' => ''
),
'bs-editbutton-sup' => array(
'tip' => wfMessage('bs-extendededitbar-uppertip')->plain(),
'open' => "<sup>",
'close' => "</sup>",
'sample' => wfMessage('bs-extendededitbar-uppersample')->plain()
),
'bs-editbutton-sub' => array(
'tip' => wfMessage('bs-extendededitbar-lowertip')->plain(),
'open' => "<sub>",
'close' => "</sub>",
'sample' => wfMessage('bs-extendededitbar-lowersample')->plain()
),
'bs-editbutton-small' => array(
'tip' => wfMessage('bs-extendededitbar-smalltip')->plain(),
'open' => "<small>",
'close' => "</small>",
'sample' => wfMessage('bs-extendededitbar-smallsample')->plain()
),
'bs-editbutton-comment' => array(
'tip' => wfMessage('bs-extendededitbar-commenttip')->plain(),
'open' => "<!-- ",
'close' => " -->",
'sample' => wfMessage('bs-extendededitbar-commentsample')->plain()
),
'bs-editbutton-gallery' => array(
'tip' => wfMessage('bs-extendededitbar-gallerytip')->plain(),
'open' => "\n<gallery>\n",
'close' => "\n</gallery>",
'sample' => $sGallery
),
'bs-editbutton-blockquote' => array(
'tip' => wfMessage('bs-extendededitbar-quotetip')->plain(),
'open' => "\n<blockquote>\n",
'close' => "\n</blockquote>",
'sample' => wfMessage('bs-extendededitbar-quotesample')->plain()
),
'bs-editbutton-table' => array(
'tip' => wfMessage('bs-extendededitbar-tabletip')->plain(),
'open' => "{| class=\"wikitable\"\n|-\n",
'close' => "\n|}",
'sample' => $sTable
),
);
$aButtonCfgs = $aMWButtonCfgs + $aBSButtonCfgs;
$aRows = array(
array('editing' => array(), 'dialogs' => array(), 'table' => array( 10 => 'bs-editbutton-table' )), //this is reserverd for BlueSpice dialogs
array(
'formatting' => array(
10 => 'mw-editbutton-bold',
20 => 'mw-editbutton-italic',
30 => 'bs-editbutton-strike',
40 => 'mw-editbutton-headline',
50 => 'bs-editbutton-linebreak',
),
'content' => array(
//10 => 'mw-editbutton-link',
//20 => 'mw-editbutton-extlink',
30 => 'mw-editbutton-strike',
//40 => 'mw-editbutton-image',
//50 => 'mw-editbutton-media',
60 => 'bs-editbutton-gallery',
),
'misc' => array(
10 => 'mw-editbutton-signature',
20 => 'bs-editbutton-redirect',
30 => 'bs-editbutton-comment',
)
)
);
wfRunHooks( 'BSExtendedEditBarBeforeEditToolbar', array( &$aRows, &$aButtonCfgs ));
$aContent = array();
foreach( $aRows as $aRow ) {
$sRow = Html::openElement( 'div', array( 'class' => 'row' ) );
foreach( $aRow as $sGroupId => $aButtons ) {
$sGroup = Html::openElement( 'div', array( 'class' => 'group' ) );
ksort( $aButtons );
foreach ( $aButtons as $iButtonSort => $sButtonId ) {
if( !isset( $aButtonCfgs[$sButtonId] ) ) continue;
$aButtonCfg = $aButtonCfgs[$sButtonId];
if( !is_array( $aButtonCfg ) ) continue;
$aDefaultAttributes = array(
'href' => '#',
'class' => 'bs-button-32 mw-toolbar-editbutton'
);
$aAttributes = array(
'title' => $aButtonCfg['tip'],
'id' => $sButtonId
) + $aDefaultAttributes;
if( isset( $aButtonCfg['open'] ) ) $aAttributes['data-open'] = $aButtonCfg['open'];
if( isset( $aButtonCfg['close'] ) ) $aAttributes['data-close'] = $aButtonCfg['close'];
if( isset( $aButtonCfg['sample'] ) ) $aAttributes['data-sample'] = $aButtonCfg['sample'];
$sButton = Html::element(
'a',
$aAttributes,
$aButtonCfg['tip']
);
$sGroup .= $sButton;
}
$sGroup .= Html::closeElement('div');
$sRow.= $sGroup;
}
$sRow.= Html::closeElement('div');
$aContent[] = $sRow;
}
//We have to keep the old toolbar (the one with ugly icons) because
//some extensions (i.e. MsUpload) rely on it to add elements to the DOM.
//Unfortunately VisualEditor wil set it to visible when toggled.
//Therefore we move it out of sight using CSS positioning. Some buttons
//May be not visible though.
//TODO: Take contents of div#toolbar as base
$toolbar .= Html::rawElement(
'div',
array( 'id' => 'bs-extendededitbar' ),
implode( '', $aContent)
);
return true;
}
} | Java |
package org.wordpress.android.ui.notifications;
import com.android.volley.VolleyError;
import org.wordpress.android.models.Note;
import java.util.List;
public class NotificationEvents {
public static class NotificationsChanged {
final public boolean hasUnseenNotes;
public NotificationsChanged() {
this.hasUnseenNotes = false;
}
public NotificationsChanged(boolean hasUnseenNotes) {
this.hasUnseenNotes = hasUnseenNotes;
}
}
public static class NoteModerationFailed {}
public static class NoteModerationStatusChanged {
final boolean isModerating;
final String noteId;
public NoteModerationStatusChanged(String noteId, boolean isModerating) {
this.noteId = noteId;
this.isModerating = isModerating;
}
}
public static class NoteLikeStatusChanged {
final String noteId;
public NoteLikeStatusChanged(String noteId) {
this.noteId = noteId;
}
}
public static class NoteVisibilityChanged {
final boolean isHidden;
final String noteId;
public NoteVisibilityChanged(String noteId, boolean isHidden) {
this.noteId = noteId;
this.isHidden = isHidden;
}
}
public static class NotificationsSettingsStatusChanged {
final String mMessage;
public NotificationsSettingsStatusChanged(String message) {
mMessage = message;
}
public String getMessage() {
return mMessage;
}
}
public static class NotificationsUnseenStatus {
final public boolean hasUnseenNotes;
public NotificationsUnseenStatus(boolean hasUnseenNotes) {
this.hasUnseenNotes = hasUnseenNotes;
}
}
public static class NotificationsRefreshCompleted {
final List<Note> notes;
public NotificationsRefreshCompleted(List<Note> notes) {
this.notes = notes;
}
}
public static class NotificationsRefreshError {
VolleyError error;
public NotificationsRefreshError(VolleyError error) {
this.error = error;
}
public NotificationsRefreshError() {
}
}
}
| Java |
<?php
/**
* @ignore
*/
function mysql_table_exists($database, $tableName) {
global $tc_db;
$tables = array();
$tablesResults = $tc_db->GetAll("SHOW TABLES FROM `$database`;");
foreach ($tablesResults AS $row) $tables[] = $row[0];
return(in_array($tableName, $tables));
}
function pgsql_table_exists($database, $tableName) {
global $tc_db;
$tables = array();
$tablesResults = $tc_db->GetAll(" select table_name from information_schema.tables where table_schema='public' and table_type='BASE TABLE'");
foreach ($tablesResults AS $row) $tables[] = $row[0];
return(in_array($tableName, $tables));
}
function sqlite_table_exists($database, $tableName) {
global $tc_db;
$tables = array();
$tablesResults = $tc_db->GetAll("SELECT name FROM sqlite_master WHERE type = 'table'" );
foreach ($tablesResults AS $row) $tables[] = $row[0];
return(in_array($tableName, $tables));
}
function CreateSalt() {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$salt = '';
for ($i = 0; $i < 3; ++$i) {
$salt .= $chars[mt_rand(0, strlen($chars) - 1)];
}
return $salt;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pl" lang="pl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Kusaba B Installation</title>
<style type="text/css">
body { font-family: sans-serif; font-size: 75%; background: #ffe }
a { text-decoration: none; color: #550 }
h1,h2 { margin: 0px; background: #fca }
h1 { font-size: 150% }
h2 { font-size: 100%; margin-top: 1em }
.hl { font-style: italic }
.plus { float: right; font-size: 8px; font-weight: normal; padding: 1px 4px 2px 4px; margin: 0px 0px; background: #eb9; color: #000; border: 1px solid #da8; cursor: hand; cursor: pointer }
.plus:hover { background: #da8; border: 1px solid #c97 }
ul { list-style: none; padding-left: 0px; margin: 0px }
li { margin: 0px }
li:hover { background: #fec; }
li a { display: block; width: 100%; }
</style>
<link rel="shortcut icon" href="/favicon.ico" />
</head>
<body>
<div style="text-align:center;"><h1>Kusaba B Installation</h1></div>
<?php
echo '<h2>Checking configuration file...</h2>';
if (file_exists('../config.php')) {
require '../config.php';
require KU_ROOTDIR . 'inc/functions.php';
if (KU_RANDOMSEED!="ENTER RANDOM LETTERS/NUMBERS HERE"&&KU_RANDOMSEED!="") {
echo 'Configuration appears correct.';
echo '<h2>Checking database...</h2>';
$reqiredtables = array("ads","announcements","banlist","bannedhashes","blotter","boards","board_filetypes","embeds","events","filetypes","front","loginattempts","modlog","module_settings","posts","reports","sections","staff","watchedthreads","wordfilter");
foreach ($reqiredtables as $tablename) {
if (KU_DBTYPE == 'mysql' || KU_DBTYPE == 'mysqli') {
if (!mysql_table_exists(KU_DBDATABASE,KU_DBPREFIX.$tablename)) {
die("Couldn't find the table <strong>".KU_DBPREFIX.$tablename."</strong> in the database. Please <a href=\"install-mysql.php\"><strong><u>insert the mySQL dump</u></strong></a>.");
}
}
if (KU_DBTYPE == 'postgres7' || KU_DBTYPE == 'postgres8' || KU_DBTYPE == 'postgres') {
if (!pgsql_table_exists(KU_DBDATABASE,KU_DBPREFIX.$tablename)) {
die("Couldn't find the table <strong>".KU_DBPREFIX.$tablename."</strong> in the database. Please <a href=\"install-pgsql.php\"><strong><u>insert the PostgreSQL dump</u></strong></a>.");
}
}
if (KU_DBTYPE == 'sqlite') {
if (!sqlite_table_exists(KU_DBDATABASE,KU_DBPREFIX.$tablename)) {
die("Couldn't find the table <strong>".KU_DBPREFIX.$tablename."</strong> in the database. Please <a href=\"install-sqlite.php\"><strong><u>insert the SQLite dump</u></strong></a>.");
}
}
}
echo 'Database appears correct.';
echo '<h2>Inserting default administrator account...</h2>';
$result_exists = $tc_db->GetOne("SELECT COUNT(*) FROM `".KU_DBPREFIX."staff` WHERE `username` = 'admin'");
if ($result_exists==0) {
$salt = CreateSalt();
$result = $tc_db->Execute("INSERT INTO `".KU_DBPREFIX."staff` ( `username` , `salt`, `password` , `type` , `addedon` ) VALUES ( 'admin' , '".$salt."', '".md5("admin".$salt)."' , '1' , '".time()."' )");
echo 'Account inserted.';
$result = true;
} else {
echo 'There is already an administrator account inserted.';
$result = true;
}
if ($result) {
require_once KU_ROOTDIR . 'inc/classes/menu.class.php';
$menu_class = new Menu();
$menu_class->Generate();
echo '<h2>Done!</h2>Installation has finished! The default administrator account is <strong>admin</strong> with the password of <strong>admin</strong>.<br /><br />Delete this and the install-mysql.php file from the server, then <a href="manage.php">add some boards</a>!';
echo '<br /><br /><br /><h1><font color="red">DELETE THIS AND install-mysql.php RIGHT NOW!</font></h1>';
} else {
echo 'Error inserting SQL. Please add <strong>$tc_db->debug = true;</strong> just before ?> in config.php to turn on debugging, and check the error message.';
}
} else {
echo 'Please enter a random string into the <strong>KU_RANDOMSEED</strong> value.';
}
} else {
echo 'Unable to locate config.php';
}
?>
</body>
</html>
| Java |
<?php
/**
* @file
* Teamwork15 sub theme template functions
*
*/
/**
* Implements hook_preprocess_maintenance_page().
*/
function teamwork_15_subtheme_preprocess_maintenance_page(&$variables) {
backdrop_add_css(backdrop_get_path('theme', 'bartik') . '/css/maintenance-page.css');
}
/**
* Implements hook_preprocess_layout().
*/
function teamwork_15_subtheme_preprocess_layout(&$variables) {
if ($variables['content']['header']) {
$variables['content']['header'] = '<div class="l-header-inner">' . $variables['content']['header'] . '</div>';
}
if (theme_get_setting('teamwork_15_subtheme_cdn') > 0)
{
backdrop_add_css('http://cdnjs.cloudflare.com/ajax/libs/pure/0.6.0/pure-min.css', array('type' => 'external', 'every_page' => TRUE, 'group' => CSS_DEFAULT));
}
$var1 = theme_get_setting('teamwork_15_subtheme_juiced_main_background');
$var2 = theme_get_setting('teamwork_15_subtheme_juiced_big_statement_background');
$var3 = theme_get_setting('teamwork_15_subtheme_juiced_main_background_blurred');
$var4 = theme_get_setting('teamwork_15_subtheme_juiced_big_statement_background_blurred');
if ($var1 && $var3 > 0)
{
backdrop_add_css("@media screen and (min-width: 769px) { .juiced-main::before { content: ' '; width: 100%; height: 100%; display: block; position: absolute; z-index: -100; -webkit-filter: blur(20px); -moz-filter: blur(20px); -o-filter: blur(20px); -ms-filter: blur(20px); filter: blur(20px); opacity: 0.4; background: url($var1) no-repeat; background-size: cover; background-position: center; } }", array('type' => 'inline'));
}
if ($var1 && $var3 == 0)
{
backdrop_add_css("@media screen and (min-width: 769px) { .juiced-main { background: url($var1) no-repeat; background-size: cover; background-position: center; } }", array('type' => 'inline'));
}
if ($var2 && $var4 > 0)
{
backdrop_add_css("@media screen and (min-width: 769px) { .l-big-statement::before { content: ' '; width: 100%; height: 100%; display: block; position: absolute; z-index: -100; -webkit-filter: blur(20px); -moz-filter: blur(20px); -o-filter: blur(20px); -ms-filter: blur(20px); filter: blur(20px); opacity: 0.4; background: url($var2) no-repeat fixed; background-size: cover; background-position: center; } }", array('type' => 'inline'));
}
if ($var2 && $var4 == 0)
{
backdrop_add_css("@media screen and (min-width: 769px) { .l-big-statement { background: url($var2) no-repeat fixed; background-size: cover; background-position: center; } }", array('type' => 'inline'));
}
$var5 = theme_get_setting('teamwork_15_subtheme_body_main_background');
$var6 = theme_get_setting('teamwork_15_subtheme_footer_main_background');
$var7 = theme_get_setting('teamwork_15_subtheme_body_main_background_blurred');
$var8 = theme_get_setting('teamwork_15_subtheme_footer_main_background_blurred');
if ($var5 && $var7 > 0)
{
backdrop_add_css("@media screen and (min-width: 769px) { .layout::before { content: ' '; width: 100%; height: 100%; display: block; position: absolute; z-index: -100; -webkit-filter: blur(20px); -moz-filter: blur(20px); -o-filter: blur(20px); -ms-filter: blur(20px); filter: blur(20px); opacity: 0.4; background: url($var5) no-repeat; background-size: cover; background-position: center; } }", array('type' => 'inline'));
}
if ($var5 && $var7 == 0)
{
backdrop_add_css("@media screen and (min-width: 769px) { .layout { background: url($var5) no-repeat; background-size: cover; background-position: center; } }", array('type' => 'inline'));
}
if ($var6 && $var8 > 0)
{
backdrop_add_css("@media screen and (min-width: 769px) { footer.l-footer::before { content: ' '; width: 100%; height: 100%; display: block; position: absolute; z-index: -100; -webkit-filter: blur(20px); -moz-filter: blur(20px); -o-filter: blur(20px); -ms-filter: blur(20px); filter: blur(20px); opacity: 0.4; background: url($var6) no-repeat fixed; background-size: cover; background-position: center; } footer.l-footer { background: transparent; } }", array('type' => 'inline'));
}
if ($var6 && $var8 == 0)
{
backdrop_add_css("@media screen and (min-width: 769px) { footer.l-footer { background: url($var6) no-repeat fixed; background-size: cover; background-position: center; } }", array('type' => 'inline'));
}
if (theme_get_setting('teamwork_15_subtheme_script1') > 0)
{
backdrop_add_js("https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js", array('type' => 'external', 'scope' => 'footer', 'every_page' => TRUE, 'preprocess' => TRUE));
}
if (theme_get_setting('teamwork_15_subtheme_script2') > 0)
{
backdrop_add_js("https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js", array('type' => 'external', 'scope' => 'footer', 'every_page' => TRUE, 'preprocess' => TRUE));
}
if (theme_get_setting('teamwork_15_subtheme_script3') > 0)
{
backdrop_add_js("https://cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", array('type' => 'external', 'scope' => 'footer', 'every_page' => TRUE, 'preprocess' => TRUE));
}
if (theme_get_setting('teamwork_15_subtheme_script4') > 0)
{
backdrop_add_js("https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.4/hammer.min.js", array('type' => 'external', 'scope' => 'footer', 'every_page' => TRUE, 'preprocess' => TRUE));
}
backdrop_add_js("themes/teamwork_15_subtheme/js/scripts.js", array('type' => 'file', 'scope' => 'footer', 'every_page' => TRUE, 'preprocess' => TRUE));
backdrop_add_js("document.write('<script src=\"http://' + (location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1\"></' + 'script>')", array('type' => 'inline', 'scope' => 'footer', 'weight' => 9999));
}
/**
* Implements theme_field__field_type().
*/
function teamwork_15_subtheme_field__taxonomy_term_reference($variables) {
$output = '';
// Render the label, if it's not hidden.
if (!$variables['label_hidden']) {
$output .= '<h3 class="field-label">' . $variables['label'] . ': </h3>';
}
// Render the items.
$output .= ($variables['element']['#label_display'] == 'inline') ? '<ul class="links inline">' : '<ul class="links">';
foreach ($variables['items'] as $delta => $item) {
$item_attributes = (isset($variables['item_attributes'][$delta])) ? backdrop_attributes($variables['item_attributes'][$delta]) : '';
$output .= '<li class="taxonomy-term-reference-' . $delta . '"' . $item_attributes . '>' . backdrop_render($item) . '</li>';
}
$output .= '</ul>';
// Render the surrounding DIV with appropriate classes and attributes.
if (!in_array('clearfix', $variables['classes'])) {
$variables['classes'][] = 'clearfix';
}
$output = '<div class="' . implode(' ', $variables['classes']) . '"' . backdrop_attributes($variables['attributes']) . '>' . $output . '</div>';
return $output;
}
/**
* Implements theme_preprocess_image_style().
*/
function teamwork_15_subtheme_preprocess_image_style(&$vars) {
$vars['attributes']['class'][] = 'pure-img';
}
function teamwork_15_subtheme_button(&$vars) {
$classes = array('button-success', 'pure-button-primary', 'button-xlarge', 'pure-button');
if (!isset($vars['#attributes']['class'])) {
$vars['#attributes'] = array('class' => $classes);
}
else {
$vars['#attributes']['class'] = array_merge($vars['#attributes']['class'], $classes);
}
if (!isset($vars['element']['#attributes']['class'])) {
$vars['element']['#attributes'] = array('class' => $classes);
}
else {
$vars['element']['#attributes']['class'] = array_merge($vars['element']['#attributes']['class'], $classes);
}
return theme_button($vars);
}
function teamwork_15_subtheme_css_alter(&$css) {
$css_to_remove = array();
if (theme_get_setting('teamwork_15_subtheme_cdn') > 0)
{
$css_to_remove[] = backdrop_get_path('theme','teamwork_15') . '/css/pure.min.css';
}
if (theme_get_setting('teamwork_15_subtheme_sass') > 0)
{
$css_to_remove[] = backdrop_get_path('theme','teamwork_15') . '/css/style.css';
$css_to_remove[] = backdrop_get_path('theme','teamwork_15') . '/css/pure.min.css';
}
foreach ($css_to_remove as $index => $css_file) {
unset($css[$css_file]);
}
}
/**
* Implements hook_form_alter()
*/
function teamwork_15_subtheme_form_alter(&$form, &$form_state, $form_id) {
$classes = array('pure-form', 'pure-form-aligned');
if (!isset($form['#attributes']['class'])) {
$form['#attributes'] = array('class' => $classes);
}
else {
$form['#attributes']['class'] = array_merge($form['#attributes']['class'], $classes);
}
}
function teamwork_15_subtheme_menu_tree($variables) {
return '<ul class="menu">' . $variables['tree'] . '</ul>';
}
/**
* Overrides theme_form_element_label().
*/
function teamwork_15_subtheme_form_element_label(&$variables) {
$element = $variables['element'];
$title = filter_xss_admin($element['#title']);
// If the element is required, a required marker is appended to the label.
$required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';
// // This is also used in the installer, pre-database setup.
$t = get_t();
$attributes = array();
if (!empty($element['#id'])) {
$attributes['for'] = $element['#id'];
}
$output = '';
if (isset($variables['#children'])) {
if ($element['#type'] === "radio")
{
$output .= $variables['#children'];
}
if ($element['#type'] === "checkbox")
{
$output .= $variables['#children'];
}
}
return ' <label' . backdrop_attributes($attributes) . '></label><div>' . $t('!title', array('!title' => $title)) . "</div> \n";
}
/**
* Implements theme_preprocess_menu_link().
*/
function teamwork_15_subtheme_menu_link(array $variables) {
$element = $variables['element'];
$classes = array('pure-menu-item');
$element['#attributes']['class'] = array_merge($element['#attributes']['class'], $classes);
$sub_menu = '';
if ($element['#below']) {
$sub_menu = backdrop_render($element['#below']);
}
$output = l($element['#title'], $element['#href'], $element['#localized_options']);
return '<li' . backdrop_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}
| Java |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2006, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* $Id: getinfo.c,v 1.1 2006/07/05 22:41:22 victor Exp $
***************************************************************************/
#include "setup.h"
#include <curl/curl.h>
#include "urldata.h"
#include "getinfo.h"
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include "memory.h"
#include "sslgen.h"
/* Make this the last #include */
#include "memdebug.h"
/*
* This is supposed to be called in the beginning of a perform() session
* and should reset all session-info variables
*/
CURLcode Curl_initinfo(struct SessionHandle *data)
{
struct Progress *pro = &data->progress;
struct PureInfo *info =&data->info;
pro->t_nslookup = 0;
pro->t_connect = 0;
pro->t_pretransfer = 0;
pro->t_starttransfer = 0;
pro->timespent = 0;
pro->t_redirect = 0;
info->httpcode = 0;
info->httpversion=0;
info->filetime=-1; /* -1 is an illegal time and thus means unknown */
if (info->contenttype)
free(info->contenttype);
info->contenttype = NULL;
info->header_size = 0;
info->request_size = 0;
info->numconnects = 0;
return CURLE_OK;
}
CURLcode Curl_getinfo(struct SessionHandle *data, CURLINFO info, ...)
{
va_list arg;
long *param_longp=NULL;
double *param_doublep=NULL;
char **param_charp=NULL;
struct curl_slist **param_slistp=NULL;
va_start(arg, info);
switch(info&CURLINFO_TYPEMASK) {
default:
return CURLE_BAD_FUNCTION_ARGUMENT;
case CURLINFO_STRING:
param_charp = va_arg(arg, char **);
if(NULL == param_charp)
return CURLE_BAD_FUNCTION_ARGUMENT;
break;
case CURLINFO_LONG:
param_longp = va_arg(arg, long *);
if(NULL == param_longp)
return CURLE_BAD_FUNCTION_ARGUMENT;
break;
case CURLINFO_DOUBLE:
param_doublep = va_arg(arg, double *);
if(NULL == param_doublep)
return CURLE_BAD_FUNCTION_ARGUMENT;
break;
case CURLINFO_SLIST:
param_slistp = va_arg(arg, struct curl_slist **);
if(NULL == param_slistp)
return CURLE_BAD_FUNCTION_ARGUMENT;
break;
}
switch(info) {
case CURLINFO_EFFECTIVE_URL:
*param_charp = data->change.url?data->change.url:(char *)"";
break;
case CURLINFO_RESPONSE_CODE:
*param_longp = data->info.httpcode;
break;
case CURLINFO_HTTP_CONNECTCODE:
*param_longp = data->info.httpproxycode;
break;
case CURLINFO_FILETIME:
*param_longp = data->info.filetime;
break;
case CURLINFO_HEADER_SIZE:
*param_longp = data->info.header_size;
break;
case CURLINFO_REQUEST_SIZE:
*param_longp = data->info.request_size;
break;
case CURLINFO_TOTAL_TIME:
*param_doublep = data->progress.timespent;
break;
case CURLINFO_NAMELOOKUP_TIME:
*param_doublep = data->progress.t_nslookup;
break;
case CURLINFO_CONNECT_TIME:
*param_doublep = data->progress.t_connect;
break;
case CURLINFO_PRETRANSFER_TIME:
*param_doublep = data->progress.t_pretransfer;
break;
case CURLINFO_STARTTRANSFER_TIME:
*param_doublep = data->progress.t_starttransfer;
break;
case CURLINFO_SIZE_UPLOAD:
*param_doublep = (double)data->progress.uploaded;
break;
case CURLINFO_SIZE_DOWNLOAD:
*param_doublep = (double)data->progress.downloaded;
break;
case CURLINFO_SPEED_DOWNLOAD:
*param_doublep = (double)data->progress.dlspeed;
break;
case CURLINFO_SPEED_UPLOAD:
*param_doublep = (double)data->progress.ulspeed;
break;
case CURLINFO_SSL_VERIFYRESULT:
*param_longp = data->set.ssl.certverifyresult;
break;
case CURLINFO_CONTENT_LENGTH_DOWNLOAD:
*param_doublep = (double)data->progress.size_dl;
break;
case CURLINFO_CONTENT_LENGTH_UPLOAD:
*param_doublep = (double)data->progress.size_ul;
break;
case CURLINFO_REDIRECT_TIME:
*param_doublep = data->progress.t_redirect;
break;
case CURLINFO_REDIRECT_COUNT:
*param_longp = data->set.followlocation;
break;
case CURLINFO_CONTENT_TYPE:
*param_charp = data->info.contenttype;
break;
case CURLINFO_PRIVATE:
*param_charp = data->set.private_data;
break;
case CURLINFO_HTTPAUTH_AVAIL:
*param_longp = data->info.httpauthavail;
break;
case CURLINFO_PROXYAUTH_AVAIL:
*param_longp = data->info.proxyauthavail;
break;
case CURLINFO_OS_ERRNO:
*param_longp = data->state.os_errno;
break;
case CURLINFO_NUM_CONNECTS:
*param_longp = data->info.numconnects;
break;
case CURLINFO_SSL_ENGINES:
*param_slistp = Curl_ssl_engines_list(data);
break;
case CURLINFO_COOKIELIST:
*param_slistp = Curl_cookie_list(data);
break;
case CURLINFO_LASTSOCKET:
if((data->state.lastconnect != -1) &&
(data->state.connects[data->state.lastconnect] != NULL))
*param_longp = data->state.connects[data->state.lastconnect]->
sock[FIRSTSOCKET];
else
*param_longp = -1;
break;
default:
return CURLE_BAD_FUNCTION_ARGUMENT;
}
return CURLE_OK;
}
| Java |
/*
* Copyright (c) 2017 Red Hat, Inc. and/or its affiliates.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
/**
* @test TestMemoryMXBeans
* @key gc
* @summary Test JMX memory beans
* @modules java.base/jdk.internal.misc
* java.management
* @run main/othervm -XX:+UseShenandoahGC -Xmx1g TestMemoryMXBeans -1 1024
* @run main/othervm -XX:+UseShenandoahGC -Xms1g -Xmx1g TestMemoryMXBeans 1024 1024
* @run main/othervm -XX:+UseShenandoahGC -Xms128m -Xmx1g TestMemoryMXBeans 128 1024
*/
import java.lang.management.*;
import java.util.*;
public class TestMemoryMXBeans {
public static void main(String[] args) throws Exception {
if (args.length < 2) {
throw new IllegalStateException("Should provide expected heap sizes");
}
long initSize = 1L * Integer.parseInt(args[0]) * 1024 * 1024;
long maxSize = 1L * Integer.parseInt(args[1]) * 1024 * 1024;
testMemoryBean(initSize, maxSize);
}
public static void testMemoryBean(long initSize, long maxSize) {
MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
long heapInit = memoryMXBean.getHeapMemoryUsage().getInit();
long heapMax = memoryMXBean.getHeapMemoryUsage().getMax();
long nonHeapInit = memoryMXBean.getNonHeapMemoryUsage().getInit();
long nonHeapMax = memoryMXBean.getNonHeapMemoryUsage().getMax();
if (initSize > 0 && heapInit != initSize) {
throw new IllegalStateException("Init heap size is wrong: " + heapInit + " vs " + initSize);
}
if (maxSize > 0 && heapMax != maxSize) {
throw new IllegalStateException("Max heap size is wrong: " + heapMax + " vs " + maxSize);
}
}
}
| Java |
typedef struct effect_uuid_s
{
uint32_t timeLow;
uint16_t timeMid;
uint16_t timeHiAndVersion;
uint16_t clockSeq;
uint8_t node[6];
} effect_uuid_t;
// Maximum length of character strings in structures defines by this API.
#define EFFECT_STRING_LEN_MAX 64
// NULL UUID definition (matches SL_IID_NULL_)
#define EFFECT_UUID_INITIALIZER { 0xec7178ec, 0xe5e1, 0x4432, 0xa3f4, \
{ 0x46, 0x57, 0xe6, 0x79, 0x52, 0x10 } }
static const effect_uuid_t EFFECT_UUID_NULL_ = EFFECT_UUID_INITIALIZER;
static const effect_uuid_t * const EFFECT_UUID_NULL = &EFFECT_UUID_NULL_;
static const char * const EFFECT_UUID_NULL_STR = "ec7178ec-e5e1-4432-a3f4-4657e6795210";
// The effect descriptor contains necessary information to facilitate the enumeration of the effect
// engines present in a library.
typedef struct effect_descriptor_s
{
effect_uuid_t type; // UUID of to the OpenSL ES interface implemented by this effect
effect_uuid_t uuid; // UUID for this particular implementation
uint32_t apiVersion; // Version of the effect control API implemented
uint32_t flags; // effect engine capabilities/requirements flags (see below)
uint16_t cpuLoad; // CPU load indication (see below)
uint16_t memoryUsage; // Data Memory usage (see below)
char name[EFFECT_STRING_LEN_MAX]; // human readable effect name
char implementor[EFFECT_STRING_LEN_MAX]; // human readable effect implementor name
} effect_descriptor_t;
// CPU load and memory usage indication: each effect implementation must provide an indication of
// its CPU and memory usage for the audio effect framework to limit the number of effects
// instantiated at a given time on a given platform.
// The CPU load is expressed in 0.1 MIPS units as estimated on an ARM9E core (ARMv5TE) with 0 WS.
// The memory usage is expressed in KB and includes only dynamically allocated memory
// Definitions for flags field of effect descriptor.
// +---------------------------+-----------+-----------------------------------
// | description | bits | values
// +---------------------------+-----------+-----------------------------------
// | connection mode | 0..2 | 0 insert: after track process
// | | | 1 auxiliary: connect to track auxiliary
// | | | output and use send level
// | | | 2 replace: replaces track process function;
// | | | must implement SRC, volume and mono to stereo.
// | | | 3 pre processing: applied below audio HAL on input
// | | | 4 post processing: applied below audio HAL on output
// | | | 5 - 7 reserved
// +---------------------------+-----------+-----------------------------------
// | insertion preference | 3..5 | 0 none
// | | | 1 first of the chain
// | | | 2 last of the chain
// | | | 3 exclusive (only effect in the insert chain)
// | | | 4..7 reserved
// +---------------------------+-----------+-----------------------------------
// | Volume management | 6..8 | 0 none
// | | | 1 implements volume control
// | | | 2 requires volume indication
// | | | 4 reserved
// +---------------------------+-----------+-----------------------------------
// | Device indication | 9..11 | 0 none
// | | | 1 requires device updates
// | | | 2, 4 reserved
// +---------------------------+-----------+-----------------------------------
// | Sample input mode | 12..13 | 1 direct: process() function or EFFECT_CMD_SET_CONFIG
// | | | command must specify a buffer descriptor
// | | | 2 provider: process() function uses the
// | | | bufferProvider indicated by the
// | | | EFFECT_CMD_SET_CONFIG command to request input.
// | | | buffers.
// | | | 3 both: both input modes are supported
// +---------------------------+-----------+-----------------------------------
// | Sample output mode | 14..15 | 1 direct: process() function or EFFECT_CMD_SET_CONFIG
// | | | command must specify a buffer descriptor
// | | | 2 provider: process() function uses the
// | | | bufferProvider indicated by the
// | | | EFFECT_CMD_SET_CONFIG command to request output
// | | | buffers.
// | | | 3 both: both output modes are supported
// +---------------------------+-----------+-----------------------------------
// | Hardware acceleration | 16..17 | 0 No hardware acceleration
// | | | 1 non tunneled hw acceleration: the process() function
// | | | reads the samples, send them to HW accelerated
// | | | effect processor, reads back the processed samples
// | | | and returns them to the output buffer.
// | | | 2 tunneled hw acceleration: the process() function is
// | | | transparent. The effect interface is only used to
// | | | control the effect engine. This mode is relevant for
// | | | global effects actually applied by the audio
// | | | hardware on the output stream.
// +---------------------------+-----------+-----------------------------------
// | Audio Mode indication | 18..19 | 0 none
// | | | 1 requires audio mode updates
// | | | 2..3 reserved
// +---------------------------+-----------+-----------------------------------
// | Audio source indication | 20..21 | 0 none
// | | | 1 requires audio source updates
// | | | 2..3 reserved
// +---------------------------+-----------+-----------------------------------
// | Effect offload supported | 22 | 0 The effect cannot be offloaded to an audio DSP
// | | | 1 The effect can be offloaded to an audio DSP
// +---------------------------+-----------+-----------------------------------
// Insert mode
#define EFFECT_FLAG_TYPE_SHIFT 0
#define EFFECT_FLAG_TYPE_SIZE 3
#define EFFECT_FLAG_TYPE_MASK (((1 << EFFECT_FLAG_TYPE_SIZE) -1) \
<< EFFECT_FLAG_TYPE_SHIFT)
#define EFFECT_FLAG_TYPE_INSERT (0 << EFFECT_FLAG_TYPE_SHIFT)
#define EFFECT_FLAG_TYPE_AUXILIARY (1 << EFFECT_FLAG_TYPE_SHIFT)
#define EFFECT_FLAG_TYPE_REPLACE (2 << EFFECT_FLAG_TYPE_SHIFT)
#define EFFECT_FLAG_TYPE_PRE_PROC (3 << EFFECT_FLAG_TYPE_SHIFT)
#define EFFECT_FLAG_TYPE_POST_PROC (4 << EFFECT_FLAG_TYPE_SHIFT)
// Insert preference
#define EFFECT_FLAG_INSERT_SHIFT (EFFECT_FLAG_TYPE_SHIFT + EFFECT_FLAG_TYPE_SIZE)
#define EFFECT_FLAG_INSERT_SIZE 3
#define EFFECT_FLAG_INSERT_MASK (((1 << EFFECT_FLAG_INSERT_SIZE) -1) \
<< EFFECT_FLAG_INSERT_SHIFT)
#define EFFECT_FLAG_INSERT_ANY (0 << EFFECT_FLAG_INSERT_SHIFT)
#define EFFECT_FLAG_INSERT_FIRST (1 << EFFECT_FLAG_INSERT_SHIFT)
#define EFFECT_FLAG_INSERT_LAST (2 << EFFECT_FLAG_INSERT_SHIFT)
#define EFFECT_FLAG_INSERT_EXCLUSIVE (3 << EFFECT_FLAG_INSERT_SHIFT)
// Volume control
#define EFFECT_FLAG_VOLUME_SHIFT (EFFECT_FLAG_INSERT_SHIFT + EFFECT_FLAG_INSERT_SIZE)
#define EFFECT_FLAG_VOLUME_SIZE 3
#define EFFECT_FLAG_VOLUME_MASK (((1 << EFFECT_FLAG_VOLUME_SIZE) -1) \
<< EFFECT_FLAG_VOLUME_SHIFT)
#define EFFECT_FLAG_VOLUME_CTRL (1 << EFFECT_FLAG_VOLUME_SHIFT)
#define EFFECT_FLAG_VOLUME_IND (2 << EFFECT_FLAG_VOLUME_SHIFT)
#define EFFECT_FLAG_VOLUME_NONE (0 << EFFECT_FLAG_VOLUME_SHIFT)
// Device indication
#define EFFECT_FLAG_DEVICE_SHIFT (EFFECT_FLAG_VOLUME_SHIFT + EFFECT_FLAG_VOLUME_SIZE)
#define EFFECT_FLAG_DEVICE_SIZE 3
#define EFFECT_FLAG_DEVICE_MASK (((1 << EFFECT_FLAG_DEVICE_SIZE) -1) \
<< EFFECT_FLAG_DEVICE_SHIFT)
#define EFFECT_FLAG_DEVICE_IND (1 << EFFECT_FLAG_DEVICE_SHIFT)
#define EFFECT_FLAG_DEVICE_NONE (0 << EFFECT_FLAG_DEVICE_SHIFT)
// Sample input modes
#define EFFECT_FLAG_INPUT_SHIFT (EFFECT_FLAG_DEVICE_SHIFT + EFFECT_FLAG_DEVICE_SIZE)
#define EFFECT_FLAG_INPUT_SIZE 2
#define EFFECT_FLAG_INPUT_MASK (((1 << EFFECT_FLAG_INPUT_SIZE) -1) \
<< EFFECT_FLAG_INPUT_SHIFT)
#define EFFECT_FLAG_INPUT_DIRECT (1 << EFFECT_FLAG_INPUT_SHIFT)
#define EFFECT_FLAG_INPUT_PROVIDER (2 << EFFECT_FLAG_INPUT_SHIFT)
#define EFFECT_FLAG_INPUT_BOTH (3 << EFFECT_FLAG_INPUT_SHIFT)
// Sample output modes
#define EFFECT_FLAG_OUTPUT_SHIFT (EFFECT_FLAG_INPUT_SHIFT + EFFECT_FLAG_INPUT_SIZE)
#define EFFECT_FLAG_OUTPUT_SIZE 2
#define EFFECT_FLAG_OUTPUT_MASK (((1 << EFFECT_FLAG_OUTPUT_SIZE) -1) \
<< EFFECT_FLAG_OUTPUT_SHIFT)
#define EFFECT_FLAG_OUTPUT_DIRECT (1 << EFFECT_FLAG_OUTPUT_SHIFT)
#define EFFECT_FLAG_OUTPUT_PROVIDER (2 << EFFECT_FLAG_OUTPUT_SHIFT)
#define EFFECT_FLAG_OUTPUT_BOTH (3 << EFFECT_FLAG_OUTPUT_SHIFT)
// Hardware acceleration mode
#define EFFECT_FLAG_HW_ACC_SHIFT (EFFECT_FLAG_OUTPUT_SHIFT + EFFECT_FLAG_OUTPUT_SIZE)
#define EFFECT_FLAG_HW_ACC_SIZE 2
#define EFFECT_FLAG_HW_ACC_MASK (((1 << EFFECT_FLAG_HW_ACC_SIZE) -1) \
<< EFFECT_FLAG_HW_ACC_SHIFT)
#define EFFECT_FLAG_HW_ACC_SIMPLE (1 << EFFECT_FLAG_HW_ACC_SHIFT)
#define EFFECT_FLAG_HW_ACC_TUNNEL (2 << EFFECT_FLAG_HW_ACC_SHIFT)
// Audio mode indication
#define EFFECT_FLAG_AUDIO_MODE_SHIFT (EFFECT_FLAG_HW_ACC_SHIFT + EFFECT_FLAG_HW_ACC_SIZE)
#define EFFECT_FLAG_AUDIO_MODE_SIZE 2
#define EFFECT_FLAG_AUDIO_MODE_MASK (((1 << EFFECT_FLAG_AUDIO_MODE_SIZE) -1) \
<< EFFECT_FLAG_AUDIO_MODE_SHIFT)
#define EFFECT_FLAG_AUDIO_MODE_IND (1 << EFFECT_FLAG_AUDIO_MODE_SHIFT)
#define EFFECT_FLAG_AUDIO_MODE_NONE (0 << EFFECT_FLAG_AUDIO_MODE_SHIFT)
// Audio source indication
#define EFFECT_FLAG_AUDIO_SOURCE_SHIFT (EFFECT_FLAG_AUDIO_MODE_SHIFT + EFFECT_FLAG_AUDIO_MODE_SIZE)
#define EFFECT_FLAG_AUDIO_SOURCE_SIZE 2
#define EFFECT_FLAG_AUDIO_SOURCE_MASK (((1 << EFFECT_FLAG_AUDIO_SOURCE_SIZE) -1) \
<< EFFECT_FLAG_AUDIO_SOURCE_SHIFT)
#define EFFECT_FLAG_AUDIO_SOURCE_IND (1 << EFFECT_FLAG_AUDIO_SOURCE_SHIFT)
#define EFFECT_FLAG_AUDIO_SOURCE_NONE (0 << EFFECT_FLAG_AUDIO_SOURCE_SHIFT)
// Effect offload indication
#define EFFECT_FLAG_OFFLOAD_SHIFT (EFFECT_FLAG_AUDIO_SOURCE_SHIFT + \
EFFECT_FLAG_AUDIO_SOURCE_SIZE)
#define EFFECT_FLAG_OFFLOAD_SIZE 1
#define EFFECT_FLAG_OFFLOAD_MASK (((1 << EFFECT_FLAG_OFFLOAD_SIZE) -1) \
<< EFFECT_FLAG_OFFLOAD_SHIFT)
#define EFFECT_FLAG_OFFLOAD_SUPPORTED (1 << EFFECT_FLAG_OFFLOAD_SHIFT)
#define EFFECT_MAKE_API_VERSION(M, m) (((M)<<16) | ((m) & 0xFFFF))
#define EFFECT_API_VERSION_MAJOR(v) ((v)>>16)
#define EFFECT_API_VERSION_MINOR(v) ((m) & 0xFFFF)
/////////////////////////////////////////////////
// Effect control interface
/////////////////////////////////////////////////
// Effect control interface version 2.0
#define EFFECT_CONTROL_API_VERSION EFFECT_MAKE_API_VERSION(2,0)
// Effect control interface structure: effect_interface_s
// The effect control interface is exposed by each effect engine implementation. It consists of
// a set of functions controlling the configuration, activation and process of the engine.
// The functions are grouped in a structure of type effect_interface_s.
//
// Effect control interface handle: effect_handle_t
// The effect_handle_t serves two purposes regarding the implementation of the effect engine:
// - 1 it is the address of a pointer to an effect_interface_s structure where the functions
// of the effect control API for a particular effect are located.
// - 2 it is the address of the context of a particular effect instance.
// A typical implementation in the effect library would define a structure as follows:
// struct effect_module_s {
// const struct effect_interface_s *itfe;
// effect_config_t config;
// effect_context_t context;
// }
// The implementation of EffectCreate() function would then allocate a structure of this
// type and return its address as effect_handle_t
typedef struct effect_interface_s **effect_handle_t;
// Forward definition of type audio_buffer_t
typedef struct audio_buffer_s audio_buffer_t;
// Effect control interface definition
struct effect_interface_s
{
////////////////////////////////////////////////////////////////////////////////
//
// Function: process
//
// Description: Effect process function. Takes input samples as specified
// (count and location) in input buffer descriptor and output processed
// samples as specified in output buffer descriptor. If the buffer descriptor
// is not specified the function must use either the buffer or the
// buffer provider function installed by the EFFECT_CMD_SET_CONFIG command.
// The effect framework will call the process() function after the EFFECT_CMD_ENABLE
// command is received and until the EFFECT_CMD_DISABLE is received. When the engine
// receives the EFFECT_CMD_DISABLE command it should turn off the effect gracefully
// and when done indicate that it is OK to stop calling the process() function by
// returning the -ENODATA status.
//
// NOTE: the process() function implementation should be "real-time safe" that is
// it should not perform blocking calls: malloc/free, sleep, read/write/open/close,
// pthread_cond_wait/pthread_mutex_lock...
//
// Input:
// self: handle to the effect interface this function
// is called on.
// inBuffer: buffer descriptor indicating where to read samples to process.
// If NULL, use the configuration passed by EFFECT_CMD_SET_CONFIG command.
//
// outBuffer: buffer descriptor indicating where to write processed samples.
// If NULL, use the configuration passed by EFFECT_CMD_SET_CONFIG command.
//
// Output:
// returned value: 0 successful operation
// -ENODATA the engine has finished the disable phase and the framework
// can stop calling process()
// -EINVAL invalid interface handle or
// invalid input/output buffer description
////////////////////////////////////////////////////////////////////////////////
int32_t (*process)(effect_handle_t self,
audio_buffer_t *inBuffer,
audio_buffer_t *outBuffer);
////////////////////////////////////////////////////////////////////////////////
//
// Function: command
//
// Description: Send a command and receive a response to/from effect engine.
//
// Input:
// self: handle to the effect interface this function
// is called on.
// cmdCode: command code: the command can be a standardized command defined in
// effect_command_e (see below) or a proprietary command.
// cmdSize: size of command in bytes
// pCmdData: pointer to command data
// pReplyData: pointer to reply data
//
// Input/Output:
// replySize: maximum size of reply data as input
// actual size of reply data as output
//
// Output:
// returned value: 0 successful operation
// -EINVAL invalid interface handle or
// invalid command/reply size or format according to command code
// The return code should be restricted to indicate problems related to the this
// API specification. Status related to the execution of a particular command should be
// indicated as part of the reply field.
//
// *pReplyData updated with command response
//
////////////////////////////////////////////////////////////////////////////////
int32_t (*command)(effect_handle_t self,
uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t *replySize,
void *pReplyData);
////////////////////////////////////////////////////////////////////////////////
//
// Function: get_descriptor
//
// Description: Returns the effect descriptor
//
// Input:
// self: handle to the effect interface this function
// is called on.
//
// Input/Output:
// pDescriptor: address where to return the effect descriptor.
//
// Output:
// returned value: 0 successful operation.
// -EINVAL invalid interface handle or invalid pDescriptor
// *pDescriptor: updated with the effect descriptor.
//
////////////////////////////////////////////////////////////////////////////////
int32_t (*get_descriptor)(effect_handle_t self,
effect_descriptor_t *pDescriptor);
////////////////////////////////////////////////////////////////////////////////
//
// Function: process_reverse
//
// Description: Process reverse stream function. This function is used to pass
// a reference stream to the effect engine. If the engine does not need a reference
// stream, this function pointer can be set to NULL.
// This function would typically implemented by an Echo Canceler.
//
// Input:
// self: handle to the effect interface this function
// is called on.
// inBuffer: buffer descriptor indicating where to read samples to process.
// If NULL, use the configuration passed by EFFECT_CMD_SET_CONFIG_REVERSE command.
//
// outBuffer: buffer descriptor indicating where to write processed samples.
// If NULL, use the configuration passed by EFFECT_CMD_SET_CONFIG_REVERSE command.
// If the buffer and buffer provider in the configuration received by
// EFFECT_CMD_SET_CONFIG_REVERSE are also NULL, do not return modified reverse
// stream data
//
// Output:
// returned value: 0 successful operation
// -ENODATA the engine has finished the disable phase and the framework
// can stop calling process_reverse()
// -EINVAL invalid interface handle or
// invalid input/output buffer description
////////////////////////////////////////////////////////////////////////////////
int32_t (*process_reverse)(effect_handle_t self,
audio_buffer_t *inBuffer,
audio_buffer_t *outBuffer);
};
//
//--- Standardized command codes for command() function
//
enum effect_command_e
{
EFFECT_CMD_INIT, // initialize effect engine
EFFECT_CMD_SET_CONFIG, // configure effect engine (see effect_config_t)
EFFECT_CMD_RESET, // reset effect engine
EFFECT_CMD_ENABLE, // enable effect process
EFFECT_CMD_DISABLE, // disable effect process
EFFECT_CMD_SET_PARAM, // set parameter immediately (see effect_param_t)
EFFECT_CMD_SET_PARAM_DEFERRED, // set parameter deferred
EFFECT_CMD_SET_PARAM_COMMIT, // commit previous set parameter deferred
EFFECT_CMD_GET_PARAM, // get parameter
EFFECT_CMD_SET_DEVICE, // set audio device (see audio.h, audio_devices_t)
EFFECT_CMD_SET_VOLUME, // set volume
EFFECT_CMD_SET_AUDIO_MODE, // set the audio mode (normal, ring, ...)
EFFECT_CMD_SET_CONFIG_REVERSE, // configure effect engine reverse stream(see effect_config_t)
EFFECT_CMD_SET_INPUT_DEVICE, // set capture device (see audio.h, audio_devices_t)
EFFECT_CMD_GET_CONFIG, // read effect engine configuration
EFFECT_CMD_GET_CONFIG_REVERSE, // read configure effect engine reverse stream configuration
EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS,// get all supported configurations for a feature.
EFFECT_CMD_GET_FEATURE_CONFIG, // get current feature configuration
EFFECT_CMD_SET_FEATURE_CONFIG, // set current feature configuration
EFFECT_CMD_SET_AUDIO_SOURCE, // set the audio source (see audio.h, audio_source_t)
EFFECT_CMD_OFFLOAD, // set if effect thread is an offload one,
// send the ioHandle of the effect thread
EFFECT_CMD_FIRST_PROPRIETARY = 0x10000 // first proprietary command code
};
//==================================================================================================
// command: EFFECT_CMD_INIT
//--------------------------------------------------------------------------------------------------
// description:
// Initialize effect engine: All configurations return to default
//--------------------------------------------------------------------------------------------------
// command format:
// size: 0
// data: N/A
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(int)
// data: status
//==================================================================================================
// command: EFFECT_CMD_SET_CONFIG
//--------------------------------------------------------------------------------------------------
// description:
// Apply new audio parameters configurations for input and output buffers
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(effect_config_t)
// data: effect_config_t
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(int)
// data: status
//==================================================================================================
// command: EFFECT_CMD_RESET
//--------------------------------------------------------------------------------------------------
// description:
// Reset the effect engine. Keep configuration but resets state and buffer content
//--------------------------------------------------------------------------------------------------
// command format:
// size: 0
// data: N/A
//--------------------------------------------------------------------------------------------------
// reply format:
// size: 0
// data: N/A
//==================================================================================================
// command: EFFECT_CMD_ENABLE
//--------------------------------------------------------------------------------------------------
// description:
// Enable the process. Called by the framework before the first call to process()
//--------------------------------------------------------------------------------------------------
// command format:
// size: 0
// data: N/A
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(int)
// data: status
//==================================================================================================
// command: EFFECT_CMD_DISABLE
//--------------------------------------------------------------------------------------------------
// description:
// Disable the process. Called by the framework after the last call to process()
//--------------------------------------------------------------------------------------------------
// command format:
// size: 0
// data: N/A
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(int)
// data: status
//==================================================================================================
// command: EFFECT_CMD_SET_PARAM
//--------------------------------------------------------------------------------------------------
// description:
// Set a parameter and apply it immediately
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(effect_param_t) + size of param and value
// data: effect_param_t + param + value. See effect_param_t definition below for value offset
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(int)
// data: status
//==================================================================================================
// command: EFFECT_CMD_SET_PARAM_DEFERRED
//--------------------------------------------------------------------------------------------------
// description:
// Set a parameter but apply it only when receiving EFFECT_CMD_SET_PARAM_COMMIT command
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(effect_param_t) + size of param and value
// data: effect_param_t + param + value. See effect_param_t definition below for value offset
//--------------------------------------------------------------------------------------------------
// reply format:
// size: 0
// data: N/A
//==================================================================================================
// command: EFFECT_CMD_SET_PARAM_COMMIT
//--------------------------------------------------------------------------------------------------
// description:
// Apply all previously received EFFECT_CMD_SET_PARAM_DEFERRED commands
//--------------------------------------------------------------------------------------------------
// command format:
// size: 0
// data: N/A
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(int)
// data: status
//==================================================================================================
// command: EFFECT_CMD_GET_PARAM
//--------------------------------------------------------------------------------------------------
// description:
// Get a parameter value
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(effect_param_t) + size of param
// data: effect_param_t + param
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(effect_param_t) + size of param and value
// data: effect_param_t + param + value. See effect_param_t definition below for value offset
//==================================================================================================
// command: EFFECT_CMD_SET_DEVICE
//--------------------------------------------------------------------------------------------------
// description:
// Set the rendering device the audio output path is connected to. See audio.h, audio_devices_t
// for device values.
// The effect implementation must set EFFECT_FLAG_DEVICE_IND flag in its descriptor to receive this
// command when the device changes
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(uint32_t)
// data: uint32_t
//--------------------------------------------------------------------------------------------------
// reply format:
// size: 0
// data: N/A
//==================================================================================================
// command: EFFECT_CMD_SET_VOLUME
//--------------------------------------------------------------------------------------------------
// description:
// Set and get volume. Used by audio framework to delegate volume control to effect engine.
// The effect implementation must set EFFECT_FLAG_VOLUME_IND or EFFECT_FLAG_VOLUME_CTRL flag in
// its descriptor to receive this command before every call to process() function
// If EFFECT_FLAG_VOLUME_CTRL flag is set in the effect descriptor, the effect engine must return
// the volume that should be applied before the effect is processed. The overall volume (the volume
// actually applied by the effect engine multiplied by the returned value) should match the value
// indicated in the command.
//--------------------------------------------------------------------------------------------------
// command format:
// size: n * sizeof(uint32_t)
// data: volume for each channel defined in effect_config_t for output buffer expressed in
// 8.24 fixed point format
//--------------------------------------------------------------------------------------------------
// reply format:
// size: n * sizeof(uint32_t) / 0
// data: - if EFFECT_FLAG_VOLUME_CTRL is set in effect descriptor:
// volume for each channel defined in effect_config_t for output buffer expressed in
// 8.24 fixed point format
// - if EFFECT_FLAG_VOLUME_CTRL is not set in effect descriptor:
// N/A
// It is legal to receive a null pointer as pReplyData in which case the effect framework has
// delegated volume control to another effect
//==================================================================================================
// command: EFFECT_CMD_SET_AUDIO_MODE
//--------------------------------------------------------------------------------------------------
// description:
// Set the audio mode. The effect implementation must set EFFECT_FLAG_AUDIO_MODE_IND flag in its
// descriptor to receive this command when the audio mode changes.
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(uint32_t)
// data: audio_mode_t
//--------------------------------------------------------------------------------------------------
// reply format:
// size: 0
// data: N/A
//==================================================================================================
// command: EFFECT_CMD_SET_CONFIG_REVERSE
//--------------------------------------------------------------------------------------------------
// description:
// Apply new audio parameters configurations for input and output buffers of reverse stream.
// An example of reverse stream is the echo reference supplied to an Acoustic Echo Canceler.
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(effect_config_t)
// data: effect_config_t
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(int)
// data: status
//==================================================================================================
// command: EFFECT_CMD_SET_INPUT_DEVICE
//--------------------------------------------------------------------------------------------------
// description:
// Set the capture device the audio input path is connected to. See audio.h, audio_devices_t
// for device values.
// The effect implementation must set EFFECT_FLAG_DEVICE_IND flag in its descriptor to receive this
// command when the device changes
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(uint32_t)
// data: uint32_t
//--------------------------------------------------------------------------------------------------
// reply format:
// size: 0
// data: N/A
//==================================================================================================
// command: EFFECT_CMD_GET_CONFIG
//--------------------------------------------------------------------------------------------------
// description:
// Read audio parameters configurations for input and output buffers
//--------------------------------------------------------------------------------------------------
// command format:
// size: 0
// data: N/A
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(effect_config_t)
// data: effect_config_t
//==================================================================================================
// command: EFFECT_CMD_GET_CONFIG_REVERSE
//--------------------------------------------------------------------------------------------------
// description:
// Read audio parameters configurations for input and output buffers of reverse stream
//--------------------------------------------------------------------------------------------------
// command format:
// size: 0
// data: N/A
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(effect_config_t)
// data: effect_config_t
//==================================================================================================
// command: EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS
//--------------------------------------------------------------------------------------------------
// description:
// Queries for supported configurations for a particular feature (e.g. get the supported
// combinations of main and auxiliary channels for a noise suppressor).
// The command parameter is the feature identifier (See effect_feature_e for a list of defined
// features) followed by the maximum number of configuration descriptor to return.
// The reply is composed of:
// - status (uint32_t):
// - 0 if feature is supported
// - -ENOSYS if the feature is not supported,
// - -ENOMEM if the feature is supported but the total number of supported configurations
// exceeds the maximum number indicated by the caller.
// - total number of supported configurations (uint32_t)
// - an array of configuration descriptors.
// The actual number of descriptors returned must not exceed the maximum number indicated by
// the caller.
//--------------------------------------------------------------------------------------------------
// command format:
// size: 2 x sizeof(uint32_t)
// data: effect_feature_e + maximum number of configurations to return
//--------------------------------------------------------------------------------------------------
// reply format:
// size: 2 x sizeof(uint32_t) + n x sizeof (<config descriptor>)
// data: status + total number of configurations supported + array of n config descriptors
//==================================================================================================
// command: EFFECT_CMD_GET_FEATURE_CONFIG
//--------------------------------------------------------------------------------------------------
// description:
// Retrieves current configuration for a given feature.
// The reply status is:
// - 0 if feature is supported
// - -ENOSYS if the feature is not supported,
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(uint32_t)
// data: effect_feature_e
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(uint32_t) + sizeof (<config descriptor>)
// data: status + config descriptor
//==================================================================================================
// command: EFFECT_CMD_SET_FEATURE_CONFIG
//--------------------------------------------------------------------------------------------------
// description:
// Sets current configuration for a given feature.
// The reply status is:
// - 0 if feature is supported
// - -ENOSYS if the feature is not supported,
// - -EINVAL if the configuration is invalid
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(uint32_t) + sizeof (<config descriptor>)
// data: effect_feature_e + config descriptor
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(uint32_t)
// data: status
//==================================================================================================
// command: EFFECT_CMD_SET_AUDIO_SOURCE
//--------------------------------------------------------------------------------------------------
// description:
// Set the audio source the capture path is configured for (Camcorder, voice recognition...).
// See audio.h, audio_source_t for values.
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(uint32_t)
// data: uint32_t
//--------------------------------------------------------------------------------------------------
// reply format:
// size: 0
// data: N/A
//==================================================================================================
// command: EFFECT_CMD_OFFLOAD
//--------------------------------------------------------------------------------------------------
// description:
// 1.indicate if the playback thread the effect is attached to is offloaded or not
// 2.update the io handle of the playback thread the effect is attached to
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(effect_offload_param_t)
// data: effect_offload_param_t
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(uint32_t)
// data: uint32_t
//--------------------------------------------------------------------------------------------------
// command: EFFECT_CMD_FIRST_PROPRIETARY
//--------------------------------------------------------------------------------------------------
// description:
// All proprietary effect commands must use command codes above this value. The size and format of
// command and response fields is free in this case
//==================================================================================================
// Audio buffer descriptor used by process(), bufferProvider() functions and buffer_config_t
// structure. Multi-channel audio is always interleaved. The channel order is from LSB to MSB with
// regard to the channel mask definition in audio.h, audio_channel_mask_t e.g :
// Stereo: left, right
// 5 point 1: front left, front right, front center, low frequency, back left, back right
// The buffer size is expressed in frame count, a frame being composed of samples for all
// channels at a given time. Frame size for unspecified format (AUDIO_FORMAT_OTHER) is 8 bit by
// definition
typedef struct audio_buffer_s {
size_t frameCount; // number of frames in buffer
union {
void* raw; // raw pointer to start of buffer
float* f32; // pointer to float 32 bit data at start of buffer
int32_t* s32; // pointer to signed 32 bit data at start of buffer
int16_t* s16; // pointer to signed 16 bit data at start of buffer
uint8_t* u8; // pointer to unsigned 8 bit data at start of buffer
};
} audio_buffer_t;
typedef int32_t (* buffer_function_t)(void *cookie, audio_buffer_t *buffer);
typedef struct buffer_provider_s
{
buffer_function_t getBuffer; // retrieve next buffer
buffer_function_t releaseBuffer; // release used buffer
void *cookie; // for use by client of buffer provider functions
} buffer_provider_t;
// The buffer_config_s structure specifies the input or output audio format
// to be used by the effect engine. It is part of the effect_config_t
// structure that defines both input and output buffer configurations and is
// passed by the EFFECT_CMD_SET_CONFIG or EFFECT_CMD_SET_CONFIG_REVERSE command.
typedef struct buffer_config_s
{
audio_buffer_t buffer; // buffer for use by process() function if not passed explicitly
uint32_t samplingRate; // sampling rate
uint32_t channels; // channel mask (see audio_channel_mask_t in audio.h)
buffer_provider_t bufferProvider; // buffer provider
uint8_t format; // Audio format (see audio_format_t in audio.h)
uint8_t accessMode; // read/write or accumulate in buffer (effect_buffer_access_e)
uint16_t mask; // indicates which of the above fields is valid
} buffer_config_t;
// Values for "accessMode" field of buffer_config_t:
// overwrite, read only, accumulate (read/modify/write)
typedef enum
{
EFFECT_BUFFER_ACCESS_WRITE,
EFFECT_BUFFER_ACCESS_READ,
EFFECT_BUFFER_ACCESS_ACCUMULATE
} effect_buffer_access_e;
// effect_config_s structure describes the format of the pCmdData argument of EFFECT_CMD_SET_CONFIG
// command to configure audio parameters and buffers for effect engine input and output.
typedef struct effect_config_s
{
buffer_config_t inputCfg;
buffer_config_t outputCfg;
} effect_config_t;
// effect_param_s structure describes the format of the pCmdData argument of EFFECT_CMD_SET_PARAM
// command and pCmdData and pReplyData of EFFECT_CMD_GET_PARAM command.
// psize and vsize represent the actual size of parameter and value.
//
// NOTE: the start of value field inside the data field is always on a 32 bit boundary:
//
// +-----------+
// | status | sizeof(int)
// +-----------+
// | psize | sizeof(int)
// +-----------+
// | vsize | sizeof(int)
// +-----------+
// | | | |
// ~ parameter ~ > psize |
// | | | > ((psize - 1)/sizeof(int) + 1) * sizeof(int)
// +-----------+ |
// | padding | |
// +-----------+
// | | |
// ~ value ~ > vsize
// | | |
// +-----------+
typedef struct effect_param_s
{
int32_t status; // Transaction status (unused for command, used for reply)
uint32_t psize; // Parameter size
uint32_t vsize; // Value size
char data[]; // Start of Parameter + Value data
} effect_param_t;
/////////////////////////////////////////////////
// Effect library interface
/////////////////////////////////////////////////
// Effect library interface version 3.0
// Note that EffectsFactory.c only checks the major version component, so changes to the minor
// number can only be used for fully backwards compatible changes
#define EFFECT_LIBRARY_API_VERSION EFFECT_MAKE_API_VERSION(3,0)
#define AUDIO_EFFECT_LIBRARY_TAG ((('A') << 24) | (('E') << 16) | (('L') << 8) | ('T'))
// Every effect library must have a data structure named AUDIO_EFFECT_LIBRARY_INFO_SYM
// and the fields of this data structure must begin with audio_effect_library_t
typedef struct audio_effect_library_s
{
// tag must be initialized to AUDIO_EFFECT_LIBRARY_TAG
uint32_t tag;
// Version of the effect library API : 0xMMMMmmmm MMMM: Major, mmmm: minor
uint32_t version;
// Name of this library
const char *name;
// Author/owner/implementor of the library
const char *implementor;
////////////////////////////////////////////////////////////////////////////////
//
// Function: create_effect
//
// Description: Creates an effect engine of the specified implementation uuid and
// returns an effect control interface on this engine. The function will allocate the
// resources for an instance of the requested effect engine and return
// a handle on the effect control interface.
//
// Input:
// uuid: pointer to the effect uuid.
// sessionId: audio session to which this effect instance will be attached. All effects
// created with the same session ID are connected in series and process the same signal
// stream. Knowing that two effects are part of the same effect chain can help the
// library implement some kind of optimizations.
// ioId: identifies the output or input stream this effect is directed to at audio HAL.
// For future use especially with tunneled HW accelerated effects
//
// Input/Output:
// pHandle: address where to return the effect interface handle.
//
// Output:
// returned value: 0 successful operation.
// -ENODEV library failed to initialize
// -EINVAL invalid pEffectUuid or pHandle
// -ENOENT no effect with this uuid found
// *pHandle: updated with the effect interface handle.
//
////////////////////////////////////////////////////////////////////////////////
int32_t (*create_effect)(const effect_uuid_t *uuid,
int32_t sessionId,
int32_t ioId,
effect_handle_t *pHandle);
////////////////////////////////////////////////////////////////////////////////
//
// Function: release_effect
//
// Description: Releases the effect engine whose handle is given as argument.
// All resources allocated to this particular instance of the effect are
// released.
//
// Input:
// handle: handle on the effect interface to be released.
//
// Output:
// returned value: 0 successful operation.
// -ENODEV library failed to initialize
// -EINVAL invalid interface handle
//
////////////////////////////////////////////////////////////////////////////////
int32_t (*release_effect)(effect_handle_t handle);
////////////////////////////////////////////////////////////////////////////////
//
// Function: get_descriptor
//
// Description: Returns the descriptor of the effect engine which implementation UUID is
// given as argument.
//
// Input/Output:
// uuid: pointer to the effect uuid.
// pDescriptor: address where to return the effect descriptor.
//
// Output:
// returned value: 0 successful operation.
// -ENODEV library failed to initialize
// -EINVAL invalid pDescriptor or uuid
// *pDescriptor: updated with the effect descriptor.
//
////////////////////////////////////////////////////////////////////////////////
int32_t (*get_descriptor)(const effect_uuid_t *uuid,
effect_descriptor_t *pDescriptor);
} audio_effect_library_t;
// Name of the hal_module_info
#define AUDIO_EFFECT_LIBRARY_INFO_SYM AELI
// Name of the hal_module_info as a string
#define AUDIO_EFFECT_LIBRARY_INFO_SYM_AS_STR "AELI"
// Values for bit field "mask" in buffer_config_t. If a bit is set, the corresponding field
// in buffer_config_t must be taken into account when executing the EFFECT_CMD_SET_CONFIG command
#define EFFECT_CONFIG_BUFFER 0x0001 // buffer field must be taken into account
#define EFFECT_CONFIG_SMP_RATE 0x0002 // samplingRate field must be taken into account
#define EFFECT_CONFIG_CHANNELS 0x0004 // channels field must be taken into account
#define EFFECT_CONFIG_FORMAT 0x0008 // format field must be taken into account
#define EFFECT_CONFIG_ACC_MODE 0x0010 // accessMode field must be taken into account
#define EFFECT_CONFIG_PROVIDER 0x0020 // bufferProvider field must be taken into account
#define EFFECT_CONFIG_ALL (EFFECT_CONFIG_BUFFER | EFFECT_CONFIG_SMP_RATE | \
EFFECT_CONFIG_CHANNELS | EFFECT_CONFIG_FORMAT | \
EFFECT_CONFIG_ACC_MODE | EFFECT_CONFIG_PROVIDER)
enum {
AUDIO_IO_HANDLE_NONE = 0,
AUDIO_MODULE_HANDLE_NONE = 0,
AUDIO_PORT_HANDLE_NONE = 0,
AUDIO_PATCH_HANDLE_NONE = 0,
};
typedef enum {
AUDIO_STREAM_DEFAULT = -1, // (-1)
AUDIO_STREAM_MIN = 0,
AUDIO_STREAM_VOICE_CALL = 0,
AUDIO_STREAM_SYSTEM = 1,
AUDIO_STREAM_RING = 2,
AUDIO_STREAM_MUSIC = 3,
AUDIO_STREAM_ALARM = 4,
AUDIO_STREAM_NOTIFICATION = 5,
AUDIO_STREAM_BLUETOOTH_SCO = 6,
AUDIO_STREAM_ENFORCED_AUDIBLE = 7,
AUDIO_STREAM_DTMF = 8,
AUDIO_STREAM_TTS = 9,
AUDIO_STREAM_ACCESSIBILITY = 10,
#ifndef AUDIO_NO_SYSTEM_DECLARATIONS
/** For dynamic policy output mixes. Only used by the audio policy */
AUDIO_STREAM_REROUTING = 11,
/** For audio flinger tracks volume. Only used by the audioflinger */
AUDIO_STREAM_PATCH = 12,
#endif // AUDIO_NO_SYSTEM_DECLARATIONS
} audio_stream_type_t;
typedef enum {
AUDIO_SOURCE_DEFAULT = 0,
AUDIO_SOURCE_MIC = 1,
AUDIO_SOURCE_VOICE_UPLINK = 2,
AUDIO_SOURCE_VOICE_DOWNLINK = 3,
AUDIO_SOURCE_VOICE_CALL = 4,
AUDIO_SOURCE_CAMCORDER = 5,
AUDIO_SOURCE_VOICE_RECOGNITION = 6,
AUDIO_SOURCE_VOICE_COMMUNICATION = 7,
AUDIO_SOURCE_REMOTE_SUBMIX = 8,
AUDIO_SOURCE_UNPROCESSED = 9,
AUDIO_SOURCE_FM_TUNER = 1998,
#ifndef AUDIO_NO_SYSTEM_DECLARATIONS
/**
* A low-priority, preemptible audio source for for background software
* hotword detection. Same tuning as VOICE_RECOGNITION.
* Used only internally by the framework.
*/
AUDIO_SOURCE_HOTWORD = 1999,
#endif // AUDIO_NO_SYSTEM_DECLARATIONS
} audio_source_t;
typedef enum {
AUDIO_SESSION_OUTPUT_STAGE = -1, // (-1)
AUDIO_SESSION_OUTPUT_MIX = 0,
AUDIO_SESSION_ALLOCATE = 0,
AUDIO_SESSION_NONE = 0,
} audio_session_t;
typedef enum {
AUDIO_FORMAT_INVALID = 0xFFFFFFFFu,
AUDIO_FORMAT_DEFAULT = 0,
AUDIO_FORMAT_PCM = 0x00000000u,
AUDIO_FORMAT_MP3 = 0x01000000u,
AUDIO_FORMAT_AMR_NB = 0x02000000u,
AUDIO_FORMAT_AMR_WB = 0x03000000u,
AUDIO_FORMAT_AAC = 0x04000000u,
AUDIO_FORMAT_HE_AAC_V1 = 0x05000000u,
AUDIO_FORMAT_HE_AAC_V2 = 0x06000000u,
AUDIO_FORMAT_VORBIS = 0x07000000u,
AUDIO_FORMAT_OPUS = 0x08000000u,
AUDIO_FORMAT_AC3 = 0x09000000u,
AUDIO_FORMAT_E_AC3 = 0x0A000000u,
AUDIO_FORMAT_DTS = 0x0B000000u,
AUDIO_FORMAT_DTS_HD = 0x0C000000u,
AUDIO_FORMAT_IEC61937 = 0x0D000000u,
AUDIO_FORMAT_DOLBY_TRUEHD = 0x0E000000u,
AUDIO_FORMAT_EVRC = 0x10000000u,
AUDIO_FORMAT_EVRCB = 0x11000000u,
AUDIO_FORMAT_EVRCWB = 0x12000000u,
AUDIO_FORMAT_EVRCNW = 0x13000000u,
AUDIO_FORMAT_AAC_ADIF = 0x14000000u,
AUDIO_FORMAT_WMA = 0x15000000u,
AUDIO_FORMAT_WMA_PRO = 0x16000000u,
AUDIO_FORMAT_AMR_WB_PLUS = 0x17000000u,
AUDIO_FORMAT_MP2 = 0x18000000u,
AUDIO_FORMAT_QCELP = 0x19000000u,
AUDIO_FORMAT_DSD = 0x1A000000u,
AUDIO_FORMAT_FLAC = 0x1B000000u,
AUDIO_FORMAT_ALAC = 0x1C000000u,
AUDIO_FORMAT_APE = 0x1D000000u,
AUDIO_FORMAT_AAC_ADTS = 0x1E000000u,
AUDIO_FORMAT_SBC = 0x1F000000u,
AUDIO_FORMAT_APTX = 0x20000000u,
AUDIO_FORMAT_APTX_HD = 0x21000000u,
AUDIO_FORMAT_AC4 = 0x22000000u,
AUDIO_FORMAT_LDAC = 0x23000000u,
AUDIO_FORMAT_MAT = 0x24000000u,
AUDIO_FORMAT_MAIN_MASK = 0xFF000000u,
AUDIO_FORMAT_SUB_MASK = 0x00FFFFFFu,
/* Subformats */
AUDIO_FORMAT_PCM_SUB_16_BIT = 0x1u,
AUDIO_FORMAT_PCM_SUB_8_BIT = 0x2u,
AUDIO_FORMAT_PCM_SUB_32_BIT = 0x3u,
AUDIO_FORMAT_PCM_SUB_8_24_BIT = 0x4u,
AUDIO_FORMAT_PCM_SUB_FLOAT = 0x5u,
AUDIO_FORMAT_PCM_SUB_24_BIT_PACKED = 0x6u,
AUDIO_FORMAT_MP3_SUB_NONE = 0x0u,
AUDIO_FORMAT_AMR_SUB_NONE = 0x0u,
AUDIO_FORMAT_AAC_SUB_MAIN = 0x1u,
AUDIO_FORMAT_AAC_SUB_LC = 0x2u,
AUDIO_FORMAT_AAC_SUB_SSR = 0x4u,
AUDIO_FORMAT_AAC_SUB_LTP = 0x8u,
AUDIO_FORMAT_AAC_SUB_HE_V1 = 0x10u,
AUDIO_FORMAT_AAC_SUB_SCALABLE = 0x20u,
AUDIO_FORMAT_AAC_SUB_ERLC = 0x40u,
AUDIO_FORMAT_AAC_SUB_LD = 0x80u,
AUDIO_FORMAT_AAC_SUB_HE_V2 = 0x100u,
AUDIO_FORMAT_AAC_SUB_ELD = 0x200u,
AUDIO_FORMAT_AAC_SUB_XHE = 0x300u,
AUDIO_FORMAT_VORBIS_SUB_NONE = 0x0u,
AUDIO_FORMAT_E_AC3_SUB_JOC = 0x1u,
AUDIO_FORMAT_MAT_SUB_1_0 = 0x1u,
AUDIO_FORMAT_MAT_SUB_2_0 = 0x2u,
AUDIO_FORMAT_MAT_SUB_2_1 = 0x3u,
/* Aliases */
AUDIO_FORMAT_PCM_16_BIT = 0x1u, // (PCM | PCM_SUB_16_BIT)
AUDIO_FORMAT_PCM_8_BIT = 0x2u, // (PCM | PCM_SUB_8_BIT)
AUDIO_FORMAT_PCM_32_BIT = 0x3u, // (PCM | PCM_SUB_32_BIT)
AUDIO_FORMAT_PCM_8_24_BIT = 0x4u, // (PCM | PCM_SUB_8_24_BIT)
AUDIO_FORMAT_PCM_FLOAT = 0x5u, // (PCM | PCM_SUB_FLOAT)
AUDIO_FORMAT_PCM_24_BIT_PACKED = 0x6u, // (PCM | PCM_SUB_24_BIT_PACKED)
AUDIO_FORMAT_AAC_MAIN = 0x4000001u, // (AAC | AAC_SUB_MAIN)
AUDIO_FORMAT_AAC_LC = 0x4000002u, // (AAC | AAC_SUB_LC)
AUDIO_FORMAT_AAC_SSR = 0x4000004u, // (AAC | AAC_SUB_SSR)
AUDIO_FORMAT_AAC_LTP = 0x4000008u, // (AAC | AAC_SUB_LTP)
AUDIO_FORMAT_AAC_HE_V1 = 0x4000010u, // (AAC | AAC_SUB_HE_V1)
AUDIO_FORMAT_AAC_SCALABLE = 0x4000020u, // (AAC | AAC_SUB_SCALABLE)
AUDIO_FORMAT_AAC_ERLC = 0x4000040u, // (AAC | AAC_SUB_ERLC)
AUDIO_FORMAT_AAC_LD = 0x4000080u, // (AAC | AAC_SUB_LD)
AUDIO_FORMAT_AAC_HE_V2 = 0x4000100u, // (AAC | AAC_SUB_HE_V2)
AUDIO_FORMAT_AAC_ELD = 0x4000200u, // (AAC | AAC_SUB_ELD)
AUDIO_FORMAT_AAC_XHE = 0x4000300u, // (AAC | AAC_SUB_XHE)
AUDIO_FORMAT_AAC_ADTS_MAIN = 0x1e000001u, // (AAC_ADTS | AAC_SUB_MAIN)
AUDIO_FORMAT_AAC_ADTS_LC = 0x1e000002u, // (AAC_ADTS | AAC_SUB_LC)
AUDIO_FORMAT_AAC_ADTS_SSR = 0x1e000004u, // (AAC_ADTS | AAC_SUB_SSR)
AUDIO_FORMAT_AAC_ADTS_LTP = 0x1e000008u, // (AAC_ADTS | AAC_SUB_LTP)
AUDIO_FORMAT_AAC_ADTS_HE_V1 = 0x1e000010u, // (AAC_ADTS | AAC_SUB_HE_V1)
AUDIO_FORMAT_AAC_ADTS_SCALABLE = 0x1e000020u, // (AAC_ADTS | AAC_SUB_SCALABLE)
AUDIO_FORMAT_AAC_ADTS_ERLC = 0x1e000040u, // (AAC_ADTS | AAC_SUB_ERLC)
AUDIO_FORMAT_AAC_ADTS_LD = 0x1e000080u, // (AAC_ADTS | AAC_SUB_LD)
AUDIO_FORMAT_AAC_ADTS_HE_V2 = 0x1e000100u, // (AAC_ADTS | AAC_SUB_HE_V2)
AUDIO_FORMAT_AAC_ADTS_ELD = 0x1e000200u, // (AAC_ADTS | AAC_SUB_ELD)
AUDIO_FORMAT_AAC_ADTS_XHE = 0x1e000300u, // (AAC_ADTS | AAC_SUB_XHE)
AUDIO_FORMAT_E_AC3_JOC = 0xA000001u, // (E_AC3 | E_AC3_SUB_JOC)
AUDIO_FORMAT_MAT_1_0 = 0x24000001u, // (MAT | MAT_SUB_1_0)
AUDIO_FORMAT_MAT_2_0 = 0x24000002u, // (MAT | MAT_SUB_2_0)
AUDIO_FORMAT_MAT_2_1 = 0x24000003u, // (MAT | MAT_SUB_2_1)
} audio_format_t;
enum {
FCC_2 = 2,
FCC_8 = 8,
};
enum {
AUDIO_CHANNEL_REPRESENTATION_POSITION = 0x0u,
AUDIO_CHANNEL_REPRESENTATION_INDEX = 0x2u,
AUDIO_CHANNEL_NONE = 0x0u,
AUDIO_CHANNEL_INVALID = 0xC0000000u,
AUDIO_CHANNEL_OUT_FRONT_LEFT = 0x1u,
AUDIO_CHANNEL_OUT_FRONT_RIGHT = 0x2u,
AUDIO_CHANNEL_OUT_FRONT_CENTER = 0x4u,
AUDIO_CHANNEL_OUT_LOW_FREQUENCY = 0x8u,
AUDIO_CHANNEL_OUT_BACK_LEFT = 0x10u,
AUDIO_CHANNEL_OUT_BACK_RIGHT = 0x20u,
AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER = 0x40u,
AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER = 0x80u,
AUDIO_CHANNEL_OUT_BACK_CENTER = 0x100u,
AUDIO_CHANNEL_OUT_SIDE_LEFT = 0x200u,
AUDIO_CHANNEL_OUT_SIDE_RIGHT = 0x400u,
AUDIO_CHANNEL_OUT_TOP_CENTER = 0x800u,
AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT = 0x1000u,
AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER = 0x2000u,
AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT = 0x4000u,
AUDIO_CHANNEL_OUT_TOP_BACK_LEFT = 0x8000u,
AUDIO_CHANNEL_OUT_TOP_BACK_CENTER = 0x10000u,
AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT = 0x20000u,
AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT = 0x40000u,
AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT = 0x80000u,
AUDIO_CHANNEL_OUT_MONO = 0x1u, // OUT_FRONT_LEFT
AUDIO_CHANNEL_OUT_STEREO = 0x3u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT
AUDIO_CHANNEL_OUT_2POINT1 = 0xBu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_LOW_FREQUENCY
AUDIO_CHANNEL_OUT_2POINT0POINT2 = 0xC0003u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT
AUDIO_CHANNEL_OUT_2POINT1POINT2 = 0xC000Bu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT | OUT_LOW_FREQUENCY
AUDIO_CHANNEL_OUT_3POINT0POINT2 = 0xC0007u, // OUT_FRONT_LEFT | OUT_FRONT_CENTER | OUT_FRONT_RIGHT | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT
AUDIO_CHANNEL_OUT_3POINT1POINT2 = 0xC000Fu, // OUT_FRONT_LEFT | OUT_FRONT_CENTER | OUT_FRONT_RIGHT | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT | OUT_LOW_FREQUENCY
AUDIO_CHANNEL_OUT_QUAD = 0x33u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_BACK_LEFT | OUT_BACK_RIGHT
AUDIO_CHANNEL_OUT_QUAD_BACK = 0x33u, // OUT_QUAD
AUDIO_CHANNEL_OUT_QUAD_SIDE = 0x603u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_SIDE_LEFT | OUT_SIDE_RIGHT
AUDIO_CHANNEL_OUT_SURROUND = 0x107u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_BACK_CENTER
AUDIO_CHANNEL_OUT_PENTA = 0x37u, // OUT_QUAD | OUT_FRONT_CENTER
AUDIO_CHANNEL_OUT_5POINT1 = 0x3Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT
AUDIO_CHANNEL_OUT_5POINT1_BACK = 0x3Fu, // OUT_5POINT1
AUDIO_CHANNEL_OUT_5POINT1_SIDE = 0x60Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_LOW_FREQUENCY | OUT_SIDE_LEFT | OUT_SIDE_RIGHT
AUDIO_CHANNEL_OUT_5POINT1POINT2 = 0xC003Fu, // OUT_5POINT1 | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT
AUDIO_CHANNEL_OUT_5POINT1POINT4 = 0x2D03Fu, // OUT_5POINT1 | OUT_TOP_FRONT_LEFT | OUT_TOP_FRONT_RIGHT | OUT_TOP_BACK_LEFT | OUT_TOP_BACK_RIGHT
AUDIO_CHANNEL_OUT_6POINT1 = 0x13Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT | OUT_BACK_CENTER
AUDIO_CHANNEL_OUT_7POINT1 = 0x63Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT | OUT_SIDE_LEFT | OUT_SIDE_RIGHT
AUDIO_CHANNEL_OUT_7POINT1POINT2 = 0xC063Fu, // OUT_7POINT1 | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT
AUDIO_CHANNEL_OUT_7POINT1POINT4 = 0x2D63Fu, // OUT_7POINT1 | OUT_TOP_FRONT_LEFT | OUT_TOP_FRONT_RIGHT | OUT_TOP_BACK_LEFT | OUT_TOP_BACK_RIGHT
AUDIO_CHANNEL_IN_LEFT = 0x4u,
AUDIO_CHANNEL_IN_RIGHT = 0x8u,
AUDIO_CHANNEL_IN_FRONT = 0x10u,
AUDIO_CHANNEL_IN_BACK = 0x20u,
AUDIO_CHANNEL_IN_LEFT_PROCESSED = 0x40u,
AUDIO_CHANNEL_IN_RIGHT_PROCESSED = 0x80u,
AUDIO_CHANNEL_IN_FRONT_PROCESSED = 0x100u,
AUDIO_CHANNEL_IN_BACK_PROCESSED = 0x200u,
AUDIO_CHANNEL_IN_PRESSURE = 0x400u,
AUDIO_CHANNEL_IN_X_AXIS = 0x800u,
AUDIO_CHANNEL_IN_Y_AXIS = 0x1000u,
AUDIO_CHANNEL_IN_Z_AXIS = 0x2000u,
AUDIO_CHANNEL_IN_BACK_LEFT = 0x10000u,
AUDIO_CHANNEL_IN_BACK_RIGHT = 0x20000u,
AUDIO_CHANNEL_IN_CENTER = 0x40000u,
AUDIO_CHANNEL_IN_LOW_FREQUENCY = 0x100000u,
AUDIO_CHANNEL_IN_TOP_LEFT = 0x200000u,
AUDIO_CHANNEL_IN_TOP_RIGHT = 0x400000u,
AUDIO_CHANNEL_IN_VOICE_UPLINK = 0x4000u,
AUDIO_CHANNEL_IN_VOICE_DNLINK = 0x8000u,
AUDIO_CHANNEL_IN_MONO = 0x10u, // IN_FRONT
AUDIO_CHANNEL_IN_STEREO = 0xCu, // IN_LEFT | IN_RIGHT
AUDIO_CHANNEL_IN_FRONT_BACK = 0x30u, // IN_FRONT | IN_BACK
AUDIO_CHANNEL_IN_6 = 0xFCu, // IN_LEFT | IN_RIGHT | IN_FRONT | IN_BACK | IN_LEFT_PROCESSED | IN_RIGHT_PROCESSED
AUDIO_CHANNEL_IN_2POINT0POINT2 = 0x60000Cu, // IN_LEFT | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT
AUDIO_CHANNEL_IN_2POINT1POINT2 = 0x70000Cu, // IN_LEFT | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT | IN_LOW_FREQUENCY
AUDIO_CHANNEL_IN_3POINT0POINT2 = 0x64000Cu, // IN_LEFT | IN_CENTER | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT
AUDIO_CHANNEL_IN_3POINT1POINT2 = 0x74000Cu, // IN_LEFT | IN_CENTER | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT | IN_LOW_FREQUENCY
AUDIO_CHANNEL_IN_5POINT1 = 0x17000Cu, // IN_LEFT | IN_CENTER | IN_RIGHT | IN_BACK_LEFT | IN_BACK_RIGHT | IN_LOW_FREQUENCY
AUDIO_CHANNEL_IN_VOICE_UPLINK_MONO = 0x4010u, // IN_VOICE_UPLINK | IN_MONO
AUDIO_CHANNEL_IN_VOICE_DNLINK_MONO = 0x8010u, // IN_VOICE_DNLINK | IN_MONO
AUDIO_CHANNEL_IN_VOICE_CALL_MONO = 0xC010u, // IN_VOICE_UPLINK_MONO | IN_VOICE_DNLINK_MONO
AUDIO_CHANNEL_COUNT_MAX = 30u,
AUDIO_CHANNEL_INDEX_HDR = 0x80000000u, // REPRESENTATION_INDEX << COUNT_MAX
AUDIO_CHANNEL_INDEX_MASK_1 = 0x80000001u, // INDEX_HDR | (1 << 1) - 1
AUDIO_CHANNEL_INDEX_MASK_2 = 0x80000003u, // INDEX_HDR | (1 << 2) - 1
AUDIO_CHANNEL_INDEX_MASK_3 = 0x80000007u, // INDEX_HDR | (1 << 3) - 1
AUDIO_CHANNEL_INDEX_MASK_4 = 0x8000000Fu, // INDEX_HDR | (1 << 4) - 1
AUDIO_CHANNEL_INDEX_MASK_5 = 0x8000001Fu, // INDEX_HDR | (1 << 5) - 1
AUDIO_CHANNEL_INDEX_MASK_6 = 0x8000003Fu, // INDEX_HDR | (1 << 6) - 1
AUDIO_CHANNEL_INDEX_MASK_7 = 0x8000007Fu, // INDEX_HDR | (1 << 7) - 1
AUDIO_CHANNEL_INDEX_MASK_8 = 0x800000FFu, // INDEX_HDR | (1 << 8) - 1
};
| Java |
jQuery(function($) {
///////////////////////////////////////////////////////////////////
///// META BOXES JS
///////////////////////////////////////////////////////////////////
jQuery('.repeatable-add').live('click', function() {
var field = jQuery(this).closest('td').find('.custom_repeatable li:last').clone(true);
var fieldLocation = jQuery(this).closest('td').find('.custom_repeatable li:last');
field.find('input.regular-text, textarea, select').val('');
field.find('input, textarea, select').attr('name', function(index, name) {
return name.replace(/(\d+)/, function(fullMatch, n) {
return Number(n) + 1;
});
});
field.insertAfter(fieldLocation, jQuery(this).closest('td'));
var fieldsCount = jQuery('.repeatable-remove').length;
if( fieldsCount > 1 ) {
jQuery('.repeatable-remove').css('display','inline');
}
return false;
});
var fieldsCount = jQuery('.repeatable-remove').length;
if( fieldsCount == 1 ) {
jQuery('.repeatable-remove').css('display','none');
}
jQuery('.repeatable-remove').live('click', function() {
jQuery(this).parent().remove();
var fieldsCount = jQuery('.repeatable-remove').length;
if( fieldsCount == 1 ) {
jQuery('.repeatable-remove').css('display','none');
}
return false;
});
jQuery('.custom_repeatable').sortable({
opacity: 0.6,
revert: true,
cursor: 'move',
handle: '.sort'
});
// the upload image button, saves the id and outputs a preview of the image
var imageFrame;
$('.rg-bb_upload_image_button').live('click', function(event) {
event.preventDefault();
var options, attachment;
$self = $(event.target);
$div = $self.closest('div.rg-bb_image');
// if the frame already exists, open it
if ( imageFrame ) {
imageFrame.open();
return;
}
// set our settings
imageFrame = wp.media({
title: 'Choose Image',
multiple: true,
library: {
type: 'image'
},
button: {
text: 'Use This Image'
}
});
// set up our select handler
imageFrame.on( 'select', function() {
selection = imageFrame.state().get('selection');
if ( ! selection )
return;
// loop through the selected files
selection.each( function( attachment ) {
console.log(attachment);
var src = attachment.attributes.sizes.full.url;
var id = attachment.id;
$div.find('.rg-bb_preview_image').attr('src', src);
$div.find('.rg-bb_upload_image').val(id);
} );
});
// open the frame
imageFrame.open();
});
// the remove image link, removes the image id from the hidden field and replaces the image preview
$('.rg-bb_clear_image_button').live('click', function() {
var defaultImage = $(this).parent().siblings('.rg-bb_default_image').text();
$(this).parent().siblings('.rg-bb_upload_image').val('');
$(this).parent().siblings('.rg-bb_preview_image').attr('src', defaultImage);
return false;
});
// function to create an array of input values
function ids(inputs) {
var a = [];
for (var i = 0; i < inputs.length; i++) {
a.push(inputs[i].val);
}
//$("span").text(a.join(" "));
}
// repeatable fields
$('.toggle').on("click", function() {
console.log($(this).parent().siblings().toggleClass('closed'));
});
$('.meta_box_repeatable_add').live('click', function(e) {
e.preventDefault();
// clone
var row = $(this).closest('.meta_box_repeatable').find('tbody tr:last-child');
var clone = row.clone();
var defaultImage = clone.find('.meta_box_default_image').text();
clone.find('select.chosen').removeAttr('style', '').removeAttr('id', '').removeClass('chzn-done').data('chosen', null).next().remove();
// clone.find('input.regular-text, textarea, select').val('');
clone.find('.meta_box_preview_image').attr('src', defaultImage).removeClass('loaded');
clone.find('input[type=checkbox], input[type=radio]').attr('checked', false);
row.after(clone);
// increment name and id
clone.find('input, textarea, select').attr('name', function(index, name) {
return name.replace(/(\d+)/, function(fullMatch, n) {
return Number(n) + 1;
});
});
var arr = [];
$('input.repeatable_id:text').each(function(){ arr.push($(this).val()); });
clone.find('input.repeatable_id')
.val(Number(Math.max.apply( Math, arr )) + 1);
if (!!$.prototype.chosen) {
clone.find('select.chosen')
.chosen({allow_single_deselect: true});
}
});
$('.meta_box_repeatable_remove').live('click', function(e){
e.preventDefault();
$(this).closest('tr').remove();
});
$('.meta_box_repeatable tbody').sortable({
opacity: 0.6,
revert: true,
cursor: 'move',
handle: '.hndle'
});
// post_drop_sort
$('.sort_list').sortable({
connectWith: '.sort_list',
opacity: 0.6,
revert: true,
cursor: 'move',
cancel: '.post_drop_sort_area_name',
items: 'li:not(.post_drop_sort_area_name)',
update: function(event, ui) {
var result = $(this).sortable('toArray');
var thisID = $(this).attr('id');
$('.store-' + thisID).val(result)
}
});
$('.sort_list').disableSelection();
// turn select boxes into something magical
if (!!$.prototype.chosen)
$('.chosen').chosen({ allow_single_deselect: true });
}); | Java |
/* nip2-cli.c ... run the nip2 executable, connecting stdin and stdout to the
* console
*
* 11/12/09
* - use SetHandleInformation() to stop the child inheriting the read
* handle (thanks Leo)
*/
/*
Copyright (C) 2008 Imperial College, London
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
*/
/*
These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
*/
/* Adapted from sample code by Leo Davidson, with the author's permission.
*/
/* Windows does not let a single exe run in both command-line and GUI mode. To
* run nip2 in command-line mode, we run this CLI wrapper program instead,
* which starts the main nip2 exe, connecting stdin/out/err appropriately.
*/
#include <windows.h>
#include <stdio.h>
#include <io.h>
#include <ctype.h>
#include <glib.h>
void
print_last_error ()
{
char *buf;
if (FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError (),
MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR) & buf, 0, NULL))
{
fprintf (stderr, "%s", buf);
LocalFree (buf);
}
}
int
main (int argc, char **argv)
{
char *dirname;
char command[2048];
gboolean quote;
int i, j;
HANDLE hChildStdoutRd;
HANDLE hChildStdoutWr;
SECURITY_ATTRIBUTES saAttr;
PROCESS_INFORMATION processInformation;
STARTUPINFO startUpInfo;
DWORD dwRead;
CHAR buf[1024];
/* we run the nip2.exe in the same directory as this exe: swap the last
* pathname component for nip2.exe
* we change the argv[0] pointer, probably not a good idea
*/
dirname = g_path_get_dirname (argv[0]);
argv[0] = g_build_filename (dirname, "nip2.exe", NULL);
g_free (dirname);
if (_access (argv[0], 00))
{
fprintf (stderr, "cannot access \"%s\"\n", argv[0]);
exit (1);
}
/* build the command string ... we have to quote items containing spaces
*/
command[0] = '\0';
for (i = 0; i < argc; i++)
{
quote = FALSE;
for (j = 0; argv[i][j]; j++)
{
if (isspace (argv[i][j]))
{
quote = TRUE;
break;
}
}
if (i > 0)
{
strncat (command, " ", sizeof (command) - 1);
}
if (quote)
{
strncat (command, "\"", sizeof (command) - 1);
}
strncat (command, argv[i], sizeof (command) - 1);
if (quote)
{
strncat (command, "\"", sizeof (command) - 1);
}
}
if (strlen (command) == sizeof (command) - 1)
{
fprintf (stderr, "command too long\n");
exit (1);
}
/* Create a pipe for the child process's STDOUT.
*/
hChildStdoutRd = NULL;
hChildStdoutWr = NULL;
saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
if (!CreatePipe (&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0))
{
fprintf (stderr, "CreatePipe failed: ");
print_last_error ();
fprintf (stderr, "\n");
exit (1);
}
/* Ensure the read handle to the pipe for STDOUT is not inherited.
*/
if (!SetHandleInformation(hChildStdoutRd, HANDLE_FLAG_INHERIT, 0))
{
fprintf (stderr, "SetHandleInformation failed: ");
print_last_error ();
fprintf (stderr, "\n");
exit (1);
}
/* Run command.
*/
startUpInfo.cb = sizeof (STARTUPINFO);
startUpInfo.lpReserved = NULL;
startUpInfo.lpDesktop = NULL;
startUpInfo.lpTitle = NULL;
startUpInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
startUpInfo.hStdOutput = hChildStdoutWr;
startUpInfo.hStdError = hChildStdoutWr;
startUpInfo.cbReserved2 = 0;
startUpInfo.lpReserved2 = NULL;
startUpInfo.wShowWindow = SW_SHOWNORMAL;
if (!CreateProcess (NULL, command, NULL, /* default security */
NULL, /* default thread security */
TRUE, /* inherit handles */
CREATE_DEFAULT_ERROR_MODE | DETACHED_PROCESS, NULL, /* use default environment */
NULL, /* set default directory */
&startUpInfo, &processInformation))
{
fprintf (stderr, "error running \"%s\": ", command);
print_last_error ();
fprintf (stderr, "\n");
exit (1);
}
/* Close the write end of the pipe before reading from the read end.
*/
CloseHandle (hChildStdoutWr);
while (ReadFile (hChildStdoutRd, buf, sizeof (buf) - 1, &dwRead, NULL) &&
dwRead > 0)
{
buf[dwRead] = '\0';
printf ("%s", buf);
}
CloseHandle (hChildStdoutRd);
return (0);
}
| Java |
/*
# -- BEGIN LICENSE BLOCK --------------------------------------------------
# This file is part of Dotclear 2.
# Copyright (c) 2003-2013 Olivier Meunier & Association Dotclear
# Licensed under the GPL version 2.0 license.
# See LICENSE file or http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# -- END LICENSE BLOCK ----------------------------------------------------
LAYOUTS
HTML TAGS
FORMULAIRES
BOUTONS
MESSAGES
ELEMENTS PRINCIPAUX
REGLES SPECIFIQUES
MEDIA QUERIES
*/
/* ---------------------------------------------------------------------------
START
---------------------------------------------------------------------------- */
html {
font-size: 62.5%;
}
body {
font-size: 12px; /* ie < 9 sucks */
font-size: 1.2rem;
line-height: 1.5;
font-family: "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
margin: 0;
padding: 0;
}
/* ---------------------------------------------------------------------------
LAYOUTS
---------------------------------------------------------------------------- */
*, *:before, *:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#header {
background: #676e78;
color: #FFF;
border-bottom: 4px solid #A2CBE9;
width: 100%;
display: table;
position: relative;
}
#wrapper {
position: relative;
padding-top: 1.5em;
float: left;
width: 100%;
z-index: 10;
background: #F7F7F7 url(bg_wrapper.png) repeat-y 15em;
}
.with-js #wrapper {
padding-top: 0;
}
#main {
width: 100%;
float: right;
margin-left: -14em;
margin-top: 0;
}
#content {
margin: 0 0 0 14em;
padding: .5em 1.5em .75em 2.5em;
background: #fff;
}
#main-menu {
width: 14em;
float: left;
margin: 0;
padding-top: .5em;
padding-bottom: 1em;
overflow: hidden;
background: #f7f7f7;
}
#footer {
clear: both;
position: relative;
padding: .5em 1em .5em 0;
text-align: right;
border-top: 1px solid #ccc;
background-color: #fff;
}
/* to hide main-menu */
#collapser {
position: absolute;
top: 0;
left: 14em;
width: 15px;
height: 100%;
overflow: hidden;
display: block;
background: #f3f3f3 url(../images/collapser-hide.png) no-repeat center bottom;
border-right: double #dfdfdf;
z-index: 1;
}
.expand-mm {
display: none;
}
/* if main-menu is hidden */
#wrapper.hide-mm {
background: #fff;
}
.hide-mm #main {
margin-left: 0;
}
.hide-mm #content {
margin-left: 1em;
}
.hide-mm #main-menu {
display: none;
}
.hide-mm #collapser {
left: 0;
background: #e3e3e3 url(../images/collapser-show.png) no-repeat center bottom;
}
.hide-mm .collapse-mm {
display: none;
}
.hide-mm .expand-mm {
display: block;
}
/* -------------------------------------------------------------- layout: two-cols */
.two-cols {
position: static;
}
.two-cols .col {
width: 48%;
margin-left: 2%;
float: left;
}
.two-cols .col70 {
width: 68%;
margin-left: 0;
float: left;
}
.col30 {
width: 28%;
margin-left: 2%;
float: left;
}
.two-cols .col:first-child,
.two-cols .col30.first-col {
margin-left: 0;
margin-right: 2%;
}
.two-cols .col:last-child,
.two-cols .col70.last-col {
margin-left: 2%;
margin-right: 0;
}
.two-cols table {
width: 90%;
}
/* -------------------------------------------------------------- layout: three-cols */
.three-cols {
position: static;
}
.three-cols .col {
width: 32.3%;
float: left;
margin-left: 1%;
}
.three-cols .col:first-child {
margin-left: 0;
}
/* ------------------------------------------------- layout: optionnal one/two/three-boxes */
.one-box {
text-align: justify;
}
.two-boxes {
width: 48.5%;
}
.three-boxes {
width: 30%;
}
.two-boxes, .three-boxes {
display: inline-block;
vertical-align: top;
margin: 0 1.5% 1em;
text-align: left;
}
.two-boxes:nth-of-type(odd), .three-boxes:nth-of-type(3n+1) {
margin-left: 0;
}
.two-boxes:nth-of-type(even), .three-boxes:nth-of-type(3n) {
margin-right: 0;
}
/* ---------------------------------------------------------------- layout: popups */
.popup h1 {
display: block;
width: 100%;
margin: 0;
background: #676e78;
font-size: 1.5em;
text-indent: 1em;
line-height: 1.5em;
font-weight: normal;
color: #fff;
}
.popup #wrapper {
display: block;
float: none;
width: 100%;
margin: 0;
padding: 0;
background-position: 0 0;
}
.popup #main {
margin: 0;
padding: 0;
}
.popup #content {
margin: 0;
padding: 1em;
}
.popup #content h2 {
margin: 0 0 1em 0;
padding: 0;
}
.popup #footer p {
border: none;
}
/* -------------------------------------------------------- layout: classes de complément */
.constrained {
margin: 0;
padding: 0;
border: none;
background: transparent;
}
.table {
display: table;
}
.cell {
display: table-cell;
vertical-align: top;
}
.clear {
clear: both;
}
.lclear {
clear: left;
}
.clearer {
height: 1px;
font-size: 1px;
}
/* Micro clearfix thx to Nicolas Gallagher */
.clearfix:before, .clearfix:after {
content: " ";
display: table;
}
.clearfix:after {
clear: both;
}
.frame-shrink {
border: 1px solid #676e78;
padding: 0.5em;
margin-bottom: 1em;
height: 120px;
overflow: auto;
}
.box {
display: inline-block;
vertical-align: top;
margin: 0 10px 10px;
text-align: left;
}
.box.small {
width: 312px;
}
.box.medium {
width: 644px;
}
.box.large {
width: 100%;
}
.odd {
margin-left: 0;
}
.even {
margin-right: 0;
}
/* ---------------------------------------------------------------------------
HTML TAGS
---------------------------------------------------------------------------- */
body {
color: #333;
background: #fff;
}
/* ------------------------------------------------------------------ titres */
h1, h2, h3, .as_h3, h4, .as_h4, h5, h6 {
margin-top: 0;
margin-bottom: 1em;
}
h2 {
color: #676e78;
font-size: 1.5em;
padding: 0 0 1.5em;
font-weight: normal;
line-height: 1.25;
}
/* fil d'ariane */
#content > h2 {
padding: 0 1em .5em 1em;
margin: 0 -1em 1em -1em;
background: #fff url(bg_h2.png) repeat-x center bottom;
}
h2 a:link, h2 a:visited {
color: #676e78;
border-color: #000;
}
/* page courante dans le fil d'ariane */
.page-title {
color: #d30e60;
}
.page-title img {
padding-left: .5em;
vertical-align: middle;
}
/* autres titres */
h3, .as_h3 {
margin-top: 1em;
color: #D33800;
font-weight: normal;
font-size: 1.34em;
}
#main-menu h3 {
font-weight: bold;
}
h4, .as_h4 {
font-size: 1.16em;
color: #676e78;
}
.fieldset h3, .fieldset h4, .pretty-title {
color: #D33800;
font-size: 1em;
font-weight: bold;
}
.fieldset h3 {
font-size: 1.17em;
}
.fieldset h3.smart-title, .fieldset h4.smart-title, .smart-title {
font-size: 1em;
text-transform: uppercase;
font-weight: bold;
color: #333;
text-shadow: 0 1px 0 rgba(200, 200, 200, 0.6)
}
h5 {
font-size: 1em;
font-weight: bold;
color: #676e78;
}
#entry-sidebar h5 {
font-weight: normal;
color: #333;
}
.entry-status img.img_select_option {
padding-left: 4px;
vertical-align: text-top;
}
h4 label, h5 label {
color: #333;
}
h2:first-child, h3:first-child, h4:first-child, h5:first-child, ul:first-child, p:first-child {
margin-top: 0;
}
/* ---------------------------------------------------------------- tableaux */
/* Pour autoriser le scroll sur les petites largeurs
envelopper les tableaux dans une div.table-outer */
.table-outer {
width: 100%;
overflow: auto;
}
table {
font-size: 1em;
border-collapse: collapse;
margin: 0 0 1em 0;
width: 100%;
}
caption {
color: #333;
font-weight: bold;
text-align: left;
margin-bottom: .5em;
}
th {
border-width: 1px 0 1px 0;
border-style: solid;
border-color: #dfdfdf;
background: #eef1ec;
padding: .4em 1em .4em .5em;
vertical-align: top;
text-align: left;
}
td {
border-width: 0 0 1px 0;
border-style: solid;
border-color: #e3e3e3;
padding: .4em 1em .4em .5em;
vertical-align: top;
}
/* ---------------------------------------------------------- autres balises */
p {
margin: 0 0 1em 0;
}
hr {
height: 1px;
border-width: 1px 0 0;
border-color: #dfdfdf;
background: #dfdfdf;
border-style: solid;
}
hr.clearer {
clear: both;
}
pre, code, #debug {
font: 100% "Andale Mono","Courier New",monospace;
}
code {
background: #fefacd;
}
pre {
white-space: pre;
white-space: -moz-pre-wrap;
white-space: pre-wrap;
white-space: pre-line;
word-wrap: break-word;
}
abbr {
cursor: help;
}
input, textarea, select, option, optgroup, legend,label {
font-size: 1em;
}
/* ------------------------------------------------------------------ liens */
a, a:link, a:visited {
color: #2373A8;
text-decoration: none;
border-bottom: 1px dotted #999;
background-color: inherit;
outline: 0;
}
a:hover, a:active {
border-bottom-style: solid;
}
a img, a:link img, a:visited img {
border: none;
background: inherit;
}
h1 a:link, h1 a:visited {
border: none;
}
.discrete a {
color: #333;
}
a:link {
transition: .5s;
}
a:focus, a:focus img {
outline: 2px solid #bee74b;
border-bottom: none;
text-decoration: none;
}
/* ----------------------------------------------------------------------------
FORMULAIRES
---------------------------------------------------------------------------- */
input[type=text], input[type=password], input[type=submit],
input[type=button], input[type=reset], a.button, button, textarea, select, legend {
border-radius: 3px;
max-width: 100%;
}
form {
display: block;
margin: 0;
padding: 0;
}
fieldset {
display: block;
margin: 1em 0;
padding: 1em 0.5em;
border-width: 1px 0;
border-style: solid;
border-color: #ccc;
background: #f7f7f7;
}
input[type=text], textarea {
font: 100% "DejaVu Sans","Lucida Grande","Lucida Sans Unicode",Arial,sans-serif;
}
legend {
padding: 0.2em 0.6em;
border-width: 1px;
border-style: solid;
border-color: #676e78;
background: #fff;
margin-bottom: 0.5em;
}
label .maximal, textarea.maximal, input.maximal, select.maximal {
width: 99%;
}
input[type=text], input[type=password], textarea, select {
background: #fcfcfc;
color: #000;
border-width: 1px;
border-style: solid;
border-color: #dfdfdf;
box-shadow: 1px 1px 2px #f3f3f3 inset;
padding: 3px;
vertical-align: top;
}
input:focus, textarea:focus, select:focus {
border-color: #9bca1c;
}
textarea {
padding: 2px 0;
}
textarea.maximal {
resize: vertical;
}
.area textarea {
display: block;
width: 100%;
resize: vertical;
}
select {
padding: 2px 0;
vertical-align: middle;
}
select.l10n option {
padding-left: 16px;
}
option.avail10n {
background: transparent url(../images/check-on.png) no-repeat 0 50%;
}
option.sub-option1 {
margin-left: .5em;
}
option.sub-option2 {
margin-left: 1.5em;
}
option.sub-option3 {
margin-left: 2.5em;
}
option.sub-option4 {
margin-left: 3.5em;
}
option.sub-option5 {
margin-left: 4.5em;
}
option.sub-option6 {
margin-left: 5.5em;
}
option.sub-option7 {
margin-left: 6.5em;
}
option.sub-option8 {
margin-left: 7.5em;
}
option.sub-option1:before, option.sub-option2:before, option.sub-option3:before, option.sub-option4:before,
option.sub-option5:before, option.sub-option6:before, option.sub-option7:before, option.sub-option8:before {
content: "\002022\0000a0";
}
input.invalid, textarea.invalid, select.invalid {
border: 1px solid red;
background: #FFBABA;
color: #900;
box-shadow: 0 0 0 3px rgba(218, 62, 90, 0.3);
}
input[type=text], input[type=password], textarea {
margin-right: .3em;
}
input[type=checkbox], input[type=radio], input[type=file] {
border: none;
margin: 0 .33em 0 0;
padding: 0;
background: transparent;
}
input[type=file] {
margin-top: .3em;
margin-bottom: .3em;
}
optgroup {
font-weight: bold;
font-style: normal;
}
option {
font-weight: normal;
}
label, label span {
display: block;
}
label.ib, input.ib {
display: inline-block;
}
label.classic {
display: inline;
}
label.classic input, label span input, label.classic select, label span select {
display: inline;
}
label.required {
font-weight: bold;
}
label.required abbr {
color: #900;
font-size: 1.3em;
}
label.bold {
text-transform: uppercase;
font-weight: bold;
margin-top: 2em;
}
label.area, p.area {
width: inherit !important;
}
p.field {
position: relative;
}
p.field label {
display: inline-block;
width: 14em;
}
p.field.wide label {
width: 21em;
}
p.field input, p.field select {
display: inline-block;
}
.form-note {
font-style: italic;
font-weight: normal;
color: #676e78;
}
p.form-note {
margin-top: -.7em;
}
span.form-note {
text-transform: none;
}
/* ----------------------------------------------------------------------------
BOUTONS
---------------------------------------------------------------------------- */
/* Removes inner padding and border in FF3+ - Knacss */
button::-moz-focus-inner,
input[type=button]::-moz-focus-inner,
input[type=reset]::-moz-focus-inner,
input[type=submit]::-moz-focus-inner {
border: 0;
padding: 0;
}
/* tous les boutons */
button,
a.button,
input[type=button],
input[type=reset],
input[type=submit] {
border: 1px solid #ccc;
font-family: "DejaVu Sans","Lucida Grande","Lucida Sans Unicode",Arial,sans-serif;
padding: 3px 10px;
line-height: normal !important;
display: inline-block;
font-size: 100%;
text-align: center;
text-decoration: none;
cursor: pointer;
position: relative;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
border-style: solid;
border-width: 1px;
}
button,
input[type=button],
input[type=reset],
input[type=submit] {
-webkit-appearance: button;
}
/* validation */
input[type=submit], a.button.submit, input.button.start {
color: #fff;
background-color: #25A6E1;
background-image: -webkit-gradient(linear,left top,left bottom, from(#25A6E1), to(#188BC0));
background-image: linear-gradient(#25A6E1,#188BC0);
border-color: #25A6E1;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
}
input[type=submit]:hover, input[type=submit]:focus,
input.button.start:hover, input.button.start:focus,
a.button.submit:hover, a.button.submit:focus {
background-color: #188BC0;
background-image: -webkit-gradient(linear,left top,left bottom, from(#188BC0),to(#25A6E1));
background-image: linear-gradient(#188BC0,#25A6E1);
border-color: #188BC0;
}
/* suppression, reset, "neutres" fond gris */
button, input[type=button], input.button,
input[type=reset], input[type=submit].reset, input.reset,
input[type=submit].delete, input.delete,
a.button, a.button.delete, a.button.reset {
color: #000;
background-color: #EAEAEA;
background-image: -webkit-gradient(linear, left top, left bottom, from(#f9f9f9), to(#EAEAEA));
background-image: linear-gradient(#f9f9f9,#EAEAEA);
background-repeat: repeat-x;
border-color: #dfdfdf #dfdfdf #C5C5C5;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.9);
}
button:hover, input[type=button]:hover, input.button:hover,
button:focus, input[type=button]:focus, input.button:focus,
input[type=reset]:hover, input[type=submit].reset:hover, input.reset:hover,
input[type=reset]:focus, input[type=submit].reset:focus, input.reset:focus,
input[type=submit].delete:hover, input.delete:hover,
input[type=submit].delete:focus, input.delete:focus,
a.button.delete:hover, a.button.reset:hover, a.button:hover,
a.button.delete:focus, a.button.reset:focus, a.button:focus {
background-color: #DADADA;
background-image: -webkit-gradient( linear, left top, left bottom, from(#EAEAEA), to(#DADADA));
background-image: linear-gradient(#EAEAEA, #DADADA);
background-repeat: repeat-x;
border-color: #CCCCCC #CCCCCC #B5B5B5;
}
/* suppression */
input[type=submit].delete, input.delete, a.button.delete {
color: #900;
}
input[type=submit].delete:hover, input.delete:hover, a.button.delete:hover,
input[type=submit].delete:focus, input.delete:focus, a.button.delete:focus {
color: #FFFFFF;
background-color: #B33630;
background-image: -webkit-gradient( linear, left top, left bottom, from(#DC5F59), to(#B33630));
background-image: linear-gradient(#DC5F59, #B33630);
background-repeat: repeat-x;
border-color: #CD504A;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.3);
}
#info-box a.button {
padding: 0 .5em;
margin-left: 2em;
}
.button.add {
color: #000;
background-color: #bee74b;
background-image: -webkit-gradient(linear, left top, left bottom, from(#bee74b), to(#9BCA1C));
background-image: linear-gradient(#bee74b, #9BCA1C);
border-color: #bee74b;
padding: .33em 1.33em .5em;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.6);
font-weight: normal;
font-size: 1.16em;
}
.button.add:hover, .button.add:active, .button.add:focus {
background-color: #9BCA1C;
background-image: -webkit-gradient(linear, left top, left bottom, from(#9BCA1C), to(#bee74b));
background-image: linear-gradient(#9BCA1C, #bee74b);
border-color: #9BCA1C;
}
.button-add:focus {
outline: dotted 1px;
}
/* paragraphe pour bouton Nouveau bidule */
p.top-add {
text-align: right;
margin: 0;
}
/* disabled */
input.disabled, input[type=submit].disabled {
text-shadow: none;
color: #676e78;
background: #F5F5F5;
border: 1px solid #CCC;
}
input.disabled:hover, input[type=submit].disabled:hover {
color: #676e78;
background: #eee;
border: 1px solid #CCC;
}
/* ----------------------------------------------------------------------------
MESSAGES
---------------------------------------------------------------------------- */
.warn, .warning, .info {
font-style: normal;
padding: .2em .66em .2em;
text-indent: 24px;
color: #333;
display: inline-block;
line-height: 1.5em;
border-radius: 3px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.6)
}
div.warn, div.warning, div.info {
display: block;
padding: 1em 1em .33em 1em;
margin-bottom: 1em;
}
.warn, .warning {
background: #FEFACD url(msg-warning.png) no-repeat .3em .3em;
border: 1px solid #ffd478;
}
.info {
background: #D9EDF7 url(msg-info.png) no-repeat .3em .3em;
border: 1px solid #BCE8F1;
}
span.warn, span.warning, span.info {
padding-top: 1px;
padding-bottom: 1px;
background-position: .3em .2em;
}
.error, .message, .static-msg, .success, .warning-msg {
padding: 1em 0.5em 0.5em 48px;
margin-bottom: 1em;
border-radius: 8px;
box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}
p.error, p.message, p.static-msg, p.success, p.warning-msg {
padding-top: 1em;
padding-bottom: 1em;
margin-top: .5em;
}
.error {
background: #FFBABA url(msg-error.png) no-repeat .7em .7em;
color: #000;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.6);
}
.message, .static-msg {
background: #676e78 url(msg-std.png) no-repeat .7em .7em;
color: #fff;
}
.message a, .static-msg a, .message h3, .static-msg h3 {
color: #fff;
}
.success, .warning-msg {
color: #000;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.6)
}
.success {
background: #9bca1c url(msg-success.png) no-repeat .7em .7em;
}
.warning-msg {
background: #ffd478 url(msg-warning.png) no-repeat .7em .7em;
border: 1px solid #ffd478;
}
.success a, .warning-msg a, .info a {
color: #333;
}
.dc-update {
padding: 1em 48px 0.5em 48px;
margin-bottom: 1em;
border-radius: 8px;
background: #A2CBE9 url(msg-success.png) no-repeat .7em .7em;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.6);
color: #000;
box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1)
}
.dc-update h3 {
margin-top: 0;
color: #000;
}
.dc-update p {
display: inline-block;
vertical-align: middle;
}
.dc-update a {
color: #000;
margin-right: 1em;
}
.dc-update a.button {
padding: .5em 1em;
}
.updt-info a {
margin-left: 2em;
border-color: #000;
font-weight: bold;
}
/* ---------------------------------------------------------------------------------
ELEMENTS PRINCIPAUX
--------------------------------------------------------------------------------- */
/* -------------------------------------------------------------- HEADER ELEMENTS */
/* prelude */
#prelude {
line-height: 1.5;
margin: 0;
padding: 0;
overflow: hidden;
position: absolute;
top: 3em;
left: 0;
background: #A2CBE9;
width: 100%;
z-index: 100;
}
#prelude li {
list-style-type: none;
margin: 0;
background: transparent;
display: inline;
}
#prelude li a {
padding: 3px 16px 3px 8px;
background: #A2CBE9;
color: #000;
text-decoration: underline;
}
#prelude li a:hover, #prelude li a:focus {
background: #FFF;
}
/* si le prélude est affiché on repousse les trucs dessous */
#wrapper.with-prelude {
padding-top: 1em;
}
#help-button.with-prelude, #collapser.with-prelude {
top: 1em;
}
/* header global h1, form#top-info-blog, ul#top-info-user */
#header a {
color: #FFF;
}
#header img {
vertical-align: middle;
padding-left: .5em;
}
h1, #top-info-blog, #top-info-user {
display: table-cell;
padding: 8px 0;
margin: 0;
font-size: 1em;
vertical-align: top;
}
/* h1 */
h1 {
text-indent: 100%;
width: 16.5em;
}
h1 a {
position: absolute;
top: 0;
left: 0;
width: 150px;
height: 3em;
color: #fff;
background: transparent url(dc_logos/b-dotclear120.png) no-repeat 0 6px;
transition: none;
}
h1 a:hover, h1 a:focus {
background-position: 0 -94px;
background-color: transparent;
transition: none;
}
/* top-info-blog */
#top-info-blog select {
max-width: 20em;
}
#top-info-blog a {
margin-left: 1.5em;
}
#top-info-blog input[type=submit] {
background: #000;
border-color: #999;
margin-left: .33em;
}
#top-info-blog input[type=submit]:hover {
background: #999;
}
#top-info-blog p {
display: inline-block;
margin: 0;
}
/* top-info-user */
#top-info-user {
padding-right: 18px;
list-style-type: none;
text-align: right;
}
#top-info-user li {
display: inline-block;
margin-left: .5em;
padding-left: .5em;
border-left: 1px solid #999;
}
#top-info-user li:first-child {
border-left: none;
}
#top-info-user a.active {
border-bottom-color: #fff;
margin: 0;
padding: 18px .5em;
background-color: #fff;
color: #333;
font-weight: bold;
}
/* ---------------------------------------------------------- MAIN-MENU ELEMENTS */
#favorites-menu, #blog-menu, #system-menu, #plugins-menu {
border-bottom: 1px dashed #A2CBE9;
}
#main-menu h3 {
margin: 0;
padding: 10px 0 10px 8px;
color: #676e78;
font-size: 1.15em;
}
#favorites-menu h3 {
color: #000;
font-variant: small-caps;
padding-top: .2em;
}
#main-menu a {
color: #333;
border-bottom-color: #ccc;
}
#main-menu ul {
margin: 0 0 1.5em 0;
padding: 0;
list-style: none;
}
#main-menu li {
display: block;
margin: 0.5em 0 0;
padding: 4px 0 1px 32px;
background-repeat: no-repeat;
background-position: 8px .3em;
}
#main-menu ul li:first-child {
margin-top: 0;
}
#main-menu li.active {
background-color: #fff;
font-weight: bold;
}
#favorites-menu li.active {
background-color: transparent;
}
#main-menu .active a {
border-bottom: none;
color: #d30e60;
}
#favorites-menu .active a {
color: #000;
}
#search-menu {
padding: 4px 5px 0;
font-size: 100%
}
#search-menu * {
height: 2em;
display: inline-block;
vertical-align: top;
line-height: 24px;
}
#search-menu p {
border: 1px solid #999;
border-radius: .3em;
position: relative;
width: 95%;
overflow: hidden;
}
#qx {
width: 80%;
border-bottom-left-radius: .3em;
border-top-left-radius: .3em;
background: transparent url(search.png) no-repeat 4px center;
text-indent: 18px;
padding: 0;
border: none;
height: 2em;
}
#qx:focus {
border: 1px solid #bee74b;
}
#search-menu input[type="submit"] {
padding: 0 .25em;
margin-left: .33em;
background: #dfdfdf;
border-color: #999;
color: #333;
border-bottom-right-radius: .3em;
border-top-right-radius: .3em;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
text-shadow: none;
border: none;
border-left: 1px solid #999;
font-size: .91em;
float: right;
}
#search-menu input[type="submit"]:hover,
#search-menu input[type="submit"]:focus {
background: #676e78;
color: #fff;
}
/* ----------------------------------------------------------------- CONTENT ELEMENTS */
.part-tabs ul {
padding: .5em 0 0 1em;
border-bottom: 1px solid #ccc;
line-height: 1.8;
}
.part-tabs li {
list-style: none;
margin: 0;
display: inline;
}
.part-tabs li:first-child a {
border-top-left-radius: 3px;
}
.part-tabs li:last-child a {
border-top-right-radius: 3px;
}
.part-tabs li a {
padding: .33em 1.5em;
margin-right: -1px;
border: 1px solid #ccc;
border-bottom: none;
text-decoration: none;
color: #333;
background-color: #ecf0f1;
display: inline-block;
}
.part-tabs li a:hover, .part-tabs li a:focus {
color: #000;
background: #fff;
border-bottom-color: #fff;
}
.part-tabs li.part-tabs-active a {
background: #fff;
font-weight: bold;
border-bottom-color: #fff;
}
.multi-part {
padding-left: 1em;
}
.pseudo-tabs {
margin: -.75em 0 2em 0;
border-bottom: 1px solid #bbb;
display: table;
width: 100%;
padding: 0;
line-height: 24px;
border-collapse: collapse;
}
.pseudo-tabs li {
display: table-cell;
border-width: 0 1px;
border-style: solid;
border-color: #ccc;
padding: 0;
margin: 0;
text-align: center;
}
.pseudo-tabs a {
display: block;
font-weight: bold;
padding: 0 24px;
border-bottom: none;
}
.pseudo-tabs a:hover, .pseudo-tabs a:focus {
background-color: #ecf0f1;
color: #333;
}
.pseudo-tabs a.active {
background-color: #ecf0f1;
color: #d30e60;
}
/* contextual help */
#help {
margin-top: 4em;
background: #f5f5f5;
z-index: 100;
clear: both;
padding: 0 1em;
}
#content.with-help #help {
display: block;
position: absolute;
top: 0;
right: 0;
width: 24em;
border-left: 2px solid #FFD478;
border-top: 2px solid #FFD478;
margin-top: 0;
padding: .5em 0 0 0;
overflow: auto;
}
#help-button {
background: transparent url(help-mini.png) no-repeat 6px center;
position: absolute;
top: 0;
right: 0;
padding: 0 1.5em 0 30px;
cursor: pointer;
color: #2373A8;
line-height: 3;
}
#help-button.floatable {
border-top: 2px solid #ccc;
border-left: 2px solid #ccc;
border-bottom: 2px solid #ccc;
border-bottom-left-radius: 1em;
border-top-left-radius: 1em;
background-color: #f5f5f5;
position: fixed;
top: 10px;
-webkit-transform:translateZ(0); /* Let GPU doing his job */
}
.no-js #help-button {
top: 1em;
}
#help-button span {
padding: .5em 0 .1em 0;
}
#content.with-help #help-button {
right: 24em;
background-color: #f5f5f5;
position: fixed;
top: 50px;
z-index: 100;
border-top: 2px solid #FFD478;
border-left: 2px solid #FFD478;
border-bottom: 2px solid #FFD478;
border-bottom-left-radius: 1em;
border-top-left-radius: 1em;
}
.help-box {
display: none;
}
.help-box ul {
padding-left: 20px;
margin-left: 0;
}
#content.with-help .help-content {
padding: 0 1em 1em;
}
.help-content dt {
font-weight: bold;
color: #676e78;
margin: 0;
}
.help-content dd {
margin: 0.3em 0 1.5em 0;
}
/* lien d'aide générale dans le help content */
#helplink p {
padding: 0 0 0 .5em;
}
/* ------------------------------------------------------------------ FOOTER ELEMENTS */
#footer p {
margin: 0;
padding: 0 1em;
font-size: 1em;
}
span.credit {
font-size: 1em;
font-weight: normal;
}
span.tooltip {
position: absolute;
padding: 0;
border: 0;
height: 1px;
width: 1px;
overflow: hidden;
}
#footer a:hover span.tooltip {
padding: 10px 10px 0 40px;
color: #d30e60;
height: auto;
width: auto;
right: 0;
bottom: 0;
background: #FFF;
z-index: 99;
font-family: monospace;
border: none;
text-align: left;
}
/* ---------------------------------------------------------------------------------------
RÈGLES SPÉCIFIQUES
---------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------- LISTES TABLEAUX */
table .maximal, table.maximal {
width: 100%;
}
table .minimal {
width: 1px;
}
table .nowrap {
white-space: nowrap;
vertical-align: top;
}
table .count {
text-align: right;
padding-right: 1.5em;
}
th.first input {
padding-right: 34px;
}
.line img {
vertical-align: middle;
}
tr.line img.expand, th img.expand {
margin-right: 6px;
margin-bottom: -2px;
}
tr.line p {
margin: 0;
}
tr.line input[type=text] {
background: #FFF;
}
tr.line input, tr.line select {
vertical-align: middle;
-webkit-box-shadow: none;
box-shadow: none;
}
tr.line select {
width: 6em;
}
tr.line:hover {
background: #f3f3f3;
}
td.status {
vertical-align: middle;
}
td.status img {
margin-bottom: -2px;
}
td.status a {
border: none;
}
.noborder td, td.noborder, .noborder th, th.noborder {
border-width: 0 0 1px 0;
border-color: #dfdfdf;
line-height: 2em;
padding-bottom: 0;
}
.noborder p {
margin-bottom: 0;
}
table.posts-list {
min-width: 50%;
}
table.settings, table.prefs {
margin-bottom: 3em;
}
table.settings th:first-child, table.prefs th:first-child {
width: 20%;
}
table.settings th + th, table.prefs th + th {
width: 30%;
}
table.settings th + th + th, table.prefs th + th + th {
width: 10%;
}
table.settings th:last-child, table.prefs th:last-child {
width: 40%;
}
/* js */
td.expand {
padding: 1em;
}
tr.expand td {
border-bottom: none;
}
.handle {
padding: 0;
}
.handler {
cursor: move;
background: transparent url(drag.png) no-repeat 0 50%;
padding-left: 15px;
}
/* ----------------------------------------------------------- BOITES À FILTRES */
a.form-control {
display: none;
background: url(../images/expand.png) no-repeat 4px center;
padding-left: 20px;
color: #000;
}
a.form-control.open {
background: url(../images/hide.png) no-repeat 4px center;
}
#filters-form {
border: 1px dashed #999;
border-radius: .3em;
margin-bottom: 2em;
padding: .5em 1em 0;
}
#filters-form .table {
width: 100%;
padding: 0;
margin-bottom: 1em;
margin-top: .5em;
}
#filters-form .cell {
padding: 0 2em 0 0;
}
#filters-form .filters-sibling-cell {
padding-top: 3.8em;
}
#filters-form .filters-options {
padding-left: 2em;
border-left: 1px solid #ccc;
}
#filters-form label.ib, span.ib {
width: 7em;
}
#filters-form label.ibw, span.ibw {
width: 9em;
display: inline-block;
}
#filters-form select {
width: 14em;
vertical-align: middle;
}
#filters-form h4 {
margin-top: 0;
margin-bottom: 2em;
}
/* ---------------------------------------------------------------------------- SPEC PAGES */
/* ---------------------------------------------------------------------------- auth.php */
#login-screen {
display: block;
width: 20em;
margin: 1.5em auto 0;
font-size: 1.16em;
}
#login-screen h1 {
text-indent: -2000px;
background: transparent url(dc_logos/w-dotclear240.png) no-repeat top left;
height: 66px;
width: 20em;
margin-bottom: .5em;
margin-left: 0;
}
#login-screen .fieldset {
border: 1px solid #9bca1c;
padding: 1em 1em 0 1em;
background: #fff;
margin-bottom: 0;
margin-top: 1em;
}
#login-screen input[type=text], #login-screen input[type=password], #login-screen input[type=submit],
#login-screen input[type=text]:focus, #login-screen input[type=password]:focus, #login-screen input[type=submit]:focus {
width: 100%;
margin: 0;
padding: 5px 3px;
}
#login-screen input.login, #login-screen input.login:focus {
padding-top: 6px;
padding-bottom: 6px;
font-size: 1em;
}
#login-screen #issue {
margin-left: 1.33em;
font-size: .91em;
}
#issue p:first-child {
text-align: right;
}
#login-screen #issue strong {
font-weight: normal;
}
/* ------------------------------------------------------------------------- index.php */
#dashboard-main {
padding: 1em;
text-align: center;
}
/* raccourcis */
#icons {
overflow: hidden;
padding-bottom: 1em;
text-align: center;
}
#icons p {
width: 14em;
text-align: center;
margin: 1em 0 2em;
padding: 1em 0;
display: inline-block;
vertical-align: top;
}
#icons a,
#icons a:link,
#icons a:visited,
#icons a:hover,
#icons a:focus {
border-bottom-width: 0;
text-decoration: none;
}
#icons a span {
border-bottom: 1px dotted #999;
color: #333;
}
#icons a img {
padding: 1.5em;
background-color: #f9f9f9;
border-radius: 8px;
border: 1px solid #dadada;
display: inline-block;
}
#icons a:focus img, #icons a:hover img {
background: #bee74b;
outline: 0;
border-color: #dadada;
}
#icons a:focus {
outline: 0;
border-color: #fff;
}
#icons a:hover span, #icons a:focus span {
border-bottom-style: solid;
}
#icons a:focus span {
border: 2px solid #bee74b;
}
/* billet rapide */
#quick {
padding: 1em;
max-width: 976px;
margin: 0 auto;
background: #f5f5f5;
box-shadow: 0 1px 2px rgba(0, 0, 0, .2);
text-align: left;
}
#quick h3 {
margin-bottom: 0.2em;
font-size: 1.2em;
}
#quick p.qinfo {
margin: -.7em -1em 1em;
background: #D9EDF7 url(info.png) no-repeat .2em .2em;
border: 1px solid #BCE8F1;
padding: .2em 1em .1em 24px;
color: #000;
}
#quick #new_cat, .q-cat, .q-cat label {
display: inline-block;
vertical-align: top;
margin-right: 1em;
margin-top: 0;
}
.q-cat label {
margin-right: .3em;
}
#quick #new_cat {
margin-bottom: 2em;
}
/* modules additionnels */
#dashboard-boxes {
margin: 1em auto 1em;
padding-top: 2em;
}
.db-items, .db-contents {
display: inline-block;
text-align: center;
}
.no-js .outgoing img {
display: none;
}
#dashboard-boxes .box {
padding: 10px;
border: 1px solid #ccc;
border-radius: 3px;
min-height: 200px;
margin: 10px;
text-align: left;
}
.dc-box {
background: transparent url(dc_logos/sq-logo-32.png) no-repeat top right;
}
.db-items img, .db-contents img {
vertical-align: middle;
}
.db-items ul, .db-contents ul {
display: block;
padding-left: 1.5em;
list-style: square;
}
.db-items li, .db-contents li {
margin: 0.25em 0 0 0;
}
#news dt {
font-weight: bold;
margin: 0 0 0.4em 0;
}
#news dd {
margin: 0 0 1em 0;
}
#news dd p {
margin: 0.2em 0 0 0;
}
/* message de mise à jour */
#upg-notify ul {
padding-left: 1.5em;
}
#upg-notify li {
color: #fff;
}
/* ------------------------------------------------------------------- blog_pref.php */
#media_img_title_pattern {
margin-right: 1em;
}
.user-perm {
margin: 2em 0px;
background: transparent url(user.png) no-repeat left top;
width: 320px;
display: inline-block;
vertical-align: top;
}
.user-perm h4, .user-perm h5, .user-perm p, .user-perm ul, .user-perm li {
margin: .5em 0 .33em;
padding: 0;
}
.user-perm h4 {
padding-left: 28px;
}
.user-perm h5 {
margin: 1em 0 0 0;
}
.user-perm ul {
list-style-type: inside;
}
.user-perm li {
margin-left: 1em;
padding-left: 0;
}
li.user_super, li.user_admin {
margin-left: 0;
padding-left: 20px;
list-style: none;
background: transparent url(../images/superadmin.png) no-repeat 0 .3em;
}
li.user_admin {
background-image: url(../images/admin.png);
}
/* ------------------------------------------------------------------- blog_theme.php */
/* pour les alignements verticaux */
#theme-new, #theme-activate, #theme-deactivate, #theme-update {
margin-left: -10px;
margin-right: -10px;
}
.box.theme {
margin: 5px;
padding: 10px 10px 5px 10px;
border: 1px solid #dfdfdf;
position: relative;
}
.box.theme:hover {
background: #ecf0f1 url(texture.png);
}
.module-name, .module-name label {
margin-bottom: .5em;
color: #676e78;
}
.module-sshot {
text-align: center;
}
.module-sshot img {
padding: 5px;
background: #f7f7f7;
box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
border: 3px solid #fff;
max-width: 100%;
}
.module-actions {
margin-top: 1em;
}
.bloc-toggler {
text-align: right;
}
.bloc-toggler img {
opacity: .4;
}
.bloc-toggler img:hover {
opacity: 1;
}
.bloc-toggler a:focus img {
opacity: 1;
}
span.module-version:before {
content: "- ";
}
.toggle-bloc .mod-more {
display: block;
margin-left: 0;
}
.box.theme input {
margin-bottom: 1em;
}
.module-name input[type="checkbox"] {
margin-bottom: 0;
}
/**
Les screenshots des thèmes ont deux tailles possibles :
- dans Ajouter des thèmes : 240px (+ 10 padding image + 20 padding boîte + 6 bordure + 2 ombrage = 278)
- dans Thèmes installés : 280px (+ 10 padding-image + 20 padding-boîte + 2 ombrage = 318)
On adapte largeur et hauteur en fonction
*/
#theme-new .box.theme, #theme-update .box.theme { /* Ajouter un thème */
width: 278px;
min-height: 275px;
}
#theme-new .module-sshot img { /* Pour ceux qui n'ont pas de miniature on contraint l'image */
max-width: 240px;
max-height: 210px;
overflow: hidden;
}
#theme-deactivate .box.theme { /* Thèmes désactivés */
width: 278px;
}
#theme-activate .box.theme { /* Thèmes installés */
width: 318px;
min-height: 304px;
max-width: 100%;
}
#theme-deactivate .box.theme:hover {
background: transparent url(dc_logos/sq-logo-32.png) no-repeat top right;
}
/* si js est là, les infos viennent par dessus le screenshot */
.with-js #theme-new .module-infos.toggle-bloc,
.with-js #theme-new .module-actions.toggle-bloc {
position: absolute;
left: 10px;
width: 239px;
margin: 0;
padding: 10px;
background: rgba(250, 250, 250, .95);
}
.with-js #theme-new .module-infos.toggle-bloc {
top: 128px;
height: 80px;
border-top: 1px solid #e3e3e3;
}
.with-js #theme-new .module-actions.toggle-bloc {
top: 208px;
height: 40px;
border-bottom: 1px solid #e3e3e3;
}
.with-js .module-sshot:hover {
cursor: pointer;
}
/* mise en forme pour la boîte du thème courant */
.box.current-theme { /* Thème courant */
width: 646px;
margin: 5px;
padding: 20px 18px 6px;
background: #fff url(texture.png);
border: 1px solid #eee;
border-radius: .5em;
min-height: 326px;
box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
position: relative;
}
.current-theme .module-sshot:hover {
cursor: auto;
}
.current-theme .module-sshot img {
float: left;
margin-right: 2em;
border: 9px solid #fff;
padding: 5px;
max-width: 308px;
max-height: 273px;
}
.current-theme .module-name {
color: #D33800;
font-size: 1.5em;
margin-bottom: 1em;
}
.current-actions {
width: auto;
overflow: hidden;
padding-top: 2em;
margin: 1.5em 0 2em;
background: transparent url(../images/minus-theme.png) no-repeat left top;
}
.current-theme .actions-buttons {
position: absolute;
bottom: 0;
right: 18px;
}
/* ------------------------------------------------------------------ categories.php */
#categories {
margin: 1em 0;
}
#categories ul {
list-style: none;
margin-top: 2em;
padding: 0;
}
.cat-line {
position: relative;
margin: .66em 0;
padding: .66em 1em;
border: 1px solid #ccc;
border-radius: 3px;
}
.cat-line label {
margin-right: .25em;
}
.cat-line label a {
font-weight: bold;
}
.cat-line p, .cat-line label {
margin: 0;
display: inline-block;
}
p.cat-title {
margin-right: 1em;
}
.cat-nb-posts a {
color: #333;
}
.cat-url {
padding-left: 1em;
}
#categories .placeholder {
outline: 1px dashed #4183C4;
min-height: 2.5em;
}
.cat-buttons {
float: right;
margin-top: -.2em;
font-size: .91em;
}
.cat-buttons select {
padding: 1px 2px 3px 2px;
margin-right: .25em;
}
.cat-buttons .reset {
padding-left: 4px;
padding-right: 4px;
}
#categories ul ul {
margin-right: 2em;
margin-left: 2em;
}
.cat-line .cat-line {
border: 1px solid #dfdfdf;
}
.cat-actions {
line-height: 2;
}
#del_cat {
width: 100%;
}
/* ------------------------------------------------------------------ media.php */
.media-item {
position: relative;
border: 1px solid #dfdfdf;
margin: 9px;
padding: 10px 12px 6px;
width: 320px;
display: inline-block;
vertical-align: top;
min-height: 140px;
word-wrap: break-word;
}
.media-item p {
margin: 0 0 .5em;
}
.media-item object {
margin-top: .5em;
}
.media-item ul {
display: block;
list-style: none;
margin: 0;
padding: 0;
}
a.media-icon {
display: block;
border-bottom: none;
margin: 0 auto;
}
.media-icon img {
display: block;
}
.media-link {
font-size: 1.1em;
}
.media-action-box {
position: relative;
margin: 3em 3em 1em 1em;
display: inline-block;
vertical-align: top;
}
li.media-action {
display: block;
position: absolute;
bottom: 4px;
right: 8px;
height: 16px;
}
li.media-action a {
border: none;
}
li.media-action a.attach-media {
margin-right: 5px;
}
li.media-action form {
display: inline;
}
li.media-action input {
border: none;
}
#entry-sidebar .media-item {
width: 100%;
min-height: 0;
padding: 4px;
margin: .33em 0;
}
#entry-sidebar li.media-action {
top: 4px;
}
.folders-group .media-item {
min-height: 70px;
}
.folders-group .media-item p {
margin-bottom: 0;
}
.media-folder {
background: transparent url(bg_menu.png) repeat-y;
border-color: #eee;
}
.media-folder-up {
border-color: #fff;
padding-bottom: 6px;
}
.media-folder .media-link {
font-size: 1.25em;
margin-left: 2em;
color: #676e78;
border-bottom: none;
}
.medias-delete {
text-align: right;
}
/* upload multiple */
.enhanced_uploader .choose_files, .enhanced_uploader .cancel,
.enhanced_uploader .clean, .enhanced_uploader .start {
margin-right: .4em;
}
.enhanced_uploader #upfile {
visibility: hidden;
width: 0;
height: 0;
margin: 0;
opacity: 0;
filter: alpha(opacity=0);
cursor: pointer;
}
.button.clean, .button.cancel, .button.choose_files {
display: none;
}
.enhanced_uploader .button.choose_files {
display: inline-block;
}
.enhanced_uploader .max-size {
display: block;
}
.enhanced_uploader .one-file {
display: none;
}
label span.one-file {
display: inline;
}
.enhanced_uploader p.clear {
padding-top: 1em;
margin-bottom: 1em;
}
#add-file-f p.clear {
margin-top: 1em;
margin-bottom: 0;
clear: both;
}
.files {
list-style-type: none;
margin-left: 0;
padding-left: 0;
border-bottom: 1px solid #dfdfdf;
}
.files li {
margin-left: 0;
padding-left: 0;
}
.upload-msg {
font-weight: bold;
}
.upload-msg.upload-error {
color: #900;
}
.upload-files {
padding: 0 0.5em;
margin: 1em 0;
}
.upload-file {
margin: 0;
padding: .3em 0;
border-top: 1px solid #dfdfdf;
position: relative;
}
.upload-fileinfo {
margin-left: 0;
}
.upload-fileinfo input {
position: absolute;
top: .5em;
right: .5em;
}
.upload-fileinfo span {
padding-right: 8px;
}
.upload-fileinfo .upload-filecancel {
display: block;
padding-right: 0;
margin-top: 3px;
width: 20px;
height: 20px;
background: transparent url("cancel.png") no-repeat left top;
text-indent: -1000px;
cursor: pointer;
float: left;
}
.upload-filemsg {
font-weight: bold;
color: green;
}
.upload-filemsg.upload-error {
color: #900;
}
.upload-progress {
padding: .3em 0;
}
.upload-progress div {
width: 0;
height: 1.2em;
font-weight: bold;
line-height: 1.2em;
text-align: right;
background: green url(loader.png) repeat-x left top;
color: white;
border-radius: 3px;
}
div.template-upload {
clear: both;
}
.queue-message {
font-weight: bold;
}
/* --------------------------------------------------------------- media-item.php */
#media-icon {
float: left;
}
.near-icon {
margin-left: 70px;
margin-bottom: 3em;
}
#media-details ul {
display: block;
margin-left: 0;
padding: 0;
}
#media-details li {
list-style: square inside;
margin: 0;
padding: 0;
}
#media-original-image {
overflow: auto;
}
#media-original-image.overheight {
height: 500px;
}
/* -------------------------------------------------------------------- plugins.php */
.modules td.module-actions, .modules td.module-icon {
vertical-align: middle;
}
.modules td.module-icon img:last-child {
width: 16px;
height: 16px;
}
.modules td.module-icon img.expand {
margin-bottom: 3px;
}
.modules td.module-distrib img {
display: block;
float: right;
}
.modules dt {
font-weight: bold;
}
.modules a.module-details {
background: transparent url(search.png) no-repeat 2px center;
padding: 4px 4px 0 20px;
}
.modules a.module-support {
background: transparent url(help12.png) no-repeat 2px center;
padding: 4px 4px 0 20px;
}
.modules a.module-config {
background: transparent url(settings.png) no-repeat 2px 6px;
padding: 4px 4px 0 18px;
}
#m_search {
background: transparent url(search.png) no-repeat 4px center;
padding-left: 20px;
}
.modules tr.expand, .modules td.expand {
background: #f7f7f7;
border-color: #bee74b;
}
.modules tr.expand td:first-child {
font-weight: bold;
background: #DFE5E7;
}
.modules td.expand {
padding: 0 0 1em;
border-top: 1px solid #eaeaea;
}
.modules td.expand div {
display: inline-block;
vertical-align: top;
margin-right: 3em;
}
.mod-more, .mod-more li {
margin: .25em 0 0 1em;
padding: 0;
list-style-type: none;
}
.mod-more {
padding-top: .5em;
}
#plugin-update td {
vertical-align: baseline;
}
/* ---------------------------------------------------------- post.php, page.php */
#entry-wrapper {
float: left;
width: 100%;
margin-right: -16em;
}
#entry-content {
margin-right: 18em;
margin-left: 0;
}
#entry-sidebar {
width: 16em;
float: right;
}
#entry-sidebar h4 {
font-size: 1.08em;
margin-top: .3em;
}
#entry-sidebar select {
width: 100%;
}
#entry-sidebar input#post_position {
width: 4em;
}
.sb-box {
border-bottom: 1px solid #dfdfdf;
margin-bottom: 1em;
}
#tb_excerpt {
width: 100%;
}
/* ---------------------------------------------------------- preferences.php */
.fav-list {
list-style-type: none;
margin-left: 0;
padding-left: 0;
}
#my-favs .fav-list {
border-top: 1px solid #eee;
}
.fav-list li {
margin-left: 0;
padding-left: 0;
padding-top: 3px;
padding-bottom: 3px;
position: relative;
}
#my-favs .fav-list li {
line-height: 2;
border-bottom: 1px solid #eee;
padding-top: 3px;
padding-bottom: 3px;
position: relative;
}
.fav-list img {
vertical-align: middle;
margin-right: .2em;
}
.fav-list li span.zoom {
display: none;
}
.fav-list li:hover span.zoom {
display: block;
position: absolute;
bottom: 0;
left: 10em;
background-color: #f7f7f7;
border: 1px solid #dfdfdf;
padding: .2em;
border-radius: .5em;
}
#my-favs {
border-color: #9bca1c;
}
#my-favs input.position {
margin: 0 0 .4em .2em;
}
#available-favs input, #available-favs label, #available-favs label span {
white-space: normal;
display: inline;
}
#available-favs label span.zoom {
display: none;
}
#available-favs li:hover label span.zoom {
display: block;
position: absolute;
bottom: 0;
left: 10em;
background-color: #f7f7f7;
border: 1px solid #dfdfdf;
padding: .2em;
border-radius: .5em;
}
#user-options label.ib {
display: inline-block;
width: 14em;
padding-right: 1em;
}
/* --------------------------------------------------------------------- user.php */
.blog-perm {
padding-top: 2em;
}
.blog-perm {
margin-top: 2em;
font-weight: bold;
}
.ul-perm {
list-style-type: square;
margin-left: 0;
padding-left: 3.5em;
margin-bottom: 0
}
.add-perm {
padding-top: .5em;
padding-left: 2.5em;
margin-left: 0;
}
/* --------------------------------------------------------------------- _charte.php */
.guideline #content h2 {
color: #D33800;
padding: 2em 0 0 0;
margin: 1em 0;
font-size: 2em;
}
.guideline #content h2:first-child {
margin-top: 0;
padding-top: .5em;
}
.guideline h3 {
margin-top: 2em;
}
.guideline .dc-update h3 {
margin-top: 0;
}
.guideline .one-box .box {
border: 1px solid #dfdfdf;
padding: 2px .5em;
}
.guideline #main-menu ul {
margin: 0;
padding: 0;
font-weight: normal;
}
.guideline #main-menu li {
padding-left: 1em;
}
/* ------------------------------------------------------------------------------------
CLASSES
------------------------------------------------------------------------------------ */
/* jQuery Autocomplete plugin */
.ac_results {
padding: 0px;
border: 1px dotted #f90;
background-color: white;
overflow: hidden;
z-index: 99999;
}
.ac_results ul {
width: 100%;
list-style-position: outside;
list-style: none;
padding: 0;
margin: 0;
}
.ac_results li {
margin: 0px;
padding: 2px 5px;
cursor: default;
display: block;
font-size: 1em;
line-height: 16px;
overflow: hidden;
}
.ac_loading {
background: transparent url('loader.gif') right center no-repeat;
}
.ac_over {
background-color: #2373A8;
color: white;
}
/* password indicator */
.pw-table {
display: table;
margin-bottom: 1em;
}
.pw-cell {
display: table-cell;
margin-bottom: 1em;
}
#pwindicator {
display: table-cell;
vertical-align: bottom;
padding-left: 1.5em;
height: 3.8em;
}
#pwindicator .bar {
height: 6px;
margin-bottom: 4px;
}
.pw-very-weak .bar {
background: #b33630;
width: 30px;
}
.pw-weak .bar {
background: #b33630;
width: 60px;
}
.pw-mediocre .bar {
background: #f90;
width: 90px;
}
.pw-strong .bar {
background: #9bca1c;
width: 120px;
}
.pw-very-strong .bar {
background: #9bca1c;
width: 150px;
}
/* ------------------------------------------------------------------ navigation */
/* selects accès rapide */
.anchor-nav {
background: #ecf0f1;
color: #000;
padding: 4px 1em;
}
.anchor-nav label {
vertical-align: bottom;
}
/* nav links */
.nav_prevnext {
margin-bottom: 2em;
color: #fff;
}
.nav_prevnext a, a.back {
color: #2373A8;
border: 1px solid #dfdfdf;
padding: 2px 1.5em;
border-radius: .75em;
background-color: #f3f3f3;
}
a.back:before {
content: "\ab\a0";
}
a.onblog_link {
color: #333;
float: right;
border: 1px solid #eee;
padding: 2px 1.5em;
border-radius: .75em;
background-color: #ECF0F1;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
}
/* Pagination */
.pager {
margin: 2em 0 1em 0;
clear: left;
}
.pager ul {
list-style-type: none;
margin: 0;
padding: 0;
}
.pager li, .pager input {
display: inline-block;
vertical-align: middle;
margin: 0 .33em 0 0;
padding: 0;
text-align: center;
}
.pager .btn {
border: 1px solid #dfdfdf;
background-color: #fcfcfc;
color: #676e78;
border-radius: 3px;
overflow: hidden;
}
.btn.no-link {
border-color: #dfdfdf;
background-color: #f9f9f9;
padding: 1px 3px 0;
}
.pager .active {
padding: 4px 12px;
color: #676e78;
}
.pager .direct-access {
margin-left: 2em;
}
.direct-access input[type=text] {
border: 1px solid #dfdfdf;
padding: 3px 8px;
margin-left: .25em;
background-color: #fff;
}
.direct-access input[type=submit] {
padding: 3px 6px;
}
.pager a {
display: block;
padding: 1px 3px 0;
border: none;
}
.pager a:hover, .pager a:focus {
background-color: #ecf0f1;
}
.index .btn.no-link, .index a {
padding: 2px 8px 3px;
font-variant: small-caps;
}
.index li {margin-bottom: 3px;}
.index a {
font-weight: bold;
}
.index .btn.no-link {
color: #ccc;
}
.index .active {
padding: 4px 8px;
color: #fff;
background: #676e78;
border-radius: 3px;
font-variant: small-caps;
}
/* Etapes */
.step {
display: inline-block;
float: left;
margin: 3px 10px 2px 0;
padding: 5px .5em;
background: #ecf0f1;
border-radius: 3px;
font-weight: bold;
border: 1px solid #c5c5c5;
color: #676e78;
}
/* ---------------------------------------------------------------- utilisables partout */
.legible {
font-size: 1.16em;
max-width: 62em;
}
.fieldset {
background: #fff;
border: 1px solid #c5c5c5;
border-radius: 3px;
padding: 1em .7em .5em;
margin-bottom: 1em;
}
.fieldset h3 {
margin-top: 0;
}
.right, .txt-right {
text-align: right;
}
.txt-center {
text-align: center;
}
.txt-left {
text-align: left;
}
.no-margin, label.no-margin {
margin-top: 0;
margin-bottom: 0;
}
.vertical-separator {
margin-top: 2em;
}
p.clear.vertical-separator {
padding-top: 2em;
}
.border-top {
border-top: 1px solid #999;
padding-top: 1em;
margin-top: 1em;
}
.grid {
background: transparent repeat url('grid.png') 0 0;
}
ul.nice {
margin: 1em 0;
padding: 0 0 0 2em;
list-style: square;
}
ul.nice li {
margin: 0;
padding: 0;
}
ul.from-left {
list-style-type: none;
padding-left: 0;
margin: 1em 0;
}
ul.from-left > li {
margin-top: 1em;
margin-bottom: 1em;
}
ul.from-left ul {
list-style-type: square;
}
.offline {
color: #676e78;
}
/* caché pour tout le monde */
.hide, .button.hide {
display: none !important;
}
/* Caché sauf pour les revues d'écran */
.hidden, .with-js .out-of-screen-if-js {
position: absolute !important;
clip: rect(1px 1px 1px 1px);
/* IE6, IE7 */
clip: rect(1px, 1px, 1px, 1px);
padding: 0 !important;
border: 0 !important;
height: 1px !important;
width: 1px !important;
overflow: hidden;
}
/* caché si js est inactif */
.no-js .hidden-if-no-js {
display: none;
}
/* caché si js est actif */
.with-js .hidden-if-js {
display: none;
}
/* ------------------------------------------------------------------------------------
UTILS
------------------------------------------------------------------------------------ */
/* debug */
#debug {
position: absolute;
top: 0;
width: 100%;
height: 4px;
background: #ffd478;
}
#debug div {
display: none;
padding: 3px 0.5em 2px;
}
#debug p {
margin: 0.5em 0;
}
#debug:hover {
height: auto;
padding: 2px 1em;
z-index: 100;
}
#debug:hover div {
display: block;
}
.debug {
background: #ffd478;
padding: 3px 0.5em 2px;
}
input[type=submit].delete.debug, a.delete.debug {
border-color: #ffd478;
}
input[type=submit].delete.debug:hover, a.delete.debug:hover {
background: #ffd478;
color: #900;
border-color: #ffd478;
}
/* ---------------------------------------------- Couleurs ajoutées via javascript
/* color-picker.js */
.color-color-picker {
border: 1px solid #000;
width: 195px;
background: #fff;
}
/* _media_item.js */
.color-div {
border: 1px solid #ccc;
}
/* fadings ('color' est utilisé comme variable, pas comme text color) */
.colorBeginPassword,
.colorBeginValidatorErr,
.colorBeginUserMail { color: #fff; }
.colorEndPassword,
.colorEndError,
.colorEndValidatorErr,
.colorEndUserMail { color: #ffbaba; }
.colorBeginMessage { color: #ccc; }
.colorEndMessage,
.colorBeginValidatorMsg { color: #676e78; }
.colorBeginError { color: #fefacd; }
.colorBeginSuccess { color: #9BCA1C; }
.colorEndSuccess { color: #bee74b; }
.colorEndValidatorMsg { color: #ffcc00; }
/* ------------------------------------------------------------------------------------
UN POIL DE MEDIA QUERIES
------------------------------------------------------------------------------------ */
@media screen and (min-width: 80em) {
#wrapper {
background: #F7F7F7 url(bg_wrapper.png) repeat-y 18em;
}
#main {
margin-left: -17em;
}
#content {
margin: 0 0 0 17em;
}
#main-menu {
width: 17em;
}
#collapser {
left: 17em;
}
h1 {
width: 19.5em;
}
}
@media screen and (max-width: 61em) {
#top-info-blog #switchblog {
max-width: 16em;
}
#top-info-blog a {
margin-left: 2em;
}
#header {
display: block;
width: 100%;
text-align: right;
background: #333;
}
#header h1, #header h1 a {
width: 120px;
padding: 0;
margin: 0;
}
h1, #top-info-blog {
display: inline-block;
vertical-align: top;
margin-right: 1em;
}
#top-info-user {
display: block;
width: 100%;
background: #676e78;
padding-right: 0;
}
#top-info-user li:last-child {
padding-right: 1em;
}
#top-info-user a.active {
padding: 2px 8px;
background: #999;
color: #FFF;
border-width: 0;
border-radius: 6px;
}
.three-boxes, .three-boxes .box,
.two-cols .col70, .two-cols .col30 {
width: 100%;
margin-left: 0;
margin-right: 0;
}
}
@media screen and (max-width: 48em) {
#dashboard-boxes .box.medium, .box.medium,
#dashboard-boxes .box.small, .box.small,
#dashboard-boxes .box.large, .box.large {
width: 95%;
margin: 10px auto;
}
}
@media screen and (max-width: 44em) {
#help-button {
height: 26px;
width: 26px;
background-color: #A2CBE9;
padding: 0;
margin: 0;
font-size: .83em;
line-height: 68px;
overflow: hidden;
}
#content.with-help #help-button {
top: 77px;
}
.one-box, .two-boxes, .box,
.two-cols .col {
width: 96%;
margin-left: 0;
margin-right: 0;
}
#entry-wrapper {
float: none;
width: 100%;
margin-right: 0;
}
#entry-content {
margin-right: 0;
margin-left: 0;
}
#entry-sidebar {
width: 100%;
float: none;
}
}
@media screen and (max-width: 38em) {
#header h1, #header h1 a {
width: 42px !important;
height: 42px;
}
h1 a:link {
background: transparent url(dc_logos/b-dotclear120.png) no-repeat -270px 6px;
border-right: 1px solid #ccc;
}
h1 a:hover, h1 a:focus {
background: url(dc_logos/b-dotclear120.png) no-repeat -270px -94px;
border-right: 1px solid #A2CBE9;
}
#wrapper, #main, #main-menu {
display: block;
float: none;
width: 100%;
margin: 0;
}
#dashboard-main {
padding: 0;
}
#main-menu a {
display: block;
width: 100%;
}
#main-menu h3 a {
display: inline;
}
#content, .hide-mm #content {
margin: 0;
padding: 0 .5em !important;
}
#collapser {
display: none;
}
#main #content > h2 {
margin: 0 -.5em 1em;
padding: 6px 30px 4px .5em;
}
#dashboard-boxes .box.medium, .box.medium,
#dashboard-boxes .box.small, .box.small,
#dashboard-boxes .box.large, .box.large {
width: 95%;
margin: 10px auto;
}
.cell, #filters-form .cell {
display: inline-block;
border: none;
padding: 1em;
vertical-align: bottom;
}
.pseudo-tabs li {
display: block;
float: left;
width: 50%;
border-top: 1px solid #ddd;
padding: .25em;
}
.pseudo-tabs li:first-child, .pseudo-tabs li:nth-of-type(2) {
border-top: none;
}
}
@media screen and (max-width: 26.5em) {
h1, h1 a {
padding: 0;
border-right: #333 !important;
}
#top-info-blog label, .nomobile {
display: none;
}
#top-info-blog {
margin-bottom: .5em;
max-width: 75%;
}
#top-info-blog select {
margin-bottom: .5em;
}
#wrapper {
font-size: 1.4em;
}
#content.with-help #help-button {
top: 120px;
right: 20.5em;
}
#content.with-help #help {
font-size: 12px;
}
p.top-add {
margin-bottom: .5em;
text-align: center;
}
.multi-part {
padding-left: 0;
}
.part-tabs ul {
margin: 1em 0;
padding: 0 .5em;
}
.part-tabs li a {
display: block;
width: 100%;
}
#icons p {
width: 9em;
padding: 1em .25em;
}
.media-item {
width: 90%;
}
#theme-new, #theme-activate, #theme-deactivate {
margin-left: 0;
margin-right: 0;
}
.box.current-theme {
margin: 5px;
padding: 10px;
width: 100%;
}
.current-theme .module-sshot img {
margin: 0;
float: none;
max-width: 100%;
}
table .maximal {
min-width: 14em;
}
th, td {
padding: 0.3em 1em 0.3em 0;
}
.pseudo-tabs li {
display: block;
width: 100%;
float: none;
border-top: 1px solid #ddd !important;
}
.pseudo-tabs li:first-child {
border-top: none;
}
}
| Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Poisson Distribution — SciPy v0.16.1 Reference Guide</title>
<link rel="stylesheet" type="text/css" href="../../static_/css/spc-bootstrap.css">
<link rel="stylesheet" type="text/css" href="../../static_/css/spc-extend.css">
<link rel="stylesheet" href="../../static_/scipy.css" type="text/css" >
<link rel="stylesheet" href="../../static_/pygments.css" type="text/css" >
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../../',
VERSION: '0.16.1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: false
};
</script>
<script type="text/javascript" src="../../static_/jquery.js"></script>
<script type="text/javascript" src="../../static_/underscore.js"></script>
<script type="text/javascript" src="../../static_/doctools.js"></script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/javascript" src="../../static_/js/copybutton.js"></script>
<link rel="top" title="SciPy v0.16.1 Reference Guide" href="../../index.html" >
</head>
<body>
<div class="container">
<div class="header">
</div>
</div>
<div class="container">
<div class="main">
<div class="row-fluid">
<div class="span12">
<div class="spc-navbar">
<ul class="nav nav-pills pull-left">
<li class="active"><a href="../../index.html">SciPy v0.16.1 Reference Guide</a></li>
</ul>
<ul class="nav nav-pills pull-right">
<li class="active">
<a href="../../genindex.html" title="General Index"
accesskey="I">index</a>
</li>
<li class="active">
<a href="../../py-modindex.html" title="Python Module Index"
>modules</a>
</li>
<li class="active">
<a href="../../scipy-optimize-modindex.html" title="Python Module Index"
>modules</a>
</li>
</ul>
</div>
</div>
</div>
<div class="row-fluid">
<div class="spc-rightsidebar span3">
<div class="sphinxsidebarwrapper">
<p class="logo"><a href="../../index.html">
<img class="logo" src="../../static_/scipyshiny_small.png" alt="Logo">
</a></p>
</div>
</div>
<div class="span9">
<div class="bodywrapper">
<div class="body" id="spc-section-body">
<div class="section" id="poisson-distribution">
<span id="discrete-poisson"></span><h1>Poisson Distribution<a class="headerlink" href="#poisson-distribution" title="Permalink to this headline">¶</a></h1>
<p>The Poisson random variable counts the number of successes in <span class="math">\(n\)</span> independent Bernoulli trials in the limit as <span class="math">\(n\rightarrow\infty\)</span> and <span class="math">\(p\rightarrow0\)</span> where the probability of success in each trial is <span class="math">\(p\)</span> and <span class="math">\(np=\lambda\geq0\)</span> is a constant. It can be used to approximate the Binomial random
variable or in it’s own right to count the number of events that occur
in the interval <span class="math">\(\left[0,t\right]\)</span> for a process satisfying certain “sparsity “constraints. The functions are</p>
<div class="math">
\[ \begin{eqnarray*} p\left(k;\lambda\right) & = & e^{-\lambda}\frac{\lambda^{k}}{k!}\quad k\geq0,\\ F\left(x;\lambda\right) & = & \sum_{n=0}^{\left\lfloor x\right\rfloor }e^{-\lambda}\frac{\lambda^{n}}{n!}=\frac{1}{\Gamma\left(\left\lfloor x\right\rfloor +1\right)}\int_{\lambda}^{\infty}t^{\left\lfloor x\right\rfloor }e^{-t}dt,\\ \mu & = & \lambda\\ \mu_{2} & = & \lambda\\ \gamma_{1} & = & \frac{1}{\sqrt{\lambda}}\\ \gamma_{2} & = & \frac{1}{\lambda}.\end{eqnarray*}\]</div><div class="math">
\[ M\left(t\right)=\exp\left[\lambda\left(e^{t}-1\right)\right].\]</div><p>Implementation: <a class="reference internal" href="../../generated/scipy.stats.poisson.html#scipy.stats.poisson" title="scipy.stats.poisson"><tt class="xref py py-obj docutils literal"><span class="pre">scipy.stats.poisson</span></tt></a></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container container-navbar-bottom">
<div class="spc-navbar">
</div>
</div>
<div class="container">
<div class="footer">
<div class="row-fluid">
<ul class="inline pull-left">
<li>
© Copyright 2008-2014, The Scipy community.
</li>
<li>
Last updated on Oct 24, 2015.
</li>
<li>
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.1.
</li>
</ul>
</div>
</div>
</div>
</body>
</html> | Java |
#
# Walldo - A wallpaper downloader
# Copyright (C) 2012 Fernando Castillo
#
# 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 unittest
from walldo.parser import Parser;
class ParserTestCase(unittest.TestCase):
lines = ['<select class="select" style="margin: 0 2px 0 0; margin-top: 4px; float: left; width: 145px; max-width: 145px;" name="resolution" onChange="javascript:imgload(\'ithilien\', this,\'2949\')">']
expected = ['/wallpaper/7yz4ma1/2949_ithilien_1024x768.jpg']
def setUp(self):
self.parser = Parser()
def testParse(self):
current = self.parser.parse(self.lines, '1024x768')
for i in range(len(current)):
self.assertEquals(self.expected[i], current[i], 'Entry incorrect')
| Java |
<?php
/**
* @version $Id: mod_communitysurvey.php 01 2011-11-08 11:37:09Z maverick $
* @package CoreJoomla.Surveys
* @subpackage Modules.site
* @copyright Copyright (C) 2009 - 2012 corejoomla.com, Inc. All rights reserved.
* @author Maverick
* @link http://www.corejoomla.com/
* @license License GNU General Public License version 2 or later
*/
//don't allow other scripts to grab and execute our file
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
defined('S_APP_NAME') or define('S_APP_NAME', 'com_communitysurveys');
// include the helper file
require_once(dirname(__FILE__).'/helper.php');
require_once(JPATH_SITE.'/components/com_communitysurveys/router.php');
require_once(JPATH_SITE.'/components/com_communitysurveys/helpers/constants.php');
require_once(JPATH_SITE.'/components/com_communitysurveys/helpers/helper.php');
// CJLib includes
$cjlib = JPATH_ROOT.'/components/com_cjlib/framework.php';
if(file_exists($cjlib)){
require_once $cjlib;
}else{
die('CJLib (CoreJoomla API Library) component not found. Please download and install it to continue.');
}
CJLib::import('corejoomla.framework.core');
// Get the properties
$show_latest = intval($params->get('show_latest','1'));
$show_popular = intval($params->get('show_most_popular','1'));
$show_tabs = intval($params->get('show_tabs','1'));
$tab_order = trim($params->get('tab_order', 'L,M'));
// Get the item id for community answers
$itemid = CJFunctions::get_active_menu_id(true, 'index.php?option='.S_APP_NAME.'&view=survey');
$document = JFactory::getDocument();
$document->addStyleSheet(JURI::base(true).'/modules/mod_communitysurveys/assets/communitysurveys.css');
// get the items to display from the helper
$order = explode(',', $tab_order);
if($show_tabs == 1){
CJLib::import('corejoomla.ui.bootstrap', true);
echo '<div id="cj-wrapper">';
echo '<ul class="nav nav-tabs" data-tabs="tabs">';
foreach ($order as $i=>$tab){
if((strcmp($tab, "L") == 0) && $show_latest){
echo '<li'.($i == 0 ? ' class="active"' : '').'><a href="#cstab-1" data-toggle="tab">'.JText::_('LBL_LATEST_SURVEYS').'</a></li>';
}
if((strcmp($tab, 'M') == 0) && $show_popular){
echo '<li'.($i == 0 ? ' class="active"' : '').'><a href="#cstab-2" data-toggle="tab">'.JText::_('LBL_MOST_POPULAR_SURVEYS').'</a></li>';
}
}
echo '</ul>';
foreach ($order as $i=>$tab){
if((strcmp($tab,'L') == 0) && $show_latest){
$latest_surveys = modCommunitySurveysHelper::getLatestSurveys($params);
echo '<div id="cstab-1" class="tab-pane fade'.($i == 0 ? ' in active' : '').'">';
require(JModuleHelper::getLayoutPath('mod_communitysurveys','latest_surveys'));
echo '</div>';
}
if((strcmp($tab,'M') == 0) && $show_popular){
$popular_surveys = modCommunitySurveysHelper::getMostPopularSurveys($params);
echo '<div id="cstab-2" class="tab-pane fade'.($i == 0 ? ' in active' : '').'">';
require(JModuleHelper::getLayoutPath('mod_communitysurveys','most_popular'));
echo '</div>';
}
}
echo '</div>';
}else{
foreach ($order as $tab){
if((strcmp($tab,'L') == 0) && $show_latest){
$latest_surveys = modCommunitySurveysHelper::getLatestSurveys($params);
require(JModuleHelper::getLayoutPath('mod_communitysurveys','latest_surveys'));
}
if((strcmp($tab,'M') == 0) && $show_popular){
$popular_surveys = modCommunitySurveysHelper::getMostPopularSurveys($params);
require(JModuleHelper::getLayoutPath('mod_communitysurveys','most_popular'));
}
}
}
?>
| Java |
#!/usr/bin/perl -w
# This script was originally based on the script of the same name from
# the KDE SDK (by dfaure@kde.org)
#
# This version is
# Copyright (C) 2007, 2008 Adam D. Barratt
#
# 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.
=head1 NAME
licensecheck - simple license checker for source files
=head1 SYNOPSIS
B<licensecheck> B<--help|--version>
B<licensecheck> [B<--no-conf>] [B<--verbose>] [B<--copyright>]
[B<-l|--lines=N>] [B<-i|--ignore=regex>] [B<-c|--check=regex>]
[B<-r|--recursive>] I<list of files and directories to check>
=head1 DESCRIPTION
B<licensecheck> attempts to determine the license that applies to each file
passed to it, by searching the start of the file for text belonging to
various licenses.
If any of the arguments passed are directories, B<licensecheck> will add
the files contained within to the list of files to process.
=head1 OPTIONS
=over 4
=item B<--verbose> B<--no-verbose>
Specify whether to output the text being processed from each file before
the corresponding license information.
Default is to be quiet.
=item B<-l=N> B<--lines=N>
Specify the number of lines of each file's header which should be parsed
for license information. (Default is 60).
=item B<-i=regex> B<--ignore=regex>
When processing the list of files and directories, the regular
expression specified by this option will be used to indicate those which
should not be considered (e.g. backup files, VCS metadata).
=item B<-r> B<--recursive>
Specify that the contents of directories should be added
recursively.
=item B<-c=regex> B<--check=regex>
Specify a pattern against which filenames will be matched in order to
decide which files to check the license of.
The default includes common source files.
=item B<--copyright>
Also display copyright text found within the file
=item B<--no-conf> B<--noconf>
Do not read any configuration files. This can only be used as the first
option given on the command-line.
=back
=head1 CONFIGURATION VARIABLES
The two configuration files F<__SYSCONFDIR__/rpmdevtools/devscripts.conf> and
F<~/.devscripts> are sourced by a shell in that order to set
configuration variables. Command line options can be used to override
configuration file settings. Environment variable settings are
ignored for this purpose. The currently recognised variables are:
=over 4
=item B<LICENSECHECK_VERBOSE>
If this is set to I<yes>, then it is the same as the --verbose command
line parameter being used. The default is I<no>.
=item B<LICENSECHECK_PARSELINES>
If this is set to a positive number then the specified number of lines
at the start of each file will be read whilst attempting to determine
the license(s) in use. This is equivalent to the --lines command line
option.
=back
=head1 LICENSE
This code is copyright by Adam D. Barratt <adam@adam-barratt.org.uk>,
all rights reserved; based on a script of the same name from the KDE
SDK, which is copyright by <dfaure@kde.org>.
This program comes with ABSOLUTELY NO WARRANTY.
You are free to redistribute this code under the terms of the GNU
General Public License, version 2 or later.
=head1 AUTHOR
Adam D. Barratt <adam@adam-barratt.org.uk>
=cut
use strict;
use warnings;
use Getopt::Long;
use File::Basename;
sub fatal($);
sub parse_copyright($);
sub parselicense($);
my $progname = basename($0);
# From dpkg-source
my $default_ignore_regex = '
# Ignore general backup files
(?:^|/).*~$|
# Ignore emacs recovery files
(?:^|/)\.#.*$|
# Ignore vi swap files
(?:^|/)\..*\.swp$|
# Ignore baz-style junk files or directories
(?:^|/),,.*(?:$|/.*$)|
# File-names that should be ignored (never directories)
(?:^|/)(?:DEADJOE|\.cvsignore|\.arch-inventory|\.bzrignore|\.gitignore)$|
# File or directory names that should be ignored
(?:^|/)(?:CVS|RCS|\.deps|\{arch\}|\.arch-ids|\.svn|\.hg|_darcs|\.git|
\.shelf|_MTN|\.bzr(?:\.backup|tags)?)(?:$|/.*$)
';
# Take out comments and newlines
$default_ignore_regex =~ s/^#.*$//mg;
$default_ignore_regex =~ s/\n//sg;
my $default_check_regex = '\.(c(c|pp|xx)?|h(h|pp|xx)?|f(77|90)?|p(l|m)|xs|sh|php|py|rb|java|vala|el|sc(i|e)|cs)$';
my $modified_conf_msg;
my ($opt_verbose, $opt_lines, $opt_noconf, $opt_ignore_regex, $opt_check_regex)
= ('', '', '', '', '');
my $opt_recursive = 0;
my $opt_copyright = 0;
my ($opt_help, $opt_version);
my $def_lines = 60;
# Read configuration files and then command line
# This is boilerplate
if (@ARGV and $ARGV[0] =~ /^--no-?conf$/) {
$modified_conf_msg = " (no configuration files read)";
shift;
} else {
my @config_files = ('__SYSCONFDIR__/rpmdevtools/devscripts.conf', '~/.devscripts');
my %config_vars = (
'LICENSECHECK_VERBOSE' => 'no',
'LICENSECHECK_PARSELINES' => $def_lines,
);
my %config_default = %config_vars;
my $shell_cmd;
# Set defaults
foreach my $var (keys %config_vars) {
$shell_cmd .= qq[$var="$config_vars{$var}";\n];
}
$shell_cmd .= 'for file in ' . join(" ", @config_files) . "; do\n";
$shell_cmd .= '[ -f $file ] && . $file; done;' . "\n";
# Read back values
foreach my $var (keys %config_vars) { $shell_cmd .= "echo \$$var;\n" }
my $shell_out = `/bin/bash -c '$shell_cmd'`;
@config_vars{keys %config_vars} = split /\n/, $shell_out, -1;
# Check validity
$config_vars{'LICENSECHECK_VERBOSE'} =~ /^(yes|no)$/
or $config_vars{'LICENSECHECK_VERBOSE'} = 'no';
$config_vars{'LICENSECHECK_PARSELINES'} =~ /^[1-9][0-9]*$/
or $config_vars{'LICENSECHECK_PARSELINES'} = $def_lines;
foreach my $var (sort keys %config_vars) {
if ($config_vars{$var} ne $config_default{$var}) {
$modified_conf_msg .= " $var=$config_vars{$var}\n";
}
}
$modified_conf_msg ||= " (none)\n";
chomp $modified_conf_msg;
$opt_verbose = $config_vars{'LICENSECHECK_VERBOSE'} eq 'yes' ? 1 : 0;
$opt_lines = $config_vars{'LICENSECHECK_PARSELINES'};
}
GetOptions("help|h" => \$opt_help,
"version|v" => \$opt_version,
"verbose!" => \$opt_verbose,
"lines|l=i" => \$opt_lines,
"ignore|i=s" => \$opt_ignore_regex,
"recursive|r" => \$opt_recursive,
"check|c=s" => \$opt_check_regex,
"copyright" => \$opt_copyright,
"noconf" => \$opt_noconf,
"no-conf" => \$opt_noconf,
)
or die "Usage: $progname [options] filelist\nRun $progname --help for more details\n";
$opt_lines = $def_lines if $opt_lines !~ /^[1-9][0-9]*$/;
$opt_ignore_regex = $default_ignore_regex if ! length $opt_ignore_regex;
$opt_check_regex = $default_check_regex if ! length $opt_check_regex;
if ($opt_noconf) {
fatal "--no-conf is only acceptable as the first command-line option!";
}
if ($opt_help) { help(); exit 0; }
if ($opt_version) { version(); exit 0; }
die "Usage: $progname [options] filelist\nRun $progname --help for more details\n" unless @ARGV;
$opt_lines = $def_lines if not defined $opt_lines;
my @files = ();
my @find_args = ();
my $files_count = @ARGV;
push @find_args, qw(-maxdepth 1) unless $opt_recursive;
push @find_args, qw(-follow -type f -print);
while (@ARGV) {
my $file = shift @ARGV;
if (-d $file) {
open FIND, '-|', 'find', $file, @find_args
or die "$progname: couldn't exec find: $!\n";
while (<FIND>) {
chomp;
next unless m%$opt_check_regex%;
# Skip empty files
next if (-z $_);
push @files, $_ unless m%$opt_ignore_regex%;
}
close FIND;
} else {
next unless ($files_count == 1) or $file =~ m%$opt_check_regex%;
push @files, $file unless $file =~ m%$opt_ignore_regex%;
}
}
while (@files) {
my $file = shift @files;
my $content = '';
my $copyright_match;
my $copyright = '';
my $license = '';
my %copyrights;
open (F, "<$file") or die "Unable to access $file\n";
while (<F>) {
last if ($. > $opt_lines);
$content .= $_;
$copyright_match = parse_copyright($_);
if ($copyright_match) {
$copyrights{lc("$copyright_match")} = "$copyright_match";
}
}
close(F);
$copyright = join(" / ", values %copyrights);
print qq(----- $file header -----\n$content----- end header -----\n\n)
if $opt_verbose;
$content =~ tr/\t\r\n/ /;
# Remove C / C++ comments
$content =~ s#(\*/|/[/*])##g;
$content =~ tr% A-Za-z.,@;0-9\(\)/-%%cd;
$content =~ s/ c //g; # Remove fortran comments
$content =~ tr/ //s;
$license = parselicense($content);
print "$file: ";
print "*No copyright* " unless $copyright;
print $license . "\n";
print " [Copyright: " . $copyright . "]\n"
if $copyright and $opt_copyright;
print "\n" if $opt_copyright;
}
sub parse_copyright($) {
my $copyright = '';
my $match;
my $copyright_indicator_regex = '
(?:copyright # The full word
|copr\. # Legally-valid abbreviation
|\x{00a9} # Unicode character COPYRIGHT SIGN
|\xc2\xa9 # Unicode copyright sign encoded in iso8859
|\(c\) # Legally-null representation of sign
)';
my $copyright_disindicator_regex = '
\b(?:info(?:rmation)? # Discussing copyright information
|notice # Discussing the notice
|and|or # Part of a sentence
)\b';
if (m%$copyright_indicator_regex(?::\s*|\s+)(\S.*)$%ix) {
$match = $1;
# Ignore lines matching "see foo for copyright information" etc.
if ($match !~ m%^\s*$copyright_disindicator_regex%ix) {
# De-cruft
$match =~ s/([,.])?\s*$//;
$match =~ s/$copyright_indicator_regex//igx;
$match =~ s/^\s+//;
$match =~ s/\s{2,}/ /g;
$match =~ s/\\@/@/g;
$copyright = $match;
}
}
return $copyright;
}
sub help {
print <<"EOF";
Usage: $progname [options] filename [filename ...]
Valid options are:
--help, -h Display this message
--version, -v Display version and copyright info
--no-conf, --noconf Don't read devscripts config files; must be
the first option given
--verbose Display the header of each file before its
license information
--lines, -l Specify how many lines of the file header
should be parsed for license information
(Default: $def_lines)
--check, -c Specify a pattern indicating which files should
be checked
(Default: '$default_check_regex')
--recursive, -r Add the contents of directories recursively
--copyright Also display the file's copyright
--ignore, -i Specify that files / directories matching the
regular expression should be ignored when
checking files
(Default: '$default_ignore_regex')
Default settings modified by devscripts configuration files:
$modified_conf_msg
EOF
}
sub version {
print <<"EOF";
This is $progname, from the Debian devscripts package, version ###VERSION###
Copyright (C) 2007, 2008 by Adam D. Barratt <adam\@adam-barratt.org.uk>; based
on a script of the same name from the KDE SDK by <dfaure\@kde.org>.
This program comes with ABSOLUTELY NO WARRANTY.
You are free to redistribute this code under the terms of the
GNU General Public License, version 2, or (at your option) any
later version.
EOF
}
sub parselicense($) {
my ($licensetext) = @_;
my $gplver = "";
my $extrainfo = "";
my $license = "";
if ($licensetext =~ /version ([^ ]+) (?:\(?only\)?.? )?(?:of the GNU (Affero )?General Public License )?as published by the Free Software Foundation/i or
$licensetext =~ /GNU (?:Affero )?General Public License as published by the Free Software Foundation; version ([^ ]+) /i) {
$gplver = " (v$1)";
} elsif ($licensetext =~ /GNU (Affero ?)General Public License, version ([^ ]+?)[ .]/) {
$gplver = " (v$1)";
} elsif ($licensetext =~ /either version ([^ ]+) of the License, or \(at your option\) any later version/) {
$gplver = " (v$1 or later)";
}
if ($licensetext =~ /(?:675 Mass Ave|59 Temple Place|51 Franklin Steet|02139|02111-1307)/i) {
$extrainfo = " (with incorrect FSF address)$extrainfo";
}
if ($licensetext =~ /permission (?:is (also granted|given))? to link (the code of )?this program with (any edition of )?(Qt|the Qt library)/i) {
$extrainfo = " (with Qt exception)$extrainfo"
}
if ($licensetext =~ /(All changes made in this file will be lost|DO NOT (EDIT|delete this file)|Generated by)/i) {
$license = "GENERATED FILE";
}
if ($licensetext =~ /is free software.? you can redistribute it and\/or modify it under the terms of the (GNU (Library|Lesser) General Public License|LGPL)/i) {
$license = "LGPL$gplver$extrainfo $license";
}
if ($licensetext =~ /is free software.? you can redistribute it and\/or modify it under the terms of the (GNU Affero General Public License|AGPL)/i) {
$license = "AGPL$gplver$extrainfo $license";
}
if ($licensetext =~ /is free software.? you (can|may) redistribute it and\/or modify it under the terms of (?:version [^ ]+ (?:\(?only\)? )?of )?the GNU General Public License/i) {
$license = "GPL$gplver$extrainfo $license";
}
if ($licensetext =~ /is distributed under the terms of the GNU General Public License,/
and length $gplver) {
$license = "GPL$gplver$extrainfo $license";
}
if ($licensetext =~ /is distributed.*terms.*GPL/) {
$license = "GPL (unversioned/unknown version) $license";
}
if ($licensetext =~ /This file is part of the .*Qt GUI Toolkit. This file may be distributed under the terms of the Q Public License as defined/) {
$license = "QPL (part of Qt) $license";
} elsif ($licensetext =~ /may be distributed under the terms of the Q Public License as defined/) {
$license = "QPL $license";
}
if ($licensetext =~ /http:\/\/opensource\.org\/licenses\/mit-license\.php/) {
$license = "MIT/X11 (BSD like) $license";
} elsif ($licensetext =~ /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/) {
$license = "MIT/X11 (BSD like) $license";
}
if ($licensetext =~ /Permission to use, copy, modify, and(\/or)? distribute this software for any purpose with or without fee is hereby granted, provided.*copyright notice.*permission notice.*all copies/) {
$license = "ISC $license";
}
if ($licensetext =~ /THIS SOFTWARE IS PROVIDED .*AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY/) {
if ($licensetext =~ /All advertising materials mentioning features or use of this software must display the following acknowledge?ment.*This product includes software developed by/i) {
$license = "BSD (4 clause) $license";
} elsif ($licensetext =~ /(The name of .*? may not|Neither the names? of .*? nor the names of (its|their) contributors may) be used to endorse or promote products derived from this software/i) {
$license = "BSD (3 clause) $license";
} elsif ($licensetext =~ /Redistributions of source code must retain the above copyright notice/i) {
$license = "BSD (2 clause) $license";
} else {
$license = "BSD $license";
}
}
if ($licensetext =~ /Mozilla Public License Version ([^ ]+)/) {
$license = "MPL (v$1) $license";
}
if ($licensetext =~ /Released under the terms of the Artistic License ([^ ]+)/) {
$license = "Artistic (v$1) $license";
}
if ($licensetext =~ /is free software under the Artistic [Ll]icense/) {
$license = "Artistic $license";
}
if ($licensetext =~ /This program is free software; you can redistribute it and\/or modify it under the same terms as Perl itself/) {
$license = "Perl $license";
}
if ($licensetext =~ /under the Apache License, Version ([^ ]+) \(the License\)/) {
$license = "Apache (v$1) $license";
}
if ($licensetext =~ /This source file is subject to version ([^ ]+) of the PHP license/) {
$license = "PHP (v$1) $license";
}
if ($licensetext =~ /under the terms of the CeCILL /) {
$license = "CeCILL $license";
}
if ($licensetext =~ /under the terms of the CeCILL-([^ ]+) /) {
$license = "CeCILL-$1 $license";
}
if ($licensetext =~ /under the SGI Free Software License B/) {
$license = "SGI Free Software License B $license";
}
if ($licensetext =~ /is in the public domain/i) {
$license = "Public domain";
}
if ($licensetext =~ /terms of the Common Development and Distribution License(, Version ([^(]+))? \(the License\)/) {
$license = "CDDL " . ($1 ? "(v$2) " : '') . $license;
}
if ($licensetext =~ /Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license \(the \"Software\"\)/ or
$licensetext =~ /Boost Software License([ ,-]+Version ([^ ]+)?(\.))/i) {
$license = "BSL " . ($1 ? "(v$2) " : '') . $license;
}
if ($licensetext =~ /PYTHON SOFTWARE FOUNDATION LICENSE (VERSION ([^ ]+))/i) {
$license = "PSF " . ($1 ? "(v$2) " : '') . $license;
}
if ($licensetext =~ /The origin of this software must not be misrepresented.*Altered source versions must be plainly marked as such.*This notice may not be removed or altered from any source distribution/ or
$licensetext =~ /see copyright notice in zlib\.h/) {
$license = "zlib/libpng $license";
}
if ($licensetext =~ /Do What The Fuck You Want To Public License, Version ([^, ]+)/i) {
$license = "WTFPL (v$1)";
}
if ($licensetext =~ /Do what The Fuck You Want To Public License/i) {
$license = "WTFPL";
}
if ($licensetext =~ /(License WTFPL|Under (the|a) WTFPL)/i) {
$license = "WTFPL";
}
$license = "UNKNOWN" if (!length($license));
return $license;
}
sub fatal($) {
my ($pack,$file,$line);
($pack,$file,$line) = caller();
(my $msg = "$progname: fatal error at line $line:\n@_\n") =~ tr/\0//d;
$msg =~ s/\n\n$/\n/;
die $msg;
}
| Java |
#!/bin/sh
if [ $# -gt 0 ]; then
echo $1 > .version
fi
buildid=$(( $1 + 1 ))
zipfile="Chroma.Kernel-r$buildid.zip"
. ./env_setup.sh ${1} || exit 1;
if [ -e .config ]; then
rm .config
fi
cp arch/arm/configs/aosp_defconfig .config >> /dev/null
make aosp_defconfig >> /dev/null
make -j$NUMBEROFCPUS CONFIG_NO_ERROR_ON_MISMATCH=y
cp arch/arm/boot/zImage-dtb ramdisk/
cd ramdisk/
./mkbootfs boot.img-ramdisk | gzip > ramdisk.gz
./mkbootimg --kernel zImage-dtb --cmdline 'console=ttyHSL0,115200,n8 androidboot.hardware=hammerhead user_debug=31 msm_watchdog_v2.enable=1' --base 0x00000000 --pagesize 2048 --ramdisk_offset 0x02900000 --tags_offset 0x02700000 --ramdisk ramdisk.gz --output ../boot.img
rm -rf ramdisk.gz
rm -rf zImage
cd ..
if [ -e arch/arm/boot/zImage ]; then
cp boot.img zip/
rm -rf ramdisk/boot.img
cd zip/
rm -f *.zip
zip -r -9 $zipfile *
rm -f /tmp/*.zip
cp *.zip /tmp
cd ..
else
echo "Something goes wrong aborting!"
return
fi
| Java |
"""
SALTS XBMC Addon
Copyright (C) 2015 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import xbmcaddon
import xbmcplugin
import xbmcgui
import xbmc
import xbmcvfs
import urllib
import urlparse
import sys
import os
import re
addon = xbmcaddon.Addon()
get_setting = addon.getSetting
show_settings = addon.openSettings
def get_path():
return addon.getAddonInfo('path').decode('utf-8')
def get_profile():
return addon.getAddonInfo('profile').decode('utf-8')
def translate_path(path):
return xbmc.translatePath(path).decode('utf-8')
def set_setting(id, value):
if not isinstance(value, basestring): value = str(value)
addon.setSetting(id, value)
def get_version():
return addon.getAddonInfo('version')
def get_id():
return addon.getAddonInfo('id')
def get_name():
return addon.getAddonInfo('name')
def get_plugin_url(queries):
try:
query = urllib.urlencode(queries)
except UnicodeEncodeError:
for k in queries:
if isinstance(queries[k], unicode):
queries[k] = queries[k].encode('utf-8')
query = urllib.urlencode(queries)
return sys.argv[0] + '?' + query
def end_of_directory(cache_to_disc=True):
xbmcplugin.endOfDirectory(int(sys.argv[1]), cacheToDisc=cache_to_disc)
def set_content(content):
xbmcplugin.setContent(int(sys.argv[1]), content)
def create_item(queries, label, thumb='', fanart='', is_folder=None, is_playable=None, total_items=0, menu_items=None, replace_menu=False):
list_item = xbmcgui.ListItem(label, iconImage=thumb, thumbnailImage=thumb)
add_item(queries, list_item, fanart, is_folder, is_playable, total_items, menu_items, replace_menu)
def add_item(queries, list_item, fanart='', is_folder=None, is_playable=None, total_items=0, menu_items=None, replace_menu=False):
if menu_items is None: menu_items = []
if is_folder is None:
is_folder = False if is_playable else True
if is_playable is None:
playable = 'false' if is_folder else 'true'
else:
playable = 'true' if is_playable else 'false'
liz_url = get_plugin_url(queries)
if fanart: list_item.setProperty('fanart_image', fanart)
list_item.setInfo('video', {'title': list_item.getLabel()})
list_item.setProperty('isPlayable', playable)
list_item.addContextMenuItems(menu_items, replaceItems=replace_menu)
xbmcplugin.addDirectoryItem(int(sys.argv[1]), liz_url, list_item, isFolder=is_folder, totalItems=total_items)
def parse_query(query):
q = {'mode': 'main'}
if query.startswith('?'): query = query[1:]
queries = urlparse.parse_qs(query)
for key in queries:
if len(queries[key]) == 1:
q[key] = queries[key][0]
else:
q[key] = queries[key]
return q
def notify(header=None, msg='', duration=2000, sound=None):
if header is None: header = get_name()
if sound is None: sound = get_setting('mute_notifications') == 'false'
icon_path = os.path.join(get_path(), 'icon.png')
try:
xbmcgui.Dialog().notification(header, msg, icon_path, duration, sound)
except:
builtin = "XBMC.Notification(%s,%s, %s, %s)" % (header, msg, duration, icon_path)
xbmc.executebuiltin(builtin)
def get_current_view():
skinPath = translate_path('special://skin/')
xml = os.path.join(skinPath, 'addon.xml')
f = xbmcvfs.File(xml)
read = f.read()
f.close()
try: src = re.search('defaultresolution="([^"]+)', read, re.DOTALL).group(1)
except: src = re.search('<res.+?folder="([^"]+)', read, re.DOTALL).group(1)
src = os.path.join(skinPath, src, 'MyVideoNav.xml')
f = xbmcvfs.File(src)
read = f.read()
f.close()
match = re.search('<views>([^<]+)', read, re.DOTALL)
if match:
views = match.group(1)
for view in views.split(','):
if xbmc.getInfoLabel('Control.GetLabel(%s)' % (view)): return view
| Java |
using System;
using System.Collections.Generic;
using UnityEngine;
using YinYang.CodeProject.Projects.SimplePathfinding.PathFinders.AStar;
namespace YinYang.CodeProject.Projects.SimplePathfinding.PathFinders
{
public abstract class BaseGraphSearchMap<TNode, TValue> where TNode : BaseGraphSearchNode<TNode, TValue>
{
#region | Fields |
private Dictionary<TValue, TNode> nodes;
#endregion
#region | Properties |
/// <summary>
/// Gets the open nodes count.
/// </summary>
public Int32 OpenCount
{
get { return OnGetCount(); }
}
public Dictionary<TValue, TNode> Nodes
{
get { return nodes; }
}
#endregion
#region | Indexers |
/// <summary>
/// Gets the <see cref="AStarNode"/> on a given coordinates.
/// </summary>
public TNode this[TValue value]
{
get { return nodes[value]; }
}
#endregion
#region | Constructors |
/// <summary>
/// Initializes a new instance of the <see cref="BaseGraphSearchMap{TNode}"/> class.
/// </summary>
protected BaseGraphSearchMap()
{
nodes = new Dictionary<TValue, TNode>();
}
#endregion
#region | Helper methods |
private void OpenNodeInternal(TValue value, TNode result)
{
nodes[value] = result;
OnAddNewNode(result);
}
#endregion
#region | Virtual/abstract methods |
protected abstract TNode OnCreateFirstNode(TValue startPosition, TValue endPosition);
protected abstract TNode OnCreateNode(TValue position, TNode origin, params object[] arguments);
protected abstract Int32 OnGetCount();
protected abstract void OnAddNewNode(TNode result);
protected abstract TNode OnGetTopNode();
protected abstract void OnClear();
#endregion
#region | Methods |
/// <summary>
/// Creates new open node on a map at given coordinates and parameters.
/// </summary>
public void OpenNode(TValue value, TNode origin, params object[] arguments)
{
TNode result = OnCreateNode(value, origin, arguments);
OpenNodeInternal(value, result);
}
public void OpenFirstNode(TValue startPosition, TValue endPosition)
{
TNode result = OnCreateFirstNode(startPosition, endPosition);
OpenNodeInternal(startPosition, result);
}
/// <summary>
/// Creates the empty node at given point.
/// </summary>
/// <param name="position">The point.</param>
/// <returns></returns>
public TNode CreateEmptyNode(TValue position)
{
return OnCreateNode(position, null);
}
/// <summary>
/// Returns top node (best estimated score), and closes it.
/// </summary>
/// <returns></returns>
public TNode CloseTopNode()
{
TNode result = OnGetTopNode();
result.MarkClosed();
return result;
}
/// <summary>
/// Clears map for another round.
/// </summary>
public void Clear()
{
nodes.Clear();
OnClear();
}
#endregion
}
}
| Java |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright held by original author
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Class
Foam::DICGaussSeidelSmoother
Description
Combined DIC/GaussSeidel smoother for symmetric
matrices in which DIC smoothing is followed by GaussSeidel to ensure that
any "spikes" created by the DIC sweeps are smoothed-out.
SourceFiles
DICGaussSeidelSmoother.C
\*---------------------------------------------------------------------------*/
#ifndef DICGaussSeidelSmoother_H
#define DICGaussSeidelSmoother_H
#include "DICSmoother.H"
#include "GaussSeidelSmoother.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class DICGaussSeidelSmoother Declaration
\*---------------------------------------------------------------------------*/
class DICGaussSeidelSmoother
:
public lduSmoother
{
// Private data
DICSmoother dicSmoother_;
GaussSeidelSmoother gsSmoother_;
public:
//- Runtime type information
TypeName("DICGaussSeidel");
// Constructors
//- Construct from matrix components
DICGaussSeidelSmoother
(
const lduMatrix& matrix,
const FieldField<Field, scalar>& coupleBouCoeffs,
const FieldField<Field, scalar>& coupleIntCoeffs,
const lduInterfaceFieldPtrsList& interfaces
);
// Member Functions
//- Execute smoothing
virtual void smooth
(
scalarField& psi,
const scalarField& Source,
const direction cmpt,
const label nSweeps
) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| Java |
/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*-
this file is part of rcssserver3D
Fri May 9 2003
Copyright (C) 2002,2003 Koblenz University
Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group
$Id$
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "soccerbase.h"
#include <oxygen/physicsserver/rigidbody.h>
#include <oxygen/physicsserver/spherecollider.h>
#include <oxygen/agentaspect/perceptor.h>
#include <oxygen/agentaspect/agentaspect.h>
#include <oxygen/sceneserver/sceneserver.h>
#include <oxygen/sceneserver/scene.h>
#include <oxygen/sceneserver/transform.h>
#include <oxygen/controlaspect/controlaspect.h>
#include <oxygen/gamecontrolserver/gamecontrolserver.h>
#include <gamestateaspect/gamestateaspect.h>
#include <soccerruleaspect/soccerruleaspect.h>
#include <agentstate/agentstate.h>
#include <ball/ball.h>
#include <oxygen/physicsserver/space.h>
#include <zeitgeist/leaf.h>
using namespace boost;
using namespace zeitgeist;
using namespace oxygen;
using namespace std;
using namespace salt;
bool
SoccerBase::GetSceneServer(const Leaf& base,
boost::shared_ptr<SceneServer>& scene_server)
{
scene_server = static_pointer_cast<SceneServer>
(base.GetCore()->Get("/sys/server/scene"));
if (scene_server.get() == 0)
{
base.GetLog()->Error()
<< "Error: (SoccerBase: " << base.GetName()
<< ") scene server not found.\n";
return false;
}
return true;
}
bool
SoccerBase::GetTransformParent(const Leaf& base,
boost::shared_ptr<Transform>& transform_parent)
{
transform_parent = dynamic_pointer_cast<Transform>
((base.FindParentSupportingClass<Transform>()).lock());
if (transform_parent.get() == 0)
{
base.GetLog()->Error()
<< "Error: (SoccerBase: " << base.GetName()
<< ") parent node is not derived from TransformNode\n";
return false;
}
return true;
}
bool
SoccerBase::GetAgentState(const boost::shared_ptr<Transform> transform,
boost::shared_ptr<AgentState>& agent_state)
{
agent_state =
dynamic_pointer_cast<AgentState>(transform->GetChild("AgentState", true));
if (agent_state.get() == 0)
{
return false;
}
return true;
}
bool
SoccerBase::GetAgentBody(const boost::shared_ptr<Transform> transform,
boost::shared_ptr<RigidBody>& agent_body)
{
agent_body = transform->FindChildSupportingClass<RigidBody>(true);
if (agent_body.get() == 0)
{
transform->GetLog()->Error()
<< "(SoccerBase) ERROR: " << transform->GetName()
<< " node has no Body child\n";
return false;
}
return true;
}
bool
SoccerBase::GetAgentBody(const Leaf& base, TTeamIndex idx,
int unum, boost::shared_ptr<RigidBody>& agent_body)
{
boost::shared_ptr<AgentState> agentState;
boost::shared_ptr<Transform> parent;
// get matching AgentState
if (!GetAgentState(base, idx, unum, agentState))
return false;
// get AgentAspect
if (!GetTransformParent(*agentState, parent))
return false;
// call GetAgentBody with matching AgentAspect
return GetAgentBody(parent, agent_body);
}
bool
SoccerBase::GetAgentState(const Leaf& base,
boost::shared_ptr<AgentState>& agent_state)
{
boost::shared_ptr<Transform> parent;
if (! GetTransformParent(base,parent))
{
return false;
}
return GetAgentState(parent,agent_state);
}
bool
SoccerBase::GetAgentState(const Leaf& base, TTeamIndex idx,
int unum, boost::shared_ptr<AgentState>& agentState)
{
static TAgentStateMap mAgentStateMapLeft;
static TAgentStateMap mAgentStateMapRight;
if (idx == TI_NONE)
return false;
// do we have a cached reference?
if (
idx == TI_LEFT &&
!mAgentStateMapLeft.empty()
)
{
TAgentStateMap::iterator iter = mAgentStateMapLeft.find(unum);
if (iter != mAgentStateMapLeft.end())
{
// is the pointer to the parent (AgentAspect) still valid
// (maybe the agent disconnected)?
if (!(iter->second)->GetParent().lock().get())
{
base.GetLog()->Error() << "(SoccerBase) WARNING: "
<< "AgentState has invalid parent! "
<< "The agent probably disconnected, removing from map."
<< "\n";
mAgentStateMapLeft.erase(iter);
}
else
{
agentState = (*iter).second;
return true;
}
}
}
else if (
idx == TI_RIGHT &&
!mAgentStateMapRight.empty()
)
{
TAgentStateMap::iterator iter = mAgentStateMapRight.find(unum);
if (iter != mAgentStateMapRight.end())
{
// is the pointer to the parent (AgentAspect) still valid
// (maybe the agent disconnected)?
if ((iter->second)->GetParent().lock().get() == 0)
{
base.GetLog()->Error() << "(SoccerBase) WARNING: "
<< "AgentState has invalid parent! "
<< "The agent probably disconnected, removing from map."
<< "\n";
mAgentStateMapRight.erase(iter);
}
else
{
agentState = (*iter).second;
return true;
}
}
}
// we have to get all agent states for this team
TAgentStateList agentStates;
GetAgentStates(base, agentStates, idx);
for (TAgentStateList::iterator iter = agentStates.begin();
iter != agentStates.end();
++iter)
{
if ((*iter)->GetUniformNumber() == unum)
{
agentState = *iter;
if (idx == TI_LEFT)
{
mAgentStateMapLeft[unum] = agentState;
}
else
{
mAgentStateMapRight[unum] = agentState;
}
return true;
}
}
return false;
}
bool
SoccerBase::GetAgentStates(const zeitgeist::Leaf& base,
TAgentStateList& agentStates,
TTeamIndex idx)
{
static boost::shared_ptr<GameControlServer> gameCtrl;
if (gameCtrl.get() == 0)
{
GetGameControlServer(base, gameCtrl);
if (gameCtrl.get() == 0)
{
base.GetLog()->Error() << "(SoccerBase) ERROR: can't get "
<< "GameControlServer\n";
return false;
}
}
GameControlServer::TAgentAspectList aspectList;
gameCtrl->GetAgentAspectList(aspectList);
GameControlServer::TAgentAspectList::iterator iter;
boost::shared_ptr<AgentState> agentState;
for (
iter = aspectList.begin();
iter != aspectList.end();
++iter
)
{
agentState = dynamic_pointer_cast<AgentState>((*iter)->GetChild("AgentState", true));
if (
agentState.get() != 0 &&
(
agentState->GetTeamIndex() == idx ||
idx == TI_NONE
)
)
{
agentStates.push_back(agentState);
}
}
return true;
}
bool
SoccerBase::GetGameState(const Leaf& base,
boost::shared_ptr<GameStateAspect>& game_state)
{
game_state = dynamic_pointer_cast<GameStateAspect>
(base.GetCore()->Get("/sys/server/gamecontrol/GameStateAspect"));
if (game_state.get() == 0)
{
base.GetLog()->Error()
<< "Error: (SoccerBase: " << base.GetName()
<< ") found no GameStateAspect\n";
return false;
}
return true;
}
bool
SoccerBase::GetSoccerRuleAspect(const Leaf& base,
boost::shared_ptr<SoccerRuleAspect> & soccer_rule_aspect)
{
soccer_rule_aspect = dynamic_pointer_cast<SoccerRuleAspect>
(base.GetCore()->Get("/sys/server/gamecontrol/SoccerRuleAspect"));
if (soccer_rule_aspect.get() == 0)
{
base.GetLog()->Error()
<< "Error: (SoccerBase: " << base.GetName()
<< " found no SoccerRuleAspect\n";
return false;
}
return true;
}
bool
SoccerBase::GetGameControlServer(const Leaf& base,
boost::shared_ptr<GameControlServer> & game_control_server)
{
static boost::shared_ptr<GameControlServer> gameControlServer;
if (gameControlServer.get() == 0)
{
gameControlServer = boost::dynamic_pointer_cast<GameControlServer>
(base.GetCore()->Get("/sys/server/gamecontrol"));
if (gameControlServer.get() == 0)
{
base.GetLog()->Error()
<< "Error: (SoccerBase: " << base.GetName()
<< " found no GameControlServer\n";
return false;
}
}
game_control_server = gameControlServer;
return true;
}
bool
SoccerBase::GetActiveScene(const Leaf& base,
boost::shared_ptr<Scene>& active_scene)
{
static boost::shared_ptr<SceneServer> sceneServer;
if (sceneServer.get() == 0)
{
if (! GetSceneServer(base,sceneServer))
{
base.GetLog()->Error()
<< "(SoccerBase) ERROR: " << base.GetName()
<< ", could not get SceneServer\n";
return false;
}
}
active_scene = sceneServer->GetActiveScene();
if (active_scene.get() == 0)
{
base.GetLog()->Error()
<< "ERROR: (SoccerBase: " << base.GetName()
<< ", SceneServer reports no active scene\n";
return false;
}
return true;
}
bool
SoccerBase::GetBody(const Leaf& base, boost::shared_ptr<RigidBody>& body)
{
boost::shared_ptr<Transform> parent;
if (! GetTransformParent(base,parent))
{
base.GetLog()->Error() << "(SoccerBase) ERROR: no transform parent "
<< "found in GetBody()\n";
return false;
}
body = dynamic_pointer_cast<RigidBody>(parent->FindChildSupportingClass<RigidBody>());
if (body.get() == 0)
{
base.GetLog()->Error()
<< "ERROR: (SoccerBase: " << base.GetName()
<< ") parent node has no Body child.";
return false;
}
return true;
}
bool
SoccerBase::GetBall(const Leaf& base, boost::shared_ptr<Ball>& ball)
{
static boost::shared_ptr<Scene> scene;
static boost::shared_ptr<Ball> ballRef;
if (scene.get() == 0)
{
if (! GetActiveScene(base,scene))
{
base.GetLog()->Error()
<< "(SoccerBase) ERROR: " << base.GetName()
<< ", could not get active scene.\n";
return false;
}
}
if (ballRef.get() == 0)
{
ballRef = dynamic_pointer_cast<Ball>
(base.GetCore()->Get(scene->GetFullPath() + "Ball"));
if (ballRef.get() == 0)
{
base.GetLog()->Error()
<< "(SoccerBase) ERROR: " << base.GetName()
<< ", found no ball node\n";
return false;
}
}
ball = ballRef;
return true;
}
bool
SoccerBase::GetBallBody(const Leaf& base, boost::shared_ptr<RigidBody>& body)
{
static boost::shared_ptr<Scene> scene;
static boost::shared_ptr<RigidBody> bodyRef;
if (scene.get() == 0)
{
if (! GetActiveScene(base,scene))
{
base.GetLog()->Error()
<< "(SoccerBase) ERROR: " << base.GetName()
<< ", could not get active scene.\n";
return false;
}
}
if (bodyRef.get() == 0)
{
bodyRef = dynamic_pointer_cast<RigidBody>
(base.GetCore()->Get(scene->GetFullPath() + "Ball/physics"));
if (bodyRef.get() == 0)
{
base.GetLog()->Error()
<< "(SoccerBase) ERROR: " << base.GetName()
<< ", found no ball body node\n";
return false;
}
}
body = bodyRef;
return true;
}
bool
SoccerBase::GetBallCollider(const zeitgeist::Leaf& base,
boost::shared_ptr<oxygen::SphereCollider>& sphere)
{
static boost::shared_ptr<Scene> scene;
static boost::shared_ptr<SphereCollider> sphereRef;
if (scene.get() == 0)
{
if (! GetActiveScene(base,scene))
{
base.GetLog()->Error()
<< "(SoccerBase) ERROR: " << base.GetName()
<< ", could not get active scene.\n";
return false;
}
}
if (sphereRef.get() == 0)
{
sphereRef = dynamic_pointer_cast<SphereCollider>
(base.GetCore()->Get(scene->GetFullPath() + "Ball/geometry"));
if (sphereRef.get() == 0)
{
base.GetLog()->Error()
<< "(SoccerBase) ERROR:" << base.GetName()
<< ", Ball got no SphereCollider node\n";
return false;
}
}
sphere = sphereRef;
return true;
}
salt::Vector3f
SoccerBase::FlipView(const salt::Vector3f& pos, TTeamIndex ti)
{
salt::Vector3f newPos;
switch (ti)
{
case TI_RIGHT:
newPos[0] = -pos[0];
newPos[1] = -pos[1];
newPos[2] = pos[2];
break;
case TI_NONE:
case TI_LEFT:
newPos = pos;
break;
}
return newPos;
}
TTeamIndex
SoccerBase::OpponentTeam(TTeamIndex ti)
{
switch (ti)
{
case TI_RIGHT:
return TI_LEFT;
case TI_LEFT:
return TI_RIGHT;
default:
return TI_NONE;
}
}
string
SoccerBase::PlayMode2Str(const TPlayMode mode)
{
switch (mode)
{
case PM_BeforeKickOff:
return STR_PM_BeforeKickOff;
case PM_KickOff_Left:
return STR_PM_KickOff_Left;
case PM_KickOff_Right:
return STR_PM_KickOff_Right;
case PM_PlayOn:
return STR_PM_PlayOn;
case PM_KickIn_Left:
return STR_PM_KickIn_Left;
case PM_KickIn_Right:
return STR_PM_KickIn_Right;
case PM_CORNER_KICK_LEFT:
return STR_PM_CORNER_KICK_LEFT;
case PM_CORNER_KICK_RIGHT:
return STR_PM_CORNER_KICK_RIGHT;
case PM_GOAL_KICK_LEFT:
return STR_PM_GOAL_KICK_LEFT;
case PM_GOAL_KICK_RIGHT:
return STR_PM_GOAL_KICK_RIGHT;
case PM_OFFSIDE_LEFT:
return STR_PM_OFFSIDE_LEFT;
case PM_OFFSIDE_RIGHT:
return STR_PM_OFFSIDE_RIGHT;
case PM_GameOver:
return STR_PM_GameOver;
case PM_Goal_Left:
return STR_PM_Goal_Left;
case PM_Goal_Right:
return STR_PM_Goal_Right;
case PM_FREE_KICK_LEFT:
return STR_PM_FREE_KICK_LEFT;
case PM_FREE_KICK_RIGHT:
return STR_PM_FREE_KICK_RIGHT;
default:
return STR_PM_Unknown;
};
}
boost::shared_ptr<ControlAspect>
SoccerBase::GetControlAspect(const zeitgeist::Leaf& base,const string& name)
{
static const string gcsPath = "/sys/server/gamecontrol/";
boost::shared_ptr<ControlAspect> aspect = dynamic_pointer_cast<ControlAspect>
(base.GetCore()->Get(gcsPath + name));
if (aspect.get() == 0)
{
base.GetLog()->Error()
<< "ERROR: (SoccerBase: " << base.GetName()
<< ") found no ControlAspect " << name << "\n";
}
return aspect;
}
bool
SoccerBase::MoveAgent(boost::shared_ptr<Transform> agent_aspect, const Vector3f& pos)
{
Vector3f agentPos = agent_aspect->GetWorldTransform().Pos();
boost::shared_ptr<Transform> parent = dynamic_pointer_cast<Transform>
(agent_aspect->FindParentSupportingClass<Transform>().lock());
if (parent.get() == 0)
{
agent_aspect->GetLog()->Error() << "(MoveAgent) ERROR: can't get parent node.\n";
return false;
}
Leaf::TLeafList leafList;
parent->ListChildrenSupportingClass<RigidBody>(leafList, true);
if (leafList.size() == 0)
{
agent_aspect->GetLog()->Error()
<< "(MoveAgent) ERROR: agent aspect doesn't have "
<< "children of type Body\n";
return false;
}
Leaf::TLeafList::iterator iter = leafList.begin();
// move all child bodies
for (; iter != leafList.end(); ++iter)
{
boost::shared_ptr<RigidBody> childBody =
dynamic_pointer_cast<RigidBody>(*iter);
Vector3f childPos = childBody->GetPosition();
childBody->SetPosition(pos + (childPos-agentPos));
childBody->SetVelocity(Vector3f(0,0,0));
childBody->SetAngularVelocity(Vector3f(0,0,0));
}
return true;
}
bool
SoccerBase::MoveAndRotateAgent(boost::shared_ptr<Transform> agent_aspect, const Vector3f& pos, float angle)
{
boost::shared_ptr<Transform> parent = dynamic_pointer_cast<Transform>
(agent_aspect->FindParentSupportingClass<Transform>().lock());
if (parent.get() == 0)
{
agent_aspect->GetLog()->Error() << "(MoveAndRotateAgent) ERROR: can't get parent node.\n";
return false;
}
Leaf::TLeafList leafList;
parent->ListChildrenSupportingClass<RigidBody>(leafList, true);
if (leafList.size() == 0)
{
agent_aspect->GetLog()->Error()
<< "(MoveAndRotateAgent) ERROR: agent aspect doesn't have "
<< "children of type Body\n";
return false;
}
boost::shared_ptr<RigidBody> body;
GetAgentBody(agent_aspect, body);
const Vector3f& agentPos = body->GetPosition();
Matrix bodyR = body->GetRotation();
bodyR.InvertRotationMatrix();
Matrix mat;
mat.RotationZ(gDegToRad(angle));
mat *= bodyR;
Leaf::TLeafList::iterator iter = leafList.begin();
// move all child bodies
for (;
iter != leafList.end();
++iter
)
{
boost::shared_ptr<RigidBody> childBody =
dynamic_pointer_cast<RigidBody>(*iter);
Vector3f childPos = childBody->GetPosition();
Matrix childR = childBody->GetRotation();
childR = mat*childR;
childBody->SetPosition(pos + mat.Rotate(childPos-agentPos));
childBody->SetVelocity(Vector3f(0,0,0));
childBody->SetAngularVelocity(Vector3f(0,0,0));
childBody->SetRotation(childR);
}
return true;
}
AABB3 SoccerBase::GetAgentBoundingBox(const Leaf& base)
{
AABB3 boundingBox;
boost::shared_ptr<Space> parent = base.FindParentSupportingClass<Space>().lock();
if (!parent)
{
base.GetLog()->Error()
<< "(GetAgentBoundingBox) ERROR: can't get parent node.\n";
return boundingBox;
}
/* We can't simply use the GetWorldBoundingBox of the space node, becuase
* (at least currently) it'll return a wrong answer. Currently, the space
* object is always at (0,0,0) which is encapsulated in the result of it's
* GetWorldBoundingBox method call.
*/
Leaf::TLeafList baseNodes;
parent->ListChildrenSupportingClass<BaseNode>(baseNodes);
if (baseNodes.empty())
{
base.GetLog()->Error()
<< "(GetAgentBoundingBox) ERROR: space object doesn't have any"
<< " children of type BaseNode.\n";
}
for (Leaf::TLeafList::iterator i = baseNodes.begin(); i!= baseNodes.end(); ++i)
{
boost::shared_ptr<BaseNode> node = static_pointer_cast<BaseNode>(*i);
boundingBox.Encapsulate(node->GetWorldBoundingBox());
}
return boundingBox;
}
AABB2 SoccerBase::GetAgentBoundingRect(const Leaf& base)
{
AABB2 boundingRect;
boost::shared_ptr<Space> parent = base.FindParentSupportingClass<Space>().lock();
if (!parent)
{
base.GetLog()->Error()
<< "(GetAgentBoundingBox) ERROR: can't get parent node.\n";
return boundingRect;
}
/* We can't simply use the GetWorldBoundingBox of the space node, becuase
* (at least currently) it'll return a wrong answer. Currently, the space
* object is always at (0,0,0) which is encapsulated in the result of it's
* GetWorldBoundingBox method call.
*/
Leaf::TLeafList baseNodes;
parent->ListChildrenSupportingClass<Collider>(baseNodes,true);
if (baseNodes.empty())
{
base.GetLog()->Error()
<< "(GetAgentBoundingBox) ERROR: space object doesn't have any"
<< " children of type BaseNode.\n";
}
for (Leaf::TLeafList::iterator i = baseNodes.begin(); i!= baseNodes.end(); ++i)
{
boost::shared_ptr<BaseNode> node = static_pointer_cast<BaseNode>(*i);
const AABB3 &box = node->GetWorldBoundingBox();
boundingRect.Encapsulate(box.minVec.x(), box.minVec.y());
boundingRect.Encapsulate(box.maxVec.x(), box.maxVec.y());
}
return boundingRect;
}
std::string SoccerBase::SPLState2Str(const spl::TSPLState state)
{
switch (state)
{
case spl::Initial:
return STR_SPL_STATE_INITIAL;
case spl::Ready:
return STR_SPL_STATE_READY;
case spl::Set:
return STR_SPL_STATE_SET;
case spl::Playing:
return STR_SPL_STATE_PLAYING;
case spl::Finished:
return STR_SPL_STATE_FINISHED;
case spl::Penalized:
return STR_SPL_STATE_PENALIZED;
default:
return STR_SPL_STATE_UNKNOWN;
}
}
| Java |
# -*- coding: utf-8 -*-
#
# HnTool rules - php
# Copyright (C) 2009-2010 Candido Vieira <cvieira.br@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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 os
import ConfigParser
import HnTool.modules.util
from HnTool.modules.rule import Rule as MasterRule
class Rule(MasterRule):
def __init__(self, options):
MasterRule.__init__(self, options)
self.short_name="php"
self.long_name="Checks security problems on php config file"
self.type="config"
self.required_files = ['/etc/php5/apache2/php.ini', '/etc/php5/cli/php.ini', '/etc/php.ini']
def requires(self):
return self.required_files
def analyze(self, options):
check_results = self.check_results
conf_files = self.required_files
for php_conf in conf_files:
if os.path.isfile(php_conf):
config = ConfigParser.ConfigParser()
try:
config.read(php_conf)
except ConfigParser.ParsingError, (errno, strerror):
check_results['info'].append('Could not parse %s: %s' % (php_conf, strerror))
continue
if not config.has_section('PHP'):
check_results['info'].append('%s is not a PHP config file' % (php_conf))
continue
if config.has_option('PHP', 'register_globals'):
rg = config.get('PHP', 'register_globals').lower()
if rg == 'on':
check_results['medium'].append('Register globals is on (%s)' % (php_conf))
elif rg == 'off':
check_results['ok'].append('Register globals is off (%s)' % (php_conf))
else:
check_results['info'].append('Unknown value for register globals (%s)' % (php_conf))
else:
check_results['info'].append('Register globals not found (%s)' % (php_conf))
if config.has_option('PHP', 'safe_mode'):
sm = config.get('PHP', 'safe_mode').lower()
if sm == 'on':
check_results['low'].append('Safe mode is on (fake security) (%s)' % (php_conf))
elif sm == 'off':
check_results['info'].append('Safe mode is off (%s)' % (php_conf))
else:
check_results['info'].append('Unknown value for safe mode (%s)' % (php_conf))
else:
check_results['info'].append('Safe mode not found (%s)' % (php_conf))
if config.has_option('PHP', 'display_errors'):
de = config.get('PHP', 'display_errors').lower()
if de == 'on':
check_results['medium'].append('Display errors is on (stdout) (%s)' % (php_conf))
elif de == 'off':
check_results['ok'].append('Display errors is off (%s)' % (php_conf))
elif de == 'stderr':
check_results['info'].append('Display errors set to stderr (%s)' % (php_conf))
else:
check_results['info'].append('Unknown value for display errors (%s)' % (php_conf))
else:
check_results['info'].append('Display errors not found (%s)' % (php_conf))
if config.has_option('PHP', 'expose_php'):
ep = config.get('PHP', 'expose_php').lower()
if ep == 'on':
check_results['low'].append('Expose PHP is on (%s)' % (php_conf))
elif ep == 'off':
check_results['ok'].append('Expose PHP is off (%s)' % (php_conf))
else:
check_results['info'].append('Unknown value for expose PHP (%s)' % (php_conf))
else:
check_results['info'].append('Expose PHP not found (%s)' % (php_conf))
return check_results
| Java |
#ifndef _UMLINTERRUPTIBLEACTIVITYREGION_H
#define _UMLINTERRUPTIBLEACTIVITYREGION_H
#include "UmlBaseInterruptibleActivityRegion.h"
#include <qcstring.h>
class UmlInterruptibleActivityRegion : public UmlBaseInterruptibleActivityRegion {
public:
// the constructor, do not call it yourself !!!!!!!!!!
UmlInterruptibleActivityRegion(void * id, const QCString & s) : UmlBaseInterruptibleActivityRegion(id, s) {
}
//returns a string indicating the king of the element
virtual QCString sKind();
//entry to produce the html code receiving chapter number
//path, rank in the mother and level in the browser tree
virtual void html(QCString pfix, unsigned int rank, unsigned int level);
};
#endif
| Java |
/* JavaScript User Interface Library -- Common datatypes for user elements
* Copyright 2010 Jaakko-Heikki Heusala <jhh@jhh.me>
* $Id: common.js 415 2010-10-15 05:00:51Z jheusala $
*/
/** Simple message box constructor
* @params type The message type: error, notice, info or success
* @params msg Message
*/
function UIMessage(type, msg) {
var undefined;
if(this instanceof arguments.callee) {
if(type === undefined) throw TypeError("type undefined");
if(msg === undefined) {
msg = type;
type = undefined;
}
this.type = type || "info";
this.msg = ""+msg;
} else {
return new UIMessage(type, msg);
}
}
/** Get the message as a string */
UIMessage.prototype.toString = function() {
return this.type + ": " + this.msg;
}
/** Convert to JSON using JSONObject extension */
UIMessage.prototype.toJSON = function() {
return new JSONObject("UIMessage", this.type + ":" + this.msg );
};
/* Setup reviver for JSONObject */
JSONObject.revivers.UIMessage = function(value) {
var parts = (""+value).split(":");
return new UIMessage(parts.shift(), parts.join(":"));
};
/* EOF */
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.