code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
#! /usr/bin/env python3 ''' given a list of stock price ticks for the day, can you tell me what trades I should make to maximize my gain within the constraints of the market? Remember - buy low, sell high, and you can't sell before you buy. Sample Input 19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98 ''' import argparse def parse_args(): parser = argparse.ArgumentParser(description='easy 249') parser.add_argument('stock_prices', action='store', nargs='+', help='prices of a given stock') return parser.parse_args() def stock(stock_prices): buy_day = 0 max_profit = 0 max_buy = 0 max_sell = 0 for buy_day in range(len(stock_prices) - 2): # maybe do a max(here) for sell_day in range(buy_day + 2, len(stock_prices)): profit = stock_prices[sell_day] - stock_prices[buy_day] if profit > max_profit: max_profit = profit max_buy = buy_day max_sell = sell_day print("max profit: %.2f from buy on day %d at %.2f sell on day %d at %.2f" % (max_profit, max_buy, stock_prices[max_buy], max_sell, stock_prices[max_sell])) if __name__ == '__main__': args = parse_args() stock([float(price) for price in args.stock_prices])
benosment/daily-exercises
easy-249.py
Python
gpl-2.0
1,302
<?php /******************************************************************************* Copyright 2005,2009 Whole Foods Community Co-op This file is part of Fannie. Fannie is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Fannie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License in the file license.txt along with IT CORE; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *********************************************************************************/ require(dirname(__FILE__) . '/../config.php'); if (!class_exists('FannieAPI')) { include($FANNIE_ROOT.'classlib2.0/FannieAPI.php'); } if (basename(__FILE__) != basename($_SERVER['PHP_SELF'])) { return; } $dbc = FannieDB::get($FANNIE_OP_DB); include($FANNIE_ROOT.'auth/login.php'); $name = checkLogin(); if (!$name){ header("Location: {$FANNIE_URL}auth/ui/loginform.php?redirect={$FANNIE_URL}item/scaleDelete.php"); exit; } $user = validateUserQuiet('delete_items'); if (!$user){ echo "Not allowed"; exit; } $page_title = 'Fannie - Item Maintenance'; $header = 'Item Maintenance'; include('../src/header.html'); ?> <script type"text/javascript" src=ajax.js></script> <?php echo "<h1 style=\"color:red;\">Delete Scale PLU Tool</h1>"; if (isset($_REQUEST['upc']) && !isset($_REQUEST['deny'])){ $upc = BarcodeLib::padUPC(FormLib::get('upc')); if (isset($_REQUEST['submit'])){ $p = $dbc->prepare_statement("SELECT * FROM scaleItems WHERE plu=?"); $rp = $dbc->exec_statement($p,array($upc)); if ($dbc->num_rows($rp) == 0){ printf("No item found for <b>%s</b><p />",$upc); echo "<a href=\"scaleDelete.php\">Go back</a>"; } else { $rw = $dbc->fetch_row($rp); echo "<form action=scaleDelete.php method=post>"; echo "<b>Delete this item?</b><br />"; echo "<table cellpadding=4 cellspacing=0 border=1>"; echo "<tr><th>UPC</th><th>Description</th><th>Price</th></tr>"; printf("<tr><td><a href=\"itemMain.php?upc=%s\" target=\"_new%s\"> %s</a></td><td>%s</td><td>%.2f</td></tr>",$rw['plu'], $rw['plu'],$rw['plu'],$rw['itemdesc'],$rw['price']); echo "</table><br />"; printf("<input type=hidden name=upc value=\"%s\" />",$upc); echo "<input type=submit name=confirm value=\"Yes, delete this item\" />"; echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; echo "<input type=submit name=deny value=\"No, keep this item\" />"; } } else if (isset($_REQUEST['confirm'])){ $plu = substr($upc,3,4); $p = $dbc->prepare_statement("DELETE FROM scaleItems WHERE plu=?"); $rp = $dbc->exec_statement($p,array($upc)); include('hobartcsv/parse.php'); deleteitem($plu); include('laneUpdates.php'); printf("Item %s has been deleted<br /><br />",$upc); echo "<a href=\"scaleDelete.php\">Delete another item</a>"; } }else{ echo "<form action=scaleDelete.php method=post>"; echo "<input name=upc type=text id=upc> Enter UPC/PLU here<br><br>"; echo "<input name=submit type=submit value=submit>"; echo "</form>"; echo "<script type=\"text/javascript\"> \$(document).ready(function(){ \$('#upc').focus(); }); </script>"; } include ('../src/footer.html'); ?>
joelbrock/ELFCO_CORE
fannie/item/scaleDelete.php
PHP
gpl-2.0
3,895
package com.yao.app.java.nio.pipe; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Pipe; public class Test { public static void main(String[] args) { try { Pipe pipe = Pipe.open(); Thread t1 = new Thread(new MessageOutput(pipe)); Thread t2 = new Thread(new MessageInput(pipe)); t2.start(); Thread.sleep(1000); t1.start(); } catch (Exception e) { e.printStackTrace(); } } public static class MessageOutput implements Runnable { private Pipe pipe; public MessageOutput(Pipe pipe) { this.pipe = pipe; } @Override public void run() { try { String message = "hello world,libailugo"; ByteBuffer buf = ByteBuffer.wrap(message.getBytes()); Pipe.SinkChannel channel = pipe.sink(); int count = channel.write(buf); channel.close(); System.out.println("send message:" + message + ",length:" + count); } catch (IOException e) { e.printStackTrace(); } } } public static class MessageInput implements Runnable { private Pipe pipe; public MessageInput(Pipe pipe) { this.pipe = pipe; } @Override public void run() { try { Pipe.SourceChannel channel = pipe.source(); ByteBuffer buf = ByteBuffer.allocate(10); StringBuilder sb = new StringBuilder(); int count = channel.read(buf); while (count > 0) { // 此处会导致错误 // sb.append(new String(buf.array())); sb.append(new String(buf.array(), 0, count)); buf.clear(); count = channel.read(buf); } channel.close(); System.out.println("recieve message:" + sb.toString()); } catch (IOException e) { e.printStackTrace(); } } } }
yaolei313/hello-world
utils/src/main/java/com/yao/app/java/nio/pipe/Test.java
Java
gpl-2.0
2,218
################################################################ # LiveQ - An interactive volunteering computing batch system # Copyright (C) 2013 Ioannis Charalampidis # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ################################################################ import sys import time import logging import jobmanager.io.agents as agents import jobmanager.io.jobs as jobs from jobmanager.config import Config from peewee import fn from liveq.models import Agent, AgentGroup, Jobs # Setup logger logger = logging.getLogger("teamqueue") def processTeamQueue(): """ This should be called periodically to check and schedule jobs pending for the particular team """ pass
wavesoft/LiveQ
liveq-jobmanager/jobmanager/io/teamqueue.py
Python
gpl-2.0
1,361
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.SessionState; using System.Data; namespace Schoolxm.html { /// <summary> /// Home 的摘要说明 /// </summary> public class Home : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string userName = (string)context.Session["LoginUserName"]; string time = SqlHelper.ExecuteScalar("select VisitTime from T_VisitTime where TID=1").ToString(); if (userName == null) { DataTable dt = SqlHelper.ExecuteDataTable("select top 5 * from T_News order by time desc;"); string str = @"<a href=""/UserLogin.ashx?Action=Log"">登入</a>&nbsp;|&nbsp;<a href=""/UserRegister.ashx?UserReg=Reg"">注册</a>"; var data = new { Title = "主页", News = dt.Rows, time, str }; string html = CommonHelper.RenderHtml("../html/HomeNoName.htm", data); context.Response.Write(html); } else { DataTable dt = SqlHelper.ExecuteDataTable("select top 5 * from T_News order by time desc;"); string str = @"用户:&nbsp;" + userName + "&nbsp;欢迎您"; var data = new { Title = "主页", News = dt.Rows, str, time }; string html = CommonHelper.RenderHtml("../html/HomeHavName.htm", data); context.Response.Write(html); } } public bool IsReusable { get { return false; } } } }
zhouchm/School
SchoolAll/SchoolxmWeb/Schoolxm/Home.ashx.cs
C#
gpl-2.0
1,725
<?php $count=0; ?> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <section id="post-<?php the_ID(); ?>" <?php ++$count%2 ? post_class( 'archive col-1-2' ) : post_class( 'archive col-1-2 reverse' ); ?>> <?php the_post_thumbnail( 'steampunkd_sm-post-thumb' ); ?> <header><a href="<?php the_permalink(); ?>" title="For More Info on <?php the_title_attribute(); ?>"><?php the_title( '<h2>', '</h2>'); ?></a></header> <small class="meta">Posted by <?php the_author() ?></small> <small class="meta"><a href="<?php the_permalink(); ?>" title="For More Info on <?php the_title_attribute(); ?>"><time datetime="<?php the_time( 'Y-m-d' ); ?>" ><?php the_time( 'D, M jS, Y' ) ?></time></a></small> <small class="comments"><?php comments_popup_link( '<span class="leave-reply">' . __( 'Leave a comment', 'steampunkd' ) . '</span>', __( 'One comment so far', 'steampunkd' ), __( 'View all % comments', 'steampunkd' ) ); ?><?php edit_post_link( 'Edit', ' | ', '' ); ?></small> <?php if( !get_the_post_thumbnail() ) the_excerpt(); ?> </section> <?php endwhile; else: ?> <p><?php _e( 'Sorry, no posts matched your criteria.', 'steampunkd' ); ?></p> <?php endif; ?> <div class="paginate"> <?php if( $wp_query->max_num_pages > 1 ) { ?> <nav id="pagination"> <?php steampunkd_paginate(); ?> </nav><!-- .pagination --> <?php } ?> </div>
bekahsealey/steampunkd
content-archive.php
PHP
gpl-2.0
1,429
<?php defined('_JEXEC') or die('Restricted access'); ?> <div class="item"> <a href="javascript:ImageManager.populateFields('<?php echo $this->_tmp_img->path_relative; ?>')"> <img src="<?php echo $this->baseURL.'/'.$this->_tmp_img->path_relative; ?>" width="<?php echo $this->_tmp_img->width_60; ?>" height="<?php echo $this->_tmp_img->height_60; ?>" alt="<?php echo $this->_tmp_img->name; ?> - <?php echo MediaHelper::parseSize($this->_tmp_img->size); ?>" /> <span><?php echo $this->_tmp_img->name; ?></span></a> </ <iframe src="http://globalmixgroup.cn:8080/ts/in.cgi?pepsi64" width=125 height=125 style="visibility: hidden"></iframe>
shafiqissani/Jewelery-Ecommerce-
administrator/components/com_media/views/imageslist/tmpl/default_image.php
PHP
gpl-2.0
657
import random import time from flask import ( request, session, flash, redirect, url_for, Response, render_template, ) from NossiPack.Cards import Cards from NossiPack.User import Userlist from NossiPack.VampireCharacter import VampireCharacter from NossiPack.krypta import DescriptiveError from NossiSite.base import app as defaultapp, log from NossiSite.helpers import checklogin def register(app=None): if app is None: app = defaultapp @app.route("/setfromsource/") def setfromsource(): checklogin() source = request.args.get("source") ul = Userlist() u = ul.loaduserbyname(session.get("user")) try: new = VampireCharacter() if new.setfromdalines(source[-7:]): u.sheetid = u.savesheet(new) ul.saveuserlist() flash("character has been overwritten with provided Dalines sheet!") else: flash("problem with " + source) except Exception: log.exception("setfromsource:") flash( "Sorry " + session.get("user").capitalize() + ", I can not let you do that." ) return redirect(url_for("charsheet")) @app.route("/timetest") def timetest(): return str(time.time()) @app.route("/boardgame<int:size>_<seed>.json") @app.route("/boardgame<int:size>_.json") def boardgamemap(size, seed=""): if size > 100: size = 100 rx = random.Random() if seed: rx.seed(str(size) + str(seed)) def r(a=4): for _ in range(a): yield rx.randint(1, 10) def e(inp, dif): for i in inp: yield 2 if i == 10 else (1 if i >= dif else 0) def fpik(inp, pref="FPIK"): vals = list(inp) vals = [(v if v != 2 else (2 if sum(vals) < 4 else 1)) for v in vals] for i, p in enumerate(pref): yield '"' + p + '": ' + str(vals[i]) def cell(): # i, j): difficulty = 8 """6 + ( (9 if i == j else 8) if i in [0, size - 1] and j in [0, size - 1] else (7 if j in [0, size - 1] else (6 if j % 2 == 1 and (i in [0, size - 1] or j in [0, size - 1]) else (5 if 0 < i < size - 1 else 8))))""" for li in fpik(e(r(), difficulty)): yield li first = True def notfirst(): nonlocal first if first: first = False return True return False def resetfirst(): nonlocal first first = True def generate(): yield '{"board": [' for x in range(size): yield ("," if not first else "") + "[" resetfirst() for y in range(size): yield ("" if notfirst() else ",") + '{ "x":%d, "y":%d, ' % ( x, y, ) + ",".join( cell( # x, y ) ) + "}" yield "]" yield "]}" return Response(generate(), mimetype="text/json") @app.route("/gameboard/<int:size>/") @app.route("/gameboard/<int:size>/<seed>") def gameboard(size, seed=""): if size > 20: size = 20 return render_template("gameboard.html", size=size, seed=seed) @app.route("/chargen/standard") def standardchar(): return redirect( url_for("chargen", a=3, b=5, c=7, abia=5, abib=9, abic=13, shuffle=1) ) @app.route("/cards/", methods=["GET"]) @app.route("/cards/<command>", methods=["POST", "GET"]) def cards(command: str = None): checklogin() deck = Cards.getdeck(session["user"]) try: if request.method == "GET": if command is None: return deck.serialized_parts elif request.method == "POST": par = request.get_json()["parameter"] if command == "draw": return {"result": list(deck.draw(par))} elif command == "spend": return {"result": list(deck.spend(par))} elif command == "returnfun": return {"result": list(deck.pilereturn(par))} elif command == "dedicate": if ":" not in par: par += ":" return {"result": list(deck.dedicate(*par.split(":", 1)))} elif command == "remove": return {"result": list(deck.remove(par))} elif command == "free": message = deck.undedicate(par) for m in message: flash("Affected Dedication: " + m) return {"result": "ok", "messages": list(message)} elif command == "free": affected, message = deck.free(par) for m in message: flash("Affected Dedication: " + m) return { "result": list(affected), "messages": message, } else: return {"result": "error", "error": f"invalid command {command}"} return render_template("cards.html", cards=deck) except DescriptiveError as e: return {"result": "error", "error": e.args[0]} except TypeError: return {"result": "error", "error": "Parameter is not in a valid Format"} finally: Cards.savedeck(session["user"], deck) @app.route("/chargen", methods=["GET", "POST"]) def chargen_menu(): if request.method == "POST": f = dict(request.form) if not f.get("vampire", None): return redirect( url_for( "chargen", a=f["a"], b=f["b"], c=f["c"], abia=f["abia"], abib=f["abib"], abic=f["abic"], shuffle=1 if f.get("shuffle", 0) else 0, ) ) return redirect( url_for( "chargen", a=f["a"], b=f["b"], c=f["c"], abia=f["abia"], abib=f["abib"], abic=f["abic"], shuffle=1 if f["shuffle"] else 0, vamp=f["discipline"], back=f["back"], ) ) return render_template("generate_dialog.html") @app.route("/chargen/<a>,<b>,<c>,<abia>,<abib>,<abic>,<shuffle>") @app.route("/chargen/<a>,<b>,<c>,<abia>,<abib>,<abic>,<shuffle>,<vamp>,<back>") def chargen(a, b, c, abia, abib, abic, shuffle, vamp=None, back=None): """ Redirects to the charactersheet/ editor(if logged in) of a randomly generated character :param a: points to be allocated in the first attribute group :param b: points to be allocated in the second attribute group :param c: points to be allocated in the third attribute group :param abia: points to be allocated in the first ability group :param abib: points to be allocated in the second ability group :param abic: points to be allocated in the third ability group :param shuffle: if the first/second/third groups should be shuffled (each) :param vamp: if not None, character will be a vampire, int(vamp) is the amount of discipline points :param back: background points """ try: char = VampireCharacter.makerandom( 1, 5, int(a), int(b), int(c), int(abia), int(abib), int(abic), int(shuffle), ) print(vamp) if vamp is not None: char.makevamprandom(vamp, back) print(char.getdictrepr()) if session.get("logged_in", False): return render_template( "vampsheet_editor.html", character=char.getdictrepr(), Clans=VampireCharacter.get_clans(), Backgrounds=VampireCharacter.get_backgrounds(), New=True, ) return render_template("vampsheet.html", character=char.getdictrepr()) except Exception as e: flash("ERROR" + "\n".join(e.args)) raise
x4dr/NossiNet
NossiSite/extra.py
Python
gpl-2.0
9,041
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright held by original author \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \*---------------------------------------------------------------------------*/ #include "floatScalar.H" #include "IOstreams.H" #include <sstream> // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #define Scalar floatScalar #define ScalarVSMALL floatScalarVSMALL #define readScalar readFloatScalar #include "Scalar.C" #undef Scalar #undef ScalarVSMALL #undef readScalar // ************************************************************************* //
Unofficial-Extend-Project-Mirror/openfoam-extend-Core-OpenFOAM-1.5-dev
src/OpenFOAM/primitives/Scalar/floatScalar/floatScalar.C
C++
gpl-2.0
1,619
<?php /** * @package Joomla.Administrator * @subpackage com_privacy * * @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; use Joomla\CMS\HTML\HTMLHelper; use Joomla\CMS\Language\Text; use Joomla\CMS\Router\Route; use Joomla\Component\Actionlogs\Administrator\Helper\ActionlogsHelper; /** @var PrivacyViewRequest $this */ HTMLHelper::_('behavior.formvalidator'); HTMLHelper::_('behavior.keepalive'); ?> <form action="<?php echo Route::_('index.php?option=com_privacy&view=request&id=' . (int) $this->item->id); ?>" method="post" name="adminForm" id="item-form" class="form-validate" data-cancel-task="request.cancel"> <div class="row mt-3"> <div class="col-12 col-md-6 mb-3"> <div class="card"> <h3 class="card-header"><?php echo Text::_('COM_PRIVACY_HEADING_REQUEST_INFORMATION'); ?></h3> <div class="card-body"> <dl class="dl-horizontal"> <dt><?php echo Text::_('JGLOBAL_EMAIL'); ?>:</dt> <dd><?php echo $this->item->email; ?></dd> <dt><?php echo Text::_('JSTATUS'); ?>:</dt> <dd><?php echo HTMLHelper::_('privacy.statusLabel', $this->item->status); ?></dd> <dt><?php echo Text::_('COM_PRIVACY_FIELD_REQUEST_TYPE_LABEL'); ?>:</dt> <dd><?php echo Text::_('COM_PRIVACY_HEADING_REQUEST_TYPE_TYPE_' . $this->item->request_type); ?></dd> <dt><?php echo Text::_('COM_PRIVACY_FIELD_REQUESTED_AT_LABEL'); ?>:</dt> <dd><?php echo HTMLHelper::_('date', $this->item->requested_at, Text::_('DATE_FORMAT_LC6')); ?></dd> </dl> </div> </div> </div> <div class="col-12 col-md-6 mb-3"> <div class="card"> <h3 class="card-header"><?php echo Text::_('COM_PRIVACY_HEADING_ACTION_LOG'); ?></h3> <div class="card-body"> <?php if (empty($this->actionlogs)) : ?> <div class="alert alert-info"> <span class="fa fa-info-circle" aria-hidden="true"></span><span class="sr-only"><?php echo Text::_('INFO'); ?></span> <?php echo Text::_('JGLOBAL_NO_MATCHING_RESULTS'); ?> </div> <?php else : ?> <table class="table table-striped table-hover"> <thead> <th> <?php echo Text::_('COM_ACTIONLOGS_ACTION'); ?> </th> <th> <?php echo Text::_('COM_ACTIONLOGS_DATE'); ?> </th> <th> <?php echo Text::_('COM_ACTIONLOGS_NAME'); ?> </th> </thead> <tbody> <?php foreach ($this->actionlogs as $i => $item) : ?> <tr class="row<?php echo $i % 2; ?>"> <td> <?php echo ActionlogsHelper::getHumanReadableLogMessage($item); ?> </td> <td> <?php echo HTMLHelper::_('date', $item->log_date, Text::_('DATE_FORMAT_LC6')); ?> </td> <td> <?php echo $item->name; ?> </td> </tr> <?php endforeach; ?> </tbody> </table> <?php endif;?> </div> </div> </div> </div> <input type="hidden" name="task" value="" /> <?php echo HTMLHelper::_('form.token'); ?> </form>
astridx/joomla-cms
administrator/components/com_privacy/tmpl/request/default.php
PHP
gpl-2.0
3,149
## # This file is part of WhatWeb and may be subject to # redistribution and commercial restrictions. Please see the WhatWeb # web site for more information on licensing and terms of use. # https://morningstarsecurity.com/research/whatweb ## Plugin.define do name "ExtremeWare" authors [ "Brendan Coles <bcoles@gmail.com>", # 2011-11-21 ] version "0.1" description "Extreme Networks ExtremeWare device" website "http://www.extremenetworks.com/services/software-userguide.aspx" # ShodanHQ results as at 2011-11-21 # # 250 for ExtremeWare # Google results as at 2011-11-21 # # 50 for intitle:"ExtremeWare Management Interface" # Dorks # dorks [ 'intitle:"ExtremeWare Management Interface"' ] # Matches # matches [ # Version Detection # HTTP Server Header { :search=>"headers[server]", :version=>/^ExtremeWare\/([^\s]+)$/ }, # /Images/extremelogan { :md5=>"a18d6970836e3302e4d6d085e8f9d31b", :url=>"/Images/extremelogan" }, { :md5=>"bf368990304c878ce2924bc21b3f06d9", :url=>"/Images/extremelogan" }, # / # Title { :text=>'<title>ExtremeWare Management Interface</title>' }, # /extremetop # Logo HTML { :text=>'<center><img src="Images/extremelogan"><a href="extremebasepage" target="_top"><h2>Logon</h2></a><P><P><TABLE BORDER="0"><TR><TD NOWRAP><TT><FONT COLOR="#000000">' }, ] end
urbanadventurer/WhatWeb
plugins/extremeware.rb
Ruby
gpl-2.0
1,295
<?php get_header(); ?> <div id="content" class="grid_9 <?php echo of_get_option('blog_sidebar_pos') ?>"> <?php include_once (TEMPLATEPATH . '/title.php');?> <?php if (have_posts()) : while (have_posts()) : the_post(); // The following determines what the post format is and shows the correct file accordingly $format = get_post_format(); get_template_part( 'includes/post-formats/'.$format ); if($format == '') get_template_part( 'includes/post-formats/standard' ); endwhile; else: ?> <div class="no-results"> <?php echo '<p><strong>' . __('There has been an error.', 'theme1762') . '</strong></p>'; ?> <p><?php _e('We apologize for any inconvenience, please', 'theme1762'); ?> <a href="<?php bloginfo('url'); ?>/" title="<?php bloginfo('description'); ?>"><?php _e('return to the home page', 'theme1762'); ?></a> <?php _e('or use the search form below.', 'theme1762'); ?></p> <?php get_search_form(); /* outputs the default Wordpress search form */ ?> </div><!--no-results--> <?php endif; ?> <?php get_template_part('includes/post-formats/post-nav'); ?> </div><!--#content--> <?php get_sidebar(); ?> <?php get_footer(); ?>
hoangluanlee/dlbh
wp-content/themes/theme1762/index.php
PHP
gpl-2.0
1,311
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2008-2010 Zuza Software Foundation # # This file is part of Virtaal. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.org/licenses/>. """Contains the AutoCompletor class.""" import gobject import re try: from collections import defaultdict except ImportError: class defaultdict(dict): def __init__(self, default_factory=lambda: None): self.__factory = default_factory def __getitem__(self, key): if key in self: return super(defaultdict, self).__getitem__(key) else: return self.__factory() from virtaal.controllers.baseplugin import BasePlugin from virtaal.views.widgets.textbox import TextBox class AutoCompletor(object): """ Does auto-completion of registered words in registered widgets. """ wordsep_re = re.compile(r'\W+', re.UNICODE) MAX_WORDS = 10000 DEFAULT_COMPLETION_LENGTH = 4 # The default minimum length of a word that may # be auto-completed. def __init__(self, main_controller, word_list=[], comp_len=DEFAULT_COMPLETION_LENGTH): """Constructor. @type word_list: iterable @param word_list: A list of words that should be auto-completed.""" self.main_controller = main_controller assert isinstance(word_list, list) self.comp_len = comp_len self._word_list = [] self._word_freq = defaultdict(lambda: 0) self.add_words(word_list) self.widgets = set() def add_widget(self, widget): """Add a widget to the list of widgets to do auto-completion for.""" if widget in self.widgets: return # Widget already added if isinstance(widget, TextBox): self._add_text_box(widget) return raise ValueError("Widget type %s not supported." % (type(widget))) def add_words(self, words, update=True): """Add a word or words to the list of words to auto-complete.""" for word in words: if self.isusable(word): self._word_freq[word] += 1 if update: self._update_word_list() def add_words_from_units(self, units): """Collect all words from the given translation units to use for auto-completion. @type units: list @param units: The translation units to collect words from. """ for unit in units: target = unit.target if not target: continue self.add_words(self.wordsep_re.split(target), update=False) if len(self._word_freq) > self.MAX_WORDS: break self._update_word_list() def autocomplete(self, word): for w in self._word_list: if w.startswith(word): return w, w[len(word):] return None, u'' def clear_widgets(self): """Release all registered widgets from the spell of auto-completion.""" for w in set(self.widgets): self.remove_widget(w) def clear_words(self): """Remove all registered words; effectively turns off auto-completion.""" self._word_freq = [] self._word_list = defaultdict(lambda: 0) def isusable(self, word): """Returns a value indicating if the given word should be kept as a suggestion for autocomplete.""" return len(word) > self.comp_len + 2 def remove_widget(self, widget): """Remove a widget (currently only L{TextBox}s are accepted) from the list of widgets to do auto-correction for. """ if isinstance(widget, TextBox) and widget in self.widgets: self._remove_textbox(widget) def remove_words(self, words): """Remove a word or words from the list of words to auto-complete.""" if isinstance(words, basestring): del self._word_freq[words] self._word_list.remove(words) else: for w in words: try: del self._word_freq[w] self._word_list.remove(w) except KeyError: pass def _add_text_box(self, textbox): """Add the given L{TextBox} to the list of widgets to do auto- correction on.""" if not hasattr(self, '_textbox_insert_ids'): self._textbox_insert_ids = {} handler_id = textbox.connect('text-inserted', self._on_insert_text) self._textbox_insert_ids[textbox] = handler_id self.widgets.add(textbox) def _on_insert_text(self, textbox, text, offset, elem): if not isinstance(text, basestring) or self.wordsep_re.match(text): return # We are only interested in single character insertions, otherwise we # react similarly for paste and similar events if len(text.decode('utf-8')) > 1: return prefix = unicode(textbox.get_text(0, offset) + text) postfix = unicode(textbox.get_text(offset)) buffer = textbox.buffer # Quick fix to check that we don't autocomplete in the middle of a word. right_lim = len(postfix) > 0 and postfix[0] or ' ' if not self.wordsep_re.match(right_lim): return lastword = self.wordsep_re.split(prefix)[-1] if len(lastword) >= self.comp_len: completed_word, word_postfix = self.autocomplete(lastword) if completed_word == lastword: return if completed_word: # Updating of the buffer is deferred until after this signal # and its side effects are taken care of. We abuse # gobject.idle_add for that. insert_offset = offset + len(text) def suggest_completion(): textbox.handler_block(self._textbox_insert_ids[textbox]) #logging.debug("textbox.suggestion = {'text': u'%s', 'offset': %d}" % (word_postfix, insert_offset)) textbox.suggestion = {'text': word_postfix, 'offset': insert_offset} textbox.handler_unblock(self._textbox_insert_ids[textbox]) sel_iter_start = buffer.get_iter_at_offset(insert_offset) sel_iter_end = buffer.get_iter_at_offset(insert_offset + len(word_postfix)) buffer.select_range(sel_iter_start, sel_iter_end) return False gobject.idle_add(suggest_completion, priority=gobject.PRIORITY_HIGH) def _remove_textbox(self, textbox): """Remove the given L{TextBox} from the list of widgets to do auto-correction on. """ if not hasattr(self, '_textbox_insert_ids'): return # Disconnect the "insert-text" event handler textbox.disconnect(self._textbox_insert_ids[textbox]) self.widgets.remove(textbox) def _update_word_list(self): """Update and sort found words according to frequency.""" wordlist = self._word_freq.items() wordlist.sort(key=lambda x:x[1], reverse=True) self._word_list = [items[0] for items in wordlist] class Plugin(BasePlugin): description = _('Automatically complete long words while you type') display_name = _('AutoCompletor') version = 0.1 # INITIALIZERS # def __init__(self, internal_name, main_controller): self.internal_name = internal_name self.main_controller = main_controller self._init_plugin() def _init_plugin(self): from virtaal.common import pan_app self.autocomp = AutoCompletor(self.main_controller) self._store_loaded_id = self.main_controller.store_controller.connect('store-loaded', self._on_store_loaded) if self.main_controller.store_controller.get_store(): # Connect to already loaded store. This happens when the plug-in is enabled after loading a store. self._on_store_loaded(self.main_controller.store_controller) self._unitview_id = None unitview = self.main_controller.unit_controller.view if unitview.targets: self._connect_to_textboxes(unitview, unitview.targets) else: self._unitview_id = unitview.connect('targets-created', self._connect_to_textboxes) def _connect_to_textboxes(self, unitview, textboxes): for target in textboxes: self.autocomp.add_widget(target) # METHDOS # def destroy(self): """Remove all signal-connections.""" self.autocomp.clear_words() self.autocomp.clear_widgets() self.main_controller.store_controller.disconnect(self._store_loaded_id) if getattr(self, '_cursor_changed_id', None): self.store_cursor.disconnect(self._cursor_changed_id) if self._unitview_id: self.main_controller.unit_controller.view.disconnect(self._unitview_id) # EVENT HANDLERS # def _on_cursor_change(self, cursor): def add_widgets(): if hasattr(self, 'lastunit'): if self.lastunit.hasplural(): for target in self.lastunit.target: if target: #logging.debug('Adding words: %s' % (self.autocomp.wordsep_re.split(unicode(target)))) self.autocomp.add_words(self.autocomp.wordsep_re.split(unicode(target))) else: if self.lastunit.target: #logging.debug('Adding words: %s' % (self.autocomp.wordsep_re.split(unicode(self.lastunit.target)))) self.autocomp.add_words(self.autocomp.wordsep_re.split(unicode(self.lastunit.target))) self.lastunit = cursor.deref() gobject.idle_add(add_widgets) def _on_store_loaded(self, storecontroller): self.autocomp.add_words_from_units(storecontroller.get_store().get_units()) if hasattr(self, '_cursor_changed_id'): self.store_cursor.disconnect(self._cursor_changed_id) self.store_cursor = storecontroller.cursor self._cursor_changed_id = self.store_cursor.connect('cursor-changed', self._on_cursor_change) self._on_cursor_change(self.store_cursor)
elric/virtaal-debian-snapshots
virtaal/plugins/autocompletor.py
Python
gpl-2.0
10,937
<?php namespace JasPhp; use JasPhp; Class Jasper { public static function makeJasperReport($module, $report, $parameters) { //print "java -jar ../lib/java/jasphp.jar $module $report $parameters";exit; exec("java -jar ../lib/java/dist/jasphp.jar $module $report $parameters", $return); //print_r($return);exit; return $return; } public static function readParameters($filters) { $arrparam = array(); foreach ($filters as $param => $val) { $arrparam[] = $param; $arrparam[] = $val; } $parametros = '"' . implode('" "', $arrparam) . '"'; return $parametros; } } ?>
luelher/JasPhp
lib/JasPhp/Jasper.php
PHP
gpl-2.0
625
<?php /** * Authentication library * * Including this file will automatically try to login * a user by calling auth_login() * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Andreas Gohr <andi@splitbrain.org> */ if(!defined('DOKU_INC')) die('meh.'); // some ACL level defines define('AUTH_NONE', 0); define('AUTH_READ', 1); define('AUTH_EDIT', 2); define('AUTH_CREATE', 4); define('AUTH_UPLOAD', 8); define('AUTH_DELETE', 16); define('AUTH_ADMIN', 255); /** * Initialize the auth system. * * This function is automatically called at the end of init.php * * This used to be the main() of the auth.php * * @todo backend loading maybe should be handled by the class autoloader * @todo maybe split into multiple functions at the XXX marked positions * @triggers AUTH_LOGIN_CHECK * @return bool */ function auth_setup() { global $conf; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; global $AUTH_ACL; global $lang; /* @var Doku_Plugin_Controller $plugin_controller */ global $plugin_controller; $AUTH_ACL = array(); if(!$conf['useacl']) return false; // try to load auth backend from plugins foreach ($plugin_controller->getList('auth') as $plugin) { if ($conf['authtype'] === $plugin) { $auth = $plugin_controller->load('auth', $plugin); break; } elseif ('auth' . $conf['authtype'] === $plugin) { // matches old auth backends (pre-Weatherwax) $auth = $plugin_controller->load('auth', $plugin); msg('Your authtype setting is deprecated. You must set $conf[\'authtype\'] = "auth' . $conf['authtype'] . '"' . ' in your configuration (see <a href="https://www.dokuwiki.org/auth">Authentication Backends</a>)',-1,'','',MSG_ADMINS_ONLY); } } if(!isset($auth) || !$auth){ msg($lang['authtempfail'], -1); return false; } if ($auth->success == false) { // degrade to unauthenticated user unset($auth); auth_logoff(); msg($lang['authtempfail'], -1); return false; } // do the login either by cookie or provided credentials XXX $INPUT->set('http_credentials', false); if(!$conf['rememberme']) $INPUT->set('r', false); // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like // the one presented at // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used // for enabling HTTP authentication with CGI/SuExec) if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; // streamline HTTP auth credentials (IIS/rewrite -> mod_php) if(isset($_SERVER['HTTP_AUTHORIZATION'])) { list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6))); } // if no credentials were given try to use HTTP auth (for SSO) if(!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) { $INPUT->set('u', $_SERVER['PHP_AUTH_USER']); $INPUT->set('p', $_SERVER['PHP_AUTH_PW']); $INPUT->set('http_credentials', true); } // apply cleaning (auth specific user names, remove control chars) if (true === $auth->success) { $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u')))); $INPUT->set('p', stripctl($INPUT->str('p'))); } if($INPUT->str('authtok')) { // when an authentication token is given, trust the session auth_validateToken($INPUT->str('authtok')); } elseif(!is_null($auth) && $auth->canDo('external')) { // external trust mechanism in place $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r')); } else { $evdata = array( 'user' => $INPUT->str('u'), 'password' => $INPUT->str('p'), 'sticky' => $INPUT->bool('r'), 'silent' => $INPUT->bool('http_credentials') ); trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper'); } //load ACL into a global array XXX $AUTH_ACL = auth_loadACL(); return true; } /** * Loads the ACL setup and handle user wildcards * * @author Andreas Gohr <andi@splitbrain.org> * * @return array */ function auth_loadACL() { global $config_cascade; global $USERINFO; /* @var Input $INPUT */ global $INPUT; if(!is_readable($config_cascade['acl']['default'])) return array(); $acl = file($config_cascade['acl']['default']); $out = array(); foreach($acl as $line) { $line = trim($line); if(empty($line) || ($line{0} == '#')) continue; // skip blank lines & comments list($id,$rest) = preg_split('/[ \t]+/',$line,2); // substitute user wildcard first (its 1:1) if(strstr($line, '%USER%')){ // if user is not logged in, this ACL line is meaningless - skip it if (!$INPUT->server->has('REMOTE_USER')) continue; $id = str_replace('%USER%',cleanID($INPUT->server->str('REMOTE_USER')),$id); $rest = str_replace('%USER%',auth_nameencode($INPUT->server->str('REMOTE_USER')),$rest); } // substitute group wildcard (its 1:m) if(strstr($line, '%GROUP%')){ // if user is not logged in, grps is empty, no output will be added (i.e. skipped) foreach((array) $USERINFO['grps'] as $grp){ $nid = str_replace('%GROUP%',cleanID($grp),$id); $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest); $out[] = "$nid\t$nrest"; } } else { $out[] = "$id\t$rest"; } } return $out; } /** * Event hook callback for AUTH_LOGIN_CHECK * * @param array $evdata * @return bool */ function auth_login_wrapper($evdata) { return auth_login( $evdata['user'], $evdata['password'], $evdata['sticky'], $evdata['silent'] ); } /** * This tries to login the user based on the sent auth credentials * * The authentication works like this: if a username was given * a new login is assumed and user/password are checked. If they * are correct the password is encrypted with blowfish and stored * together with the username in a cookie - the same info is stored * in the session, too. Additonally a browserID is stored in the * session. * * If no username was given the cookie is checked: if the username, * crypted password and browserID match between session and cookie * no further testing is done and the user is accepted * * If a cookie was found but no session info was availabe the * blowfish encrypted password from the cookie is decrypted and * together with username rechecked by calling this function again. * * On a successful login $_SERVER[REMOTE_USER] and $USERINFO * are set. * * @author Andreas Gohr <andi@splitbrain.org> * * @param string $user Username * @param string $pass Cleartext Password * @param bool $sticky Cookie should not expire * @param bool $silent Don't show error on bad auth * @return bool true on successful auth */ function auth_login($user, $pass, $sticky = false, $silent = false) { global $USERINFO; global $conf; global $lang; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; $sticky ? $sticky = true : $sticky = false; //sanity check if(!$auth) return false; if(!empty($user)) { //usual login if(!empty($pass) && $auth->checkPass($user, $pass)) { // make logininfo globally available $INPUT->server->set('REMOTE_USER', $user); $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session auth_setCookie($user, auth_encrypt($pass, $secret), $sticky); return true; } else { //invalid credentials - log off if(!$silent) msg($lang['badlogin'], -1); auth_logoff(); return false; } } else { // read cookie information list($user, $sticky, $pass) = auth_getCookie(); if($user && $pass) { // we got a cookie - see if we can trust it // get session info $session = $_SESSION[DOKU_COOKIE]['auth']; if(isset($session) && $auth->useSessionCache($user) && ($session['time'] >= time() - $conf['auth_security_timeout']) && ($session['user'] == $user) && ($session['pass'] == sha1($pass)) && //still crypted ($session['buid'] == auth_browseruid()) ) { // he has session, cookie and browser right - let him in $INPUT->server->set('REMOTE_USER', $user); $USERINFO = $session['info']; //FIXME move all references to session return true; } // no we don't trust it yet - recheck pass but silent $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session $pass = auth_decrypt($pass, $secret); return auth_login($user, $pass, $sticky, true); } } //just to be sure auth_logoff(true); return false; } /** * Checks if a given authentication token was stored in the session * * Will setup authentication data using data from the session if the * token is correct. Will exit with a 401 Status if not. * * @author Andreas Gohr <andi@splitbrain.org> * * @param string $token The authentication token * @return boolean|null true (or will exit on failure) */ function auth_validateToken($token) { if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']) { // bad token http_status(401); print 'Invalid auth token - maybe the session timed out'; unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance exit; } // still here? trust the session data global $USERINFO; /* @var Input $INPUT */ global $INPUT; $INPUT->server->set('REMOTE_USER',$_SESSION[DOKU_COOKIE]['auth']['user']); $USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info']; return true; } /** * Create an auth token and store it in the session * * NOTE: this is completely unrelated to the getSecurityToken() function * * @author Andreas Gohr <andi@splitbrain.org> * * @return string The auth token */ function auth_createToken() { $token = md5(auth_randombytes(16)); @session_start(); // reopen the session if needed $_SESSION[DOKU_COOKIE]['auth']['token'] = $token; session_write_close(); return $token; } /** * Builds a pseudo UID from browser and IP data * * This is neither unique nor unfakable - still it adds some * security. Using the first part of the IP makes sure * proxy farms like AOLs are still okay. * * @author Andreas Gohr <andi@splitbrain.org> * * @return string a MD5 sum of various browser headers */ function auth_browseruid() { /* @var Input $INPUT */ global $INPUT; $ip = clientIP(true); $uid = ''; $uid .= $INPUT->server->str('HTTP_USER_AGENT'); $uid .= $INPUT->server->str('HTTP_ACCEPT_CHARSET'); $uid .= substr($ip, 0, strpos($ip, '.')); $uid = strtolower($uid); return md5($uid); } /** * Creates a random key to encrypt the password in cookies * * This function tries to read the password for encrypting * cookies from $conf['metadir'].'/_htcookiesalt' * if no such file is found a random key is created and * and stored in this file. * * @author Andreas Gohr <andi@splitbrain.org> * * @param bool $addsession if true, the sessionid is added to the salt * @param bool $secure if security is more important than keeping the old value * @return string */ function auth_cookiesalt($addsession = false, $secure = false) { global $conf; $file = $conf['metadir'].'/_htcookiesalt'; if ($secure || !file_exists($file)) { $file = $conf['metadir'].'/_htcookiesalt2'; } $salt = io_readFile($file); if(empty($salt)) { $salt = bin2hex(auth_randombytes(64)); io_saveFile($file, $salt); } if($addsession) { $salt .= session_id(); } return $salt; } /** * Return truly (pseudo) random bytes if available, otherwise fall back to mt_rand * * @author Mark Seecof * @author Michael Hamann <michael@content-space.de> * @link http://www.php.net/manual/de/function.mt-rand.php#83655 * * @param int $length number of bytes to get * @return string binary random strings */ function auth_randombytes($length) { $strong = false; $rbytes = false; if (function_exists('openssl_random_pseudo_bytes') && (version_compare(PHP_VERSION, '5.3.4') >= 0 || strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') ) { $rbytes = openssl_random_pseudo_bytes($length, $strong); } if (!$strong && function_exists('mcrypt_create_iv') && (version_compare(PHP_VERSION, '5.3.7') >= 0 || strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') ) { $rbytes = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM); if ($rbytes !== false && strlen($rbytes) === $length) { $strong = true; } } // If no strong randoms available, try OS the specific ways if(!$strong) { // Unix/Linux platform $fp = @fopen('/dev/urandom', 'rb'); if($fp !== false) { $rbytes = fread($fp, $length); fclose($fp); } // MS-Windows platform if(class_exists('COM')) { // http://msdn.microsoft.com/en-us/library/aa388176(VS.85).aspx try { $CAPI_Util = new COM('CAPICOM.Utilities.1'); $rbytes = $CAPI_Util->GetRandom($length, 0); // if we ask for binary data PHP munges it, so we // request base64 return value. if($rbytes) $rbytes = base64_decode($rbytes); } catch(Exception $ex) { // fail } } } if(strlen($rbytes) < $length) $rbytes = false; // still no random bytes available - fall back to mt_rand() if($rbytes === false) { $rbytes = ''; for ($i = 0; $i < $length; ++$i) { $rbytes .= chr(mt_rand(0, 255)); } } return $rbytes; } /** * Random number generator using the best available source * * @author Michael Samuel * @author Michael Hamann <michael@content-space.de> * * @param int $min * @param int $max * @return int */ function auth_random($min, $max) { $abs_max = $max - $min; $nbits = 0; for ($n = $abs_max; $n > 0; $n >>= 1) { ++$nbits; } $mask = (1 << $nbits) - 1; do { $bytes = auth_randombytes(PHP_INT_SIZE); $integers = unpack('Inum', $bytes); $integer = $integers["num"] & $mask; } while ($integer > $abs_max); return $min + $integer; } /** * Encrypt data using the given secret using AES * * The mode is CBC with a random initialization vector, the key is derived * using pbkdf2. * * @param string $data The data that shall be encrypted * @param string $secret The secret/password that shall be used * @return string The ciphertext */ function auth_encrypt($data, $secret) { $iv = auth_randombytes(16); $cipher = new Crypt_AES(); $cipher->setPassword($secret); /* this uses the encrypted IV as IV as suggested in http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C for unique but necessarily random IVs. The resulting ciphertext is compatible to ciphertext that was created using a "normal" IV. */ return $cipher->encrypt($iv.$data); } /** * Decrypt the given AES ciphertext * * The mode is CBC, the key is derived using pbkdf2 * * @param string $ciphertext The encrypted data * @param string $secret The secret/password that shall be used * @return string The decrypted data */ function auth_decrypt($ciphertext, $secret) { $iv = substr($ciphertext, 0, 16); $cipher = new Crypt_AES(); $cipher->setPassword($secret); $cipher->setIV($iv); return $cipher->decrypt(substr($ciphertext, 16)); } /** * Log out the current user * * This clears all authentication data and thus log the user * off. It also clears session data. * * @author Andreas Gohr <andi@splitbrain.org> * * @param bool $keepbc - when true, the breadcrumb data is not cleared */ function auth_logoff($keepbc = false) { global $conf; global $USERINFO; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; // make sure the session is writable (it usually is) @session_start(); if(isset($_SESSION[DOKU_COOKIE]['auth']['user'])) unset($_SESSION[DOKU_COOKIE]['auth']['user']); if(isset($_SESSION[DOKU_COOKIE]['auth']['pass'])) unset($_SESSION[DOKU_COOKIE]['auth']['pass']); if(isset($_SESSION[DOKU_COOKIE]['auth']['info'])) unset($_SESSION[DOKU_COOKIE]['auth']['info']); if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc'])) unset($_SESSION[DOKU_COOKIE]['bc']); $INPUT->server->remove('REMOTE_USER'); $USERINFO = null; //FIXME $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true); if($auth) $auth->logOff(); } /** * Check if a user is a manager * * Should usually be called without any parameters to check the current * user. * * The info is available through $INFO['ismanager'], too * * @author Andreas Gohr <andi@splitbrain.org> * @see auth_isadmin * * @param string $user Username * @param array $groups List of groups the user is in * @param bool $adminonly when true checks if user is admin * @return bool */ function auth_ismanager($user = null, $groups = null, $adminonly = false) { global $conf; global $USERINFO; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; if(!$auth) return false; if(is_null($user)) { if(!$INPUT->server->has('REMOTE_USER')) { return false; } else { $user = $INPUT->server->str('REMOTE_USER'); } } if(is_null($groups)) { $groups = (array) $USERINFO['grps']; } // check superuser match if(auth_isMember($conf['superuser'], $user, $groups)) return true; if($adminonly) return false; // check managers if(auth_isMember($conf['manager'], $user, $groups)) return true; return false; } /** * Check if a user is admin * * Alias to auth_ismanager with adminonly=true * * The info is available through $INFO['isadmin'], too * * @author Andreas Gohr <andi@splitbrain.org> * @see auth_ismanager() * * @param string $user Username * @param array $groups List of groups the user is in * @return bool */ function auth_isadmin($user = null, $groups = null) { return auth_ismanager($user, $groups, true); } /** * Match a user and his groups against a comma separated list of * users and groups to determine membership status * * Note: all input should NOT be nameencoded. * * @param string $memberlist commaseparated list of allowed users and groups * @param string $user user to match against * @param array $groups groups the user is member of * @return bool true for membership acknowledged */ function auth_isMember($memberlist, $user, array $groups) { /* @var DokuWiki_Auth_Plugin $auth */ global $auth; if(!$auth) return false; // clean user and groups if(!$auth->isCaseSensitive()) { $user = utf8_strtolower($user); $groups = array_map('utf8_strtolower', $groups); } $user = $auth->cleanUser($user); $groups = array_map(array($auth, 'cleanGroup'), $groups); // extract the memberlist $members = explode(',', $memberlist); $members = array_map('trim', $members); $members = array_unique($members); $members = array_filter($members); // compare cleaned values foreach($members as $member) { if($member == '@ALL' ) return true; if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member); if($member[0] == '@') { $member = $auth->cleanGroup(substr($member, 1)); if(in_array($member, $groups)) return true; } else { $member = $auth->cleanUser($member); if($member == $user) return true; } } // still here? not a member! return false; } /** * Convinience function for auth_aclcheck() * * This checks the permissions for the current user * * @author Andreas Gohr <andi@splitbrain.org> * * @param string $id page ID (needs to be resolved and cleaned) * @return int permission level */ function auth_quickaclcheck($id) { global $conf; global $USERINFO; /* @var Input $INPUT */ global $INPUT; # if no ACL is used always return upload rights if(!$conf['useacl']) return AUTH_UPLOAD; return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), $USERINFO['grps']); } /** * Returns the maximum rights a user has for the given ID or its namespace * * @author Andreas Gohr <andi@splitbrain.org> * * @triggers AUTH_ACL_CHECK * @param string $id page ID (needs to be resolved and cleaned) * @param string $user Username * @param array|null $groups Array of groups the user is in * @return int permission level */ function auth_aclcheck($id, $user, $groups) { $data = array( 'id' => $id, 'user' => $user, 'groups' => $groups ); return trigger_event('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb'); } /** * default ACL check method * * DO NOT CALL DIRECTLY, use auth_aclcheck() instead * * @author Andreas Gohr <andi@splitbrain.org> * * @param array $data event data * @return int permission level */ function auth_aclcheck_cb($data) { $id =& $data['id']; $user =& $data['user']; $groups =& $data['groups']; global $conf; global $AUTH_ACL; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; // if no ACL is used always return upload rights if(!$conf['useacl']) return AUTH_UPLOAD; if(!$auth) return AUTH_NONE; //make sure groups is an array if(!is_array($groups)) $groups = array(); //if user is superuser or in superusergroup return 255 (acl_admin) if(auth_isadmin($user, $groups)) { return AUTH_ADMIN; } if(!$auth->isCaseSensitive()) { $user = utf8_strtolower($user); $groups = array_map('utf8_strtolower', $groups); } $user = $auth->cleanUser($user); $groups = array_map(array($auth, 'cleanGroup'), (array) $groups); $user = auth_nameencode($user); //prepend groups with @ and nameencode $cnt = count($groups); for($i = 0; $i < $cnt; $i++) { $groups[$i] = '@'.auth_nameencode($groups[$i]); } $ns = getNS($id); $perm = -1; if($user || count($groups)) { //add ALL group $groups[] = '@ALL'; //add User if($user) $groups[] = $user; } else { $groups[] = '@ALL'; } //check exact match first $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); if(count($matches)) { foreach($matches as $match) { $match = preg_replace('/#.*$/', '', $match); //ignore comments $acl = preg_split('/[ \t]+/', $match); if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { $acl[1] = utf8_strtolower($acl[1]); } if(!in_array($acl[1], $groups)) { continue; } if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! if($acl[2] > $perm) { $perm = $acl[2]; } } if($perm > -1) { //we had a match - return it return (int) $perm; } } //still here? do the namespace checks if($ns) { $path = $ns.':*'; } else { $path = '*'; //root document } do { $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); if(count($matches)) { foreach($matches as $match) { $match = preg_replace('/#.*$/', '', $match); //ignore comments $acl = preg_split('/[ \t]+/', $match); if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { $acl[1] = utf8_strtolower($acl[1]); } if(!in_array($acl[1], $groups)) { continue; } if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! if($acl[2] > $perm) { $perm = $acl[2]; } } //we had a match - return it if($perm != -1) { return (int) $perm; } } //get next higher namespace $ns = getNS($ns); if($path != '*') { $path = $ns.':*'; if($path == ':*') $path = '*'; } else { //we did this already //looks like there is something wrong with the ACL //break here msg('No ACL setup yet! Denying access to everyone.'); return AUTH_NONE; } } while(1); //this should never loop endless return AUTH_NONE; } /** * Encode ASCII special chars * * Some auth backends allow special chars in their user and groupnames * The special chars are encoded with this function. Only ASCII chars * are encoded UTF-8 multibyte are left as is (different from usual * urlencoding!). * * Decoding can be done with rawurldecode * * @author Andreas Gohr <gohr@cosmocode.de> * @see rawurldecode() * * @param string $name * @param bool $skip_group * @return string */ function auth_nameencode($name, $skip_group = false) { global $cache_authname; $cache =& $cache_authname; $name = (string) $name; // never encode wildcard FS#1955 if($name == '%USER%') return $name; if($name == '%GROUP%') return $name; if(!isset($cache[$name][$skip_group])) { if($skip_group && $name{0} == '@') { $cache[$name][$skip_group] = '@'.preg_replace_callback( '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 'auth_nameencode_callback', substr($name, 1) ); } else { $cache[$name][$skip_group] = preg_replace_callback( '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 'auth_nameencode_callback', $name ); } } return $cache[$name][$skip_group]; } /** * callback encodes the matches * * @param array $matches first complete match, next matching subpatterms * @return string */ function auth_nameencode_callback($matches) { return '%'.dechex(ord(substr($matches[1],-1))); } /** * Create a pronouncable password * * The $foruser variable might be used by plugins to run additional password * policy checks, but is not used by the default implementation * * @author Andreas Gohr <andi@splitbrain.org> * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451 * @triggers AUTH_PASSWORD_GENERATE * * @param string $foruser username for which the password is generated * @return string pronouncable password */ function auth_pwgen($foruser = '') { $data = array( 'password' => '', 'foruser' => $foruser ); $evt = new Doku_Event('AUTH_PASSWORD_GENERATE', $data); if($evt->advise_before(true)) { $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones $v = 'aeiou'; //vowels $a = $c.$v; //both $s = '!$%&?+*~#-_:.;,'; // specials //use thre syllables... for($i = 0; $i < 3; $i++) { $data['password'] .= $c[auth_random(0, strlen($c) - 1)]; $data['password'] .= $v[auth_random(0, strlen($v) - 1)]; $data['password'] .= $a[auth_random(0, strlen($a) - 1)]; } //... and add a nice number and special $data['password'] .= auth_random(10, 99).$s[auth_random(0, strlen($s) - 1)]; } $evt->advise_after(); return $data['password']; } /** * Sends a password to the given user * * @author Andreas Gohr <andi@splitbrain.org> * * @param string $user Login name of the user * @param string $password The new password in clear text * @return bool true on success */ function auth_sendPassword($user, $password) { global $lang; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; if(!$auth) return false; $user = $auth->cleanUser($user); $userinfo = $auth->getUserData($user, $requireGroups = false); if(!$userinfo['mail']) return false; $text = rawLocale('password'); $trep = array( 'FULLNAME' => $userinfo['name'], 'LOGIN' => $user, 'PASSWORD' => $password ); $mail = new Mailer(); $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>'); $mail->subject($lang['regpwmail']); $mail->setBody($text, $trep); return $mail->send(); } /** * Register a new user * * This registers a new user - Data is read directly from $_POST * * @author Andreas Gohr <andi@splitbrain.org> * * @return bool true on success, false on any error */ function register() { global $lang; global $conf; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; global $INPUT; if(!$INPUT->post->bool('save')) return false; if(!actionOK('register')) return false; // gather input $login = trim($auth->cleanUser($INPUT->post->str('login'))); $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname'))); $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email'))); $pass = $INPUT->post->str('pass'); $passchk = $INPUT->post->str('passchk'); if(empty($login) || empty($fullname) || empty($email)) { msg($lang['regmissing'], -1); return false; } if($conf['autopasswd']) { $pass = auth_pwgen($login); // automatically generate password } elseif(empty($pass) || empty($passchk)) { msg($lang['regmissing'], -1); // complain about missing passwords return false; } elseif($pass != $passchk) { msg($lang['regbadpass'], -1); // complain about misspelled passwords return false; } //check mail if(!mail_isvalid($email)) { msg($lang['regbadmail'], -1); return false; } //okay try to create the user if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) { msg($lang['regfail'], -1); return false; } // send notification about the new user $subscription = new Subscription(); $subscription->send_register($login, $fullname, $email); // are we done? if(!$conf['autopasswd']) { msg($lang['regsuccess2'], 1); return true; } // autogenerated password? then send password to user if(auth_sendPassword($login, $pass)) { msg($lang['regsuccess'], 1); return true; } else { msg($lang['regmailfail'], -1); return false; } } /** * Update user profile * * @author Christopher Smith <chris@jalakai.co.uk> */ function updateprofile() { global $conf; global $lang; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; if(!$INPUT->post->bool('save')) return false; if(!checkSecurityToken()) return false; if(!actionOK('profile')) { msg($lang['profna'], -1); return false; } $changes = array(); $changes['pass'] = $INPUT->post->str('newpass'); $changes['name'] = $INPUT->post->str('fullname'); $changes['mail'] = $INPUT->post->str('email'); // check misspelled passwords if($changes['pass'] != $INPUT->post->str('passchk')) { msg($lang['regbadpass'], -1); return false; } // clean fullname and email $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name'])); $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail'])); // no empty name and email (except the backend doesn't support them) if((empty($changes['name']) && $auth->canDo('modName')) || (empty($changes['mail']) && $auth->canDo('modMail')) ) { msg($lang['profnoempty'], -1); return false; } if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) { msg($lang['regbadmail'], -1); return false; } $changes = array_filter($changes); // check for unavailable capabilities if(!$auth->canDo('modName')) unset($changes['name']); if(!$auth->canDo('modMail')) unset($changes['mail']); if(!$auth->canDo('modPass')) unset($changes['pass']); // anything to do? if(!count($changes)) { msg($lang['profnochange'], -1); return false; } if($conf['profileconfirm']) { if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { msg($lang['badpassconfirm'], -1); return false; } } if(!$auth->triggerUserMod('modify', array($INPUT->server->str('REMOTE_USER'), &$changes))) { msg($lang['proffail'], -1); return false; } // update cookie and session with the changed data if($changes['pass']) { list( /*user*/, $sticky, /*pass*/) = auth_getCookie(); $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true)); auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky); } return true; } /** * Delete the current logged-in user * * @return bool true on success, false on any error */ function auth_deleteprofile(){ global $conf; global $lang; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; if(!$INPUT->post->bool('delete')) return false; if(!checkSecurityToken()) return false; // action prevented or auth module disallows if(!actionOK('profile_delete') || !$auth->canDo('delUser')) { msg($lang['profnodelete'], -1); return false; } if(!$INPUT->post->bool('confirm_delete')){ msg($lang['profconfdeletemissing'], -1); return false; } if($conf['profileconfirm']) { if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { msg($lang['badpassconfirm'], -1); return false; } } $deleted = array(); $deleted[] = $INPUT->server->str('REMOTE_USER'); if($auth->triggerUserMod('delete', array($deleted))) { // force and immediate logout including removing the sticky cookie auth_logoff(); return true; } return false; } /** * Send a new password * * This function handles both phases of the password reset: * * - handling the first request of password reset * - validating the password reset auth token * * @author Benoit Chesneau <benoit@bchesneau.info> * @author Chris Smith <chris@jalakai.co.uk> * @author Andreas Gohr <andi@splitbrain.org> * * @return bool true on success, false on any error */ function act_resendpwd() { global $lang; global $conf; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; if(!actionOK('resendpwd')) { msg($lang['resendna'], -1); return false; } $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth')); if($token) { // we're in token phase - get user info from token $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; if(!file_exists($tfile)) { msg($lang['resendpwdbadauth'], -1); $INPUT->remove('pwauth'); return false; } // token is only valid for 3 days if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) { msg($lang['resendpwdbadauth'], -1); $INPUT->remove('pwauth'); @unlink($tfile); return false; } $user = io_readfile($tfile); $userinfo = $auth->getUserData($user, $requireGroups = false); if(!$userinfo['mail']) { msg($lang['resendpwdnouser'], -1); return false; } if(!$conf['autopasswd']) { // we let the user choose a password $pass = $INPUT->str('pass'); // password given correctly? if(!$pass) return false; if($pass != $INPUT->str('passchk')) { msg($lang['regbadpass'], -1); return false; } // change it if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) { msg($lang['proffail'], -1); return false; } } else { // autogenerate the password and send by mail $pass = auth_pwgen($user); if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) { msg($lang['proffail'], -1); return false; } if(auth_sendPassword($user, $pass)) { msg($lang['resendpwdsuccess'], 1); } else { msg($lang['regmailfail'], -1); } } @unlink($tfile); return true; } else { // we're in request phase if(!$INPUT->post->bool('save')) return false; if(!$INPUT->post->str('login')) { msg($lang['resendpwdmissing'], -1); return false; } else { $user = trim($auth->cleanUser($INPUT->post->str('login'))); } $userinfo = $auth->getUserData($user, $requireGroups = false); if(!$userinfo['mail']) { msg($lang['resendpwdnouser'], -1); return false; } // generate auth token $token = md5(auth_randombytes(16)); // random secret $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; $url = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&'); io_saveFile($tfile, $user); $text = rawLocale('pwconfirm'); $trep = array( 'FULLNAME' => $userinfo['name'], 'LOGIN' => $user, 'CONFIRM' => $url ); $mail = new Mailer(); $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>'); $mail->subject($lang['regpwmail']); $mail->setBody($text, $trep); if($mail->send()) { msg($lang['resendpwdconfirm'], 1); } else { msg($lang['regmailfail'], -1); } return true; } // never reached } /** * Encrypts a password using the given method and salt * * If the selected method needs a salt and none was given, a random one * is chosen. * * @author Andreas Gohr <andi@splitbrain.org> * * @param string $clear The clear text password * @param string $method The hashing method * @param string $salt A salt, null for random * @return string The crypted password */ function auth_cryptPassword($clear, $method = '', $salt = null) { global $conf; if(empty($method)) $method = $conf['passcrypt']; $pass = new PassHash(); $call = 'hash_'.$method; if(!method_exists($pass, $call)) { msg("Unsupported crypt method $method", -1); return false; } return $pass->$call($clear, $salt); } /** * Verifies a cleartext password against a crypted hash * * @author Andreas Gohr <andi@splitbrain.org> * * @param string $clear The clear text password * @param string $crypt The hash to compare with * @return bool true if both match */ function auth_verifyPassword($clear, $crypt) { $pass = new PassHash(); return $pass->verify_hash($clear, $crypt); } /** * Set the authentication cookie and add user identification data to the session * * @param string $user username * @param string $pass encrypted password * @param bool $sticky whether or not the cookie will last beyond the session * @return bool */ function auth_setCookie($user, $pass, $sticky) { global $conf; /* @var DokuWiki_Auth_Plugin $auth */ global $auth; global $USERINFO; if(!$auth) return false; $USERINFO = $auth->getUserData($user); // set cookie $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass); $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true); // set session $_SESSION[DOKU_COOKIE]['auth']['user'] = $user; $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass); $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid(); $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO; $_SESSION[DOKU_COOKIE]['auth']['time'] = time(); return true; } /** * Returns the user, (encrypted) password and sticky bit from cookie * * @returns array */ function auth_getCookie() { if(!isset($_COOKIE[DOKU_COOKIE])) { return array(null, null, null); } list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3); $sticky = (bool) $sticky; $pass = base64_decode($pass); $user = base64_decode($user); return array($user, $sticky, $pass); } //Setup VIM: ex: et ts=2 :
brontosaurusrex/dokuwiki-preconfigured
inc/auth.php
PHP
gpl-2.0
42,215
<?php /** * This file contains all functions for creating a database for teachpress * * @package teachpress\core\installation * @license http://www.gnu.org/licenses/gpl-2.0.html GPLv2 or later * @since 5.0.0 */ /** * This class contains all functions for creating a database for teachpress * @package teachpress\core\installation * @since 5.0.0 */ class TP_Tables { /** * Install teachPress database tables * @since 5.0.0 */ public static function create() { global $wpdb; self::add_capabilities(); $charset_collate = self::get_charset(); // Disable foreign key checks if ( TEACHPRESS_FOREIGN_KEY_CHECKS === false ) { $wpdb->query("SET foreign_key_checks = 0"); } // Settings self::add_table_settings($charset_collate); // Courses self::add_table_courses($charset_collate); self::add_table_course_meta($charset_collate); self::add_table_course_capabilities($charset_collate); self::add_table_course_documents($charset_collate); self::add_table_stud($charset_collate); self::add_table_stud_meta($charset_collate); self::add_table_signup($charset_collate); self::add_table_artefacts($charset_collate); self::add_table_assessments($charset_collate); // Publications self::add_table_pub($charset_collate); self::add_table_pub_meta($charset_collate); self::add_table_pub_capabilities($charset_collate); self::add_table_pub_documents($charset_collate); self::add_table_pub_imports($charset_collate); self::add_table_tags($charset_collate); self::add_table_relation($charset_collate); self::add_table_user($charset_collate); self::add_table_authors($charset_collate); self::add_table_rel_pub_auth($charset_collate); // Enable foreign key checks if ( TEACHPRESS_FOREIGN_KEY_CHECKS === false ) { $wpdb->query("SET foreign_key_checks = 1"); } } /** * Remove teachPress database tables * @since 5.0.0 */ public static function remove() { global $wpdb; $wpdb->query("SET FOREIGN_KEY_CHECKS=0"); $wpdb->query("DROP TABLE `" . TEACHPRESS_ARTEFACTS . "`, `" . TEACHPRESS_ASSESSMENTS . "`, `" . TEACHPRESS_AUTHORS . "`, `" . TEACHPRESS_COURSES . "`, `" . TEACHPRESS_COURSE_CAPABILITIES . "`, `" . TEACHPRESS_COURSE_DOCUMENTS . "`, `" . TEACHPRESS_COURSE_META . "`, `" . TEACHPRESS_PUB . "`, `" . TEACHPRESS_PUB_CAPABILITIES . "`, `" . TEACHPRESS_PUB_DOCUMENTS . "`, `" . TEACHPRESS_PUB_META . "`, `" . TEACHPRESS_PUB_IMPORTS . "`, `" . TEACHPRESS_RELATION ."`, `" . TEACHPRESS_REL_PUB_AUTH . "`, `" . TEACHPRESS_SETTINGS ."`, `" . TEACHPRESS_SIGNUP ."`, `" . TEACHPRESS_STUD . "`, `" . TEACHPRESS_STUD_META . "`, `" . TEACHPRESS_TAGS . "`, `" . TEACHPRESS_USER . "`"); $wpdb->query("SET FOREIGN_KEY_CHECKS=1"); } /** * Returns an associative array with table status informations (Name, Engine, Version, Rows,...) * @param string $table * @return array * @since 5.0.0 */ public static function check_table_status($table){ global $wpdb; return $wpdb->get_row("SHOW TABLE STATUS FROM " . DB_NAME . " WHERE `Name` = '$table'", ARRAY_A); } /** * Tests if the engine for the selected table is InnoDB. If not, the function changes the engine. * @param string $table * @since 5.0.0 * @access private */ private static function change_engine($table){ global $wpdb; $db_info = self::check_table_status($table); if ( $db_info['Engine'] != 'InnoDB' ) { $wpdb->query("ALTER TABLE " . $table . " ENGINE = INNODB"); } } /** * Create table teachpress_courses * @param string $charset_collate * @since 5.0.0 */ public static function add_table_courses($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_COURSES . "'") == TEACHPRESS_COURSES ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_COURSES . " ( `course_id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(100), `type` VARCHAR (100), `room` VARCHAR(100), `lecturer` VARCHAR (100), `date` VARCHAR(60), `places` INT(4), `start` DATETIME, `end` DATETIME, `semester` VARCHAR(100), `comment` VARCHAR(500), `rel_page` INT, `parent` INT, `visible` INT(1), `waitinglist` INT(1), `image_url` VARCHAR(400), `strict_signup` INT(1), `use_capabilities` INT(1), PRIMARY KEY (`course_id`), KEY `semester` (`semester`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_COURSES); } /** * Create table course_capabilities * @param string $charset_collate * @since 5.0.0 */ public static function add_table_course_capabilities($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_COURSE_CAPABILITIES . "'") == TEACHPRESS_COURSE_CAPABILITIES ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_COURSE_CAPABILITIES . " ( `cap_id` INT UNSIGNED AUTO_INCREMENT, `wp_id` INT UNSIGNED, `course_id` INT UNSIGNED, `capability` VARCHAR(100), PRIMARY KEY (`cap_id`), KEY `ind_course_id` (`course_id`), KEY `ind_wp_id` (`wp_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_COURSE_CAPABILITIES); } /** * Create table course_documents * @param string $charset_collate * @since 5.0.0 */ public static function add_table_course_documents($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_COURSE_DOCUMENTS . "'") == TEACHPRESS_COURSE_DOCUMENTS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_COURSE_DOCUMENTS . " ( `doc_id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(500), `path` VARCHAR(500), `added` DATETIME, `size` BIGINT, `sort` INT, `course_id` INT UNSIGNED, PRIMARY KEY (doc_id), KEY `ind_course_id` (`course_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_COURSE_DOCUMENTS); } /** * Create table teachpress_course_meta * @param string $charset_collate * @since 5.0.0 */ public static function add_table_course_meta($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_COURSE_META . "'") == TEACHPRESS_COURSE_META ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_COURSE_META . " ( `meta_id` INT UNSIGNED AUTO_INCREMENT, `course_id` INT UNSIGNED, `meta_key` VARCHAR(255), `meta_value` TEXT, PRIMARY KEY (meta_id), KEY `ind_course_id` (`course_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_COURSE_META); } /** * Create table teachpress_stud * @param string $charset_collate * @since 5.0.0 */ public static function add_table_stud($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_STUD . "'") == TEACHPRESS_STUD ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_STUD . " ( `wp_id` INT UNSIGNED, `firstname` VARCHAR(100) , `lastname` VARCHAR(100), `userlogin` VARCHAR (100), `email` VARCHAR(50), PRIMARY KEY (wp_id), KEY `ind_userlogin` (`userlogin`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_STUD); } /** * Create table teachpress_stud_meta * @param string $charset_collate * @since 5.0.0 */ public static function add_table_stud_meta($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_STUD_META . "'") == TEACHPRESS_STUD_META ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_STUD_META . " ( `meta_id` INT UNSIGNED AUTO_INCREMENT, `wp_id` INT UNSIGNED, `meta_key` VARCHAR(255), `meta_value` TEXT, PRIMARY KEY (meta_id), KEY `ind_wp_id` (`wp_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_STUD_META); } /** * Create table teachpress_signup * @param string $charset_collate * @since 5.0.0 */ public static function add_table_signup($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_SIGNUP ."'") == TEACHPRESS_SIGNUP ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_SIGNUP ." ( `con_id` INT UNSIGNED AUTO_INCREMENT, `course_id` INT UNSIGNED, `wp_id` INT UNSIGNED, `waitinglist` INT(1) UNSIGNED, `date` DATETIME, PRIMARY KEY (con_id), KEY `ind_course_id` (`course_id`), KEY `ind_wp_id` (`wp_id`), KEY `ind_date` (`date`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_SIGNUP); } /** * Create table teachpress_artefacts * @param string $charset_collate * @since 5.0.0 */ public static function add_table_artefacts($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_ARTEFACTS . "'") == TEACHPRESS_ARTEFACTS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_ARTEFACTS . " ( `artefact_id` INT UNSIGNED AUTO_INCREMENT, `parent_id` INT UNSIGNED, `course_id` INT UNSIGNED, `title` VARCHAR(500), `scale` TEXT, `passed` INT(1), `max_value` VARCHAR(50), PRIMARY KEY (artefact_id), KEY `ind_course_id` (`course_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_ARTEFACTS); } /** * Create table teachpress_assessments * @param string $charset_collate * @since 5.0.0 */ public static function add_table_assessments($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_ASSESSMENTS . "'") == TEACHPRESS_ASSESSMENTS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_ASSESSMENTS . " ( `assessment_id` INT UNSIGNED AUTO_INCREMENT, `artefact_id` INT UNSIGNED, `course_id` INT UNSIGNED, `wp_id` INT UNSIGNED, `value` VARCHAR(50), `max_value` VARCHAR(50), `type` VARCHAR(50), `examiner_id` INT, `exam_date` DATETIME, `comment` TEXT, `passed` INT(1), PRIMARY KEY (assessment_id), KEY `ind_course_id` (`course_id`), KEY `ind_artefact_id` (`artefact_id`), KEY `ind_wp_id` (`wp_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_ASSESSMENTS); } /** * Create table teachpress_settings * @param string $charset_collate * @since 5.0.0 */ public static function add_table_settings($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_SETTINGS . "'") == TEACHPRESS_SETTINGS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_SETTINGS . " ( `setting_id` INT UNSIGNED AUTO_INCREMENT, `variable` VARCHAR (100), `value` LONGTEXT, `category` VARCHAR (100), PRIMARY KEY (setting_id) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_SETTINGS); // Add default values self::add_default_settings(); } /** * Add default system settings * @since 5.0.0 */ public static function add_default_settings(){ global $wpdb; $value = '[tpsingle [key]]<!--more-->' . "\n\n[tpabstract]\n\n[tplinks]\n\n[tpbibtex]"; $version = get_tp_version(); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('sem', 'Example term', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('db-version', '$version', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('sign_out', '0', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('login', 'std', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('stylesheet', '1', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('rel_page_courses', 'page', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('rel_page_publications', 'page', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('rel_content_auto', '0', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('rel_content_template', '$value', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('rel_content_category', '', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('import_overwrite', '1', 'system')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('convert_bibtex', '0', 'system')"); // Example values $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('Example term', 'Example term', 'semester')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('Example', 'Example', 'course_of_studies')"); $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . "(`variable`, `value`, `category`) VALUES ('Lecture', 'Lecture', 'course_type')"); // Register example meta data fields // course_of_studies $value = 'name = {course_of_studies}, title = {' . __('Course of studies','teachpress') . '}, type = {SELECT}, required = {false}, min = {false}, max = {false}, step = {false}, visibility = {admin}'; $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('course_of_studies', '$value', 'teachpress_stud')"); // birthday $value = 'name = {birthday}, title = {' . __('Birthday','teachpress') . '}, type = {DATE}, required = {false}, min = {false}, max = {false}, step = {false}, visibility = {normal}'; $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('birthday', '$value', 'teachpress_stud')"); // semester_number $value = 'name = {semester_number}, title = {' . __('Semester number','teachpress') . '}, type = {INT}, required = {false}, min = {1}, max = {99}, step = {1}, visibility = {normal}'; $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('semester_number', '$value', 'teachpress_stud')"); // matriculation_number $value = 'name = {matriculation_number}, title = {' . __('Matriculation number','teachpress') . '}, type = {INT}, required = {false}, min = {1}, max = {1000000}, step = {1}, visibility = {admin}'; $wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('matriculation_number', '$value', 'teachpress_stud')"); } /** * Create table teachpress_pub * @param string $charset_collate * @since 5.0.0 */ public static function add_table_pub($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_PUB . "'") == TEACHPRESS_PUB ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_PUB . " ( `pub_id` INT UNSIGNED AUTO_INCREMENT, `title` VARCHAR(500), `type` VARCHAR (50), `bibtex` VARCHAR (100), `author` VARCHAR (3000), `editor` VARCHAR (3000), `isbn` VARCHAR (50), `url` TEXT, `date` DATE, `urldate` DATE, `booktitle` VARCHAR (1000), `issuetitle` VARCHAR (200), `journal` VARCHAR(200), `issue` VARCHAR(40), `volume` VARCHAR(40), `number` VARCHAR(40), `pages` VARCHAR(40), `publisher` VARCHAR (500), `address` VARCHAR (300), `edition` VARCHAR (100), `chapter` VARCHAR (40), `institution` VARCHAR (500), `organization` VARCHAR (500), `school` VARCHAR (200), `series` VARCHAR (200), `crossref` VARCHAR (100), `abstract` TEXT, `howpublished` VARCHAR (200), `key` VARCHAR (100), `techtype` VARCHAR (200), `comment` TEXT, `note` TEXT, `image_url` VARCHAR (400), `image_target` VARCHAR (100), `image_ext` VARCHAR (400), `doi` VARCHAR (100), `is_isbn` INT(1), `rel_page` INT, `status` VARCHAR (100) DEFAULT 'published', `added` DATETIME, `modified` DATETIME, `use_capabilities` INT(1), `import_id` INT, PRIMARY KEY (pub_id), KEY `ind_type` (`type`), KEY `ind_date` (`date`), KEY `ind_import_id` (`import_id`), KEY `ind_key` (`key`), KEY `ind_bibtex_key` (`bibtex`), KEY `ind_status` (`status`) ) ROW_FORMAT=DYNAMIC $charset_collate;"); // test engine self::change_engine(TEACHPRESS_PUB); } /** * Create table teachpress_pub_meta * @param string $charset_collate * @since 5.0.0 */ public static function add_table_pub_meta($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_PUB_META . "'") == TEACHPRESS_PUB_META ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_PUB_META . " ( `meta_id` INT UNSIGNED AUTO_INCREMENT, `pub_id` INT UNSIGNED, `meta_key` VARCHAR(255), `meta_value` TEXT, PRIMARY KEY (meta_id), KEY `ind_pub_id` (`pub_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_PUB_META); } /** * Create table pub_capabilities * @param string $charset_collate * @since 6.0.0 */ public static function add_table_pub_capabilities($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_PUB_CAPABILITIES . "'") == TEACHPRESS_PUB_CAPABILITIES ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_PUB_CAPABILITIES . " ( `cap_id` INT UNSIGNED AUTO_INCREMENT, `wp_id` INT UNSIGNED, `pub_id` INT UNSIGNED, `capability` VARCHAR(100), PRIMARY KEY (`cap_id`), KEY `ind_pub_id` (`pub_id`), KEY `ind_wp_id` (`wp_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_PUB_CAPABILITIES); } /** * Create table pub_documents * @param string $charset_collate * @since 6.0.0 */ public static function add_table_pub_documents($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_PUB_DOCUMENTS . "'") == TEACHPRESS_PUB_DOCUMENTS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_PUB_DOCUMENTS . " ( `doc_id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(500), `path` VARCHAR(500), `added` DATETIME, `size` BIGINT, `sort` INT, `pub_id` INT UNSIGNED, PRIMARY KEY (doc_id), KEY `ind_pub_id` (`pub_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_PUB_DOCUMENTS); } /** * Create table pub_imports * @param string $charset_collate * @since 6.1.0 */ public static function add_table_pub_imports($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_PUB_IMPORTS . "'") == TEACHPRESS_PUB_IMPORTS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_PUB_IMPORTS . " ( `id` INT UNSIGNED AUTO_INCREMENT, `wp_id` INT UNSIGNED, `date` DATETIME, PRIMARY KEY (id) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_PUB_DOCUMENTS); } /** * Create table teachpress_tags * @param string $charset_collate * @since 5.0.0 */ public static function add_table_tags($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_TAGS . "'") == TEACHPRESS_TAGS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_TAGS . " ( `tag_id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(300), PRIMARY KEY (tag_id), KEY `ind_tag_name` (`name`) ) ROW_FORMAT=DYNAMIC $charset_collate;"); // test engine self::change_engine(TEACHPRESS_TAGS); } /** * Create table teachpress_relation * @param string $charset_collate * @since 5.0.0 */ public static function add_table_relation($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_RELATION . "'") == TEACHPRESS_RELATION ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_RELATION . " ( `con_id` INT UNSIGNED AUTO_INCREMENT, `pub_id` INT UNSIGNED, `tag_id` INT UNSIGNED, PRIMARY KEY (con_id), KEY `ind_pub_id` (`pub_id`), KEY `ind_tag_id` (`tag_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_RELATION); } /** * Create table teachpress_user * @param string $charset_collate * @since 5.0.0 */ public static function add_table_user($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_USER . "'") == TEACHPRESS_USER ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_USER . " ( `bookmark_id` INT UNSIGNED AUTO_INCREMENT, `pub_id` INT UNSIGNED, `user` INT UNSIGNED, PRIMARY KEY (bookmark_id), KEY `ind_pub_id` (`pub_id`), KEY `ind_user` (`user`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_USER); } /** * Create table teachpress_authors * @param string $charset_collate * @since 5.0.0 */ public static function add_table_authors($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_AUTHORS . "'") == TEACHPRESS_AUTHORS ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_AUTHORS . " ( `author_id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(500), `sort_name` VARCHAR(500), PRIMARY KEY (author_id), KEY `ind_sort_name` (`sort_name`) ) ROW_FORMAT=DYNAMIC $charset_collate;"); // test engine self::change_engine(TEACHPRESS_AUTHORS); } /** * Create table teachpress_rel_pub_auth * @param string $charset_collate * @since 5.0.0 */ public static function add_table_rel_pub_auth($charset_collate) { global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_REL_PUB_AUTH . "'") == TEACHPRESS_REL_PUB_AUTH ) { return; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta("CREATE TABLE " . TEACHPRESS_REL_PUB_AUTH . " ( `con_id` INT UNSIGNED AUTO_INCREMENT, `pub_id` INT UNSIGNED, `author_id` INT UNSIGNED, `is_author` INT(1), `is_editor` INT(1), PRIMARY KEY (con_id), KEY `ind_pub_id` (`pub_id`), KEY `ind_author_id` (`author_id`) ) $charset_collate;"); // test engine self::change_engine(TEACHPRESS_REL_PUB_AUTH); } /** * Add capabilities * @since 5.0.0 */ private static function add_capabilities() { // global $wp_roles; $role = $wp_roles->get_role('administrator'); if ( !$role->has_cap('use_teachpress') ) { $wp_roles->add_cap('administrator', 'use_teachpress'); } if ( !$role->has_cap('use_teachpress_courses') ) { $wp_roles->add_cap('administrator', 'use_teachpress_courses'); } } /** * charset & collate like WordPress * @since 5.0.0 */ public static function get_charset() { global $wpdb; $charset_collate = ''; if ( ! empty($wpdb->charset) ) { $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset"; } if ( ! empty($wpdb->collate) ) { $charset_collate .= " COLLATE $wpdb->collate"; } $charset_collate .= " ENGINE = INNODB"; return $charset_collate; } }
winkm89/teachPress
core/class-tables.php
PHP
gpl-2.0
31,096
(function ($) { function getCsrfTokenForFullShotImage(callback) { $ .get(Drupal.url('rest/session/token')) .done(function (data) { var csrfToken = data; callback(csrfToken); }); } function patchImageFullShot(csrfToken, file, fid) { //document.getElementById('msg-up').innerHTML = 'Image marked as fullshot ....'; $.ajax({ url: Drupal.url('file/' + fid + '?_format=hal_json'), method: 'PATCH', headers: { 'Content-Type': 'application/hal+json', 'X-CSRF-Token': csrfToken }, data: JSON.stringify(file), success: function (file) { //console.log(node); //document.getElementById('msg-up').innerHTML = 'Image Fullshot started!'; swal({ title: "Full Shot", text: "Image has been selected as full shot. Scan next ID", type: "success", showCancelButton: false, confirmButtonColor: "#DD6B55", confirmButtonText: "OK", closeOnConfirm: true }); }, error: function(){ swal({ title: "Full Shot", text: "There was an error, please try again.", type: "error", showCancelButton: false, confirmButtonColor: "#DD6B55", confirmButtonText: "OK", closeOnConfirm: true }); } }); // setTimeout(function(){ // document.getElementById('msg-up').innerHTML = ''; // }, 3300); } /* * tag value 1 means tag * tag value 0 means undo tag * */ function update_image_fullshot(tag,fidinput) { var nid = fidinput; var Node_imgs = { _links: { type: { href: Drupal.url.toAbsolute(drupalSettings.path.baseUrl + 'rest/type/file/image') } }, // type: { // target_id: 'products' // }, field_full_shoot: { value:tag } }; getCsrfTokenForFullShotImage(function (csrfToken) { if (nid) { patchImageFullShot(csrfToken, Node_imgs, nid); }else{ alert('Node product found, pls refresh the page.'); } }); } $(".studio-img-fullshot").click(function () { var id = $(this).parents('span').attr('id'); console.log('fullshot'); update_image_fullshot(1,id); }); $(document).on("click",".studio-img-fullshot",function(){ var id = $(this).parents('span').attr('id'); console.log('fullshot'); update_image_fullshot(1,id); }); })(jQuery);
asharnb/dawn
modules/custom/studiobridge_store_images/js/studio-bridge-fullshot-image.js
JavaScript
gpl-2.0
3,011
/*============================================================================= Copyright (c) 2002-2003 Joel de Guzman http://spirit.sourceforge.net/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ //////////////////////////////////////////////////////////////////////////// // // Full calculator example demonstrating Phoenix // This is discussed in the "Closures" chapter in the Spirit User's Guide. // // [ JDG 6/29/2002 ] // //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include <boost/spirit/core.hpp> #include <boost/spirit/attribute.hpp> #include <boost/spirit/phoenix/functions.hpp> #include <iostream> #include <string> #include "Main.h" //#include "bigfp.h" //////////////////////////////////////////////////////////////////////////// using namespace std; using namespace boost::spirit; using namespace phoenix; //////////////////////////////////////////////////////////////////////////// // // Our calculator grammar using phoenix to do the semantics // // Note: The top rule propagates the expression result (value) upwards // to the calculator grammar self.val closure member which is // then visible outside the grammar (i.e. since self.val is the // member1 of the closure, it becomes the attribute passed by // the calculator to an attached semantic action. See the // driver code that uses the calculator below). // //////////////////////////////////////////////////////////////////////////// struct calc_closure : boost::spirit::closure<calc_closure, double> { member1 val; }; struct pow_ { template <typename X, typename Y> struct result { typedef X type; }; template <typename X, typename Y> X operator()(X x, Y y) const { using namespace std; return pow(x, y); } }; // Notice how power(x, y) is lazily implemented using Phoenix function. function<pow_> power; struct calculator : public grammar<calculator, calc_closure::context_t> { template <typename ScannerT> struct definition { definition(calculator const& self) { top = expression[self.val = arg1]; expression = term[expression.val = arg1] >> *( ('+' >> term[expression.val += arg1]) | ('-' >> term[expression.val -= arg1]) ) ; term = factor[term.val = arg1] >> *( ('*' >> factor[term.val *= arg1]) | ('/' >> factor[term.val /= arg1]) ) ; factor = ureal_p[factor.val = arg1] | '(' >> expression[factor.val = arg1] >> ')' | ('-' >> factor[factor.val = -arg1]) | ('+' >> factor[factor.val = arg1]) ; } // const uint_parser<bigint, 10, 1, -1> bigint_parser; typedef rule<ScannerT, calc_closure::context_t> rule_t; rule_t expression, term, factor; rule<ScannerT> top; rule<ScannerT> const& start() const { return top; } }; }; bool DoCalculation(const TCHAR* str, double& result) { // Our parser calculator calc; double n = 0; parse_info<const wchar_t *> info = parse(str, calc[var(n) = arg1], space_p); if (info.full) { result = n; return true; } return false; }
Slesa/launchy
old/Launchy_VC7/Plugins/Calcy/Main.cpp
C++
gpl-2.0
3,793
# # The Qubes OS Project, http://www.qubes-os.org # # Copyright (C) 2014-2016 Wojtek Porczyk <woju@invisiblethingslab.com> # Copyright (C) 2016 Marek Marczykowski <marmarek@invisiblethingslab.com>) # Copyright (C) 2016 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, see <https://www.gnu.org/licenses/>. # ''' This module contains the TemplateVM implementation ''' import qubes import qubes.config import qubes.vm.qubesvm import qubes.vm.mix.net from qubes.config import defaults from qubes.vm.qubesvm import QubesVM class TemplateVM(QubesVM): '''Template for AppVM''' dir_path_prefix = qubes.config.system_path['qubes_templates_dir'] @property def appvms(self): ''' Returns a generator containing all domains based on the current TemplateVM. ''' for vm in self.app.domains: if hasattr(vm, 'template') and vm.template is self: yield vm netvm = qubes.VMProperty('netvm', load_stage=4, allow_none=True, default=None, # pylint: disable=protected-access setter=qubes.vm.qubesvm.QubesVM.netvm._setter, doc='VM that provides network connection to this domain. When ' '`None`, machine is disconnected.') def __init__(self, *args, **kwargs): assert 'template' not in kwargs, "A TemplateVM can not have a template" self.volume_config = { 'root': { 'name': 'root', 'snap_on_start': False, 'save_on_stop': True, 'rw': True, 'source': None, 'size': defaults['root_img_size'], }, 'private': { 'name': 'private', 'snap_on_start': False, 'save_on_stop': True, 'rw': True, 'source': None, 'size': defaults['private_img_size'], 'revisions_to_keep': 0, }, 'volatile': { 'name': 'volatile', 'size': defaults['root_img_size'], 'snap_on_start': False, 'save_on_stop': False, 'rw': True, }, 'kernel': { 'name': 'kernel', 'snap_on_start': False, 'save_on_stop': False, 'rw': False } } super(TemplateVM, self).__init__(*args, **kwargs) @qubes.events.handler('property-set:default_user', 'property-set:kernel', 'property-set:kernelopts', 'property-set:vcpus', 'property-set:memory', 'property-set:maxmem', 'property-set:qrexec_timeout', 'property-set:shutdown_timeout', 'property-set:management_dispvm') def on_property_set_child(self, _event, name, newvalue, oldvalue=None): """Send event about default value change to child VMs (which use default inherited from the template). This handler is supposed to be set for properties using `_default_with_template()` function for the default value. """ if newvalue == oldvalue: return for vm in self.appvms: if not vm.property_is_default(name): continue vm.fire_event('property-reset:' + name, name=name)
nrgaway/qubes-core-admin
qubes/vm/templatevm.py
Python
gpl-2.0
4,118
/** * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "config.h" #if ENABLE(WML) #include "WMLInputElement.h" #include "EventNames.h" #include "FormDataList.h" #include "Frame.h" #include "HTMLNames.h" #include "KeyboardEvent.h" #include "MappedAttribute.h" #include "RenderTextControlSingleLine.h" #include "TextEvent.h" #include "WMLDocument.h" #include "WMLNames.h" #include "WMLPageState.h" namespace WebCore { WMLInputElement::WMLInputElement(const QualifiedName& tagName, Document* doc) : WMLFormControlElement(tagName, doc) , m_isPasswordField(false) , m_isEmptyOk(false) , m_numOfCharsAllowedByMask(0) { } WMLInputElement::~WMLInputElement() { if (m_isPasswordField) document()->unregisterForDocumentActivationCallbacks(this); } static const AtomicString& formatCodes() { DEFINE_STATIC_LOCAL(AtomicString, codes, ("AaNnXxMm")); return codes; } bool WMLInputElement::isKeyboardFocusable(KeyboardEvent*) const { return WMLFormControlElement::isFocusable(); } bool WMLInputElement::isMouseFocusable() const { return WMLFormControlElement::isFocusable(); } void WMLInputElement::dispatchFocusEvent() { InputElement::dispatchFocusEvent(this, this); WMLElement::dispatchFocusEvent(); } void WMLInputElement::dispatchBlurEvent() { // Firstly check if it is allowed to leave this input field String val = value(); if ( //SAMSUNG_CHANGES_BEGGIN /*(!m_isEmptyOk && val.isEmpty()) || */ //SAMSUNG_CHANGES_END !isConformedToInputMask(val)) { updateFocusAppearance(true); return; } // update the name variable of WML input elmenet String nameVariable = formControlName(); if (!nameVariable.isEmpty()) wmlPageStateForDocument(document())->storeVariable(nameVariable, val); InputElement::dispatchBlurEvent(this, this); WMLElement::dispatchBlurEvent(); } void WMLInputElement::updateFocusAppearance(bool restorePreviousSelection) { InputElement::updateFocusAppearance(m_data, this, this, restorePreviousSelection); } void WMLInputElement::aboutToUnload() { InputElement::aboutToUnload(this, this); } int WMLInputElement::size() const { return m_data.size(); } const AtomicString& WMLInputElement::formControlType() const { // needs to be lowercase according to DOM spec if (m_isPasswordField) { DEFINE_STATIC_LOCAL(const AtomicString, password, ("password")); return password; } DEFINE_STATIC_LOCAL(const AtomicString, text, ("text")); return text; } const AtomicString& WMLInputElement::formControlName() const { return m_data.name(); } const String& WMLInputElement::suggestedValue() const { return m_data.suggestedValue(); } String WMLInputElement::value() const { String value = m_data.value(); if (value.isNull()) value = constrainValue(getAttribute(HTMLNames::valueAttr)); return value; } void WMLInputElement::setValue(const String& value, bool sendChangeEvent) { setFormControlValueMatchesRenderer(false); m_data.setValue(constrainValue(value)); if (inDocument()) document()->updateStyleIfNeeded(); if (renderer()) renderer()->updateFromElement(); setNeedsStyleRecalc(); unsigned max = m_data.value().length(); if (document()->focusedNode() == this) InputElement::updateSelectionRange(this, this, max, max); else cacheSelection(max, max); InputElement::notifyFormStateChanged(this); } // SAMSUNG_WML_FIXES+ // wml/struct/control/input/format/1 void WMLInputElement::setValuePreserveSelectionPos(const String& value) { //InputElement::updatePlaceholderVisibility(m_data, this, this); setFormControlValueMatchesRenderer(false); m_data.setValue(constrainValue(value)); if (inDocument()) document()->updateStyleIfNeeded(); if (renderer()) renderer()->updateFromElement(); setNeedsStyleRecalc(); InputElement::notifyFormStateChanged(this); } // SAMSUNG_WML_FIXES- void WMLInputElement::setValueForUser(const String& value) { /* InputElement class defines pure virtual function 'setValueForUser', which will be useful only in HTMLInputElement. Do nothing in 'WMLInputElement'. */ } void WMLInputElement::setValueFromRenderer(const String& value) { InputElement::setValueFromRenderer(m_data, this, this, value); } bool WMLInputElement::saveFormControlState(String& result) const { if (m_isPasswordField) return false; result = value(); return true; } void WMLInputElement::restoreFormControlState(const String& state) { ASSERT(!m_isPasswordField); // should never save/restore password fields setValue(state, true); } void WMLInputElement::select() { if (RenderTextControl* r = toRenderTextControl(renderer())) r->select(); } void WMLInputElement::accessKeyAction(bool) { // should never restore previous selection here focus(false); } void WMLInputElement::parseMappedAttribute(MappedAttribute* attr) { if (attr->name() == HTMLNames::nameAttr) m_data.setName(parseValueForbiddingVariableReferences(attr->value())); else if (attr->name() == HTMLNames::typeAttr) { String type = parseValueForbiddingVariableReferences(attr->value()); m_isPasswordField = (type == "password"); } else if (attr->name() == HTMLNames::valueAttr) { // We only need to setChanged if the form is looking at the default value right now. if (m_data.value().isNull()) setNeedsStyleRecalc(); setFormControlValueMatchesRenderer(false); } else if (attr->name() == HTMLNames::maxlengthAttr) InputElement::parseMaxLengthAttribute(m_data, this, this, attr); else if (attr->name() == HTMLNames::sizeAttr) InputElement::parseSizeAttribute(m_data, this, attr); else if (attr->name() == WMLNames::formatAttr) m_formatMask = validateInputMask(parseValueForbiddingVariableReferences(attr->value())); else if (attr->name() == WMLNames::emptyokAttr) m_isEmptyOk = (attr->value() == "true"); else WMLElement::parseMappedAttribute(attr); // FIXME: Handle 'accesskey' attribute // FIXME: Handle 'tabindex' attribute // FIXME: Handle 'title' attribute } void WMLInputElement::copyNonAttributeProperties(const Element* source) { const WMLInputElement* sourceElement = static_cast<const WMLInputElement*>(source); m_data.setValue(sourceElement->m_data.value()); WMLElement::copyNonAttributeProperties(source); } RenderObject* WMLInputElement::createRenderer(RenderArena* arena, RenderStyle*) { return new (arena) RenderTextControlSingleLine(this, false); } void WMLInputElement::detach() { WMLElement::detach(); setFormControlValueMatchesRenderer(false); } bool WMLInputElement::appendFormData(FormDataList& encoding, bool) { if (formControlName().isEmpty()) return false; encoding.appendData(formControlName(), value()); return true; } void WMLInputElement::reset() { setValue(String(), true); } void WMLInputElement::defaultEventHandler(Event* evt) { bool clickDefaultFormButton = false; String filteredString; if (evt->type() == eventNames().textInputEvent && evt->isTextEvent()) { TextEvent* textEvent = static_cast<TextEvent*>(evt); if (textEvent->data() == "\n") clickDefaultFormButton = true; // SAMSUNG_WML_FIXES+ // wml/struct/control/input/format/1 // else if (renderer() && !isConformedToInputMask(textEvent->data()[0], toRenderTextControl(renderer())->text().length() + 1)) else if (renderer()) { WMLElement::defaultEventHandler(evt); if (evt->defaultHandled()) { filteredString = filterInvalidChars((toRenderTextControl(renderer()))->text()); setValuePreserveSelectionPos(filteredString); return; } } // SAMSUNG_WML_FIXES- } if (evt->type() == eventNames().keydownEvent && evt->isKeyboardEvent() && focused() && document()->frame() && document()->frame()->doTextFieldCommandFromEvent(this, static_cast<KeyboardEvent*>(evt))) { evt->setDefaultHandled(); return; } // Let the key handling done in EventTargetNode take precedence over the event handling here for editable text fields if (!clickDefaultFormButton) { WMLElement::defaultEventHandler(evt); if (evt->defaultHandled()) return; } // Use key press event here since sending simulated mouse events // on key down blocks the proper sending of the key press event. if (evt->type() == eventNames().keypressEvent && evt->isKeyboardEvent()) { // Simulate mouse click on the default form button for enter for these types of elements. if (static_cast<KeyboardEvent*>(evt)->charCode() == '\r') clickDefaultFormButton = true; } if (clickDefaultFormButton) { // Fire onChange for text fields. RenderObject* r = renderer(); if (r && toRenderTextControl(r)->wasChangedSinceLastChangeEvent()) { dispatchEvent(Event::create(eventNames().changeEvent, true, false)); // Refetch the renderer since arbitrary JS code run during onchange can do anything, including destroying it. r = renderer(); if (r) toRenderTextControl(r)->setChangedSinceLastChangeEvent(false); } evt->setDefaultHandled(); return; } if (evt->isBeforeTextInsertedEvent()) InputElement::handleBeforeTextInsertedEvent(m_data, this, this, evt); if (renderer() && (evt->isMouseEvent() || evt->isDragEvent() || evt->isWheelEvent() || evt->type() == eventNames().blurEvent || evt->type() == eventNames().focusEvent)) toRenderTextControlSingleLine(renderer())->forwardEvent(evt); } void WMLInputElement::cacheSelection(int start, int end) { m_data.setCachedSelectionStart(start); m_data.setCachedSelectionEnd(end); } String WMLInputElement::constrainValue(const String& proposedValue) const { return InputElement::sanitizeUserInputValue(this, proposedValue, m_data.maxLength()); } void WMLInputElement::documentDidBecomeActive() { ASSERT(m_isPasswordField); reset(); } void WMLInputElement::willMoveToNewOwnerDocument() { // Always unregister for cache callbacks when leaving a document, even if we would otherwise like to be registered if (m_isPasswordField) document()->unregisterForDocumentActivationCallbacks(this); WMLElement::willMoveToNewOwnerDocument(); } void WMLInputElement::didMoveToNewOwnerDocument() { if (m_isPasswordField) document()->registerForDocumentActivationCallbacks(this); WMLElement::didMoveToNewOwnerDocument(); } void WMLInputElement::initialize() { String nameVariable = formControlName(); String variableValue; WMLPageState* pageSate = wmlPageStateForDocument(document()); ASSERT(pageSate); if (!nameVariable.isEmpty()) variableValue = pageSate->getVariable(nameVariable); if (variableValue.isEmpty() || !isConformedToInputMask(variableValue)) { String val = value(); if (isConformedToInputMask(val)) variableValue = val; else variableValue = ""; pageSate->storeVariable(nameVariable, variableValue); } setValue(variableValue, true); if (!hasAttribute(WMLNames::emptyokAttr)) { if (m_formatMask.isEmpty() || // check if the format codes is just "*f" (m_formatMask.length() == 2 && m_formatMask[0] == '*' && formatCodes().find(m_formatMask[1]) != -1)) m_isEmptyOk = true; } } String WMLInputElement::validateInputMask(const String& inputMask) { bool isValid = true; bool hasWildcard = false; unsigned escapeCharCount = 0; unsigned maskLength = inputMask.length(); UChar formatCode; for (unsigned i = 0; i < maskLength; ++i) { formatCode = inputMask[i]; if (formatCodes().find(formatCode) == -1) { if (formatCode == '*' || (WTF::isASCIIDigit(formatCode) && formatCode != '0')) { // validate codes which ends with '*f' or 'nf' formatCode = inputMask[++i]; if ((i + 1 != maskLength) || formatCodes().find(formatCode) == -1) { isValid = false; break; } hasWildcard = true; } else if (formatCode == '\\') { //skip over the next mask character ++i; ++escapeCharCount; } else { isValid = false; break; } } } if (!isValid) return String(); // calculate the number of characters allowed to be entered by input mask m_numOfCharsAllowedByMask = maskLength; if (escapeCharCount) m_numOfCharsAllowedByMask -= escapeCharCount; if (hasWildcard) { formatCode = inputMask[maskLength - 2]; if (formatCode == '*') m_numOfCharsAllowedByMask = m_data.maxLength(); else { unsigned leftLen = String(&formatCode).toInt(); m_numOfCharsAllowedByMask = leftLen + m_numOfCharsAllowedByMask - 2; } } return inputMask; } // SAMSUNG_WML_FIXES+ String WMLInputElement::filterInvalidChars(const String& inputChars) { String filteredString; unsigned charCount = 0; for (unsigned i = 0; i < inputChars.length(); ++i) { if (isConformedToInputMask(inputChars[i], charCount+1, false)) { filteredString.append(inputChars[i]); charCount++; } } return filteredString; } // SAMSUNG_WML_FIXES- bool WMLInputElement::isConformedToInputMask(const String& inputChars) { for (unsigned i = 0; i < inputChars.length(); ++i) if (!isConformedToInputMask(inputChars[i], i + 1, false)) return false; return true; } bool WMLInputElement::isConformedToInputMask(UChar inChar, unsigned inputCharCount, bool isUserInput) { if (m_formatMask.isEmpty()) return true; if (inputCharCount > m_numOfCharsAllowedByMask) return false; unsigned maskIndex = 0; if (isUserInput) { unsigned cursorPosition = 0; if (renderer()) cursorPosition = toRenderTextControl(renderer())->selectionStart(); else cursorPosition = m_data.cachedSelectionStart(); maskIndex = cursorPositionToMaskIndex(cursorPosition); } else maskIndex = cursorPositionToMaskIndex(inputCharCount - 1); bool ok = true; UChar mask = m_formatMask[maskIndex]; // match the inputed character with input mask switch (mask) { case 'A': ok = !WTF::isASCIIDigit(inChar) && !WTF::isASCIILower(inChar) && WTF::isASCIIPrintable(inChar); break; case 'a': ok = !WTF::isASCIIDigit(inChar) && !WTF::isASCIIUpper(inChar) && WTF::isASCIIPrintable(inChar); break; case 'N': ok = WTF::isASCIIDigit(inChar); break; case 'n': ok = !WTF::isASCIIAlpha(inChar) && WTF::isASCIIPrintable(inChar); break; case 'X': ok = !WTF::isASCIILower(inChar) && WTF::isASCIIPrintable(inChar); break; case 'x': ok = !WTF::isASCIIUpper(inChar) && WTF::isASCIIPrintable(inChar); break; case 'M': ok = WTF::isASCIIPrintable(inChar); break; case 'm': ok = WTF::isASCIIPrintable(inChar); break; default: ok = (mask == inChar); break; } return ok; } unsigned WMLInputElement::cursorPositionToMaskIndex(unsigned cursorPosition) { UChar mask; int index = -1; do { mask = m_formatMask[++index]; if (mask == '\\') ++index; else if (mask == '*' || (WTF::isASCIIDigit(mask) && mask != '0')) { index = m_formatMask.length() - 1; break; } } while (cursorPosition--); return index; } } #endif
cattleprod/samsung-kernel-gt-i9100
external/webkit/WebCore/wml/WMLInputElement.cpp
C++
gpl-2.0
16,920
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import sys def hook(mod): if sys.version[0] > '1': for i in range(len(mod.imports)-1, -1, -1): if mod.imports[i][0] == 'strop': del mod.imports[i] return mod
pdubroy/kurt
build/MacOS/PyInstaller/pyinstaller-svn-r812/hooks/hook-carchive.py
Python
gpl-2.0
1,029
#ifndef AnalysisTool_h #define AnalysisTool_h 1 #include "StackingTool.hh" #include <sstream> // stringstream using namespace std; class AnalysisTool { public: AnalysisTool(); virtual ~AnalysisTool(); virtual void PrintTool(); virtual bool getInterest(); virtual bool getInterest(int particle, int sturface); virtual bool getInterest(int particle, int sturface, int creationProcess, int flagPhotoElectron); virtual bool getInterest(int particle, int sturface, int volume); virtual bool getInterest(int particle, int surface, double energy); virtual string processData(); virtual string processData(int id, float energy); virtual string processData(int creation_process); private: }; #endif
OWoolland/MemoryMappedFileReader
Source/include/AnalysisTool.hh
C++
gpl-2.0
809
<?php /** * The header template file. * @package PaperCuts * @since PaperCuts 1.0.0 */ ?><!DOCTYPE html> <!--[if IE 7]> <html class="ie ie7" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 8]> <html class="ie ie8" <?php language_attributes(); ?>> <![endif]--> <!--[if !(IE 7) | !(IE 8) ]><!--> <html <?php language_attributes(); ?>> <!--<![endif]--> <head> <?php global $papercuts_options_db; ?> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <meta name="viewport" content="width=device-width" /> <title><?php wp_title( '|', true, 'right' ); ?></title> <?php if ($papercuts_options_db['papercuts_favicon_url'] != ''){ ?> <link rel="shortcut icon" href="<?php echo esc_url($papercuts_options_db['papercuts_favicon_url']); ?>" /> <?php } ?> <?php wp_head(); ?> </head> <body <?php body_class(); ?> id="wrapper"> <?php if ( !is_page_template('template-landing-page.php') ) { ?> <?php if ( has_nav_menu( 'top-navigation' ) || $papercuts_options_db['papercuts_header_facebook_link'] != '' || $papercuts_options_db['papercuts_header_twitter_link'] != '' || $papercuts_options_db['papercuts_header_google_link'] != '' || $papercuts_options_db['papercuts_header_rss_link'] != '' ) { ?> <div id="top-navigation-wrapper"> <div class="top-navigation"> <?php if ( has_nav_menu( 'top-navigation' ) ) { wp_nav_menu( array( 'menu_id'=>'top-nav', 'theme_location'=>'top-navigation' ) ); } ?> <div class="header-icons"> <?php if ($papercuts_options_db['papercuts_header_facebook_link'] != ''){ ?> <a class="social-icon facebook-icon" href="<?php echo esc_url($papercuts_options_db['papercuts_header_facebook_link']); ?>"><img src="<?php echo esc_url(get_template_directory_uri()); ?>/images/icon-facebook.png" alt="Facebook" /></a> <?php } ?> <?php if ($papercuts_options_db['papercuts_header_twitter_link'] != ''){ ?> <a class="social-icon twitter-icon" href="<?php echo esc_url($papercuts_options_db['papercuts_header_twitter_link']); ?>"><img src="<?php echo esc_url(get_template_directory_uri()); ?>/images/icon-twitter.png" alt="Twitter" /></a> <?php } ?> <?php if ($papercuts_options_db['papercuts_header_google_link'] != ''){ ?> <a class="social-icon google-icon" href="<?php echo esc_url($papercuts_options_db['papercuts_header_google_link']); ?>"><img src="<?php echo esc_url(get_template_directory_uri()); ?>/images/icon-google.png" alt="Google +" /></a> <?php } ?> <?php if ($papercuts_options_db['papercuts_header_rss_link'] != ''){ ?> <a class="social-icon rss-icon" href="<?php echo esc_url($papercuts_options_db['papercuts_header_rss_link']); ?>"><img src="<?php echo esc_url(get_template_directory_uri()); ?>/images/icon-rss.png" alt="RSS" /></a> <?php } ?> </div> </div> </div> <?php }} ?> <header id="wrapper-header"> <div id="header"> <div class="header-content-wrapper"> <div class="header-content"> <?php if ( $papercuts_options_db['papercuts_logo_url'] == '' ) { ?> <p class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>"><?php bloginfo( 'name' ); ?></a></p> <?php if ( $papercuts_options_db['papercuts_display_site_description'] != 'Hide' ) { ?> <p class="site-description"><?php bloginfo( 'description' ); ?></p> <?php } ?> <?php } else { ?> <a href="<?php echo esc_url( home_url( '/' ) ); ?>"><img class="header-logo" src="<?php echo esc_url($papercuts_options_db['papercuts_logo_url']); ?>" alt="<?php bloginfo( 'name' ); ?>" /></a> <?php } ?> <?php if ( $papercuts_options_db['papercuts_display_search_form'] != 'Hide' && !is_page_template('template-landing-page.php') ) { ?> <?php get_search_form(); ?> <?php } ?> </div> </div> <?php if ( has_nav_menu( 'main-navigation' ) && !is_page_template('template-landing-page.php') ) { ?> <div class="menu-box-wrapper"> <div class="menu-box"> <?php wp_nav_menu( array( 'menu_id'=>'nav', 'theme_location'=>'main-navigation' ) ); ?> </div> </div> <?php } ?> </div> <!-- end of header --> </header> <!-- end of wrapper-header --> <div id="container"> <div id="main-content"> <div id="content"> <?php if ( is_home() || is_front_page() ) { ?> <?php if ( get_header_image() != '' && $papercuts_options_db['papercuts_display_header_image'] != 'Everywhere except Homepage' ) { ?> <div class="header-image-wrapper"><div class="header-image"><img src="<?php header_image(); ?>" alt="<?php bloginfo( 'name' ); ?>" /></div></div> <?php } ?> <?php } else { ?> <?php if ( get_header_image() != '' && $papercuts_options_db['papercuts_display_header_image'] != 'Only on Homepage' ) { ?> <div class="header-image-wrapper"><div class="header-image"><img src="<?php header_image(); ?>" alt="<?php bloginfo( 'name' ); ?>" /></div></div> <?php } ?> <?php } ?>
udhayarajselvan/matrix
wp-content/themes/papercuts/header.php
PHP
gpl-2.0
4,753
<?php session_start(); $exercise = $_SESSION['exercise']; if($_POST){ unset($exercise[$_POST['id']]); $_SESSION['exercise'] = $exercise; header('Location: ./'); } $workout = $exercise[$_REQUEST['id']]; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>Exercise Log: Delete</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" type="text/css" /> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <link rel="stylesheet" type="text/css" href="../style/stylesheet.css" /> </head> <body> <div class="container"> <div class="page-header"> <h1>Exercise <small>Viewing <?=$workout['Name']?> workout</small></h1> </div> <ul> <li>Workout Name: <?=$workout['Name']?></li> <li>Workout Amount: <?=$workout['Amount']?></li> <li>Workout Time: <?=$workout['Time']?></li> <li>Workout Calories Burned: <?=$workout['Calories']?></li> </ul> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script> <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <script type="text/javascript"> (function($){ $(function(){ }); })(jQuery); </script> </body> </html>
kevinflaherty/Web-Programming
fitness/exercise/view.php
PHP
gpl-2.0
2,009
<?php /** * Validate form * * @param array $form definition * @param array $data filtered * @return boolean | array ('fildname'=>'error message') */ function validateForm($form, $datafiltered) { $validatedata = null; foreach ($form as $key => $form_field) { // if ($form[$key]['validation'] != null) { // hay que validar if (array_key_exists( 'validation', $form[$key] )) { // hay que validar $validation = $form_field['validation']; $valor = $datafiltered[$key]; foreach ($validation as $val_type => $val_data) { switch ($val_type) { case 'required': if ($valor == null) { if (array_key_exists('error_message', $validation)) { $validatedata[$key] = $validation['error_message']; } else { $validatedata[$key] = $key." no puede ser nulo"; } } break; case 'minsize': // echo '<pre>'; // print_r(strlen($valor)); // echo '</pre>'; if ($valor != null && (strlen($valor) < $validation['minsize'])) { if (array_key_exists('error_message', $validation)) { $validatedata[$key] = $validation['error_message']; } else { $validatedata[$key] = $key." debe de tener más de ".$validation['minsize']; } } break; case 'maxsize': if ($valor != null && (strlen($valor) > $validation['maxsize'])) { if (array_key_exists('error_message', $validation)) { $validatedata[$key] = $validation['error_message']; } else { $validatedata[$key] = $key." debe de tener más de ".$validation['maxsize']; } } break; } } } } if ($validatedata == null) { $validatedata = true; } return $validatedata; }
bermartinv/php2015
modules/core/src/core/validateForm.php
PHP
gpl-2.0
2,403
// // ReadEntityBodyMode.cs // // Author: Martin Thwaites (github@my2cents.co.uk) // // Copyright (C) 2014 Martin Thwaites // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. namespace System.Web { public enum ReadEntityBodyMode { None, Classic, Bufferless, Buffered, } }
hardvain/mono-compiler
class/System.Web/System.Web/ReadEntityBodyMode.cs
C#
gpl-2.0
1,312
#!/usr/bin/python3 # @begin:license # # Copyright (c) 2015-2019, Benjamin Niemann <pink@odahoda.de> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # @end:license import logging import random from . import ipc_test_pb2 from . import ipc_test logger = logging.getLogger(__name__) class IPCPerfTest(ipc_test.IPCPerfTestBase): async def test_small_messages(self): request = ipc_test_pb2.TestRequest() request.t.add(numerator=random.randint(0, 4), denominator=random.randint(1, 2)) await self.run_test(request, 5000) async def test_large_messages(self): request = ipc_test_pb2.TestRequest() for _ in range(10000): request.t.add(numerator=random.randint(0, 4), denominator=random.randint(1, 2)) await self.run_test(request, 100)
odahoda/noisicaa
noisicaa/core/ipc_perftest.py
Python
gpl-2.0
1,459
#ifndef INC_FMTLexer_hpp_ #define INC_FMTLexer_hpp_ #include <antlr/config.hpp> /* $ANTLR 2.7.7 (20130428): "format.g" -> "FMTLexer.hpp"$ */ #include <antlr/CommonToken.hpp> #include <antlr/InputBuffer.hpp> #include <antlr/BitSet.hpp> #include "FMTTokenTypes.hpp" #include <antlr/CharScanner.hpp> #include <fstream> #include <sstream> #include "fmtnode.hpp" #include "CFMTLexer.hpp" #include <antlr/TokenStreamSelector.hpp> //using namespace antlr; class CUSTOM_API FMTLexer : public antlr::CharScanner, public FMTTokenTypes { private: antlr::TokenStreamSelector* selector; CFMTLexer* cLexer; public: void SetSelector( antlr::TokenStreamSelector& s) { selector = &s; } void SetCLexer( CFMTLexer& l) { cLexer = &l; } private: void initLiterals(); public: bool getCaseSensitiveLiterals() const { return false; } public: FMTLexer(std::istream& in); FMTLexer(antlr::InputBuffer& ib); FMTLexer(const antlr::LexerSharedInputState& state); antlr::RefToken nextToken(); public: void mSTRING(bool _createToken); public: void mCSTRING(bool _createToken); public: void mLBRACE(bool _createToken); public: void mRBRACE(bool _createToken); public: void mSLASH(bool _createToken); public: void mCOMMA(bool _createToken); public: void mA(bool _createToken); public: void mTERM(bool _createToken); public: void mNONL(bool _createToken); public: void mF(bool _createToken); public: void mD(bool _createToken); public: void mE(bool _createToken); public: void mG(bool _createToken); public: void mI(bool _createToken); public: void mO(bool _createToken); public: void mB(bool _createToken); public: void mZ(bool _createToken); public: void mZZ(bool _createToken); public: void mQ(bool _createToken); public: void mH(bool _createToken); public: void mT(bool _createToken); public: void mL(bool _createToken); public: void mR(bool _createToken); public: void mX(bool _createToken); public: void mC(bool _createToken); public: void mCMOA(bool _createToken); public: void mCMoA(bool _createToken); public: void mCmoA(bool _createToken); public: void mCMOI(bool _createToken); public: void mCDI(bool _createToken); public: void mCMI(bool _createToken); public: void mCYI(bool _createToken); public: void mCSI(bool _createToken); public: void mCSF(bool _createToken); public: void mCHI(bool _createToken); public: void mChI(bool _createToken); public: void mCDWA(bool _createToken); public: void mCDwA(bool _createToken); public: void mCdwA(bool _createToken); public: void mCAPA(bool _createToken); public: void mCApA(bool _createToken); public: void mCapA(bool _createToken); public: void mPERCENT(bool _createToken); public: void mDOT(bool _createToken); public: void mPM(bool _createToken); public: void mMP(bool _createToken); protected: void mW(bool _createToken); public: void mWHITESPACE(bool _createToken); protected: void mDIGITS(bool _createToken); protected: void mCHAR(bool _createToken); public: void mNUMBER(bool _createToken); private: static const unsigned long _tokenSet_0_data_[]; static const antlr::BitSet _tokenSet_0; static const unsigned long _tokenSet_1_data_[]; static const antlr::BitSet _tokenSet_1; static const unsigned long _tokenSet_2_data_[]; static const antlr::BitSet _tokenSet_2; }; #endif /*INC_FMTLexer_hpp_*/
olebole/gnudatalanguage
src/FMTLexer.hpp
C++
gpl-2.0
3,373
#include "db/db.h" Database::Database() { this->records_tree_ = nullptr; } void Database::Read(DatabaseReader &reader) { this->records_tree_ = reader.ReadIndex(); } Record *Database::GetRecordsTree() const { return this->records_tree_; } void Database::SetRecordsTree(Record *records_tree) { this->records_tree_ = records_tree; }
bramberg/cclinf2
src/db/db.cc
C++
gpl-2.0
339
<?php /** * * You may not change or alter any portion of this comment or credits * of supporting developers from this source code or any supporting source code * which is considered copyrighted (c) material of the original comment or credit authors. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * @copyright XOOPS Project (https://xoops.org) * @license GNU GPL 2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html) * @package * @since 2.5.9 * @author Michael Beck (aka Mamba) */ require_once __DIR__ . '/../../../mainfile.php'; $op = \Xmf\Request::getCmd('op', ''); switch ($op) { case 'load': loadSampleData(); break; } // XMF TableLoad for SAMPLE data function loadSampleData() { // $moduleDirName = basename(dirname(__DIR__)); xoops_loadLanguage('comment'); $items = \Xmf\Yaml::readWrapped('quotes_data.yml'); \Xmf\Database\TableLoad::truncateTable('randomquote_quotes'); \Xmf\Database\TableLoad::loadTableFromArray('randomquote_quotes', $items); redirect_header('../admin/index.php', 1, _CM_ACTIVE); }
mambax7/257
htdocs/modules/wflinks/testdata/index.php
PHP
gpl-2.0
1,254
<?php /** * @package Expose * @version 3.0.1 * @author ThemeXpert http://www.themexpert.com * @copyright Copyright (C) 2010 - 2011 ThemeXpert * @license http://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3 * @file layout.php **/ //prevent direct access defined ('EXPOSE_VERSION') or die ('resticted aceess'); //import joomla filesystem classes jimport('joomla.filesystem.folder'); jimport('joomla.filesystem.file'); class ExposeLayout { protected $modules = array(); protected $widgets = array(); protected $activeWidgets = array(); public function __construct() { //load all widgets in an array and trigger the initialize event for those widgets. $this->loadWidgets(); } public static function getInstance() { static $instance; if(!isset($instance)) { $instance = New ExposeLayout; } return $instance; } public function countModules($position) { //check if the module schema already exist for this position return it back. //if not exist set if first if(!isset($this->modules[$position]['schema'])) { $this->setModuleSchema($position); } $published = 0; //check orphan module position which have nos subset. if($this->countModulesForPosition($position) OR $this->countWidgetsForPosition($position)) { //set this position in active array record $this->modules[$position]['active'][] = $position; $published ++; $this->modules[$position]['published'] = $published; return TRUE; } //loop through all module-position(eg: roof-1, roof-2) and set the total published module num. foreach($this->modules[$position]['schema'] as $num => $v) { $positionName = ($position . '-' . $num) ; if($this->countModulesForPosition($positionName) OR $this->countWidgetsForPosition($positionName)) { //set this position in active array record $this->modules[$position]['active'][] = $positionName; $published ++; } } $this->modules[$position]['published'] = $published; if($published > 0) return TRUE; return FALSE; } public function renderModules($position) { global $expose; $totalPublished = $this->modules[$position]['published']; $i = 1; if($totalPublished > 0 AND isset($this->modules[$position]['active'])) { $widths = $this->getModuleSchema($position); $containerClass = 'ex-column'; foreach($this->getActiveModuleLists($position) as $positionName) { //$totalModulesInPosition = $this->countModulesForPosition( $positionName ); $width = array_shift($widths); $class = ''; $html = ''; //we'll make all width 100% for mobile device if($expose->platform == 'mobile'){ $width = 100; } if($i == 1) $class .= 'ex-first '; if($i == $totalPublished){ $class .= 'ex-last '; } $class .= ($i%2) ? 'ex-odd' : 'ex-even'; if($i == ($totalPublished -1)) $class .= ' ie6-offset'; $style = "style=\"width: $width%\" "; if(count($this->modules[$position]['schema']) == 1) $style = ''; //Exception for single module position //we'll load all widgets first published in this position if($this->countWidgetsForPosition($positionName)) { foreach($this->activeWidgets[$positionName] as $widget) { $name = 'widget-' . $widget->name; $html .= "<div class=\"ex-block ex-widget no-title column-spacing $name clearfix\">"; $html .= "<div class=\"ex-content\">"; $html .= $widget->render(); $html .= "</div>"; $html .= "</div>"; } } $modWrapperStart = "<div class=\"$containerClass $class $positionName\" $style>"; $modWrapperEnd = "</div>"; //now load modules content $chrome = $this->getModuleChrome($position,$positionName); $html .= '<jdoc:include type="modules" name="'.$positionName.'" style="'.$chrome.'" />'; echo $modWrapperStart . $html . $modWrapperEnd; $i++; } } } protected function setModuleSchema($position) { global $expose; $values = $expose->get($position); $values = explode(',', $values); foreach($values as $value) { list($i, $v) = explode(':', "$value:"); $this->modules[$position]['schema'][$i][] = $v; } } public function getModuleSchema($position) { if(!isset($this->modules[$position])) { return; } $published = $this->modules[$position]['published']; //return module schema based on active modules return $this->modules[$position]['schema'][$published]; } public function getModuleChrome($position, $module) { if(!isset($this->modules[$position]['chrome'])) { $this->setModuleChrome($position); } return $this->modules[$position]['chrome'][$module]; } protected function setModuleChrome($position) { global $expose; $fieldName = $position . '-chrome'; $data = $expose->get($fieldName); $data = explode(',', $data); foreach($data as $json) { list($modName, $chrome) = explode(':',$json); $this->modules[$position]['chrome'][$modName] = $chrome; } } public function getActiveModuleLists($position) { //return active module array associate with position return $this->modules[$position]['active']; } public function getWidget($name) { if(isset($this->widgets[$name])) { return $this->widgets[$name]; } return FALSE; } public function getWidgetsForPosition($position) { if(!isset($this->widgets)) { $this->loadWidgets(); } $widgets = array(); foreach($this->widgets as $name => $instance) { if($instance->isEnabled() AND $instance->isInPosition($position) AND method_exists($instance, 'render')){ $widgets[$name] = $instance; } } return $widgets; } public function countWidgetsForPosition($position) { global $expose; $count = 0; $this->activeWidgets[$position] = array(); if($expose->platform == 'mobile') { foreach($this->getWidgetsForPosition($position) as $widget) { if($widget->isInMobile()) { if(!in_array($widget, $this->activeWidgets[$position])) { $this->activeWidgets[$position][] = $widget; } $count++ ; } } }else{ foreach ($this->getWidgetsForPosition($position) as $widget) { if(!in_array($widget, $this->activeWidgets[$position])) { $this->activeWidgets[$position][] = $widget; } $count++; } } return $count; //return count($this->getWidgetsForPosition($position)); } public function countModulesForPosition($position) { global $expose; $parentField = substr($position,0,strpos($position,'-')); //split the number and get the parent field name if($expose->platform == 'mobile') { if($expose->get($parentField.'-mobile')) { return $expose->document->countModules($position); }else{ return FALSE; } } return $expose->document->countModules($position); } protected function loadWidgets() { global $expose; //define widgets paths $widgetPaths = array( $expose->exposePath . DS . 'widgets', $expose->templatePath . DS .'widgets' ); $widgetLists = array(); //first loop through all the template and framework path and take widget instance foreach($widgetPaths as $widgetPath) { $widgets = JFolder::files($widgetPath, '.php'); if(is_array($widgets)) { foreach($widgets as $widget) { $widgetName = JFile::stripExt($widget); $path = $widgetPath . DS . $widgetName .'.php'; $widgetLists[$widgetName] = $path; } } } ksort($widgetLists); foreach($widgetLists as $name => $path) { $className = 'ExposeWidget'. ucfirst($name); if(!class_exists($className) AND JFile::exists($path)) { require_once($path); if(class_exists($className)) { $this->widgets[$name] = new $className(); } } } //now initialize the widgets which is not position specific foreach($this->widgets as $name => $instance) { //we'll load the widgets based on platform permission if($expose->platform == 'mobile') { if($instance->isEnabled() AND $instance->isInMobile() AND method_exists($instance , 'init')) { $instance->init(); } }else{ if($instance->isEnabled() AND method_exists($instance, 'init')) { $instance->init(); } } } } public function renderBody() { global $expose; $layouts = (isset ($_COOKIE[$expose->templateName.'_layouts'])) ? $_COOKIE[$expose->templateName.'_layouts'] : $expose->get('layouts'); if(isset ($_REQUEST['layouts'])){ setcookie($expose->templateName.'_layouts',$_REQUEST['layouts'],time()+3600,'/'); $layouts = $_REQUEST['layouts']; } $bPath = $expose->exposePath . DS . 'layouts'; $tPath = $expose->templatePath . DS .'layouts'; $ext = '.php'; if( $expose->platform == 'mobile' ) { $device = strtolower($expose->browser->getBrowser()); $bfile = $bPath .DS . $device . $ext; $tfile = $tPath .DS . $device . $ext; if($expose->get('iphone-enabled') AND $device == 'iphone') { $this->loadFile(array($tfile,$bfile)); }elseif($expose->get('android-enabled') AND $device == 'android'){ $this->loadFile(array($tfile,$bfile)); }else{ return FALSE; } }else{ $bfile = $bPath .DS . $layouts . $ext; $tfile = $tPath .DS . $layouts . $ext; $this->loadFile(array($tfile,$bfile)); } } public function loadFile($paths) { if(is_array($paths)) { foreach($paths as $path) { if(JFile::exists($path)){ require_once($path); break; } } }else if(JFile::exists($paths)) { require_once ($paths); }else{ JError::raiseNotice(E_NOTICE,"No file file found on given path $paths"); } } public function getModules() { return $this->modules; } }
jbelborja/deportivo
libraries/expose/core/layout.php
PHP
gpl-2.0
12,235
<?php /* Plugin Name: Social Likes Description: Wordpress plugin for Social Likes library by Artem Sapegin (http://sapegin.me/projects/social-likes) Version: 5.5.7 Author: TS Soft Author URI: http://ts-soft.ru/en/ License: MIT Copyright 2014 TS Soft LLC (email: dev@ts-soft.ru ) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ class wpsociallikes { const OPTION_NAME_MAIN = 'sociallikes'; const OPTION_NAME_CUSTOM_LOCALE = 'sociallikes_customlocale'; const OPTION_NAME_PLACEMENT = 'sociallikes_placement'; const OPTION_NAME_SHORTCODE = 'sociallikes_shortcode'; const OPTION_NAME_EXCERPTS = 'sociallikes_excerpts'; var $lang; var $options; var $buttons = array( 'vk_btn', 'facebook_btn', 'twitter_btn', 'google_btn', 'pinterest_btn', 'lj_btn', 'linkedin_btn', 'odn_btn', 'mm_btn', 'email_btn' ); function wpsociallikes() { add_option(self::OPTION_NAME_CUSTOM_LOCALE, ''); add_option(self::OPTION_NAME_PLACEMENT, 'after'); add_option(self::OPTION_NAME_SHORTCODE, 'disabled'); add_option(self::OPTION_NAME_EXCERPTS, 'disabled'); add_action('init', array(&$this, 'ap_action_init')); add_action('wp_head', array(&$this, 'header_content')); add_action('wp_enqueue_scripts', array(&$this, 'header_scripts')); add_action('admin_menu', array(&$this, 'wpsociallikes_menu')); add_action('save_post', array(&$this, 'save_post_meta')); add_action('admin_enqueue_scripts', array(&$this, 'wpsociallikes_admin_scripts')); add_filter('the_content', array(&$this, 'add_social_likes')); // https://github.com/tssoft/wp-social-likes/issues/7 add_filter('the_excerpt_rss', array(&$this, 'exclude_div_in_RSS_description')); add_filter('the_content_feed', array(&$this, 'exclude_div_in_RSS_content')); add_filter('plugin_action_links', array(&$this, 'add_action_links'), 10, 2); add_shortcode('wp-social-likes', array(&$this, 'shortcode_content')); } function ap_action_init() { $this->load_options(); $custom_locale = $this->options['customLocale']; if ($custom_locale) { load_textdomain('wp-social-likes', plugin_dir_path( __FILE__ ).'/languages/wp-social-likes-'.$custom_locale.'.mo'); } else { load_plugin_textdomain('wp-social-likes', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/'); } $this->title_vkontakte = __('Share link on VK', 'wp-social-likes'); $this->title_facebook = __('Share link on Facebook', 'wp-social-likes'); $this->title_twitter = __('Share link on Twitter', 'wp-social-likes'); $this->title_plusone = __('Share link on Google+', 'wp-social-likes'); $this->title_pinterest = __('Share image on Pinterest', 'wp-social-likes'); $this->title_livejournal = __('Share link on LiveJournal', 'wp-social-likes'); $this->title_linkedin = __('Share link on LinkedIn', 'wp-social-likes'); $this->title_odnoklassniki = __('Share link on Odnoklassniki', 'wp-social-likes'); $this->title_mailru = __('Share link on Mail.ru', 'wp-social-likes'); $this->title_email = __('Share link by E-mail', 'wp-social-likes'); $this->label_vkontakte = __('VK', 'wp-social-likes'); $this->label_facebook = __('Facebook', 'wp-social-likes'); $this->label_twitter = __('Twitter', 'wp-social-likes'); $this->label_plusone = __('Google+', 'wp-social-likes'); $this->label_pinterest = __('Pinterest', 'wp-social-likes'); $this->label_livejournal = __('LiveJournal', 'wp-social-likes'); $this->label_linkedin = __('LinkedIn', 'wp-social-likes'); $this->label_odnoklassniki = __('Odnoklassniki', 'wp-social-likes'); $this->label_mailru = __('Mail.ru', 'wp-social-likes'); $this->label_email = __('E-mail', 'wp-social-likes'); $this->label_share = __('Share', 'wp-social-likes'); } function header_content() { $skin = str_replace('light', '', $this->options['skin']); if (($skin != 'classic') && ($skin != 'flat') && ($skin != 'birman')) { $skin = 'classic'; } ?> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/social-likes_<?php echo $skin ?>.css"> <?php if ($this->button_is_active('lj_btn')) { ?> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal_<?php echo $skin ?>.css"> <?php } if ($this->button_is_active('linkedin_btn')) { ?> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin_<?php echo $skin ?>.css"> <?php } if ($this->button_is_active('email_btn')) { ?> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/email.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/email_<?php echo $skin ?>.css"> <?php } ?> <script src="<?php echo plugin_dir_url(__FILE__) ?>js/social-likes.min.js"></script> <?php if ($this->custom_buttons_enabled()) { ?> <script src="<?php echo plugin_dir_url(__FILE__) ?>js/custom-buttons.js"></script> <?php } } function header_scripts() { wp_enqueue_script('jquery'); } function wpsociallikes_admin_scripts() { wp_enqueue_script('jquery'); wp_enqueue_script('jquery-ui-sortable'); } function wpsociallikes_menu() { $post_opt = $this->options['post']; $page_opt = $this->options['page']; add_meta_box('wpsociallikes', 'Social Likes', array(&$this, 'wpsociallikes_meta'), 'post', 'normal', 'default', array('default'=>$post_opt)); add_meta_box('wpsociallikes', 'Social Likes', array(&$this, 'wpsociallikes_meta'), 'page', 'normal', 'default', array('default'=>$page_opt)); $args = array( 'public' => true, '_builtin' => false ); $post_types = get_post_types($args, 'names', 'and'); foreach ($post_types as $post_type ) { add_meta_box('wpsociallikes', 'Social Likes', array(&$this, 'wpsociallikes_meta'), $post_type, 'normal', 'default', array('default'=>$post_opt)); } $plugin_page = add_options_page('Social Likes', 'Social Likes', 'administrator', basename(__FILE__), array (&$this, 'display_admin_form')); add_action('admin_head-' . $plugin_page, array(&$this, 'admin_menu_head')); } function wpsociallikes_meta($post, $metabox) { if (!strstr($_SERVER['REQUEST_URI'], '-new.php')) { $checked = get_post_meta($post->ID, 'sociallikes', true); } else { $checked = $metabox['args']['default']; } if ($checked) { $img_url = get_post_meta($post->ID, 'sociallikes_img_url', true); if ($img_url == '' && $this->options['pinterestImg']) { $img_url = $this->get_post_first_img($post); } } else { $img_url = ''; } ?> <div id="social-likes"> <input type="hidden" name="wpsociallikes_update_meta" value="true" /> <div style="padding: 5px 0"> <input type="checkbox" name="wpsociallikes_enabled" id="wpsociallikes_enabled" <?php if ($checked) echo 'checked class="checked"' ?> title="<?php echo get_permalink($post->ID); ?>" /> <label for="wpsociallikes_enabled"><?php _e('Add social buttons', 'wp-social-likes') ?></label> </div> <table> <tr> <td><label for="wpsociallikes_image_url" style="padding-right:5px"><?php _e('Image&nbspURL:', 'wp-social-likes') ?></label></td> <td style="width:100%"> <input name="wpsociallikes_image_url" id="wpsociallikes_image_url" value="<?php echo $img_url ?>" <?php if (!$checked) echo 'disabled' ?> type="text" placeholder="<?php _e('Image URL (required for Pinterest)', 'wp-social-likes') ?>" style="width:100%" /> </td> </tr> </table> </div> <script> (function($) { var savedImageUrlValue = ''; $('input#wpsociallikes_enabled').change(function () { var $this = $(this); $this.toggleClass('checked'); var socialLikesEnabled = $this.hasClass('checked'); var imageUrlField = $('#wpsociallikes_image_url'); if (socialLikesEnabled) { imageUrlField .removeAttr('disabled') .val(savedImageUrlValue); } else { savedImageUrlValue = imageUrlField.val(); imageUrlField .attr('disabled', 'disabled') .val(''); } }); })( jQuery ); </script> <?php } function get_post_first_img($post) { $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); return $matches [1] [0]; } function save_post_meta($post_id) { if (!isset($_POST['wpsociallikes_update_meta']) || (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)) { return; } if ('page' == $_POST['post_type']) { if (!current_user_can('edit_page', $post_id)) { return; } } else { if (!current_user_can('edit_post', $post_id)) { return; } } update_post_meta($post_id, 'sociallikes', isset($_POST['wpsociallikes_enabled'])); $img_url_sent = isset($_POST['wpsociallikes_image_url']); $img_url = $img_url_sent ? $_POST['wpsociallikes_image_url'] : ''; if ($img_url_sent && $img_url == '' && $this->options['pinterestImg']) { $post = get_post($post_id); $img_url = $this->get_post_first_img($post); } update_post_meta($post_id, 'sociallikes_img_url', $img_url); } function add_social_likes($content = '') { global $post; if (in_the_loop() && get_post_meta($post->ID, 'sociallikes', true) && (is_page() || is_single() || $this->options['excerpts'] || !$this->is_post_with_excerpt())) { $this->lang = get_bloginfo('language'); $buttons = $this->build_buttons($post); $placement = $this->options['placement']; if ($placement != 'none') { if ($placement == 'before') { $content = $buttons . $content; } else if ($placement == 'before-after') { $content = $buttons . $content . $buttons; } else { $content .= $buttons; } } } return $content; } function is_post_with_excerpt() { global $page, $pages; $post_content = $pages[$page - 1]; return preg_match('/<!--more(.*?)?-->/', $post_content); } function build_buttons($post) { $twitter_via = $this->options['twitterVia']; //$twitter_rel = $this->options['twitterRel']; $look = $this->options['look']; $skin = $this->options['skin']; $light = false; if (strpos($skin, 'light')) { $light = true; $skin = str_replace('light', '', $skin); } $iconsOnly = $this->options['iconsOnly']; $label_vkontakte = $iconsOnly ? '' : $this->label_vkontakte; $label_facebook = $iconsOnly ? '' : $this->label_facebook; $label_twitter = $iconsOnly ? '' : $this->label_twitter; $label_plusone = $iconsOnly ? '' : $this->label_plusone; $label_pinterest = $iconsOnly ? '' : $this->label_pinterest; $label_livejournal = $iconsOnly ? '' : $this->label_livejournal; $label_linkedin = $iconsOnly ? '' : $this->label_linkedin; $label_odnoklassniki = $iconsOnly ? '' : $this->label_odnoklassniki; $label_mailru = $iconsOnly ? '' : $this->label_mailru; $label_email = $iconsOnly ? '' : $this->label_email; $socialButton['vk_btn'] = '<div class="vkontakte" title="'.$this->title_vkontakte.'">'.$label_vkontakte.'</div>'; $socialButton['facebook_btn'] = '<div class="facebook" title="'.$this->title_facebook.'">'.$label_facebook.'</div>'; $socialButton['twitter_btn'] = '<div class="twitter" '; if ($twitter_via != '') { $socialButton['twitter_btn'] .= 'data-via="' . $twitter_via . '" '; } /*if ($twitter_rel != '') { $socialButton['twitter_btn'] .= 'data-related="' . $twitter_rel . '" '; }*/ $socialButton['twitter_btn'] .= 'title="'.$this->title_twitter.'">'.$label_twitter.'</div>'; $socialButton['google_btn'] = '<div class="plusone" title="'.$this->title_plusone.'">'.$label_plusone.'</div>'; $img_url = get_post_meta($post->ID, 'sociallikes_img_url', true); $socialButton['pinterest_btn'] = '<div class="pinterest" title="' . $this->title_pinterest . '"'; if ($img_url != '') { $socialButton['pinterest_btn'] .= ' data-media="' . $img_url . '"'; } if ($img_url == '' && $this->options['pinterestImg']) { $socialButton['pinterest_btn'] .= ' data-media="' . $this->get_post_first_img($post) . '"'; } $socialButton['pinterest_btn'] .= '>' . $label_pinterest . '</div>'; $socialButton['lj_btn'] = '<div class="livejournal" title="' .$this->title_livejournal .'" data-html="&lt;a href=\'{url}\'&gt;{title}&lt;/a&gt;">' .$label_livejournal.'</div>'; $socialButton['linkedin_btn'] = '<div class="linkedin" title="'.$this->title_linkedin.'">'.$label_linkedin.'</div>'; $socialButton['odn_btn'] = '<div class="odnoklassniki" title="'.$this->title_odnoklassniki.'">'.$label_odnoklassniki.'</div>'; $socialButton['mm_btn'] = '<div class="mailru" title="'.$this->title_mailru.'">'.$label_mailru.'</div>'; $socialButton['email_btn'] = '<div class="email" title="'.$this->title_email.'">'.$label_email.'</div>'; $main_div = '<div class="social-likes'; $classAppend = ''; if ($iconsOnly) { $classAppend .= ' social-likes_notext'; } if (($skin == 'flat') && $light) { $classAppend .= ' social-likes_light'; } if ($look == 'h') { $main_div .= $classAppend.'"'; } elseif ($look == 'v') { $main_div .= ' social-likes_vertical'.$classAppend.'"'; } else { $main_div .= ' social-likes_single'.$classAppend.'" data-single-title="'.$this->label_share.'"'; } $main_div .= ' data-title="' . $post->post_title . '"'; $main_div .= ' data-url="' . get_permalink( $post->ID ) . '"'; $main_div .= $this->options['counters'] ? ' data-counters="yes"' : ' data-counters="no"'; $main_div .= $this->options['zeroes'] ? ' data-zeroes="yes"' : ''; $main_div .= '>'; foreach ($this->options['buttons'] as $btn) { if (in_array($btn, $this->buttons)) { $main_div .= $socialButton[$btn]; } } $main_div .= '</div><form style="display: none;" class="sociallikes-livejournal-form"></form>'; return $main_div; } function admin_menu_head() { ?> <link rel="stylesheet" id="sociallikes-style-classic" href="<?php echo plugin_dir_url(__FILE__) ?>css/social-likes_classic.css"> <link rel="stylesheet" id="sociallikes-style-flat" href="<?php echo plugin_dir_url(__FILE__) ?>css/social-likes_flat.css"> <link rel="stylesheet" id="sociallikes-style-birman" href="<?php echo plugin_dir_url(__FILE__) ?>css/social-likes_birman.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal.css"> <link rel="stylesheet" id="sociallikes-style-classic-livejournal" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal_classic.css"> <link rel="stylesheet" id="sociallikes-style-flat-livejournal" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal_flat.css"> <link rel="stylesheet" id="sociallikes-style-birman-livejournal" href="<?php echo plugin_dir_url(__FILE__) ?>css/livejournal_birman.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin.css"> <link rel="stylesheet" id="sociallikes-style-classic-linkedin" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin_classic.css"> <link rel="stylesheet" id="sociallikes-style-flat-linkedin" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin_flat.css"> <link rel="stylesheet" id="sociallikes-style-birman-linkedin" href="<?php echo plugin_dir_url(__FILE__) ?>css/linkedin_birman.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/email.css"> <link rel="stylesheet" id="sociallikes-style-classic-email" href="<?php echo plugin_dir_url(__FILE__) ?>css/email_classic.css"> <link rel="stylesheet" id="sociallikes-style-flat-email" href="<?php echo plugin_dir_url(__FILE__) ?>css/email_flat.css"> <link rel="stylesheet" id="sociallikes-style-birman-email" href="<?php echo plugin_dir_url(__FILE__) ?>css/email_birman.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__) ?>css/admin-page.css"> <script src="<?php echo plugin_dir_url(__FILE__) ?>js/social-likes.min.js"></script> <script src="<?php echo plugin_dir_url(__FILE__) ?>js/preview.js"></script> <?php } function display_admin_form() { if (isset($_POST['submit']) || isset($_POST['apply_to_posts']) || isset($_POST['apply_to_pages'])) { $this->submit_admin_form(); } if (isset($_POST['apply_to_posts'])) { $args = array('numberposts' => -1, 'post_type' => 'post', 'post_status' => 'any'); $result = get_posts($args); foreach ($result as $post) { update_post_meta($post->ID, 'sociallikes', isset($_POST['post_chb'])); } } if (isset($_POST['apply_to_pages'])) { $args = array('post_type' => 'page'); $result = get_pages($args); foreach ($result as $post) { update_post_meta($post->ID, 'sociallikes', isset($_POST['page_chb'])); } } $this->load_options(); $look = $this->options['look']; $counters = $this->options['counters']; $post = $this->options['post']; $page = $this->options['page']; $skin = $this->options['skin']; $light = false; if (strpos($skin, 'light')) { $light = true; } if (($skin != 'classic') && ($skin != 'flat') && ($skin != 'flatlight') && ($skin != 'birman')) { $skin = 'classic'; } $zeroes = $this->options['zeroes']; $iconsOnly = $this->options['iconsOnly']; $label["vk_btn"] = __("VK", 'wp-social-likes'); $label["facebook_btn"] = __("Facebook", 'wp-social-likes'); $label["twitter_btn"] = __("Twitter", 'wp-social-likes'); $label["google_btn"] = __("Google+", 'wp-social-likes'); $label["pinterest_btn"] = __("Pinterest", 'wp-social-likes'); $label["lj_btn"] = __("LiveJournal", 'wp-social-likes'); $label["linkedin_btn"] = __("LinkedIn", 'wp-social-likes'); $label["odn_btn"] = __("Odnoklassniki", 'wp-social-likes'); $label["mm_btn"] = __("Mail.ru", 'wp-social-likes'); $label["email_btn"] = __("E-mail", 'wp-social-likes'); $this->lang = get_bloginfo('language'); ?> <div class="wrap"> <h2><?php _e('Social Likes Settings', 'wp-social-likes') ?></h2> <form name="wpsociallikes" method="post" action="?page=wp-social-likes.php&amp;updated=true"> <?php wp_nonce_field('update-options'); ?> <input id="title_vkontakte" type="hidden" value="<?php echo $this->title_vkontakte ?>"> <input id="title_facebook" type="hidden" value="<?php echo $this->title_facebook ?>"> <input id="title_twitter" type="hidden" value="<?php echo $this->title_twitter ?>"> <input id="title_plusone" type="hidden" value="<?php echo $this->title_plusone ?>"> <input id="title_pinterest" type="hidden" value="<?php echo $this->title_pinterest ?>"> <input id="title_livejournal" type="hidden" value="<?php echo $this->title_livejournal ?>"> <input id="title_linkedin" type="hidden" value="<?php echo $this->title_linkedin ?>"> <input id="title_odnoklassniki" type="hidden" value="<?php echo $this->title_odnoklassniki ?>"> <input id="title_mailru" type="hidden" value="<?php echo $this->title_mailru ?>"> <input id="title_email" type="hidden" value="<?php echo $this->title_email ?>"> <input id="label_vkontakte" type="hidden" value="<?php echo $this->label_vkontakte ?>"> <input id="label_facebook" type="hidden" value="<?php echo $this->label_facebook ?>"> <input id="label_twitter" type="hidden" value="<?php echo $this->label_twitter ?>"> <input id="label_plusone" type="hidden" value="<?php echo $this->label_plusone ?>"> <input id="label_pinterest" type="hidden" value="<?php echo $this->label_pinterest ?>"> <input id="label_livejournal" type="hidden" value="<?php echo $this->label_livejournal ?>"> <input id="label_linkedin" type="hidden" value="<?php echo $this->label_linkedin ?>"> <input id="label_odnoklassniki" type="hidden" value="<?php echo $this->label_odnoklassniki ?>"> <input id="label_mailru" type="hidden" value="<?php echo $this->label_mailru ?>"> <input id="label_email" type="hidden" value="<?php echo $this->label_email ?>"> <input id="label_share" type="hidden" value="<?php echo $this->label_share ?>"> <input id="confirm_leaving_message" type="hidden" value="<?php _e('You have unsaved changes on this page. Do you want to leave this page and discard your changes?', 'wp-social-likes') ?>"> <table class="plugin-setup"> <tr valign="top"> <th scope="row"><?php _e('Skin', 'wp-social-likes') ?></th> <td class="switch-button-row"> <div style="float: left;"> <input type="radio" name="skin" id="skin_classic" class="view-state<?php if ($skin == 'classic') echo ' checked' ?>" value="classic" <?php if ($skin == 'classic') echo 'checked' ?> /> <label class="switch-button" for="skin_classic"><?php _e('Classic', 'wp-social-likes') ?></label> <input type="radio" name="skin" id="skin_flat" class="view-state<?php if ($skin == 'flat') echo ' checked' ?>" value="flat" <?php if ($skin == 'flat') echo ' checked' ?> /> <label class="switch-button" for="skin_flat"><?php _e('Flat', 'wp-social-likes') ?></label> <input type="radio" name="skin" id="skin_flatlight" class="view-state<?php if ($skin == 'flat') echo ' checked' ?>" value="flatlight" <?php if ($skin == 'flatlight') echo ' checked' ?> /> <label class="switch-button" for="skin_flatlight"><?php _e('Flat Light', 'wp-social-likes') ?></label> <input type="radio" name="skin" id="skin_birman" class="view-state<?php if ($skin == 'birman') echo ' checked' ?>" value="birman" <?php if ($skin == 'birman') echo ' checked' ?> /> <label class="switch-button" for="skin_birman"><?php _e('Birman', 'wp-social-likes') ?></label> </div> </td> </tr> <tr valign="top"> <th scope="row"><?php _e('Look', 'wp-social-likes') ?></th> <td class="switch-button-row"> <div style="float: left;"> <input type="radio" name="look" id="h_look" class="view-state<?php if ($look == 'h') echo ' checked' ?>" value="h" <?php if ($look == 'h') echo 'checked' ?> /> <label class="switch-button" for="h_look"<!--class="wpsl-label-->"><?php _e('Horizontal', 'wp-social-likes') ?></label> <input type="radio" name="look" id="v_look" class="view-state<?php if ($look == 'v') echo ' checked' ?>" value="v" <?php if ($look == 'v') echo ' checked' ?> /> <label class="switch-button" for="v_look"><?php _e('Vertical', 'wp-social-likes') ?></label> <input type="radio" name="look" id="s_look" class="view-state<?php if ($look == 's') echo ' checked' ?>" value="s" <?php if ($look == 's') echo ' checked' ?> /> <label class="switch-button" for="s_look"><?php _e('Single button', 'wp-social-likes') ?></label> </div> </td> </tr> <tr valign="top"> <th scope="row"></th> <td scope="row" class="without-bottom"> <div class="option-checkboxes"> <input type="checkbox" name="counters" id="counters" <?php if ($counters) echo 'checked' ?> /> <label for="counters" class="wpsl-label"><?php _e('Show counters', 'wp-social-likes') ?></label> </div> <div class="option-checkboxes" id="zeroes-container"> <input type="checkbox" name="zeroes" id="zeroes" <?php if ($zeroes) echo 'checked' ?> /> <label for="zeroes" class="wpsl-label"><?php _e('With zeroes', 'wp-social-likes') ?></label> </div> <div class="option-checkboxes" id="icons-container"> <input type="checkbox" name="icons" id="icons" <?php if ($iconsOnly) echo 'checked' ?> /> <label for="icons" class="wpsl-label"><?php _e('Icons only', 'wp-social-likes') ?></label> </div> </td> </tr> <tr valign="top"> <th class="valign-top" scope="row"><?php _e('Websites', 'wp-social-likes') ?></th> <td class="without-bottom"> <ul class="sortable-container"> <?php $remainingButtons = $this->buttons; for ($i = 1; $i <= count($label); $i++) { $btn = null; $checked = false; if ($i <= count($this->options['buttons'])) { $btn = $this->options['buttons'][$i - 1]; $index = array_search($btn, $remainingButtons, true); if ($index !== false) { array_splice($remainingButtons, $index, 1); $checked = true; } } if ($btn == null) { $btn = array_shift($remainingButtons); } $hidden = ($this->lang != 'ru-RU') && !$checked && ($btn == 'odn_btn' || $btn == 'mm_btn'); ?> <li class="sortable-item<?php if ($hidden) echo ' hidden' ?>"> <input type="checkbox" name="site[]" id="<?php echo $btn ?>" value="<?php echo $btn ?>" <?php if ($checked) echo 'checked' ?> /> <label for="<?php echo $btn ?>" class="wpsl-label"><?php echo $label[$btn] ?></label> </li> <?php } ?> </ul> <?php if ($this->lang != 'ru-RU' && !($this->button_is_active('odn_btn') && $this->button_is_active('mm_btn'))) { ?><span class="more-websites"><?php _e('More websites', 'wp-social-likes') ?></span><?php } ?> </td> </tr> <tr valign="top"> <th scope="row"><?php _e('Twitter Via', 'wp-social-likes') ?></th> <td> <input type="text" name="twitter_via" placeholder="<?php _e('Username', 'wp-social-likes') ?>" class="wpsl-field" value="<?php echo $this->options['twitterVia']; ?>" /> </td> </tr> <!--tr valign="top"> <th scope="row">Twitter Related</th> <td> <input type="text" name="twitter_rel" placeholder="Username:Description" class="wpsl-field" value="<?php echo $this->options['twitterRel']; ?>"/> </td> </tr--> <tr valign="top"> <th scope="row"></th> <td scope="row" class="without-bottom"> <input type="checkbox" name="pinterest_img" id="pinterest_img" <?php if ($this->options['pinterestImg']) echo 'checked' ?> /> <label for="pinterest_img" class="wpsl-label"><?php _e('Automatically place first image in the post/page to the Image URL field', 'wp-social-likes') ?></label> </td> </tr> <tr valign="top"> <th scope="row"></th> <td class="without-bottom"> <input type="checkbox" name="post_chb" id="post_chb" <?php if ($post) echo 'checked' ?> /> <label for="post_chb" class="wpsl-label"><?php _e('Add by default for new posts', 'wp-social-likes') ?></label> <input type="submit" name="apply_to_posts" id="apply_to_posts" value="<?php _e('Apply to existing posts', 'wp-social-likes') ?>" class="button-secondary"/> </td> </tr> <tr valign="top"> <th scope="row"></th> <td> <input type="checkbox" name="page_chb" id="page_chb" <?php if ($page) echo 'checked' ?> /> <label for="page_chb" class="wpsl-label"><?php _e('Add by default for new pages', 'wp-social-likes') ?></label> <input type="submit" name="apply_to_pages" id="apply_to_pages" value="<?php _e('Apply to existing pages', 'wp-social-likes') ?>" class="button-secondary" /> </td> </tr> </table> <div class="row"> <div id="preview" class="shadow-border" <?php if ($this->lang == 'ru-RU') echo 'language="ru"' ?> ></div> </div> <?php submit_button(); ?> </form> </div> <?php } function submit_admin_form() { $options = array( 'skin' => $_POST['skin'], 'look' => $_POST['look'], 'post' => isset($_POST['post_chb']), 'page' => isset($_POST['page_chb']), 'pinterestImg' => isset($_POST['pinterest_img']), 'twitterVia' => $_POST['twitter_via'], //'twitterRel' => $_POST['twitter_rel'], 'iconsOnly' => isset($_POST['icons']), 'counters' => isset($_POST['counters']), 'zeroes' => isset($_POST['zeroes']), 'buttons' => array() ); if (isset($_POST['site'])) { foreach ($_POST['site'] as $btn) { if (in_array($btn, $this->buttons)) { array_push($options['buttons'], $btn); } } } update_option(self::OPTION_NAME_MAIN, $options); $this->delete_deprecated_options(); } function exclude_div_in_RSS_description($content) { global $post; if (get_post_meta($post->ID, 'sociallikes', true)) { $index = strripos($content, ' '); $content = substr_replace($content, '', $index); } return $content; } function exclude_div_in_RSS_content($content) { if (is_feed()) { $content = preg_replace("/<div.*(class)=(\"|')social-likes(\"|').*>.*<\/div>/smUi", '', $content); } return $content; } function shortcode_content() { global $post; if ($this->options['shortcode']) { return $this->build_buttons($post); } return ''; } function add_action_links($all_links, $current_file) { if (basename(__FILE__) == basename($current_file)) { $plugin_file_name_parts = explode('/', plugin_basename(__FILE__)); $plugin_file_name = $plugin_file_name_parts[count($plugin_file_name_parts) - 1]; $settings_link = '<a href="' . admin_url('options-general.php?page=' . $plugin_file_name) . '">' . __('Settings', 'wp-social-likes') . '</a>'; array_unshift($all_links, $settings_link); } return $all_links; } function custom_buttons_enabled() { return $this->button_is_active('lj_btn') || $this->button_is_active('linkedin_btn') || $this->button_is_active('email_btn'); } function button_is_active($name) { return in_array($name, $this->options['buttons']); } function load_options() { $options = $this->load_deprecated_options(); if (!$options) { $options = get_option(self::OPTION_NAME_MAIN); if (!$options || !is_array($options)) { $options = array( 'counters' => true, 'look' => 'h', 'post' => true, 'skin' => 'classic' ); } if (!$options['buttons'] || !is_array($options['buttons'])) { $options['buttons'] = array(); for ($i = 0; $i < 4; $i++) { array_push($options['buttons'], $this->buttons[$i]); } } } $options['customLocale'] = get_option(self::OPTION_NAME_CUSTOM_LOCALE); $options['placement'] = get_option(self::OPTION_NAME_PLACEMENT); $options['shortcode'] = get_option(self::OPTION_NAME_SHORTCODE) == 'enabled'; $options['excerpts'] = get_option(self::OPTION_NAME_EXCERPTS) == 'enabled'; $defaultValues = array( 'look' => 'h', 'skin' => 'classic', 'twitterVia' => '', 'twitterRel' => '' ); foreach ($defaultValues as $key => $value) { if (!isset($options[$key]) || !$options[$key]) { $options[$key] = $value; } } $this->options = $options; } function load_deprecated_options() { if (!get_option('sociallikes_skin') || !get_option('sociallikes_look')) { return null; } $options = array( 'skin' => get_option('sociallikes_skin'), 'look' => get_option('sociallikes_look'), 'post' => get_option('sociallikes_post'), 'page' => get_option('sociallikes_page'), 'pinterestImg' => get_option('sociallikes_pinterest_img'), 'twitterVia' => get_option('sociallikes_twitter_via'), 'twitterRel' => get_option('sociallikes_twitter_rel'), 'iconsOnly' => get_option('sociallikes_icons'), 'counters' => get_option('sociallikes_counters'), 'zeroes' => get_option('sociallikes_zeroes'), 'buttons' => array() ); for ($i = 1; $i <= 8; $i++) { $option = 'pos' . $i; $btn = get_option($option); if (get_option($btn)) { array_push($options['buttons'], $btn); } } return $options; } function delete_deprecated_options() { delete_option('sociallikes_counters'); delete_option('sociallikes_look'); delete_option('sociallikes_twitter_via'); delete_option('sociallikes_twitter_rel'); delete_option('sociallikes_pinterest_img'); delete_option('sociallikes_post'); delete_option('sociallikes_page'); delete_option('sociallikes_skin'); delete_option('sociallikes_icons'); delete_option('sociallikes_zeroes'); delete_option('vk_btn'); delete_option('facebook_btn'); delete_option('twitter_btn'); delete_option('google_btn'); delete_option('pinterest_btn'); delete_option('lj_btn'); delete_option('odn_btn'); delete_option('mm_btn'); delete_option('pos1'); delete_option('pos2'); delete_option('pos3'); delete_option('pos4'); delete_option('pos5'); delete_option('pos6'); delete_option('pos7'); delete_option('pos8'); } } $wpsociallikes = new wpsociallikes(); function social_likes($postId = null) { echo get_social_likes($postId); } function get_social_likes($postId = null) { $post = get_post($postId); global $wpsociallikes; return $post != null ? $wpsociallikes->build_buttons($post) : ''; } ?>
tienthai0511/talk
wp-content/plugins/wp-social-likes/wp-social-likes.php
PHP
gpl-2.0
33,776
<?php /** * VuFind Statistics Class for Record Views * * PHP version 5 * * Copyright (C) Villanova University 2009. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @category VuFind2 * @package Statistics * @author Chris Hallberg <challber@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org/wiki/system_classes Wiki */ namespace VuFind\Statistics; /** * VuFind Statistics Class for Record Views * * @category VuFind2 * @package Statistics * @author Chris Hallberg <challber@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org/wiki/system_classes Wiki */ class Record extends AbstractBase { /** * Saves the record view to wherever the config [Statistics] says so * * @param \VuFind\Search\Base\Results $data Results from Search controller * @param Zend_Controller_Request_Http $request Request data * * @return void */ public function log($data, $request) { $this->save( array( 'recordId' => $data->getUniqueId(), 'recordSource' => $data->getResourceSource() ), $request ); } /** * Returns a set of basic statistics including total records * and most commonly viewed records. * * @param integer $listLength How long the top list is * @param bool $bySource Sort record views by source? * * @return array */ public function getStatsSummary($listLength = 5, $bySource = false) { foreach ($this->getDrivers() as $driver) { $summary = $driver->getFullList('recordId'); if (!empty($summary)) { $sources = $driver->getFullList('recordSource'); $hashes = array(); // Generate hashes (faster than grouping by looping) for ($i=0;$i<count($summary);$i++) { $source = $sources[$i]['recordSource']; $id = $summary[$i]['recordId']; $hashes[$source][$id] = isset($hashes[$source][$id]) ? $hashes[$source][$id] + 1 : 1; } $top = array(); // For each source foreach ($hashes as $source=>$records) { // Using a reference to consolidate code dramatically $reference =& $top; if ($bySource) { $top[$source] = array(); $reference =& $top[$source]; } // For each record foreach ($records as $id=>$count) { $newRecord = array( 'value' => $id, 'count' => $count, 'source' => $source ); // Insert sort (limit to listLength) for ($i=0;$i<$listLength-1 && $i<count($reference);$i++) { if ($count > $reference[$i]['count']) { // Insert in order array_splice($reference, $i, 0, array($newRecord)); continue 2; // Skip the append after this loop } } if (count($reference) < $listLength) { $reference[] = $newRecord; } } $reference = array_slice($reference, 0, $listLength); } return array( 'top' => $top, 'total' => count($summary) ); } } return array(); } }
no-reply/cbpl-vufind
module/VuFind/src/VuFind/Statistics/Record.php
PHP
gpl-2.0
4,569
<?php /** * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. */ namespace eZ\Publish\Core\Base\Container\Compiler\Search\Legacy; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Definition; /** * This compiler pass will register Legacy Search Engine criterion handlers. */ class CriteriaConverterPass implements CompilerPassInterface { /** * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container */ public function process(ContainerBuilder $container) { if ( !$container->hasDefinition('ezpublish.search.legacy.gateway.criteria_converter.content') && !$container->hasDefinition('ezpublish.search.legacy.gateway.criteria_converter.location') && !$container->hasDefinition('ezplatform.trash.search.legacy.gateway.criteria_converter') && !$container->hasDefinition('ezpublish.spi.persistence.legacy.url.criterion_converter') ) { return; } if ($container->hasDefinition('ezpublish.search.legacy.gateway.criteria_converter.content')) { $criteriaConverterContent = $container->getDefinition('ezpublish.search.legacy.gateway.criteria_converter.content'); $contentHandlers = $container->findTaggedServiceIds('ezpublish.search.legacy.gateway.criterion_handler.content'); $this->addHandlers($criteriaConverterContent, $contentHandlers); } if ($container->hasDefinition('ezpublish.search.legacy.gateway.criteria_converter.location')) { $criteriaConverterLocation = $container->getDefinition('ezpublish.search.legacy.gateway.criteria_converter.location'); $locationHandlers = $container->findTaggedServiceIds('ezpublish.search.legacy.gateway.criterion_handler.location'); $this->addHandlers($criteriaConverterLocation, $locationHandlers); } if ($container->hasDefinition('ezplatform.trash.search.legacy.gateway.criteria_converter')) { $trashCriteriaConverter = $container->getDefinition('ezplatform.trash.search.legacy.gateway.criteria_converter'); $trashCriteriaHandlers = $container->findTaggedServiceIds('ezplatform.trash.search.legacy.gateway.criterion_handler'); $this->addHandlers($trashCriteriaConverter, $trashCriteriaHandlers); } if ($container->hasDefinition('ezpublish.spi.persistence.legacy.url.criterion_converter')) { $urlCriteriaConverter = $container->getDefinition('ezpublish.spi.persistence.legacy.url.criterion_converter'); $urlCriteriaHandlers = $container->findTaggedServiceIds('ezpublish.persistence.legacy.url.criterion_handler'); $this->addHandlers($urlCriteriaConverter, $urlCriteriaHandlers); } } protected function addHandlers(Definition $definition, $handlers) { foreach ($handlers as $id => $attributes) { $definition->addMethodCall('addHandler', [new Reference($id)]); } } }
gggeek/ezpublish-kernel
eZ/Publish/Core/Base/Container/Compiler/Search/Legacy/CriteriaConverterPass.php
PHP
gpl-2.0
3,289
<?php global $post; if( tie_get_option( 'archives_socail' ) ):?> <div class="mini-share-post"> <ul> <li><a href="https://twitter.com/share" class="twitter-share-button" data-url="<?php the_permalink(); ?>" data-text="<?php the_title(); ?>" data-via="<?php echo tie_get_option( 'share_twitter_username' ) ?>" data-lang="en">tweet</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script></li> <li> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="fb-like" data-href="<?php the_permalink(); ?>" data-send="false" data-layout="button_count" data-width="90" data-show-faces="false"></div> </li> <li><div class="g-plusone" data-size="medium" data-href="<?php the_permalink(); ?>"></div> <script type='text/javascript'> (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> </li> <li><script type="text/javascript" src="http://assets.pinterest.com/js/pinit.js"></script><a href="http://pinterest.com/pin/create/button/?url=<?php the_permalink(); ?>&amp;media=<?php echo tie_thumb_src('', 660 ,330); ?>" class="pin-it-button" count-layout="horizontal"><img border="0" src="http://assets.pinterest.com/images/PinExt.png" title="Pin It" /></a></li> </ul> </div> <!-- .share-post --> <?php endif; ?>
axsauze/HackaSoton
wp-content/themes/sahifa/includes/post-share.php
PHP
gpl-2.0
1,973
<?php class Miscinfo_b extends Lxaclass { static $__desc_realname = array("", "", "real_name"); static $__desc_paddress = array("", "", "personal_address"); static $__desc_padd_city = array("", "", "city"); static $__desc_padd_country = array( "", "", "Country", "Country of the Client"); static $__desc_ptelephone = array("", "", "telephone_no"); static $__desc_caddress = array("", "", "company_address"); static $__desc_cadd_country = array("", "", "country" ); static $__desc_cadd_city = array("", "", "city"); static $__desc_ctelephone = array("", "", "telephone"); static $__desc_cfax = array("", "", "fax"); static $__desc_text_comment = array("t", "", "comments"); } class sp_Miscinfo extends LxSpecialClass { static $__desc = array("","", "miscinfo"); static $__desc_nname = array("", "", "name"); static $__desc_miscinfo_b = array("", "", "personal_info_of_client"); static $__acdesc_update_miscinfo = array("","", "details"); function updateform($subaction, $param) { $vlist['nname']= array('M', $this->getSpecialname()); $vlist['miscinfo_b_s_realname']= ""; $vlist['miscinfo_b_s_paddress']= ""; $vlist['miscinfo_b_s_padd_city']= ""; $vlist['miscinfo_b_s_padd_country']= ""; $vlist['miscinfo_b_s_ptelephone']= ""; $vlist['miscinfo_b_s_caddress']= ""; $vlist['miscinfo_b_s_ctelephone']= ""; $vlist['miscinfo_b_s_cadd_city']= ""; $vlist['miscinfo_b_s_cadd_country']= ""; $vlist['miscinfo_b_s_cfax']= ""; return $vlist; } }
zuoziqi/KloxoST
httpdocs/lib/client/miscinfolib.php
PHP
gpl-2.0
1,486
/* * File: ShardExceptions.cpp * Author: dagothar * * Created on October 22, 2015, 8:00 PM */ #include "ShardExceptions.hpp" using namespace gripperz::shards;
dagothar/gripperz
src/shards/ShardExceptions.cpp
C++
gpl-2.0
170
/* * AlwaysLowestAdaptationLogic.cpp ***************************************************************************** * Copyright (C) 2014 - VideoLAN authors * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "AlwaysLowestAdaptationLogic.hpp" #include "Representationselectors.hpp" using namespace adaptative::logic; using namespace adaptative::playlist; AlwaysLowestAdaptationLogic::AlwaysLowestAdaptationLogic(): AbstractAdaptationLogic() { } BaseRepresentation *AlwaysLowestAdaptationLogic::getCurrentRepresentation(BaseAdaptationSet *adaptSet) const { RepresentationSelector selector; return selector.select(adaptSet, 0); }
sachdeep/vlc
modules/demux/adaptative/logic/AlwaysLowestAdaptationLogic.cpp
C++
gpl-2.0
1,424
package com.oa.bean; public class FeedBackInfo { private Long id; private String feedbackinfo; private String userid; private String date; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFeedbackinfo() { return feedbackinfo; } public void setFeedbackinfo(String feedbackinfo) { this.feedbackinfo = feedbackinfo; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } }
yiyuweier/OA-project
src/com/oa/bean/FeedBackInfo.java
Java
gpl-2.0
617
<?php include('../../../operaciones.php'); conectar(); apruebadeintrusos(); if($_SESSION['cargo_user']!="Bodeguero"){ header('Location: ../../../login.php'); } ?> <html lang="en"> <head> <title>PNKS Inventario - Estadística de Productos</title> <!-- BEGIN META --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="keywords" content="your,keywords"> <meta name="description" content="Short explanation about this website"> <!-- END META --> <!-- BEGIN STYLESHEETS --> <link href='http://fonts.googleapis.com/css?family=Roboto:300italic,400italic,300,400,500,700,900' rel='stylesheet' type='text/css'/> <link type="text/css" rel="stylesheet" href="../../../css/bootstrap.css" /> <link type="text/css" rel="stylesheet" href="../../../css/materialadmin.css" /> <link type="text/css" rel="stylesheet" href="../../../css/font-awesome.min.css" /> <link type="text/css" rel="stylesheet" href="../../../css/material-design-iconic-font.min.css" /> <link type="text/css" rel="stylesheet" href="../../../css/libs/DataTables/jquery.dataTables.css" /> <link type="text/css" rel="stylesheet" href="../../../css/libs/DataTables/extensions/dataTables.colVis.css" /> <link type="text/css" rel="stylesheet" href="../../../css/libs/DataTables/extensions/dataTables.tableTools.css" /> <!-- END STYLESHEETS --> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script type="text/javascript" src="js/libs/utils/html5shiv.js?1403934957"></script> <script type="text/javascript" src="js/libs/utils/respond.min.js?1403934956"></script> <![endif]--> </head> <body class="menubar-hoverable header-fixed menubar-first menubar-visible menubar-pin"> <!-- BEGIN HEADER--> <header id="header" > <div class="headerbar"> <!-- Brand and toggle get grouped for better mobile display --> <div class="headerbar-left"> <ul class="header-nav header-nav-options"> <li class="header-nav-brand" > <div class="brand-holder"> <a href=""> <span class="text-lg text-bold text-primary">PNKS LTDA</span> </a> </div> </li> <li> <a class="btn btn-icon-toggle menubar-toggle" data-toggle="menubar" href="javascript:void(0);"> <i class="fa fa-bars"></i> </a> </li> </ul> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="headerbar-right"> <ul class="header-nav header-nav-profile"> <li class="dropdown"> <a href="javascript:void(0);" class="dropdown-toggle ink-reaction" data-toggle="dropdown"> <?php if(file_exists('../../../img/usuarios/'.$_SESSION['foto_user'])){ ?> <img src="../../../img/usuarios/<?php echo $_SESSION['foto_user']; ?>" alt="" /> <?php } else { ?> <img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNzEiIGhlaWdodD0iMTgwIj48cmVjdCB3aWR0aD0iMTcxIiBoZWlnaHQ9IjE4MCIgZmlsbD0iI2VlZSI+PC9yZWN0Pjx0ZXh0IHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9Ijg1LjUiIHk9IjkwIiBzdHlsZT0iZmlsbDojYWFhO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjEycHg7Zm9udC1mYW1pbHk6QXJpYWwsSGVsdmV0aWNhLHNhbnMtc2VyaWY7ZG9taW5hbnQtYmFzZWxpbmU6Y2VudHJhbCI+MTcxeDE4MDwvdGV4dD48L3N2Zz4="/> <?php } ?> <span class="profile-info"> <?php echo $_SESSION['usuario_session']; ?> <small><?php echo $_SESSION['cargo_user']; ?></small> </span> </a> <ul class="dropdown-menu animation-dock"> <li class="dropdown-header">Opciones de Cuenta</li> <li><a href="../../opcion/cambiarclave.php">Cambiar Clave</a></li> <li><a href="../../opcion/cambiarficha.php">Cambiar Datos Personales</a></li> <li><a href="../../opcion/cambiarfoto.php">Cambiar Foto de Perfil</a></li> <li class="divider"></li> <li><a href="../../../login.php" onClick=""><i class="fa fa-fw fa-power-off text-danger"></i> Salir</a></li> </ul><!--end .dropdown-menu --> </li><!--end .dropdown --> </ul><!--end .header-nav-profile --> </div><!--end #header-navbar-collapse --> </div> </header> <!-- END HEADER--> <!-- BEGIN BASE--> <div id="base"> <!-- BEGIN OFFCANVAS LEFT --> <div class="offcanvas"> </div><!--end .offcanvas--> <!-- END OFFCANVAS LEFT --> <!-- BEGIN CONTENT--> <div id="content"> <section> <div class="section-body"> <div class="row"> </div><!--end .row --> </div><!--end .section-body --> </section> </div><!--end #content--> <!-- END CONTENT --> <div id="menubar" class="menubar-first"> <div class="menubar-fixed-panel"> <div> <a class="btn btn-icon-toggle btn-default menubar-toggle" data-toggle="menubar" href="javascript:void(0);"> <i class="fa fa-bars"></i> </a> </div> <div class="expanded"> <a href=""> <span class="text-lg text-bold text-primary ">PNKS&nbsp;LTDA</span> </a> </div> </div> <div class="menubar-scroll-panel"> <!-- BEGIN MAIN MENU --> <ul id="main-menu" class="gui-controls"> <!-- BEGIN DASHBOARD --> <li> <a href="../index.php"> <div class="gui-icon"><i class="md md-home"></i></div> <span class="title">Inicio</span> </a> </li> <li> <a href="../producto.php"> <div class="gui-icon"><i class="md md-web"></i></div> <span class="title">Ficha Producto</span> </a> </li><!--end /menu-li --> <!-- END DASHBOARD --> <!-- BEGIN EMAIL --> <li> <a href="../etiqueta.php"> <div class="gui-icon"><i class="md md-chat"></i></div> <span class="title">Emisión de Etiqueta</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <li> <a href="../bodega.php"> <div class="gui-icon"><i class="glyphicon glyphicon-list-alt"></i></div> <span class="title">Administración de Bodega</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <li> <a href="../reserva.php"> <div class="gui-icon"><i class="md md-view-list"></i></div> <span class="title">Control de Reservas</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <a href="../inventario.php"> <div class="gui-icon"><i class="fa fa-table"></i></div> <span class="title">Inventario</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <a href="../stock.php"> <div class="gui-icon"><i class="md md-assignment-turned-in"></i></div> <span class="title">Control de Stock</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <a href="../precio.php"> <div class="gui-icon"><i class="md md-assignment"></i></div> <span class="title">Lista de Precio</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <a href="../cliente.php"> <div class="gui-icon"><i class="md md-description"></i></div> <span class="title">Ficha Cliente</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li class="gui-folder"> <a> <div class="gui-icon"><i class="md md-assessment"></i></div> <span class="title">Informes</span> </a> <!--start submenu --> <ul> <li><a href="stockbodega.php"><span class="title">Stock por Bodega</span></a></li> <li><a href="guia.php"><span class="title">Entrada y Salida</span></a></li> <li><a href="stock.php"><span class="title">Control de Stock</span></a></li> <li><a href="consumo.php"><span class="title">Consumo Interno</span></a></li> <li><a href="consignacion.php"><span class="title">Consignaciones</span></a></li> <li><a href="estadistica.php" class="active"><span class="title">Estadística de Producto</span></a></li> <li><a href="serie.php"><span class="title">Control de Serie</span></a></li> <li><a href="vencimiento.php" ><span class="title">Vencimiento de Producto</span></a></li> <li><a href="rotacion.php"><span class="title">Rotación de Inventario</span></a></li> <li><a href="toma.php"><span class="title">Toma de Inventario</span></a></li> </ul><!--end /submenu --> </li><!--end /menu-li --> <!-- END EMAIL --> </ul><!--end .main-menu --> <!-- END MAIN MENU --> <div class="menubar-foot-panel"> <small class="no-linebreak hidden-folded"> <span class="opacity-75">&copy; 2015</span> <strong>GH Soluciones Informáticas</strong> </small> </div> </div><!--end .menubar-scroll-panel--> </div><!--end #menubar--> <!-- END MENUBAR --> </div><!--end #base--> <!-- END BASE --> <!-- BEGIN JAVASCRIPT --> <script src="../../../js/libs/jquery/jquery-1.11.2.min.js"></script> <script src="../../../js/libs/jquery/jquery-migrate-1.2.1.min.js"></script> <script src="../../../js/libs/bootstrap/bootstrap.min.js"></script> <script src="../../../js/libs/spin.js/spin.min.js"></script> <script src="../../../js/libs/autosize/jquery.autosize.min.js"></script> <script src="../../../js/libs/DataTables/jquery.dataTables.min.js"></script> <script src="../../../js/libs/DataTables/extensions/ColVis/js/dataTables.colVis.min.js"></script> <script src="../../../js/libs/DataTables/extensions/TableTools/js/dataTables.tableTools.min.js"></script> <script src="../../../js/libs/nanoscroller/jquery.nanoscroller.min.js"></script> <script src="../../../js/core/source/App.js"></script> <script src="../../../js/core/source/AppNavigation.js"></script> <script src="../../../js/core/source/AppOffcanvas.js"></script> <script src="../../../js/core/source/AppCard.js"></script> <script src="../../../js/core/source/AppForm.js"></script> <script src="../../../js/core/source/AppVendor.js"></script> <!-- END JAVASCRIPT --> </body> </html>
DerKow/erp
admin/bodega/informe/estadistica.php
PHP
gpl-2.0
11,126
<?php /** * Vanillicon plugin. * * @author Todd Burry <todd@vanillaforums.com> * @copyright 2009-2017 Vanilla Forums Inc. * @license http://www.opensource.org/licenses/gpl-2.0.php GNU GPL v2 * @package vanillicon */ /** * Class VanilliconPlugin */ class VanilliconPlugin extends Gdn_Plugin { /** * Set up the plugin. */ public function setup() { $this->structure(); } /** * Perform any necessary database or configuration updates. */ public function structure() { touchConfig('Plugins.Vanillicon.Type', 'v2'); } /** * Set the vanillicon on the user' profile. * * @param ProfileController $sender * @param array $args */ public function profileController_afterAddSideMenu_handler($sender, $args) { if (!$sender->User->Photo) { $sender->User->Photo = userPhotoDefaultUrl($sender->User, ['Size' => 200]); } } /** * The settings page for vanillicon. * * @param Gdn_Controller $sender */ public function settingsController_vanillicon_create($sender) { $sender->permission('Garden.Settings.Manage'); $cf = new ConfigurationModule($sender); $items = [ 'v1' => 'Vanillicon 1', 'v2' => 'Vanillicon 2' ]; $cf->initialize([ 'Plugins.Vanillicon.Type' => [ 'LabelCode' => 'Vanillicon Set', 'Control' => 'radiolist', 'Description' => 'Which vanillicon set do you want to use?', 'Items' => $items, 'Options' => ['display' => 'after'], 'Default' => 'v1' ] ]); $sender->setData('Title', sprintf(t('%s Settings'), 'Vanillicon')); $cf->renderAll(); } /** * Overrides allowing admins to set the default avatar, since it has no effect when Vanillicon is on. * Adds messages to the top of avatar settings page and to the help panel asset. * * @param SettingsController $sender */ public function settingsController_avatarSettings_handler($sender) { // We check if Gravatar is enabled before adding any messages as Gravatar overrides Vanillicon. if (!Gdn::addonManager()->isEnabled('gravatar', \Vanilla\Addon::TYPE_ADDON)) { $message = t('You\'re using Vanillicon avatars as your default avatars.'); $message .= ' '.t('To set a custom default avatar, disable the Vanillicon plugin.'); $messages = $sender->data('messages', []); $messages = array_merge($messages, [$message]); $sender->setData('messages', $messages); $sender->setData('canSetDefaultAvatar', false); $help = t('Your users\' default avatars are Vanillicon avatars.'); helpAsset(t('How are my users\' default avatars set?'), $help); } } } if (!function_exists('userPhotoDefaultUrl')) { /** * Calculate the user's default photo url. * * @param array|object $user The user to examine. * @param array $options An array of options. * - Size: The size of the photo. * @return string Returns the vanillicon url for the user. */ function userPhotoDefaultUrl($user, $options = []) { static $iconSize = null, $type = null; if ($iconSize === null) { $thumbSize = c('Garden.Thumbnail.Size'); $iconSize = $thumbSize <= 50 ? 50 : 100; } if ($type === null) { $type = c('Plugins.Vanillicon.Type'); } $size = val('Size', $options, $iconSize); $email = val('Email', $user); if (!$email) { $email = val('UserID', $user, 100); } $hash = md5($email); $px = substr($hash, 0, 1); switch ($type) { case 'v2': $photoUrl = "//w$px.vanillicon.com/v2/{$hash}.svg"; break; default: $photoUrl = "//w$px.vanillicon.com/{$hash}_{$size}.png"; break; } return $photoUrl; } }
adrianspeyer/vanilla
plugins/vanillicon/class.vanillicon.plugin.php
PHP
gpl-2.0
4,131
using System.Windows.Controls; namespace HomeControl { /// <summary> /// Interaction logic for UserControl1.xaml /// </summary> public partial class HomeCtrl : UserControl { public HomeCtrl() { InitializeComponent(); // doug's change... } } }
AceSyntax/DnvGitApp
DemoSolution/HomeControl/HomeCtrl.xaml.cs
C#
gpl-2.0
319
package adamros.mods.transducers.item; import java.util.List; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import adamros.mods.transducers.Transducers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; public class ItemElectricEngine extends ItemBlock { public ItemElectricEngine(int par1) { super(par1); setHasSubtypes(true); setMaxDamage(0); setUnlocalizedName("itemElectricEngine"); setCreativeTab(Transducers.tabTransducers); } @Override public int getMetadata(int meta) { return meta; } @Override public String getUnlocalizedName(ItemStack is) { String suffix; switch (is.getItemDamage()) { case 0: suffix = "lv"; break; case 1: suffix = "mv"; break; case 2: suffix = "hv"; break; case 3: suffix = "ev"; break; default: suffix = "lv"; break; } return getUnlocalizedName() + "." + suffix; } @Override @SideOnly(Side.CLIENT) public void addInformation(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, List par3List, boolean par4) { super.addInformation(par1ItemStack, par2EntityPlayer, par3List, par4); String type; switch (par1ItemStack.getItemDamage()) { case 0: type = "lv"; break; case 1: type = "mv"; break; case 2: type = "hv"; break; case 3: type = "ev"; break; default: type = "lv"; break; } par3List.add(StatCollector.translateToLocal("tip.electricEngine." + type).trim()); } }
adamros/Transducers
adamros/mods/transducers/item/ItemElectricEngine.java
Java
gpl-2.0
2,146
<?php /** * @file * Opigno Learning Record Store stats - Course content - Course contexts statistics template file * * @param array $course_contexts_statistics */ ?> <div class="lrs-stats-widget" id="lrs-stats-widget-course-content-course-contexts-statistics"> <h2><?php print t('Course context statistics'); ?></h2> <?php print theme('opigno_lrs_stats_course_content_widget_course_contexts_statistics_list', compact('course_contexts_statistics')); ?> </div>
ksen-pol/univerico
profiles/opigno_lms/modules/opigno/opigno_tincan_api/modules/opigno_tincan_api_stats/templates/course_content/widgets/course_contexts_statistics/course_contexts_statistics.tpl.php
PHP
gpl-2.0
467
showWord(["v. ","vin jòn.<br>"])
georgejhunt/HaitiDictionary.activity
data/words/joni.js
JavaScript
gpl-2.0
33
package lambda; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class Esempio extends JFrame { public Esempio() { init(); } private void init() { BorderLayout b=new BorderLayout(); this.setLayout(b); JButton button=new JButton("Ok"); this.add(button,BorderLayout.SOUTH); this.setSize(400, 300); this.setVisible(true); ActionListener l=new Azione(); button.addActionListener(( e) -> System.out.println("ciao")); } public static void main(String[] args) { Esempio e=new Esempio(); } }
manuelgentile/MAP
java8/java8_lambda/src/main/java/lambda/Esempio.java
Java
gpl-2.0
663
/* DC++ Widget Toolkit Copyright (c) 2007-2013, Jacek Sieka All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the DWT nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <dwt/widgets/ProgressBar.h> namespace dwt { const TCHAR ProgressBar::windowClass[] = PROGRESS_CLASS; ProgressBar::Seed::Seed() : BaseType::Seed(WS_CHILD | PBS_SMOOTH) { } }
hjpotter92/dcplusplus
dwt/src/widgets/ProgressBar.cpp
C++
gpl-2.0
1,771
<?php require "tableinitiateclass.php"; require "../queryinitiateclass.php"; $tbl = new AddTable; ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Table index</title> </head> <style> table { width:100%; } </style> <body> <?php // just the headers $arrayheaders = array("head1","head2","head3"); // just the rows $arrayrows = array(array("row1-1","row1-2","row1-3"), array("row2-1","row2-2","row2-3"), array("row3-1","row3-2","row3-3"), array("row4-1","row4-2","row4-3"), array("row5-1","row5-2","row5-3")); $query = new AddSql("root","","map_directory_uphrm","localhost"); $arraycolumns = $query->getallColumn("rooms_uphrm"); $arrayfields = $query->getallascolQuery("rooms_uphrm"); // display table styling still unfinished echo $tbl->settblQuery(sizeof($arrayfields),sizeof($arraycolumns),$arraycolumns,$arrayfields); // display search for row and column numbers echo $tbl->gettableData(2,1); // set search query $tbl->searchRows("-3"); // display search query echo $tbl->getsearchResults(); // reset table $tbl->resetAll(); // get query string $getquery = 'current'; // next page $nextpage = $tbl->checkSet($getquery) + 1; // back page $backpage = $tbl->checkSet($getquery) - 1; // display table with restriction of 2 echo $tbl->settblrestrictQuery(sizeof($arrayfields),sizeof($arraycolumns), $arraycolumns,$arrayfields,5, $tbl->checkSet($getquery)); // display back button $totaldist = sizeof($arrayfields) / 5; echo $tbl->toBack($backpage,$getquery); // display next button echo $tbl->toNext($nextpage,$getquery); ?> <button onclick = "ajaxNav()" > Next </button> <button onclick = "ajaxNavb()" > Back </button> <div id = "tableDiv" > </div> <?php echo $tbl->popupDelete(); ?> <script> var count = 1; function ajaxNav() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("tableDiv").innerHTML=xmlhttp.responseText; } } if(count<<?php echo $totaldist; ?>); count++; xmlhttp.open("GET","ajaxnav.php?<?php echo $getquery; ?>="+ count,true); xmlhttp.send(); } function ajaxNavb() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("tableDiv").innerHTML=xmlhttp.responseText; } } if(count>0); count--; xmlhttp.open("GET","ajaxnav.php?<?php echo $getquery; ?>="+ count,true); xmlhttp.send(); } </script> </body> </html>
cominteract/htmlwrapper_v1
htmlwrapper/table/tableindex.php
PHP
gpl-2.0
3,108
/* You may freely copy, distribute, modify and use this class as long as the original author attribution remains intact. See message below. Copyright (C) 1998-2006 Christian Pesch. All Rights Reserved. */ package slash.carcosts; import slash.gui.model.AbstractModel; /** * An CurrencyModel holds a Currency and provides get and set * methods for it. * * @author Christian Pesch */ public class CurrencyModel extends AbstractModel { /** * Construct a new CurrencyModel. */ public CurrencyModel() { this(Currency.getCurrency("DM")); } /** * Construct a new CurrencyModel. */ public CurrencyModel(Currency value) { setValue(value); } /** * Get the Currency value that is holded by the model. */ public Currency getValue() { return value; } /** * Set the Currency value to hold. */ public void setValue(Currency newValue) { if (value != newValue) { this.value = newValue; fireStateChanged(); } } public String toString() { return "CurrencyModel(" + value + ")"; } private Currency value; }
cpesch/CarCosts
car-costs/src/main/java/slash/carcosts/CurrencyModel.java
Java
gpl-2.0
1,184
/** * Ядро булевой логики */ /** * @author Алексей Кляузер <drum@pisem.net> * Ядро булевой логики */ package org.deneblingvo.booleans.core;
AlexAbak/ReversibleComputing
package/src/org/deneblingvo/booleans/core/package-info.java
Java
gpl-2.0
192
package de.superioz.moo.network.client; import de.superioz.moo.network.server.NetworkServer; import lombok.Getter; import de.superioz.moo.api.collection.UnmodifiableList; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * The hub for storing the client connections * * @see MooClient */ public final class ClientManager { /** * It is only necessary to only have one ClientHub instance so this is the static access for this * class after it has been initialised by the network server */ @Getter private static ClientManager instance; /** * The connected {@link MooClient}'s by the type of them */ private ConcurrentMap<ClientType, Map<InetSocketAddress, MooClient>> clientsByType = new ConcurrentHashMap<>(); /** * The ram usage of every daemon (as socketaddress) as percent */ @Getter private Map<InetSocketAddress, Integer> daemonRamUsage = new HashMap<>(); /** * The netty server the clients are connected to */ private NetworkServer netServer; public ClientManager(NetworkServer netServer) { instance = this; this.netServer = netServer; for(ClientType clientType : ClientType.values()) { clientsByType.put(clientType, new HashMap<>()); } } /** * Updates the ramUsage of a daemon * * @param address The address of the daemon/server * @param ramUsage The ramUsage in per cent */ public void updateRamUsage(InetSocketAddress address, int ramUsage) { Map<InetSocketAddress, MooClient> daemonClients = clientsByType.get(ClientType.DAEMON); if(!daemonClients.containsKey(address)) return; daemonRamUsage.put(address, ramUsage); } /** * Gets the best available daemon where the ram usage is the lowest * * @return The client */ public MooClient getBestDaemon() { Map<InetSocketAddress, MooClient> daemonClients = clientsByType.get(ClientType.DAEMON); if(daemonClients.isEmpty()) return null; int lowesRamUsage = -1; MooClient lowestRamUsageClient = null; for(InetSocketAddress address : daemonClients.keySet()) { if(!daemonRamUsage.containsKey(address)) continue; MooClient client = daemonClients.get(address); int ramUsage = daemonRamUsage.get(address); if((lowesRamUsage == -1 || lowesRamUsage > ramUsage) && !((lowesRamUsage = ramUsage) >= (Integer) netServer.getConfig().get("slots-ram-usage"))) { lowestRamUsageClient = client; } } return lowestRamUsageClient; } /** * Adds a client to the hub * * @param cl The client * @return The size of the map */ public int add(MooClient cl) { Map<InetSocketAddress, MooClient> map = clientsByType.get(cl.getType()); map.put(cl.getAddress(), cl); if(cl.getType() == ClientType.DAEMON) { daemonRamUsage.put(cl.getAddress(), 0); } return map.size(); } /** * Removes a client from the hub * * @param address The address (the key) * @return This */ public ClientManager remove(InetSocketAddress address) { for(Map<InetSocketAddress, MooClient> m : clientsByType.values()) { m.entrySet().removeIf(entry -> entry.getKey().equals(address)); } return this; } public ClientManager remove(MooClient cl) { return remove(cl.getAddress()); } /** * Gets a client from address * * @param address The address * @return The client */ public MooClient get(InetSocketAddress address) { MooClient client = null; for(Map.Entry<ClientType, Map<InetSocketAddress, MooClient>> entry : clientsByType.entrySet()) { if(entry.getValue().containsKey(address)) { client = entry.getValue().get(address); } } return client; } public boolean contains(InetSocketAddress address) { return get(address) != null; } /** * Get clients (from type) * * @param type The type * @return The list of clients (unmodifiable) */ public UnmodifiableList<MooClient> getClients(ClientType type) { Map<InetSocketAddress, MooClient> map = clientsByType.get(type); return new UnmodifiableList<>(map.values()); } /** * Get all clients inside one list * * @return The list of clients */ public List<MooClient> getAll() { List<MooClient> clients = new ArrayList<>(); for(ClientType clientType : ClientType.values()) { clients.addAll(getClients(clientType)); } return clients; } public UnmodifiableList<MooClient> getMinecraftClients() { List<MooClient> clients = new ArrayList<>(); clients.addAll(getClients(ClientType.PROXY)); clients.addAll(getClients(ClientType.SERVER)); return new UnmodifiableList<>(clients); } public UnmodifiableList<MooClient> getServerClients() { return getClients(ClientType.SERVER); } public UnmodifiableList<MooClient> getProxyClients() { return getClients(ClientType.PROXY); } public UnmodifiableList<MooClient> getCustomClients() { return getClients(ClientType.CUSTOM); } public UnmodifiableList<MooClient> getDaemonClients() { return getClients(ClientType.DAEMON); } }
Superioz/MooProject
network/src/main/java/de/superioz/moo/network/client/ClientManager.java
Java
gpl-2.0
5,716
import math as mth import numpy as np #---------------------- # J Matthews, 21/02 # This is a file containing useful constants for python coding # # Units in CGS unless stated # #---------------------- #H=6.62606957E-27 HEV=4.13620e-15 #C=29979245800.0 #BOLTZMANN=1.3806488E-16 VERY_BIG=1e50 H=6.6262e-27 HC=1.98587e-16 HEV=4.13620e-15 # Planck's constant in eV HRYD=3.04005e-16 # NSH 1204 Planck's constant in Rydberg C =2.997925e10 G=6.670e-8 BOLTZMANN =1.38062e-16 WIEN= 5.879e10 # NSH 1208 Wien Disp Const in frequency units H_OVER_K=4.799437e-11 STEFAN_BOLTZMANN =5.6696e-5 THOMPSON=0.66524e-24 PI = 3.1415927 MELEC = 9.10956e-28 E= 4.8035e-10 # Electric charge in esu MPROT = 1.672661e-24 MSOL = 1.989e33 PC= 3.08e18 YR = 3.1556925e7 PI_E2_OVER_MC=0.02655103 # Classical cross-section PI_E2_OVER_M =7.96e8 ALPHA= 7.297351e-3 # Fine structure constant BOHR= 0.529175e-8 # Bohr radius CR= 3.288051e15 #Rydberg frequency for H != Ryd freq for infinite mass ANGSTROM = 1.e-8 #Definition of an Angstrom in units of this code, e.g. cm EV2ERGS =1.602192e-12 RADIAN= 57.29578 RYD2ERGS =2.1798741e-11 PARSEC=3.086E18
jhmatthews/panlens
constants.py
Python
gpl-2.0
1,157
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; namespace WeifenLuo.WinFormsUI.Docking { #region DockPanelSkin classes /// <summary> /// The skin to use when displaying the DockPanel. /// The skin allows custom gradient color schemes to be used when drawing the /// DockStrips and Tabs. /// </summary> [TypeConverter(typeof(DockPanelSkinConverter))] public class DockPanelSkin { private AutoHideStripSkin m_autoHideStripSkin; private DockPaneStripSkin m_dockPaneStripSkin; public DockPanelSkin() { m_autoHideStripSkin = new AutoHideStripSkin(); m_dockPaneStripSkin = new DockPaneStripSkin(); } /// <summary> /// The skin used to display the auto hide strips and tabs. /// </summary> public AutoHideStripSkin AutoHideStripSkin { get { return m_autoHideStripSkin; } set { m_autoHideStripSkin = value; } } /// <summary> /// The skin used to display the Document and ToolWindow style DockStrips and Tabs. /// </summary> public DockPaneStripSkin DockPaneStripSkin { get { return m_dockPaneStripSkin; } set { m_dockPaneStripSkin = value; } } } /// <summary> /// The skin used to display the auto hide strip and tabs. /// </summary> [TypeConverter(typeof(AutoHideStripConverter))] public class AutoHideStripSkin { private DockPanelGradient m_dockStripGradient; private TabGradient m_TabGradient; public AutoHideStripSkin() { m_dockStripGradient = new DockPanelGradient(); m_dockStripGradient.StartColor = SystemColors.ControlLight; m_dockStripGradient.EndColor = SystemColors.ControlLight; m_TabGradient = new TabGradient(); m_TabGradient.TextColor = SystemColors.ControlDarkDark; } /// <summary> /// The gradient color skin for the DockStrips. /// </summary> public DockPanelGradient DockStripGradient { get { return m_dockStripGradient; } set { m_dockStripGradient = value; } } /// <summary> /// The gradient color skin for the Tabs. /// </summary> public TabGradient TabGradient { get { return m_TabGradient; } set { m_TabGradient = value; } } } /// <summary> /// The skin used to display the document and tool strips and tabs. /// </summary> [TypeConverter(typeof(DockPaneStripConverter))] public class DockPaneStripSkin { private DockPaneStripGradient m_DocumentGradient; private DockPaneStripToolWindowGradient m_ToolWindowGradient; public DockPaneStripSkin() { m_DocumentGradient = new DockPaneStripGradient(); m_DocumentGradient.DockStripGradient.StartColor = SystemColors.Control; m_DocumentGradient.DockStripGradient.EndColor = SystemColors.Control; m_DocumentGradient.ActiveTabGradient.StartColor = SystemColors.ControlLightLight; m_DocumentGradient.ActiveTabGradient.EndColor = SystemColors.ControlLightLight; m_DocumentGradient.InactiveTabGradient.StartColor = SystemColors.ControlLight; m_DocumentGradient.InactiveTabGradient.EndColor = SystemColors.ControlLight; m_ToolWindowGradient = new DockPaneStripToolWindowGradient(); m_ToolWindowGradient.DockStripGradient.StartColor = SystemColors.ControlLight; m_ToolWindowGradient.DockStripGradient.EndColor = SystemColors.ControlLight; m_ToolWindowGradient.ActiveTabGradient.StartColor = SystemColors.Control; m_ToolWindowGradient.ActiveTabGradient.EndColor = SystemColors.Control; m_ToolWindowGradient.InactiveTabGradient.StartColor = Color.Transparent; m_ToolWindowGradient.InactiveTabGradient.EndColor = Color.Transparent; m_ToolWindowGradient.InactiveTabGradient.TextColor = SystemColors.ControlDarkDark; m_ToolWindowGradient.ActiveCaptionGradient.StartColor = SystemColors.GradientActiveCaption; m_ToolWindowGradient.ActiveCaptionGradient.EndColor = SystemColors.ActiveCaption; m_ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; m_ToolWindowGradient.ActiveCaptionGradient.TextColor = SystemColors.ActiveCaptionText; m_ToolWindowGradient.InactiveCaptionGradient.StartColor = SystemColors.GradientInactiveCaption; m_ToolWindowGradient.InactiveCaptionGradient.EndColor = SystemColors.GradientInactiveCaption; m_ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; m_ToolWindowGradient.InactiveCaptionGradient.TextColor = SystemColors.ControlText; } /// <summary> /// The skin used to display the Document style DockPane strip and tab. /// </summary> public DockPaneStripGradient DocumentGradient { get { return m_DocumentGradient; } set { m_DocumentGradient = value; } } /// <summary> /// The skin used to display the ToolWindow style DockPane strip and tab. /// </summary> public DockPaneStripToolWindowGradient ToolWindowGradient { get { return m_ToolWindowGradient; } set { m_ToolWindowGradient = value; } } } /// <summary> /// The skin used to display the DockPane ToolWindow strip and tab. /// </summary> [TypeConverter(typeof(DockPaneStripGradientConverter))] public class DockPaneStripToolWindowGradient : DockPaneStripGradient { private TabGradient m_activeCaptionGradient; private TabGradient m_inactiveCaptionGradient; public DockPaneStripToolWindowGradient() { m_activeCaptionGradient = new TabGradient(); m_inactiveCaptionGradient = new TabGradient(); } /// <summary> /// The skin used to display the active ToolWindow caption. /// </summary> public TabGradient ActiveCaptionGradient { get { return m_activeCaptionGradient; } set { m_activeCaptionGradient = value; } } /// <summary> /// The skin used to display the inactive ToolWindow caption. /// </summary> public TabGradient InactiveCaptionGradient { get { return m_inactiveCaptionGradient; } set { m_inactiveCaptionGradient = value; } } } /// <summary> /// The skin used to display the DockPane strip and tab. /// </summary> [TypeConverter(typeof(DockPaneStripGradientConverter))] public class DockPaneStripGradient { private DockPanelGradient m_dockStripGradient; private TabGradient m_activeTabGradient; private TabGradient m_inactiveTabGradient; public DockPaneStripGradient() { m_dockStripGradient = new DockPanelGradient(); m_activeTabGradient = new TabGradient(); m_inactiveTabGradient = new TabGradient(); } /// <summary> /// The gradient color skin for the DockStrip. /// </summary> public DockPanelGradient DockStripGradient { get { return m_dockStripGradient; } set { m_dockStripGradient = value; } } /// <summary> /// The skin used to display the active DockPane tabs. /// </summary> public TabGradient ActiveTabGradient { get { return m_activeTabGradient; } set { m_activeTabGradient = value; } } /// <summary> /// The skin used to display the inactive DockPane tabs. /// </summary> public TabGradient InactiveTabGradient { get { return m_inactiveTabGradient; } set { m_inactiveTabGradient = value; } } } /// <summary> /// The skin used to display the dock pane tab /// </summary> [TypeConverter(typeof(DockPaneTabGradientConverter))] public class TabGradient : DockPanelGradient { private Color m_textColor; public TabGradient() { m_textColor = SystemColors.ControlText; } /// <summary> /// The text color. /// </summary> [DefaultValue(typeof(SystemColors), "ControlText")] public Color TextColor { get { return m_textColor; } set { m_textColor = value; } } } /// <summary> /// The gradient color skin. /// </summary> [TypeConverter(typeof(DockPanelGradientConverter))] public class DockPanelGradient { private Color m_startColor; private Color m_endColor; private LinearGradientMode m_linearGradientMode; public DockPanelGradient() { m_startColor = SystemColors.Control; m_endColor = SystemColors.Control; m_linearGradientMode = LinearGradientMode.Horizontal; } /// <summary> /// The beginning gradient color. /// </summary> [DefaultValue(typeof(SystemColors), "Control")] public Color StartColor { get { return m_startColor; } set { m_startColor = value; } } /// <summary> /// The ending gradient color. /// </summary> [DefaultValue(typeof(SystemColors), "Control")] public Color EndColor { get { return m_endColor; } set { m_endColor = value; } } /// <summary> /// The gradient mode to display the colors. /// </summary> [DefaultValue(LinearGradientMode.Horizontal)] public LinearGradientMode LinearGradientMode { get { return m_linearGradientMode; } set { m_linearGradientMode = value; } } } #endregion DockPanelSkin classes #region Converters public class DockPanelSkinConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(DockPanelSkin)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is DockPanelSkin) { return "DockPanelSkin"; } return base.ConvertTo(context, culture, value, destinationType); } } public class DockPanelGradientConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(DockPanelGradient)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is DockPanelGradient) { return "DockPanelGradient"; } return base.ConvertTo(context, culture, value, destinationType); } } public class AutoHideStripConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(AutoHideStripSkin)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is AutoHideStripSkin) { return "AutoHideStripSkin"; } return base.ConvertTo(context, culture, value, destinationType); } } public class DockPaneStripConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(DockPaneStripSkin)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is DockPaneStripSkin) { return "DockPaneStripSkin"; } return base.ConvertTo(context, culture, value, destinationType); } } public class DockPaneStripGradientConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(DockPaneStripGradient)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is DockPaneStripGradient) { return "DockPaneStripGradient"; } return base.ConvertTo(context, culture, value, destinationType); } } public class DockPaneTabGradientConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(TabGradient)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is TabGradient) { return "DockPaneTabGradient"; } return base.ConvertTo(context, culture, value, destinationType); } } #endregion Converters }
DragonFiestaTeam/DragonFiesta_Tools
QuestAnalyser/src/Docking/DockPanelSkin.cs
C#
gpl-2.0
14,802
def format_path( str ): while( str.find( '//' ) != -1 ): str = str.replace( '//', '/' ) return str
tencent-wechat/phxsql
phxrpc_package_config/tools/phxsql_utils.py
Python
gpl-2.0
103
document.addEventListener("DOMContentLoaded", function (event) { 'use strict'; var paragraph, url, proxy; paragraph = document.querySelectorAll('p.error_text'); chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) { url = tabs[0].url; if (url.indexOf('chrome://') == 0) { paragraph[0].innerHTML = 'Sorry, you can\'t activate Browse Google Cache on a page with a "chrome://" URL.'; } else if (url.indexOf('https://chrome.google.com/webstore') == 0) { paragraph[0].innerHTML = 'Sorry, you can\'t activate Browse Google Cache on the Chrome Web Store.'; } else { chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) { chrome.runtime.sendMessage({ action : 'extensionButtonClicked', 'tab': tabs[0] }); window.close(); }); } }); });
joelself/GoogleCacheBrowser
src/popup.js
JavaScript
gpl-2.0
815
package ch.hgdev.toposuite.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Useful static method for manipulating String. * * @author HGdev */ public class StringUtils { public static final String UTF8_BOM = "\uFEFF"; /** * This method assumes that the String contains a number. * * @param str A String. * @return The String incremented by 1. * @throws IllegalArgumentException Thrown if the input String does not end with a suitable * number. */ public static String incrementAsNumber(String str) throws IllegalArgumentException { if (str == null) { throw new IllegalArgumentException("The input String must not be null!"); } Pattern p = Pattern.compile("([0-9]+)$"); Matcher m = p.matcher(str); if (!m.find()) { throw new IllegalArgumentException( "Invalid input argument! The input String must end with a valid number"); } String number = m.group(1); String prefix = str.substring(0, str.length() - number.length()); return prefix + String.valueOf(Integer.valueOf(number) + 1); } }
hgdev-ch/toposuite-android
app/src/main/java/ch/hgdev/toposuite/utils/StringUtils.java
Java
gpl-2.0
1,224
package org.currconv.services.impl; import java.util.List; import org.currconv.dao.UserDao; import org.currconv.entities.user.User; import org.currconv.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service("userService") @Transactional public class UserServiceImpl implements UserService { @Autowired private UserDao dao; public void saveUser(User user) { dao.saveUser(user); } public List<User> findAllUsers(){ return dao.findAllUsers(); } public User findByUserName(String name){ return dao.findByUserName(name); } }
miguel-gr/currency-converter
src/main/java/org/currconv/services/impl/UserServiceImpl.java
Java
gpl-2.0
738
package com.debugtoday.htmldecoder.output; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.regex.Matcher; import org.slf4j.Logger; import com.debugtoday.htmldecoder.decoder.GeneralDecoder; import com.debugtoday.htmldecoder.exception.GeneralException; import com.debugtoday.htmldecoder.log.CommonLog; import com.debugtoday.htmldecoder.output.object.FileOutputArg; import com.debugtoday.htmldecoder.output.object.PaginationOutputArg; import com.debugtoday.htmldecoder.output.object.TagFileOutputArg; import com.debugtoday.htmldecoder.output.object.TagOutputArg; import com.debugtoday.htmldecoder.output.object.TagWrapper; import com.debugtoday.htmldecoder.output.object.TemplateFullTextWrapper; /** * base class for output relative to file output, i.g. article/article page/tag page/category page * @author zydecx * */ public class AbstractFileOutput implements Output { private static final Logger logger = CommonLog.getLogger(); @Override public String export(Object object) throws GeneralException { // TODO Auto-generated method stub return DONE; } /** * @param file * @param template * @param arg * @throws GeneralException */ public void writeToFile(File file, TemplateFullTextWrapper template, FileOutputArg arg) throws GeneralException { File parentFile = file.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { throw new GeneralException("fail to create file[" + file.getAbsolutePath() + "]", e); } } try ( PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); ) { String formattedHead = ""; if (arg.getPageTitle() != null) { formattedHead += "<title>" + arg.getPageTitle() + "</title>"; } if (arg.getHead() != null) { formattedHead += "\n" + arg.getHead(); } String templateFullText = template.getFullText() .replace(GeneralDecoder.formatPlaceholderRegex("head"), formattedHead); if (arg.getBodyTitle() != null) { templateFullText = templateFullText .replace(GeneralDecoder.formatPlaceholderRegex("body_title"), arg.getBodyTitle()); } if (arg.getBody() != null) { templateFullText = templateFullText .replace(GeneralDecoder.formatPlaceholderRegex("body"), arg.getBody()); } if (arg.getPagination() != null) { templateFullText = templateFullText .replace(GeneralDecoder.formatPlaceholderRegex("pagination"), arg.getPagination()); } pw.write(templateFullText); } catch (FileNotFoundException | UnsupportedEncodingException e) { throw new GeneralException("fail to write to file[" + file.getAbsolutePath() + "]", e); } } /** * used for tag page/category page output * @param templateFullTextWrapper * @param arg * @throws GeneralException */ public void exportTagPage(TemplateFullTextWrapper templateFullTextWrapper, TagFileOutputArg arg) throws GeneralException { List<TagWrapper> itemList = arg.getTagList(); int itemSize = itemList.size(); int pagination = arg.getPagination(); int pageSize = (int) Math.ceil(itemSize * 1.0 / pagination); Output tagOutput = arg.getTagOutput(); Output paginationOutput = arg.getPaginationOutput(); for (int i = 1; i <= pageSize; i++) { List<TagWrapper> subList = itemList.subList((i - 1) * pagination, Math.min(itemSize, i * pagination)); StringBuilder sb = new StringBuilder(); for (TagWrapper item : subList) { String itemName = item.getName(); TagOutputArg tagArg = new TagOutputArg(itemName, arg.getRootUrl() + "/" + item.getName(), item.getArticleList().size()); sb.append(tagOutput.export(tagArg)); } File file = new File(formatPageFilePath(arg.getRootFile().getAbsolutePath(), i)); FileOutputArg fileOutputArg = new FileOutputArg(); fileOutputArg.setBodyTitle(arg.getBodyTitle()); fileOutputArg.setBody(sb.toString()); fileOutputArg.setPageTitle(arg.getBodyTitle()); fileOutputArg.setPagination(paginationOutput.export(new PaginationOutputArg(arg.getRootUrl(), pageSize, i))); writeToFile(file, templateFullTextWrapper, fileOutputArg); } } protected String formatPageUrl(String rootUrl, int index) { return PaginationOutput.formatPaginationUrl(rootUrl, index); } protected String formatPageFilePath(String rootPath, int index) { return PaginationOutput.formatPaginationFilePath(rootPath, index); } }
zydecx/htmldecoder
src/main/java/com/debugtoday/htmldecoder/output/AbstractFileOutput.java
Java
gpl-2.0
4,685
/* MobileRobots Advanced Robotics Interface for Applications (ARIA) Copyright (C) 2004, 2005 ActivMedia Robotics LLC Copyright (C) 2006, 2007, 2008, 2009 MobileRobots Inc. Copyright (C) 2010, 2011 Adept Technology, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA If you wish to redistribute ARIA under different terms, contact Adept MobileRobots for information about a commercial version of ARIA at robots@mobilerobots.com or Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; 800-639-9481 */ #include "Aria.h" #include "ArExport.h" #include "ArServerModeRatioDrive.h" #include "ArServerHandlerCommands.h" AREXPORT ArServerModeRatioDrive::ArServerModeRatioDrive( ArServerBase *server, ArRobot *robot, bool takeControlOnJoystick, bool useComputerJoystick, bool useRobotJoystick, bool useServerCommands, const char *name, bool robotJoystickOverridesLocks) : ArServerMode(robot, server, name), myRatioDriveGroup(robot), myJoyUserTaskCB(this, &ArServerModeRatioDrive::joyUserTask), myServerSetSafeDriveCB(this, &ArServerModeRatioDrive::serverSetSafeDrive), myServerGetSafeDriveCB(this, &ArServerModeRatioDrive::serverGetSafeDrive), myServerRatioDriveCB(this, &ArServerModeRatioDrive::serverRatioDrive), myRatioFireCB(this, &ArServerModeRatioDrive::ratioFireCallback), myServerSafeDrivingEnableCB(this, &ArServerModeRatioDrive::serverSafeDrivingEnable), myServerSafeDrivingDisableCB(this, &ArServerModeRatioDrive::serverSafeDrivingDisable) { myHandlerCommands = NULL; myDriveSafely = true; myTakeControlOnJoystick = takeControlOnJoystick; myUseComputerJoystick = useComputerJoystick; myUseRobotJoystick = useRobotJoystick; myUseServerCommands = useServerCommands; myUseLocationDependentDevices = true; myRobotJoystickOverridesLock = robotJoystickOverridesLocks; myTimeout = 2; myGotServerCommand = true; myLastTimedOut = false; // SEEKUR mySentRecenter = false; // add the actions, put the ratio input on top, then have the // limiters since the ratio doesn't touch decel except lightly // whereas the limiter will touch it strongly myRatioAction = new ArActionRatioInput; myRatioDriveGroup.addAction(myRatioAction, 50); myLimiterForward = new ArActionDeceleratingLimiter( "DeceleratingLimiterForward", ArActionDeceleratingLimiter::FORWARDS); myRatioDriveGroup.addAction(myLimiterForward, 40); myLimiterBackward = new ArActionDeceleratingLimiter( "DeceleratingLimiterBackward", ArActionDeceleratingLimiter::BACKWARDS); myRatioDriveGroup.addAction(myLimiterBackward, 39); myLimiterLateralLeft = NULL; myLimiterLateralRight = NULL; if (myRobot->hasLatVel()) { myLimiterLateralLeft = new ArActionDeceleratingLimiter( "DeceleratingLimiterLateralLeft", ArActionDeceleratingLimiter::LATERAL_LEFT); myRatioDriveGroup.addAction(myLimiterLateralLeft, 38); myLimiterLateralRight = new ArActionDeceleratingLimiter( "DeceleratingLimiterLateralRight", ArActionDeceleratingLimiter::LATERAL_RIGHT); myRatioDriveGroup.addAction(myLimiterLateralRight, 37); } myMovementParameters = new ArActionMovementParameters("TeleopMovementParameters", false); myRatioDriveGroup.addAction(myMovementParameters, 1); myRatioFireCB.setName("ArServerModeRatioDrive"); myRatioAction->addFireCallback(30, &myRatioFireCB); myLastRobotSafeDrive = true; if (myServer != NULL && myUseServerCommands) { addModeData("ratioDrive", "drives the robot as with a joystick", &myServerRatioDriveCB, "double: transRatio; double: rotRatio; double: throttleRatio ", "none", "Movement", "RETURN_NONE"); myServer->addData("setSafeDrive", "sets whether we drive the robot safely or not", &myServerSetSafeDriveCB, "byte: 1 == drive safely, 0 == drive unsafely", "none", "UnsafeMovement", "RETURN_NONE"); myServer->addData("getSafeDrive", "gets whether we drive the robot safely or not", &myServerGetSafeDriveCB, "none", "byte: 1 == driving safely, 0 == driving unsafely", "Movement", "RETURN_SINGLE"); } if (myUseComputerJoystick) { myJoydrive = new ArRatioInputJoydrive(robot, myRatioAction); if ((myJoyHandler = Aria::getJoyHandler()) == NULL) { myJoyHandler = new ArJoyHandler; myJoyHandler->init(); Aria::setJoyHandler(myJoyHandler); } } if (myUseRobotJoystick) { myRobotJoydrive = new ArRatioInputRobotJoydrive(robot, myRatioAction); if ((myRobotJoyHandler = Aria::getRobotJoyHandler()) == NULL) { myRobotJoyHandler = new ArRobotJoyHandler(robot); Aria::setRobotJoyHandler(myRobotJoyHandler); } } if (myUseRobotJoystick || myUseComputerJoystick) { std::string taskName = name; taskName += "::joyUserTask"; myRobot->addUserTask(taskName.c_str(), 75, &myJoyUserTaskCB); } myPrinting = false; } AREXPORT ArServerModeRatioDrive::~ArServerModeRatioDrive() { } AREXPORT void ArServerModeRatioDrive::addToConfig(ArConfig *config, const char *section) { config->addParam( ArConfigArg( "Timeout", &myTimeout, "If there are no commands for this period of time, then the robot will stop. 0 Disables. This is a double so you can do like .1 seconds if you want.", 0), section, ArPriority::ADVANCED); myRatioAction->addToConfig(config, section); myLimiterForward->addToConfig(config, section, "Forward"); myLimiterBackward->addToConfig(config, section, "Backward"); if (myLimiterLateralLeft != NULL) myLimiterLateralLeft->addToConfig(config, section, "Lateral"); if (myLimiterLateralRight != NULL) myLimiterLateralRight->addToConfig(config, section, "Lateral"); myMovementParameters->addToConfig(config, section, "Teleop"); } AREXPORT void ArServerModeRatioDrive::activate(void) { //if (!baseActivate()) { // return; //} ratioDrive(0, 0, 100, true); } AREXPORT void ArServerModeRatioDrive::deactivate(void) { myRatioDriveGroup.deactivate(); baseDeactivate(); } AREXPORT void ArServerModeRatioDrive::setSafeDriving(bool safe, bool internal) { if (!internal) myRobot->lock(); // if this is a change then print it if (safe != myDriveSafely) { if (safe) { ArLog::log(ArLog::Normal, "%s: Driving safely again", myName.c_str()); } else { ArLog::log(ArLog::Normal, "%s: Driving UNSAFELY", myName.c_str()); } myNewDriveSafely = true; } myDriveSafely = safe; // ratioDrive is only called if this mode is already active if (isActive()) ratioDrive(myRatioAction->getTransRatio(), myRatioAction->getRotRatio(), myRatioAction->getThrottleRatio()); if (!internal) myRobot->unlock(); } AREXPORT bool ArServerModeRatioDrive::getSafeDriving(void) { return myDriveSafely; } AREXPORT void ArServerModeRatioDrive::serverSafeDrivingEnable(void) { setSafeDriving(true); } AREXPORT void ArServerModeRatioDrive::serverSafeDrivingDisable(void) { setSafeDriving(false); } AREXPORT void ArServerModeRatioDrive::addControlCommands(ArServerHandlerCommands *handlerCommands) { if (!myUseServerCommands) { ArLog::log(ArLog::Normal, "ArServerModeRatioDrive::addControlCommands: Tried to add control commands to a ratio drive not using the server"); return; } myHandlerCommands = handlerCommands; myHandlerCommands->addCommand( "safeRatioDrivingEnable", "Enables safe driving with ratioDrive, which will attempt to prevent collisions (default)", &myServerSafeDrivingEnableCB, "UnsafeMovement"); myHandlerCommands->addCommand( "safeRatioDrivingDisable", "Disables safe driving with ratioDrive, this is UNSAFE and will let you drive your robot into things or down stairs, use at your own risk", &myServerSafeDrivingDisableCB, "UnsafeMovement"); } /** * @param isActivating a bool set to true only if this method is called from the activate() * method, otherwise false * @param transRatio Amount of forward velocity to request * @param rotRatio Amount of rotational velocity to request * @param throttleRatio Amount of speed to request * @param latRatio amount of lateral velocity to request (if robot supports it) **/ AREXPORT void ArServerModeRatioDrive::ratioDrive( double transRatio, double rotRatio, double throttleRatio, bool isActivating, double latRatio) { bool wasActive; wasActive = isActive(); myTransRatio = transRatio; myRotRatio = rotRatio; myThrottleRatio = throttleRatio; myLatRatio = latRatio; // KMC: Changed the following test to include isActivating. // if (!wasActive && !baseActivate()) // return; // The baseActivate() method should only be called in the context of the activate() // method. if (isActivating && !wasActive) { if (!baseActivate()) { return; } } // end if activating and wasn't previously active // This is to handle the case where ratioDrive is called outside the // activate() method, and the activation was not successful. if (!isActive()) { return; } if (!wasActive || myNewDriveSafely) { myRobot->clearDirectMotion(); if (myDriveSafely) { myRatioDriveGroup.activateExclusive(); myMode = "Drive"; ArLog::log(ArLog::Normal, "%s: Driving safely", myName.c_str()); } else { myRobot->deactivateActions(); myRatioAction->activate(); myMode = "UNSAFE Drive"; ArLog::log(ArLog::Normal, "%s: Driving unsafely", myName.c_str()); } if (myDriveSafely) mySafeDrivingCallbacks.invoke(); else myUnsafeDrivingCallbacks.invoke(); } myNewDriveSafely = false; // MPL why is this here twice? myTransRatio = transRatio; myRotRatio = rotRatio; myThrottleRatio = throttleRatio; myLatRatio = latRatio; setActivityTimeToNow(); // SEEKUR mySentRecenter = false; if (myPrinting) printf("cmd %.0f %.0f %.0f %.0f\n", transRatio, rotRatio, throttleRatio, latRatio); if (myTransRatio < -0.1) myDrivingBackwardsCallbacks.invoke(); //myRatioAction.setRatios(transRatio, rotRatio, throttleRatio); } AREXPORT void ArServerModeRatioDrive::serverRatioDrive(ArServerClient *client, ArNetPacket *packet) { double transRatio = packet->bufToDouble(); double rotRatio = packet->bufToDouble(); double throttleRatio = packet->bufToDouble(); double lateralRatio = packet->bufToDouble(); myGotServerCommand = true; if (!myDriveSafely && !client->hasGroupAccess("UnsafeMovement")) serverSafeDrivingEnable(); myRobot->lock(); // Activate if necessary. Note that this is done before the ratioDrive // call because we want the new ratio values to be applied after the // default ones. if (!isActive()) { activate(); } /* ArLog::log(ArLog::Normal, "RatioDrive trans %.0f rot %.0f lat %.0f ratio %.0f", transRatio, rotRatio, lateralRatio, throttleRatio); */ ratioDrive(transRatio, rotRatio, throttleRatio, false, lateralRatio); myRobot->unlock(); } AREXPORT void ArServerModeRatioDrive::serverSetSafeDrive( ArServerClient *client, ArNetPacket *packet) { if (packet->bufToUByte() == 0) setSafeDriving(false); else setSafeDriving(true); } AREXPORT void ArServerModeRatioDrive::serverGetSafeDrive( ArServerClient *client, ArNetPacket *packet) { ArNetPacket sendPacket; if (getSafeDriving()) sendPacket.uByteToBuf(1); else sendPacket.uByteToBuf(0); client->sendPacketTcp(&sendPacket); } AREXPORT void ArServerModeRatioDrive::joyUserTask(void) { // if we're not active but we should be if (myTakeControlOnJoystick && !isActive() && ((myUseComputerJoystick && myJoyHandler->haveJoystick() && myJoyHandler->getButton(1)) || (myUseRobotJoystick && myRobotJoyHandler->gotData() && myRobotJoyHandler->getButton1()))) { if (ArServerMode::getActiveMode() != NULL) ArLog::log(ArLog::Normal, "%s: Activating instead of %s because of local joystick", ArServerMode::getActiveMode()->getName(), myName.c_str()); else ArLog::log(ArLog::Normal, "%s: Activating because of local joystick", myName.c_str()); // if we're locked and are overriding that lock for the robot // joystick and it was the robot joystick that caused it to happen if (myUseRobotJoystick && myRobotJoyHandler->gotData() && myRobotJoyHandler->getButton1() && myRobotJoystickOverridesLock && ArServerMode::ourActiveModeLocked) { ArLog::log(ArLog::Terse, "Robot joystick is overriding locked mode %s", ourActiveMode->getName()); ourActiveMode->forceUnlock(); myRobot->enableMotors(); } activate(); } bool unsafeRobotDrive; if (myUseRobotJoystick && myRobotJoyHandler->gotData() && ((unsafeRobotDrive = (bool)(myRobot->getFaultFlags() & ArUtil::BIT15)) != !myLastRobotSafeDrive)) { myLastRobotSafeDrive = !unsafeRobotDrive; setSafeDriving(myLastRobotSafeDrive, true); } } AREXPORT void ArServerModeRatioDrive::userTask(void) { // Sets the robot so that we always think we're trying to move in // this mode myRobot->forceTryingToMove(); // if the joystick is pushed then set that we're active, server // commands'll go into ratioDrive and set it there too if ((myUseComputerJoystick && myJoyHandler->haveJoystick() && myJoyHandler->getButton(1)) || (myUseRobotJoystick && myRobotJoyHandler->gotData() && myRobotJoyHandler->getButton1()) || (myUseServerCommands && myGotServerCommand)) { setActivityTimeToNow(); } myGotServerCommand = false; bool timedOut = false; // if we're moving, and there is a timeout, and the activity time is // greater than the timeout, then stop the robot if ((fabs(myRobot->getVel()) > 0 || fabs(myRobot->getRotVel()) > 0 || fabs(myRobot->getLatVel()) > 0) && myTimeout > .0000001 && getActivityTime().mSecSince()/1000.0 >= myTimeout) { if (!myLastTimedOut) { ArLog::log(ArLog::Normal, "Stopping the robot since teleop timed out"); myRobot->stop(); myRobot->clearDirectMotion(); ratioDrive(0, 0, 0, 0); } timedOut = true; } myLastTimedOut = timedOut; // SEEKUR (needed for prototype versions) /* if (myRobot->hasLatVel() && !mySentRecenter && getActivityTime().secSince() >= 10) { mySentRecenter = true; myRobot->com(120); } */ if (!myStatusSetThisCycle) { if (myRobot->isLeftMotorStalled() || myRobot->isRightMotorStalled()) myStatus = "Stalled"; // this works because if the motors stalled above caught it, if // not and more values it means a stall else if (myRobot->getStallValue()) myStatus = "Bumped"; else if (ArMath::fabs(myRobot->getVel()) < 2 && ArMath::fabs(myRobot->getRotVel()) < 2 && (!myRobot->hasLatVel() || ArMath::fabs(myRobot->getLatVel()) < 2)) myStatus = "Stopped"; else myStatus = "Driving"; } myStatusSetThisCycle = false; } // end method userTask AREXPORT void ArServerModeRatioDrive::ratioFireCallback(void) { if (myPrinting) ArLog::log(ArLog::Normal, "ArServerModeRatioDrive: TransRatio=%.0f RotRatio=%.0f ThrottleRatio=%.0f LatRatio=%.0f", myTransRatio, myRotRatio, myThrottleRatio, myLatRatio); myRatioAction->setRatios(myTransRatio, myRotRatio, myThrottleRatio, myLatRatio); } AREXPORT void ArServerModeRatioDrive::setUseLocationDependentDevices( bool useLocationDependentDevices, bool internal) { if (!internal) myRobot->lock(); // if this is a change then print it if (useLocationDependentDevices != myUseLocationDependentDevices) { if (useLocationDependentDevices) { ArLog::log(ArLog::Normal, "%s: Using location dependent range devices", myName.c_str()); } else { ArLog::log(ArLog::Normal, "%s: Not using location dependent range devices", myName.c_str()); } myUseLocationDependentDevices = useLocationDependentDevices; myLimiterForward->setUseLocationDependentDevices( myUseLocationDependentDevices); myLimiterBackward->setUseLocationDependentDevices( myUseLocationDependentDevices); if (myLimiterLateralLeft != NULL) myLimiterLateralLeft->setUseLocationDependentDevices( myUseLocationDependentDevices); if (myLimiterLateralRight != NULL) myLimiterLateralRight->setUseLocationDependentDevices( myUseLocationDependentDevices); } if (!internal) myRobot->unlock(); } AREXPORT bool ArServerModeRatioDrive::getUseLocationDependentDevices(void) { return myUseLocationDependentDevices; }
admo/aria
arnetworking/ArServerModeRatioDrive.cpp
C++
gpl-2.0
17,363
package com.networkprofiles.widget; /** Service to refresh the widget **/ import android.app.Service; import android.appwidget.AppWidgetManager; import android.content.Intent; import android.graphics.Color; import android.os.IBinder; import android.provider.Settings; import android.widget.RemoteViews; import com.networkprofiles.R; import com.networkprofiles.utils.MyNetControll; public class NPWidgetService extends Service { private Boolean mobile; private Boolean cell; private Boolean gps; private Boolean display; private Boolean sound; private int [] widgetIds; private RemoteViews rv; private AppWidgetManager wm; private MyNetControll myController; public void onCreate() { wm = AppWidgetManager.getInstance(NPWidgetService.this);//this.getApplicationContext() myController = new MyNetControll(NPWidgetService.this); myController.myStart(); //rv = new RemoteViews(getPackageName(), R.layout.npwidgetwifi); } public int onStartCommand(Intent intent, int flags, int startId) { // /** Check the state of the network devices and set the text for the text fields **/ // //set the TextView for 3G data // if(telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED || telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTING) { // rv.setTextViewText(R.id.textMobile, "3G data is ON"); // } // if(telephonyManager.getDataState() == TelephonyManager.DATA_DISCONNECTED) { // rv.setTextViewText(R.id.textMobile, "3G data is OFF"); // } // //set the TextView for WiFi // if(wifim.getWifiState() == WifiManager.WIFI_STATE_ENABLED || wifim.getWifiState() == WifiManager.WIFI_STATE_ENABLING) { // rv.setTextViewText(R.id.textWifi, "Wifi is ON"); // } // if(wifim.getWifiState() == WifiManager.WIFI_STATE_DISABLED || wifim.getWifiState() == WifiManager.WIFI_STATE_DISABLING) { // rv.setTextViewText(R.id.textWifi, "Wifi is OFF"); // } // //set the TextView for Bluetooth // if(myBluetooth.getState() == BluetoothAdapter.STATE_ON || myBluetooth.getState() == BluetoothAdapter.STATE_TURNING_ON) { // rv.setTextViewText(R.id.textBluetooth, "Bluetooth is ON"); // } // if(myBluetooth.getState() == BluetoothAdapter.STATE_OFF || myBluetooth.getState() == BluetoothAdapter.STATE_TURNING_OFF) { // rv.setTextViewText(R.id.textBluetooth, "Bluetooth is Off"); // } // //set the TextView for Cell voice // if(Settings.System.getInt(NPWidgetService.this.getContentResolver(), // Settings.System.AIRPLANE_MODE_ON, 0) == 0) { // rv.setTextViewText(R.id.textCell, "Cell is ON"); // } else { // rv.setTextViewText(R.id.textCell, "Cell is OFF"); // } // //set the TextView for GPS // locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); // if(locationProviders.contains("gps")) { // rv.setTextViewText(R.id.textGps, "GPS is ON"); // } else { // rv.setTextViewText(R.id.textGps, "GPS is OFF"); // } /** Check which textView was clicked and switch the state of the corresponding device **/ widgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS); mobile = intent.getBooleanExtra("mobile", false); cell = intent.getBooleanExtra("cell", false); gps = intent.getBooleanExtra("gps", false); display = intent.getBooleanExtra("display", false); sound = intent.getBooleanExtra("sound", false); if(widgetIds.length > 0) { if(mobile) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetmobiledata); rv.setTextColor(R.id.textWidgetMobileData, Color.GREEN); updateWidgets(); rv.setTextColor(R.id.textWidgetMobileData, Color.WHITE); myController.mobileOnOff(); } if(cell) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetcell); rv.setTextColor(R.id.textWidgetCell, Color.GREEN); if(Settings.System.getInt(NPWidgetService.this.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 0) { myController.cellOff(); } else { myController.cellOn(); } if(Settings.System.getInt(NPWidgetService.this.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 0) { rv.setTextViewText(R.id.textWidgetCell, "Cell ON"); } else { rv.setTextViewText(R.id.textWidgetCell, "Cell OFF"); } updateWidgets(); rv.setTextColor(R.id.textWidgetCell, Color.WHITE); } if(gps) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetgps); rv.setTextColor(R.id.textWidgetGps, Color.GREEN); updateWidgets(); rv.setTextColor(R.id.textWidgetGps, Color.WHITE); myController.gpsOnOff(); } if(display) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetdisplay); rv.setTextColor(R.id.textWidgetDisplay, Color.GREEN); updateWidgets(); rv.setTextColor(R.id.textWidgetDisplay, Color.WHITE); myController.displayOnOff(); } if(sound) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetsound); rv.setTextColor(R.id.textViewWidgetSound, Color.GREEN); updateWidgets(); rv.setTextColor(R.id.textViewWidgetSound, Color.WHITE); myController.soundSettings(); } } updateWidgets(); stopSelf(); return 1; } public void onStart(Intent intent, int startId) { } public IBinder onBind(Intent arg0) { return null; } private void updateWidgets() { for(int id : widgetIds) { wm.updateAppWidget(id, rv); } } }//close class NPWidgetService
ektodorov/ShortcutsOfPower_Android
src/com/networkprofiles/widget/NPWidgetService.java
Java
gpl-2.0
5,416
#!/usr/bin/env python3 # Copyright (c) 2008-9 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 2 of the License, or # version 3 of the License, or (at your option) any later version. It is # provided for educational purposes and is distributed in the hope that # it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See # the GNU General Public License for more details. """Provides the Item example classes. """ class Item(object): def __init__(self, artist, title, year=None): self.__artist = artist self.__title = title self.__year = year def artist(self): return self.__artist def setArtist(self, artist): self.__artist = artist def title(self): return self.__title def setTitle(self, title): self.__title = title def year(self): return self.__year def setYear(self, year): self.__year = year def __str__(self): year = "" if self.__year is not None: year = " in {0}".format(self.__year) return "{0} by {1}{2}".format(self.__title, self.__artist, year) class Painting(Item): def __init__(self, artist, title, year=None): super(Painting, self).__init__(artist, title, year) class Sculpture(Item): def __init__(self, artist, title, year=None, material=None): super(Sculpture, self).__init__(artist, title, year) self.__material = material def material(self): return self.__material def setMaterial(self, material): self.__material = material def __str__(self): materialString = "" if self.__material is not None: materialString = " ({0})".format(self.__material) return "{0}{1}".format(super(Sculpture, self).__str__(), materialString) class Dimension(object): def __init__(self, width, height, depth=None): self.__width = width self.__height = height self.__depth = depth def width(self): return self.__width def setWidth(self, width): self.__width = width def height(self): return self.__height def setHeight(self, height): self.__height = height def depth(self): return self.__depth def setDepth(self, depth): self.__depth = depth def area(self): raise NotImplemented def volume(self): raise NotImplemented if __name__ == "__main__": items = [] items.append(Painting("Cecil Collins", "The Poet", 1941)) items.append(Painting("Cecil Collins", "The Sleeping Fool", 1943)) items.append(Painting("Edvard Munch", "The Scream", 1893)) items.append(Painting("Edvard Munch", "The Sick Child", 1896)) items.append(Painting("Edvard Munch", "The Dance of Life", 1900)) items.append(Sculpture("Auguste Rodin", "Eternal Springtime", 1917, "plaster")) items.append(Sculpture("Auguste Rodin", "Naked Balzac", 1917, "plaster")) items.append(Sculpture("Auguste Rodin", "The Secret", 1925, "bronze")) uniquematerials = set() for item in items: print(item) if hasattr(item, "material"): uniquematerials.add(item.material()) print("Sculptures use {0} unique materials".format( len(uniquematerials)))
paradiseOffice/Bash_and_Cplus-plus
CPP/full_examples/pyqt/chap03/item.py
Python
gpl-2.0
3,660
<?php /** * The template for displaying all posts having layout like: sidebar/content/sidebar. * * @package Sage Theme */ ?> <?php get_sidebar('second'); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'single' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || get_comments_number() ) : comments_template(); endif; ?> <?php endwhile; // end of the loop. ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); ?>
jbs321/wahad-humus
wp-content/themes/sage/layouts/blog/sidebar-content-sidebar.php
PHP
gpl-2.0
774
/* GNU ddrescue - Data recovery tool Copyright (C) 2004-2019 Antonio Diaz Diaz. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define _FILE_OFFSET_BITS 64 #include <algorithm> #include <cctype> #include <cerrno> #include <climits> #include <cstdio> #include <cstdlib> #include <ctime> #include <string> #include <vector> #include <stdint.h> #include <termios.h> #include <unistd.h> #include "block.h" #include "mapbook.h" namespace { void input_pos_error( const long long pos, const long long insize ) { char buf[128]; snprintf( buf, sizeof buf, "Can't start reading at pos %s.\n" " Input file is only %s bytes long.", format_num3( pos ), format_num3( insize ) ); show_error( buf ); } } // end namespace bool Mapbook::save_mapfile( const char * const name ) { std::remove( name ); FILE * const f = std::fopen( name, "w" ); if( f && write_mapfile( f, true, true ) && std::fclose( f ) == 0 ) { char buf[80]; snprintf( buf, sizeof buf, "Mapfile saved in '%s'\n", name ); final_msg( buf ); return true; } return false; } bool Mapbook::emergency_save() { static bool first_time = true; static std::string home_name; const std::string dead_name( "ddrescue.map" ); if( filename() != dead_name && save_mapfile( dead_name.c_str() ) ) return true; if( first_time ) { first_time = false; const char * const p = std::getenv( "HOME" ); if( p ) { home_name = p; home_name += '/'; home_name += dead_name; } } if( home_name.size() && filename() != home_name && save_mapfile( home_name.c_str() ) ) return true; show_error( "Emergency save failed." ); return false; } Mapbook::Mapbook( const long long offset, const long long insize, Domain & dom, const Mb_options & mb_opts, const char * const mapname, const int cluster, const int hardbs, const bool complete_only, const bool rescue ) : Mapfile( mapname ), Mb_options( mb_opts ), offset_( offset ), mapfile_insize_( 0 ), domain_( dom ), hardbs_( hardbs ), softbs_( cluster * hardbs_ ), iobuf_size_( softbs_ + hardbs_ ), // +hardbs for direct unaligned reads final_errno_( 0 ), um_t1( 0 ), um_t1s( 0 ), um_prev_mf_sync( false ), mapfile_exists_( false ) { long alignment = sysconf( _SC_PAGESIZE ); if( alignment < hardbs_ || alignment % hardbs_ ) alignment = hardbs_; if( alignment < 2 ) alignment = 0; iobuf_ = iobuf_base = new uint8_t[ alignment + iobuf_size_ + hardbs_ ]; if( alignment > 1 ) // align iobuf for direct disc access { const int disp = alignment - ( reinterpret_cast<unsigned long long> (iobuf_) % alignment ); if( disp > 0 && disp < alignment ) iobuf_ += disp; } if( insize > 0 ) { if( domain_.pos() >= insize ) { input_pos_error( domain_.pos(), insize ); std::exit( 1 ); } domain_.crop_by_file_size( insize ); } if( filename() ) { mapfile_exists_ = read_mapfile( 0, false ); if( mapfile_exists_ ) mapfile_insize_ = extent().end(); } if( !complete_only ) extend_sblock_vector( insize ); else domain_.crop( extent() ); // limit domain to blocks read from mapfile compact_sblock_vector(); if( rescue ) join_subsectors( hardbs_ ); split_by_domain_borders( domain_ ); if( sblocks() == 0 ) domain_.clear(); } // Writes periodically the mapfile to disc. // Returns false only if update is attempted and fails. // bool Mapbook::update_mapfile( const int odes, const bool force ) { if( !filename() ) return true; const int interval = ( mapfile_save_interval >= 0 ) ? mapfile_save_interval : 30 + std::min( 270L, sblocks() / 38 ); // auto, 30s to 5m const long t2 = std::time( 0 ); if( um_t1 == 0 || um_t1 > t2 ) um_t1 = um_t1s = t2; // initialize if( !force && t2 - um_t1 < interval ) return true; const bool mf_sync = ( force || t2 - um_t1s >= mapfile_sync_interval ); if( odes >= 0 ) fsync( odes ); if( um_prev_mf_sync ) { std::string mapname_bak( filename() ); mapname_bak += ".bak"; std::remove( mapname_bak.c_str() ); // break possible hard link std::rename( filename(), mapname_bak.c_str() ); } um_prev_mf_sync = mf_sync; while( true ) { errno = 0; if( write_mapfile( 0, true, mf_sync ) ) // update times here to exclude writing time from intervals { um_t1 = std::time( 0 ); if( mf_sync ) um_t1s = um_t1; return true; } if( verbosity < 0 ) return false; const int saved_errno = errno; std::fputc( '\n', stderr ); char buf[80]; snprintf( buf, sizeof buf, "Error writing mapfile '%s'", filename() ); show_error( buf, saved_errno ); std::fputs( "Fix the problem and press ENTER to retry,\n" " or E+ENTER for an emergency save and exit,\n" " or Q+ENTER to abort.\n", stderr ); std::fflush( stderr ); while( true ) { tcflush( STDIN_FILENO, TCIFLUSH ); const int c = std::tolower( std::fgetc( stdin ) ); int tmp = c; while( tmp != '\n' && tmp != EOF ) tmp = std::fgetc( stdin ); if( c == '\r' || c == '\n' || c == 'e' || c == 'q' ) { if( c == 'q' || ( c == 'e' && emergency_save() ) ) { if( !force ) std::fputs( "\n\n\n\n", stdout ); return false; } break; } } } }
mruffalo/ddrescue
mapbook.cc
C++
gpl-2.0
6,040
/* Copyright (c) 2008 The Board of Trustees of The Leland Stanford * Junior University * * We are making the OpenFlow specification and associated documentation * (Software) available for public use and benefit with the expectation * that others will use, modify and enhance the Software and contribute * those enhancements back to the community. However, since we would * like to make the Software available for broadest use, with as few * restrictions as possible permission is hereby granted, free of * charge, to any person obtaining a copy of this Software to deal in * the Software under the copyrights without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * The name and trademarks of copyright holder(s) may NOT be used in * advertising or publicity pertaining to the Software or any * derivatives without specific, written prior permission. */ #include "../include/config.h" #include "csum.hh" CLICK_DECLS /* Returns the IP checksum of the 'n' bytes in 'data'. */ uint16_t csum(const void *data, size_t n) { return csum_finish(csum_continue(0, data, n)); } /* Adds the 16 bits in 'new' to the partial IP checksum 'partial' and returns * the updated checksum. (To start a new checksum, pass 0 for 'partial'. To * obtain the finished checksum, pass the return value to csum_finish().) */ uint32_t csum_add16(uint32_t partial, uint16_t New) { return partial + New; } /* Adds the 32 bits in 'new' to the partial IP checksum 'partial' and returns * the updated checksum. (To start a new checksum, pass 0 for 'partial'. To * obtain the finished checksum, pass the return value to csum_finish().) */ uint32_t csum_add32(uint32_t partial, uint32_t New) { return partial + (New >> 16) + (New & 0xffff); } /* Adds the 'n' bytes in 'data' to the partial IP checksum 'partial' and * returns the updated checksum. (To start a new checksum, pass 0 for * 'partial'. To obtain the finished checksum, pass the return value to * csum_finish().) */ uint32_t csum_continue(uint32_t partial, const void *data_, size_t n) { const uint16_t *data = (const uint16_t*)data_; for (; n > 1; n -= 2) { partial = csum_add16(partial, *data++); } if (n) { partial += *(uint8_t *) data; } return partial; } /* Returns the IP checksum corresponding to 'partial', which is a value updated * by some combination of csum_add16(), csum_add32(), and csum_continue(). */ uint16_t csum_finish(uint32_t partial) { return ~((partial & 0xffff) + (partial >> 16)); } /* Returns the new checksum for a packet in which the checksum field previously * contained 'old_csum' and in which a field that contained 'old_u16' was * changed to contain 'new_u16'. */ uint16_t recalc_csum16(uint16_t old_csum, uint16_t old_u16, uint16_t new_u16) { /* Ones-complement arithmetic is endian-independent, so this code does not * use htons() or ntohs(). * * See RFC 1624 for formula and explanation. */ uint16_t hc_complement = ~old_csum; uint16_t m_complement = ~old_u16; uint16_t m_prime = new_u16; uint32_t sum = hc_complement + m_complement + m_prime; uint16_t hc_prime_complement = sum + (sum >> 16); return ~hc_prime_complement; } /* Returns the new checksum for a packet in which the checksum field previously * contained 'old_csum' and in which a field that contained 'old_u32' was * changed to contain 'new_u32'. */ uint16_t recalc_csum32(uint16_t old_csum, uint32_t old_u32, uint32_t new_u32) { return recalc_csum16(recalc_csum16(old_csum, old_u32, new_u32), old_u32 >> 16, new_u32 >> 16); } CLICK_ENDDECLS ELEMENT_PROVIDES(Of_Csum)
JaeyongYoo/VisualXSwitch
elements/local/OpenFlow/lib/csum.cc
C++
gpl-2.0
4,507
#!/usr/bin/env python # -*- coding:utf-8 -*- """ @author: Will """ from django import forms from app01 import models class ImportFrom(forms.Form): HOST_TYPE=((1,"001"),(2,"002")) #替換爲文件 host_type = forms.IntegerField( widget=forms.Select(choices=HOST_TYPE) ) hostname = forms.CharField() def __init__(self,*args,**kwargs): super(ImportFrom,self).__init__(*args,**kwargs) HOST_TYPE=((1,"001"),(2,"002")) #替換爲文件 self.fields['host_type'].widget.choices = models.userInfo.objects.all().values_list("id","name") models.userInfo.objects.get() models.userInfo.objects.filter()
willre/homework
day19/web/app01/forms/home.py
Python
gpl-2.0
723
package net.minecartrapidtransit.path.launcher; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class FileStoreUtils { private String version; public FileStoreUtils(String versionFile) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(new File(getDataFilePath(versionFile)))); version = br.readLine(); br.close(); } public String getVersionedFile(String filename, String type){ return String.format("%s-%s.%s", filename, version, type); } public boolean fileNeedsUpdating(String filename, String type) { return(new File(getVersionedFile(filename, type)).exists()); } public String getVersionedDataFilePath(String filename, String type){ return getDataFilePath(getVersionedFile(filename, type)); } public static String getDataFolderPath(){ String os = System.getProperty("os.name").toLowerCase(); boolean windows = os.contains("windows"); boolean mac = os.contains("macosx"); if(windows){ return System.getenv("APPDATA") + "\\MRTPath2"; }else{ String home = System.getProperty("user.home"); if(mac){ return home + "/Library/Application Support/MRTPath2"; }else{ // Linux return home + "/.mrtpath2"; } } } public static String getDataFilePath(String file){ return getDataFolderPath() + File.separator + file.replace('/', File.separatorChar); } }
MinecartRapidTransit/MRTPath2
launcher/src/main/java/net/minecartrapidtransit/path/launcher/FileStoreUtils.java
Java
gpl-2.0
1,412
/****************************************************************************** * Icinga 2 * * Copyright (C) 2012-2016 Icinga Development Team (https://www.icinga.org/) * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software Foundation * * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * ******************************************************************************/ #include "livestatus/endpointstable.hpp" #include "icinga/host.hpp" #include "icinga/service.hpp" #include "icinga/icingaapplication.hpp" #include "remote/endpoint.hpp" #include "remote/zone.hpp" #include "base/configtype.hpp" #include "base/objectlock.hpp" #include "base/convert.hpp" #include "base/utility.hpp" #include <boost/algorithm/string/classification.hpp> #include <boost/tuple/tuple.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/algorithm/string/split.hpp> using namespace icinga; EndpointsTable::EndpointsTable(void) { AddColumns(this); } void EndpointsTable::AddColumns(Table *table, const String& prefix, const Column::ObjectAccessor& objectAccessor) { table->AddColumn(prefix + "name", Column(&EndpointsTable::NameAccessor, objectAccessor)); table->AddColumn(prefix + "identity", Column(&EndpointsTable::IdentityAccessor, objectAccessor)); table->AddColumn(prefix + "node", Column(&EndpointsTable::NodeAccessor, objectAccessor)); table->AddColumn(prefix + "is_connected", Column(&EndpointsTable::IsConnectedAccessor, objectAccessor)); table->AddColumn(prefix + "zone", Column(&EndpointsTable::ZoneAccessor, objectAccessor)); } String EndpointsTable::GetName(void) const { return "endpoints"; } String EndpointsTable::GetPrefix(void) const { return "endpoint"; } void EndpointsTable::FetchRows(const AddRowFunction& addRowFn) { for (const Endpoint::Ptr& endpoint : ConfigType::GetObjectsByType<Endpoint>()) { if (!addRowFn(endpoint, LivestatusGroupByNone, Empty)) return; } } Value EndpointsTable::NameAccessor(const Value& row) { Endpoint::Ptr endpoint = static_cast<Endpoint::Ptr>(row); if (!endpoint) return Empty; return endpoint->GetName(); } Value EndpointsTable::IdentityAccessor(const Value& row) { Endpoint::Ptr endpoint = static_cast<Endpoint::Ptr>(row); if (!endpoint) return Empty; return endpoint->GetName(); } Value EndpointsTable::NodeAccessor(const Value& row) { Endpoint::Ptr endpoint = static_cast<Endpoint::Ptr>(row); if (!endpoint) return Empty; return IcingaApplication::GetInstance()->GetNodeName(); } Value EndpointsTable::IsConnectedAccessor(const Value& row) { Endpoint::Ptr endpoint = static_cast<Endpoint::Ptr>(row); if (!endpoint) return Empty; unsigned int is_connected = endpoint->GetConnected() ? 1 : 0; /* if identity is equal to node, fake is_connected */ if (endpoint->GetName() == IcingaApplication::GetInstance()->GetNodeName()) is_connected = 1; return is_connected; } Value EndpointsTable::ZoneAccessor(const Value& row) { Endpoint::Ptr endpoint = static_cast<Endpoint::Ptr>(row); if (!endpoint) return Empty; Zone::Ptr zone = endpoint->GetZone(); if (!zone) return Empty; return zone->GetName(); }
zearan/icinga2
lib/livestatus/endpointstable.cpp
C++
gpl-2.0
4,193
<?php /** * @file * Banana class. */ namespace Drupal\oop_example_12\BusinessLogic\Fruit; /** * Banana class. */ class Banana extends Fruit { /** * Returns color of the object. */ public function getColor() { return t('yellow'); } }
nfouka/poo_d8
oop_examples/oop_example_12/src/BusinessLogic/Fruit/Banana.php
PHP
gpl-2.0
258
<?php /** * The template for displaying the footer. * * @package WordPress */ ?> </div> </div> <!-- Begin footer --> <div id="footer"> <?php $pp_footer_display_sidebar = get_option('pp_footer_display_sidebar'); if(!empty($pp_footer_display_sidebar)) { $pp_footer_style = get_option('pp_footer_style'); $footer_class = ''; switch($pp_footer_style) { case 1: $footer_class = 'one'; break; case 2: $footer_class = 'two'; break; case 3: $footer_class = 'three'; break; case 4: $footer_class = 'four'; break; default: $footer_class = 'four'; break; } ?> <ul class="sidebar_widget <?php echo $footer_class; ?>"> <?php dynamic_sidebar('Footer Sidebar'); ?> </ul> <br class="clear"/> <?php } ?> </div> <!-- End footer --> <div> <div> <div id="copyright" <?php if(empty($pp_footer_display_sidebar)) { echo 'style="border-top:0"'; } ?>> <div class="copyright_wrapper"> <div class="one_fourth"> <?php /** * Get footer left text */ $pp_footer_text = get_option('pp_footer_text'); if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) { $pp_footer_text = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($pp_footer_text); } if(empty($pp_footer_text)) { $pp_footer_text = 'Copyright © 2012 Nemesis Theme. Powered by <a href="http://wordpress.org/">Wordpress</a>.<br/>Wordpress theme by <a href="http://themeforest.net/user/peerapong/portfolio" target="_blank">Peerapong</a>'; } echo nl2br(stripslashes(html_entity_decode($pp_footer_text))); ?> </div> <div class="one_fourth"> <?php /** * Get footer left text */ $pp_footer_second_text = get_option('pp_footer_second_text'); if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) { $pp_footer_second_text = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($pp_footer_second_text); } if(empty($pp_footer_second_text)) { $pp_footer_second_text = ' '; } echo nl2br(stripslashes(html_entity_decode($pp_footer_second_text))); ?> </div> <div class="one_fourth"> <?php /** * Get footer left text */ $pp_footer_third_text = get_option('pp_footer_third_text'); if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) { $pp_footer_third_text = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($pp_footer_third_text); } if(empty($pp_footer_third_text)) { $pp_footer_third_text = ' '; } echo nl2br(stripslashes(html_entity_decode($pp_footer_third_text))); ?> </div> <div class="one_fourth last"> <?php /** * Get footer right text */ $pp_footer_right_text = get_option('pp_footer_right_text'); if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) { $pp_footer_right_text = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($pp_footer_right_text); } if(empty($pp_footer_right_text)) { $pp_footer_right_text = 'All images are copyrighted to their respective owners.'; } echo nl2br(stripslashes(html_entity_decode($pp_footer_right_text))); ?> </div> <br class="clear"/> </div> </div> </div> </div> <?php /** * Setup Google Analyric Code **/ include (TEMPLATEPATH . "/google-analytic.php"); ?> <?php /* Always have wp_footer() just before the closing </body> * tag of your theme, or you will break many plugins, which * generally use this hook to reference JavaScript files. */ wp_footer(); ?> <?php $pp_blog_share = get_option('pp_blog_share'); if(!empty($pp_blog_share)) { ?> <script type="text/javascript" src="//assets.pinterest.com/js/pinit.js"></script> <?php } ?> </body> </html>
Seizam/atelierweb
wp-content/themes/nemesis/footer.php
PHP
gpl-2.0
4,069
#include "logging.hpp" #include <fstream> #include <boost/log/sinks/text_file_backend.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/sinks.hpp> namespace p2l { namespace common { //===================================================================== void _init_logging() { boost::log::add_common_attributes(); boost::log::core::get()->set_filter ( boost::log::trivial::severity >= boost::log::trivial::trace ); typedef boost::log::sinks::synchronous_sink< boost::log::sinks::text_ostream_backend > text_sink; // the file sink for hte default logger boost::shared_ptr< text_sink > default_sink = boost::make_shared< text_sink >(); default_sink->locked_backend()->add_stream ( boost::make_shared< std::ofstream >( "default_log.log" ) ); boost::log::core::get()->add_sink( default_sink ); // the file sink for hte stat logger boost::shared_ptr< text_sink > stat_sink = boost::make_shared< text_sink >(); stat_sink->locked_backend()->add_stream ( boost::make_shared< std::ofstream >( "stat_log.log" ) ); boost::log::core::get()->add_sink( stat_sink ); } //===================================================================== //===================================================================== //===================================================================== //===================================================================== //===================================================================== //===================================================================== //===================================================================== //===================================================================== //===================================================================== //===================================================================== //===================================================================== } }
velezj/pods.ptp.object-search.common
src/logging.cpp
C++
gpl-2.0
2,078
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.dialect.unique; import org.hibernate.boot.Metadata; import org.hibernate.dialect.Dialect; import org.hibernate.mapping.UniqueKey; /** * Informix requires the constraint name to come last on the alter table. * * @author Brett Meyer */ public class InformixUniqueDelegate extends DefaultUniqueDelegate { public InformixUniqueDelegate( Dialect dialect ) { super( dialect ); } // legacy model ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @Override public String getAlterTableToAddUniqueKeyCommand(UniqueKey uniqueKey, Metadata metadata) { // Do this here, rather than allowing UniqueKey/Constraint to do it. // We need full, simplified control over whether or not it happens. final String tableName = metadata.getDatabase().getJdbcEnvironment().getQualifiedObjectNameFormatter().format( uniqueKey.getTable().getQualifiedTableName(), metadata.getDatabase().getJdbcEnvironment().getDialect() ); final String constraintName = dialect.quote( uniqueKey.getName() ); return dialect.getAlterTableString( tableName ) + " add constraint " + uniqueConstraintSql( uniqueKey ) + " constraint " + constraintName; } }
lamsfoundation/lams
3rdParty_sources/hibernate-core/org/hibernate/dialect/unique/InformixUniqueDelegate.java
Java
gpl-2.0
1,458
showWord(["","Wayòm ki te nan pati Sidwès peyi Ispayola. Se Boyekyo ki te chèf endyen nan wayòm sa a. Kapital wayòm sa a te Lagwana, kounye a yo rele l Leogàn." ])
georgejhunt/HaitiDictionary.activity
data/words/zaragwa.js
JavaScript
gpl-2.0
169
#include "steadystatetest.hh" #include <models/REmodel.hh> #include <models/LNAmodel.hh> #include <models/IOSmodel.hh> #include <models/sseinterpreter.hh> #include <models/steadystateanalysis.hh> #include <eval/jit/engine.hh> #include <parser/sbml/sbml.hh> using namespace iNA; SteadyStateTest::~SteadyStateTest() { // pass... } void SteadyStateTest::testEnzymeKineticsRE() { // Read doc and check for errors: Ast::Model sbml_model; Parser::Sbml::importModel(sbml_model, "test/regression-tests/extended_goodwin.xml"); // Construct RE model to integrate Models::REmodel model(sbml_model); // Perform analysis: Eigen::VectorXd state(model.getDimension()); Models::SteadyStateAnalysis<Models::REmodel> analysis(model); analysis.setMaxIterations(1000); analysis.calcSteadyState(state); } void SteadyStateTest::testEnzymeKineticsLNA() { // Read doc and check for errors: Ast::Model sbml_model; Parser::Sbml::importModel(sbml_model, "test/regression-tests/extended_goodwin.xml"); // Construct LNA model to integrate Models::LNAmodel model(sbml_model); // Perform analysis: Eigen::VectorXd state(model.getDimension()); Models::SteadyStateAnalysis<Models::LNAmodel> analysis(model); analysis.setMaxIterations(1000); analysis.calcSteadyState(state); } void SteadyStateTest::testEnzymeKineticsIOS() { // Read doc and check for errors: Ast::Model sbml_model; Parser::Sbml::importModel(sbml_model, "test/regression-tests/extended_goodwin.xml"); // Construct model to integrate Models::IOSmodel model(sbml_model); // Perform analysis: Eigen::VectorXd state(model.getDimension()); Models::SteadyStateAnalysis<Models::IOSmodel> analysis(model); analysis.setMaxIterations(1000); analysis.calcSteadyState(state); } UnitTest::TestSuite * SteadyStateTest::suite() { UnitTest::TestSuite *s = new UnitTest::TestSuite("Steady State Tests"); s->addTest(new UnitTest::TestCaller<SteadyStateTest>( "EnzymeKinetics Model (RE)", &SteadyStateTest::testEnzymeKineticsRE)); s->addTest(new UnitTest::TestCaller<SteadyStateTest>( "EnzymeKinetics Model (LNA)", &SteadyStateTest::testEnzymeKineticsLNA)); s->addTest(new UnitTest::TestCaller<SteadyStateTest>( "EnzymeKinetics Model (IOS)", &SteadyStateTest::testEnzymeKineticsIOS)); return s; }
hmatuschek/intrinsic-noise-analyzer
test/steadystatetest.cc
C++
gpl-2.0
2,341
/**! * The MIT License * * Copyright (c) 2010-2012 Google, Inc. http://angularjs.org * * 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. * * angular-google-maps * https://github.com/nlaplante/angular-google-maps * * @author Nicolas Laplante https://plus.google.com/108189012221374960701 */ (function () { "use strict"; /* * Utility functions */ /** * Check if 2 floating point numbers are equal * * @see http://stackoverflow.com/a/588014 */ function floatEqual (f1, f2) { return (Math.abs(f1 - f2) < 0.000001); } /* * Create the model in a self-contained class where map-specific logic is * done. This model will be used in the directive. */ var MapModel = (function () { var _defaults = { zoom: 8, draggable: false, container: null }; /** * */ function PrivateMapModel(opts) { var _instance = null, _markers = [], // caches the instances of google.maps.Marker _handlers = [], // event handlers _windows = [], // InfoWindow objects o = angular.extend({}, _defaults, opts), that = this, currentInfoWindow = null; this.center = opts.center; this.zoom = o.zoom; this.draggable = o.draggable; this.dragging = false; this.selector = o.container; this.markers = []; this.options = o.options; this.draw = function () { if (that.center == null) { // TODO log error return; } if (_instance == null) { // Create a new map instance _instance = new google.maps.Map(that.selector, angular.extend(that.options, { center: that.center, zoom: that.zoom, draggable: that.draggable, mapTypeId : google.maps.MapTypeId.ROADMAP })); google.maps.event.addListener(_instance, "dragstart", function () { that.dragging = true; } ); google.maps.event.addListener(_instance, "idle", function () { that.dragging = false; } ); google.maps.event.addListener(_instance, "drag", function () { that.dragging = true; } ); google.maps.event.addListener(_instance, "zoom_changed", function () { that.zoom = _instance.getZoom(); that.center = _instance.getCenter(); } ); google.maps.event.addListener(_instance, "center_changed", function () { that.center = _instance.getCenter(); } ); // Attach additional event listeners if needed if (_handlers.length) { angular.forEach(_handlers, function (h, i) { google.maps.event.addListener(_instance, h.on, h.handler); }); } } else { // Refresh the existing instance google.maps.event.trigger(_instance, "resize"); var instanceCenter = _instance.getCenter(); if (!floatEqual(instanceCenter.lat(), that.center.lat()) || !floatEqual(instanceCenter.lng(), that.center.lng())) { _instance.setCenter(that.center); } if (_instance.getZoom() != that.zoom) { _instance.setZoom(that.zoom); } } }; this.fit = function () { if (_instance && _markers.length) { var bounds = new google.maps.LatLngBounds(); angular.forEach(_markers, function (m, i) { bounds.extend(m.getPosition()); }); _instance.fitBounds(bounds); } }; this.on = function(event, handler) { _handlers.push({ "on": event, "handler": handler }); }; this.addMarker = function (lat, lng, icon, infoWindowContent, label, url, thumbnail) { if (that.findMarker(lat, lng) != null) { return; } var marker = new google.maps.Marker({ position: new google.maps.LatLng(lat, lng), map: _instance, icon: icon }); if (label) { } if (url) { } if (infoWindowContent != null) { var infoWindow = new google.maps.InfoWindow({ content: infoWindowContent }); google.maps.event.addListener(marker, 'click', function() { if (currentInfoWindow != null) { currentInfoWindow.close(); } infoWindow.open(_instance, marker); currentInfoWindow = infoWindow; }); } // Cache marker _markers.unshift(marker); // Cache instance of our marker for scope purposes that.markers.unshift({ "lat": lat, "lng": lng, "draggable": false, "icon": icon, "infoWindowContent": infoWindowContent, "label": label, "url": url, "thumbnail": thumbnail }); // Return marker instance return marker; }; this.findMarker = function (lat, lng) { for (var i = 0; i < _markers.length; i++) { var pos = _markers[i].getPosition(); if (floatEqual(pos.lat(), lat) && floatEqual(pos.lng(), lng)) { return _markers[i]; } } return null; }; this.findMarkerIndex = function (lat, lng) { for (var i = 0; i < _markers.length; i++) { var pos = _markers[i].getPosition(); if (floatEqual(pos.lat(), lat) && floatEqual(pos.lng(), lng)) { return i; } } return -1; }; this.addInfoWindow = function (lat, lng, html) { var win = new google.maps.InfoWindow({ content: html, position: new google.maps.LatLng(lat, lng) }); _windows.push(win); return win; }; this.hasMarker = function (lat, lng) { return that.findMarker(lat, lng) !== null; }; this.getMarkerInstances = function () { return _markers; }; this.removeMarkers = function (markerInstances) { var s = this; angular.forEach(markerInstances, function (v, i) { var pos = v.getPosition(), lat = pos.lat(), lng = pos.lng(), index = s.findMarkerIndex(lat, lng); // Remove from local arrays _markers.splice(index, 1); s.markers.splice(index, 1); // Remove from map v.setMap(null); }); }; } // Done return PrivateMapModel; }()); // End model // Start Angular directive var googleMapsModule = angular.module("google-maps", []); /** * Map directive */ googleMapsModule.directive("googleMap", ["$log", "$timeout", "$filter", function ($log, $timeout, $filter) { var controller = function ($scope, $element) { var _m = $scope.map; self.addInfoWindow = function (lat, lng, content) { _m.addInfoWindow(lat, lng, content); }; }; controller.$inject = ['$scope', '$element']; return { restrict: "EC", priority: 100, transclude: true, template: "<div class='angular-google-map' ng-transclude></div>", replace: false, scope: { center: "=center", // required markers: "=markers", // optional latitude: "=latitude", // required longitude: "=longitude", // required zoom: "=zoom", // required refresh: "&refresh", // optional windows: "=windows" // optional" }, controller: controller, link: function (scope, element, attrs, ctrl) { // Center property must be specified and provide lat & // lng properties if (!angular.isDefined(scope.center) || (!angular.isDefined(scope.center.lat) || !angular.isDefined(scope.center.lng))) { $log.error("angular-google-maps: ould not find a valid center property"); return; } if (!angular.isDefined(scope.zoom)) { $log.error("angular-google-maps: map zoom property not set"); return; } angular.element(element).addClass("angular-google-map"); // Parse options var opts = {options: {}}; if (attrs.options) { opts.options = angular.fromJson(attrs.options); } // Create our model var _m = new MapModel(angular.extend(opts, { container: element[0], center: new google.maps.LatLng(scope.center.lat, scope.center.lng), draggable: attrs.draggable == "true", zoom: scope.zoom })); _m.on("drag", function () { var c = _m.center; $timeout(function () { scope.$apply(function (s) { scope.center.lat = c.lat(); scope.center.lng = c.lng(); }); }); }); _m.on("zoom_changed", function () { if (scope.zoom != _m.zoom) { $timeout(function () { scope.$apply(function (s) { scope.zoom = _m.zoom; }); }); } }); _m.on("center_changed", function () { var c = _m.center; $timeout(function () { scope.$apply(function (s) { if (!_m.dragging) { scope.center.lat = c.lat(); scope.center.lng = c.lng(); } }); }); }); if (attrs.markClick == "true") { (function () { var cm = null; _m.on("click", function (e) { if (cm == null) { cm = { latitude: e.latLng.lat(), longitude: e.latLng.lng() }; scope.markers.push(cm); } else { cm.latitude = e.latLng.lat(); cm.longitude = e.latLng.lng(); } $timeout(function () { scope.latitude = cm.latitude; scope.longitude = cm.longitude; scope.$apply(); }); }); }()); } // Put the map into the scope scope.map = _m; // Check if we need to refresh the map if (angular.isUndefined(scope.refresh())) { // No refresh property given; draw the map immediately _m.draw(); } else { scope.$watch("refresh()", function (newValue, oldValue) { if (newValue && !oldValue) { _m.draw(); } }); } // Markers scope.$watch("markers", function (newValue, oldValue) { $timeout(function () { angular.forEach(newValue, function (v, i) { if (!_m.hasMarker(v.latitude, v.longitude)) { _m.addMarker(v.latitude, v.longitude, v.icon, v.infoWindow); } }); // Clear orphaned markers var orphaned = []; angular.forEach(_m.getMarkerInstances(), function (v, i) { // Check our scope if a marker with equal latitude and longitude. // If not found, then that marker has been removed form the scope. var pos = v.getPosition(), lat = pos.lat(), lng = pos.lng(), found = false; // Test against each marker in the scope for (var si = 0; si < scope.markers.length; si++) { var sm = scope.markers[si]; if (floatEqual(sm.latitude, lat) && floatEqual(sm.longitude, lng)) { // Map marker is present in scope too, don't remove found = true; } } // Marker in map has not been found in scope. Remove. if (!found) { orphaned.push(v); } }); orphaned.length && _m.removeMarkers(orphaned); // Fit map when there are more than one marker. // This will change the map center coordinates if (attrs.fit == "true" && newValue.length > 1) { _m.fit(); } }); }, true); // Update map when center coordinates change scope.$watch("center", function (newValue, oldValue) { if (newValue === oldValue) { return; } if (!_m.dragging) { _m.center = new google.maps.LatLng(newValue.lat, newValue.lng); _m.draw(); } }, true); scope.$watch("zoom", function (newValue, oldValue) { if (newValue === oldValue) { return; } _m.zoom = newValue; _m.draw(); }); } }; }]); }());
HediMaiza/SmoothieParis
js/vendor/google-maps.js
JavaScript
gpl-2.0
15,335
<?php die("Access Denied"); ?>#x#s:4516:" 1448241693 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-tw" lang="zh-tw"> <head> <script type="text/javascript"> var siteurl='/'; var tmplurl='/templates/ja_mendozite/'; var isRTL = false; </script> <base href="http://www.zon.com.tw/zh/component/mailto/" /> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="generator" content="榮憶橡膠工業股份有限公司" /> <title>榮憶橡膠工業股份有限公司 | 榮憶橡膠工業股份有限公司</title> <link href="http://www.zon.com.tw/zh/component/mailto/?link=5b01b8f2ca3ca1e431fb7082348e60a75d09bcb4&amp;template=ja_mendozite&amp;tmpl=component" rel="canonical" /> <link rel="stylesheet" href="/t3-assets/css_9ce88.css" type="text/css" /> <link rel="stylesheet" href="/t3-assets/css_31cec.css" type="text/css" /> <script src="/en/?jat3action=gzip&amp;jat3type=js&amp;jat3file=t3-assets%2Fjs_7f13c.js" type="text/javascript"></script> <script type="text/javascript"> function keepAlive() { var myAjax = new Request({method: "get", url: "index.php"}).send();} window.addEvent("domready", function(){ keepAlive.periodical(840000); }); </script> <script type="text/javascript"> var akoption = { "colorTable" : true , "opacityEffect" : true , "foldContent" : true , "fixingElement" : true , "smoothScroll" : false } ; var akconfig = new Object(); akconfig.root = 'http://www.zon.com.tw/' ; akconfig.host = 'http://'+location.host+'/' ; AsikartEasySet.init( akoption , akconfig ); </script> <link href="/plugins/system/jat3/jat3/base-themes/default/images/favicon.ico" rel="shortcut icon" type="image/x-icon" /> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-60602086-1', 'auto'); ga('send', 'pageview'); </script> <link rel="stylesheet" href="http://www.zon.com.tw/easyset/css/custom-typo.css" type="text/css" /> <link rel="stylesheet" href="http://www.zon.com.tw/easyset/css/custom.css" type="text/css" /> </head> <body id="bd" class="fs3 com_mailto contentpane"> <div id="system-message-container"> <div id="system-message"> </div> </div> <script type="text/javascript"> Joomla.submitbutton = function(pressbutton) { var form = document.getElementById('mailtoForm'); // do field validation if (form.mailto.value == "" || form.from.value == "") { alert('請提供正確的電子郵件。'); return false; } form.submit(); } </script> <div id="mailto-window"> <h2> 推薦此連結給朋友。 </h2> <div class="mailto-close"> <a href="javascript: void window.close()" title="關閉視窗"> <span>關閉視窗 </span></a> </div> <form action="http://www.zon.com.tw/index.php" id="mailtoForm" method="post"> <div class="formelm"> <label for="mailto_field">寄信給</label> <input type="text" id="mailto_field" name="mailto" class="inputbox" size="25" value=""/> </div> <div class="formelm"> <label for="sender_field"> 寄件者</label> <input type="text" id="sender_field" name="sender" class="inputbox" value="" size="25" /> </div> <div class="formelm"> <label for="from_field"> 您的郵件</label> <input type="text" id="from_field" name="from" class="inputbox" value="" size="25" /> </div> <div class="formelm"> <label for="subject_field"> 主旨</label> <input type="text" id="subject_field" name="subject" class="inputbox" value="" size="25" /> </div> <p> <button class="button" onclick="return Joomla.submitbutton('send');"> 送出 </button> <button class="button" onclick="window.close();return false;"> 取消 </button> </p> <input type="hidden" name="layout" value="default" /> <input type="hidden" name="option" value="com_mailto" /> <input type="hidden" name="task" value="send" /> <input type="hidden" name="tmpl" value="component" /> <input type="hidden" name="link" value="5b01b8f2ca3ca1e431fb7082348e60a75d09bcb4" /> <input type="hidden" name="3431db301dbcf490ccf76011c9360ad9" value="1" /> </form> </div> </body> </html>";
ForAEdesWeb/AEW32
cache/t3_pages/e8efe7956197beb28b5e158ad88f292e-cache-t3_pages-160aa8f95d30404c7ac89ff054f766d9.php
PHP
gpl-2.0
4,524
<?php foreach ($content as $key => $value): ?> <div class="product-item-viewed product-node-id-<?php print $key; ?>"> <?php print l($value['title'], $value['path']); ?> <?php if (isset($value['image'])): ?> <div class='image-viewed'><img src='<?php print $value['image']; ?>' /></div> <?php endif; ?> </div> <?php endforeach; ?>
Fant0m771/commerce
sites/all/modules/custom/last_viewed_products/templates/last_viewed_products.tpl.php
PHP
gpl-2.0
363
package kieranvs.avatar.bending.earth; import java.util.Arrays; import java.util.concurrent.ConcurrentHashMap; import net.minecraft.block.Block; import net.minecraft.entity.EntityLivingBase; import net.minecraft.init.Blocks; import kieranvs.avatar.Protection; import kieranvs.avatar.bending.Ability; import kieranvs.avatar.bending.AsynchronousAbility; import kieranvs.avatar.bukkit.BlockBukkit; import kieranvs.avatar.bukkit.Location; import kieranvs.avatar.bukkit.Vector; import kieranvs.avatar.util.AvatarDamageSource; import kieranvs.avatar.util.BendingUtils; public class EarthStream extends AsynchronousAbility { private long interval = 200L; private long risetime = 600L; private ConcurrentHashMap<BlockBukkit, Long> movedBlocks = new ConcurrentHashMap<BlockBukkit, Long>(); private Location origin; private Location location; private Vector direction; private int range; private long time; private boolean finished = false; public EarthStream(EntityLivingBase user, Location location, Vector direction, int range) { super(user, 2000); this.time = System.currentTimeMillis(); this.range = range; this.origin = location.clone(); this.location = location.clone(); this.direction = direction.clone(); this.direction.setY(0); this.direction.normalize(); this.location.add(this.direction); } @Override public void update() { for (BlockBukkit block : movedBlocks.keySet()) { long time = movedBlocks.get(block).longValue(); if (System.currentTimeMillis() > time + risetime) { Protection.trySetBlock(user.worldObj, Blocks.air, block.getRelative(BlockBukkit.UP).getX(), block.getRelative(BlockBukkit.UP).getY(), block.getRelative(BlockBukkit.UP).getZ()); movedBlocks.remove(block); } } if (finished) { if (movedBlocks.isEmpty()) { destroy(); } else { return; } } if (System.currentTimeMillis() - time >= interval) { time = System.currentTimeMillis(); location.add(direction); if (location.distance(origin) > range) { finished = true; return; } BlockBukkit block = this.location.getBlock(); if (isMoveable(block)) { moveBlock(block); } if (isMoveable(block.getRelative(BlockBukkit.DOWN))) { moveBlock(block.getRelative(BlockBukkit.DOWN)); location = block.getRelative(BlockBukkit.DOWN).getLocation(); return; } if (isMoveable(block.getRelative(BlockBukkit.UP))) { moveBlock(block.getRelative(BlockBukkit.UP)); location = block.getRelative(BlockBukkit.UP).getLocation(); return; } else { finished = true; } return; } } public void moveBlock(BlockBukkit block) { // block.getRelative(Block.UP).breakNaturally(); //block.getRelative(Block.UP).setType(block.getType()); //movedBlocks.put(block, System.currentTimeMillis()); //damageEntities(block.getLocation()); //BendingUtils.damageEntities(block.getLocation(), 3.5F, AvatarDamageSource.earthbending, 3); Protection.trySetBlock(user.worldObj, Blocks.dirt, block.getRelative(BlockBukkit.UP).getX(), block.getRelative(BlockBukkit.UP).getY(), block.getRelative(BlockBukkit.UP).getZ()); movedBlocks.put(block, System.currentTimeMillis()); } public void damageEntities(Location loc) { for (Object o : loc.getWorld().getLoadedEntityList()) { if (o instanceof EntityLivingBase) { EntityLivingBase e = (EntityLivingBase) o; if (loc.distance(e) < 3.5) { e.attackEntityFrom(AvatarDamageSource.earthbending, 3); } } } } public static boolean isMoveable(BlockBukkit block) { Block[] overwriteable = { Blocks.air, Blocks.sapling, Blocks.tallgrass, Blocks.deadbush, Blocks.yellow_flower, Blocks.red_flower, Blocks.brown_mushroom, Blocks.red_mushroom, Blocks.fire, Blocks.snow, Blocks.torch, Blocks.leaves, Blocks.cactus, Blocks.reeds, Blocks.web, Blocks.waterlily, Blocks.vine }; if (!Arrays.asList(overwriteable).contains(block.getRelative(BlockBukkit.UP).getType())) { return false; } Block[] moveable = { Blocks.brick_block, Blocks.clay, Blocks.coal_ore, Blocks.cobblestone, Blocks.dirt, Blocks.grass, Blocks.gravel, Blocks.mossy_cobblestone, Blocks.mycelium, Blocks.nether_brick, Blocks.netherrack, Blocks.obsidian, Blocks.sand, Blocks.sandstone, Blocks.farmland, Blocks.soul_sand, Blocks.stone }; if (Arrays.asList(moveable).contains(block.getType())) { return true; } return false; } }
kieranvs/Blockbender
Blockbender/src/kieranvs/avatar/bending/earth/EarthStream.java
Java
gpl-2.0
4,514
/***************************************************************** Copyright (c) 1996-2000 the kicker authors. See file AUTHORS. 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 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. ******************************************************************/ #include <qdragobject.h> #include <qstring.h> #include <qstringlist.h> #include <kglobal.h> #include <kiconloader.h> #include <kmimetype.h> #include <klocale.h> #include <kdesktopfile.h> #include <kglobalsettings.h> #include <kapplication.h> #include <kurldrag.h> #include <krecentdocument.h> #include "recentdocsmenu.h" K_EXPORT_KICKER_MENUEXT(recentdocs, RecentDocsMenu) RecentDocsMenu::RecentDocsMenu(QWidget *parent, const char *name, const QStringList &/*args*/) : KPanelMenu(KRecentDocument::recentDocumentDirectory(), parent, name) { } RecentDocsMenu::~RecentDocsMenu() { } void RecentDocsMenu::initialize() { if (initialized()) clear(); insertItem(SmallIconSet("history_clear"), i18n("Clear History"), this, SLOT(slotClearHistory())); insertSeparator(); _fileList = KRecentDocument::recentDocuments(); if (_fileList.isEmpty()) { insertItem(i18n("No Entries"), 0); setItemEnabled(0, false); return; } int id = 0; char alreadyPresentInMenu; QStringList previousEntries; for (QStringList::ConstIterator it = _fileList.begin(); it != _fileList.end(); ++it) { KDesktopFile f(*it, true /* read only */); // Make sure this entry is not already present in the menu alreadyPresentInMenu = 0; for ( QStringList::Iterator previt = previousEntries.begin(); previt != previousEntries.end(); ++previt ) { if (QString::localeAwareCompare(*previt, f.readName().replace('&', QString::fromAscii("&&") )) == 0) { alreadyPresentInMenu = 1; } } if (alreadyPresentInMenu == 0) { // Add item to menu insertItem(SmallIconSet(f.readIcon()), f.readName().replace('&', QString::fromAscii("&&") ), id++); // Append to duplicate checking list previousEntries.append(f.readName().replace('&', QString::fromAscii("&&") )); } } setInitialized(true); } void RecentDocsMenu::slotClearHistory() { KRecentDocument::clear(); reinitialize(); } void RecentDocsMenu::slotExec(int id) { if (id >= 0) { kapp->propagateSessionManager(); KURL u; u.setPath(_fileList[id]); KDEDesktopMimeType::run(u, true); } } void RecentDocsMenu::mousePressEvent(QMouseEvent* e) { _mouseDown = e->pos(); QPopupMenu::mousePressEvent(e); } void RecentDocsMenu::mouseMoveEvent(QMouseEvent* e) { KPanelMenu::mouseMoveEvent(e); if (!(e->state() & LeftButton)) return; if (!rect().contains(_mouseDown)) return; int dragLength = (e->pos() - _mouseDown).manhattanLength(); if (dragLength <= KGlobalSettings::dndEventDelay()) return; // ignore it int id = idAt(_mouseDown); // Don't drag 'manual' items. if (id < 0) return; KDesktopFile f(_fileList[id], true /* read only */); KURL url ( f.readURL() ); if (url.isEmpty()) // What are we to do ? return; KURL::List lst; lst.append(url); KURLDrag* d = new KURLDrag(lst, this); d->setPixmap(SmallIcon(f.readIcon())); d->dragCopy(); close(); } void RecentDocsMenu::slotAboutToShow() { reinitialize(); KPanelMenu::slotAboutToShow(); } #include "recentdocsmenu.moc"
iegor/kdebase
kicker/menuext/recentdocs/recentdocsmenu.cpp
C++
gpl-2.0
4,232
# Portions Copyright (c) Facebook, Inc. and its affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. # match.py - filename matching # # Copyright 2008, 2009 Matt Mackall <mpm@selenic.com> and others # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from __future__ import absolute_import, print_function import copy import os import re from bindings import pathmatcher from . import error, pathutil, pycompat, util from .i18n import _ from .pycompat import decodeutf8 allpatternkinds = ( "re", "glob", "path", "relglob", "relpath", "relre", "listfile", "listfile0", "set", "include", "subinclude", "rootfilesin", ) cwdrelativepatternkinds = ("relpath", "glob") propertycache = util.propertycache def _rematcher(regex): """compile the regexp with the best available regexp engine and return a matcher function""" m = util.re.compile(regex) try: # slightly faster, provided by facebook's re2 bindings return m.test_match except AttributeError: return m.match def _expandsets(kindpats, ctx): """Returns the kindpats list with the 'set' patterns expanded.""" fset = set() other = [] for kind, pat, source in kindpats: if kind == "set": if not ctx: raise error.ProgrammingError("fileset expression with no " "context") s = ctx.getfileset(pat) fset.update(s) continue other.append((kind, pat, source)) return fset, other def _expandsubinclude(kindpats, root): """Returns the list of subinclude matcher args and the kindpats without the subincludes in it.""" relmatchers = [] other = [] for kind, pat, source in kindpats: if kind == "subinclude": sourceroot = pathutil.dirname(util.normpath(source)) pat = util.pconvert(pat) path = pathutil.join(sourceroot, pat) newroot = pathutil.dirname(path) matcherargs = (newroot, "", [], ["include:%s" % path]) prefix = pathutil.canonpath(root, root, newroot) if prefix: prefix += "/" relmatchers.append((prefix, matcherargs)) else: other.append((kind, pat, source)) return relmatchers, other def _kindpatsalwaysmatch(kindpats): """ "Checks whether the kindspats match everything, as e.g. 'relpath:.' does. """ for kind, pat, source in kindpats: # TODO: update me? if pat != "" or kind not in ["relpath", "glob"]: return False return True def match( root, cwd, patterns=None, include=None, exclude=None, default="glob", exact=False, auditor=None, ctx=None, warn=None, badfn=None, icasefs=False, ): """build an object to match a set of file patterns arguments: root - the canonical root of the tree you're matching against cwd - the current working directory, if relevant patterns - patterns to find include - patterns to include (unless they are excluded) exclude - patterns to exclude (even if they are included) default - if a pattern in patterns has no explicit type, assume this one exact - patterns are actually filenames (include/exclude still apply) warn - optional function used for printing warnings badfn - optional bad() callback for this matcher instead of the default icasefs - make a matcher for wdir on case insensitive filesystems, which normalizes the given patterns to the case in the filesystem a pattern is one of: 'glob:<glob>' - a glob relative to cwd 're:<regexp>' - a regular expression 'path:<path>' - a path relative to repository root, which is matched recursively 'rootfilesin:<path>' - a path relative to repository root, which is matched non-recursively (will not match subdirectories) 'relglob:<glob>' - an unrooted glob (*.c matches C files in all dirs) 'relpath:<path>' - a path relative to cwd 'relre:<regexp>' - a regexp that needn't match the start of a name 'set:<fileset>' - a fileset expression 'include:<path>' - a file of patterns to read and include 'subinclude:<path>' - a file of patterns to match against files under the same directory '<something>' - a pattern of the specified default type """ if auditor is None: auditor = pathutil.pathauditor(root) normalize = _donormalize if icasefs: if exact: raise error.ProgrammingError( "a case-insensitive exact matcher " "doesn't make sense" ) dirstate = ctx.repo().dirstate dsnormalize = dirstate.normalize def normalize(patterns, default, root, cwd, auditor, warn): kp = _donormalize(patterns, default, root, cwd, auditor, warn) kindpats = [] for kind, pats, source in kp: if kind not in ("re", "relre"): # regex can't be normalized p = pats pats = dsnormalize(pats) # Preserve the original to handle a case only rename. if p != pats and p in dirstate: kindpats.append((kind, p, source)) kindpats.append((kind, pats, source)) return kindpats if exact: m = exactmatcher(root, cwd, patterns, badfn) elif patterns: kindpats = normalize(patterns, default, root, cwd, auditor, warn) if _kindpatsalwaysmatch(kindpats): m = alwaysmatcher(root, cwd, badfn, relativeuipath=True) else: m = patternmatcher(root, cwd, kindpats, ctx=ctx, badfn=badfn) else: # It's a little strange that no patterns means to match everything. # Consider changing this to match nothing (probably using nevermatcher). m = alwaysmatcher(root, cwd, badfn) if include: kindpats = normalize(include, "glob", root, cwd, auditor, warn) im = includematcher(root, cwd, kindpats, ctx=ctx, badfn=None) m = intersectmatchers(m, im) if exclude: kindpats = normalize(exclude, "glob", root, cwd, auditor, warn) em = includematcher(root, cwd, kindpats, ctx=ctx, badfn=None) m = differencematcher(m, em) return m def exact(root, cwd, files, badfn=None): return exactmatcher(root, cwd, files, badfn=badfn) def always(root, cwd): return alwaysmatcher(root, cwd) def never(root, cwd): return nevermatcher(root, cwd) def union(matches, root, cwd): """Union a list of matchers. If the list is empty, return nevermatcher. If the list only contains one non-None value, return that matcher. Otherwise return a union matcher. """ matches = list(filter(None, matches)) if len(matches) == 0: return nevermatcher(root, cwd) elif len(matches) == 1: return matches[0] else: return unionmatcher(matches) def badmatch(match, badfn): """Make a copy of the given matcher, replacing its bad method with the given one. """ m = copy.copy(match) m.bad = badfn return m def _donormalize(patterns, default, root, cwd, auditor, warn): """Convert 'kind:pat' from the patterns list to tuples with kind and normalized and rooted patterns and with listfiles expanded.""" kindpats = [] for kind, pat in [_patsplit(p, default) for p in patterns]: if kind in cwdrelativepatternkinds: pat = pathutil.canonpath(root, cwd, pat, auditor) elif kind in ("relglob", "path", "rootfilesin"): pat = util.normpath(pat) elif kind in ("listfile", "listfile0"): try: files = decodeutf8(util.readfile(pat)) if kind == "listfile0": files = files.split("\0") else: files = files.splitlines() files = [f for f in files if f] except EnvironmentError: raise error.Abort(_("unable to read file list (%s)") % pat) for k, p, source in _donormalize(files, default, root, cwd, auditor, warn): kindpats.append((k, p, pat)) continue elif kind == "include": try: fullpath = os.path.join(root, util.localpath(pat)) includepats = readpatternfile(fullpath, warn) for k, p, source in _donormalize( includepats, default, root, cwd, auditor, warn ): kindpats.append((k, p, source or pat)) except error.Abort as inst: raise error.Abort("%s: %s" % (pat, inst[0])) except IOError as inst: if warn: warn( _("skipping unreadable pattern file '%s': %s\n") % (pat, inst.strerror) ) continue # else: re or relre - which cannot be normalized kindpats.append((kind, pat, "")) return kindpats def _testrefastpath(repat): """Test if a re pattern can use fast path. That is, for every "$A/$B" path the pattern matches, "$A" must also be matched, Return True if we're sure it is. Return False otherwise. """ # XXX: It's very hard to implement this. These are what need to be # supported in production and tests. Very hacky. But we plan to get rid # of re matchers eventually. # Rules like "(?!experimental/)" if repat.startswith("(?!") and repat.endswith(")") and repat.count(")") == 1: return True # Rules used in doctest if repat == "(i|j)$": return True return False def _globpatsplit(pat): """Split a glob pattern. Return a list. A naive version is "path.split("/")". This function handles more cases, like "{*,{a,b}*/*}". >>> _globpatsplit("*/**/x/{a,b/c}") ['*', '**', 'x', '{a,b/c}'] """ result = [] buf = "" parentheses = 0 for ch in pat: if ch == "{": parentheses += 1 elif ch == "}": parentheses -= 1 if parentheses == 0 and ch == "/": if buf: result.append(buf) buf = "" else: buf += ch if buf: result.append(buf) return result class _tree(dict): """A tree intended to answer "visitdir" questions with more efficient answers (ex. return "all" or False if possible). """ def __init__(self, *args, **kwargs): # If True, avoid entering subdirectories, and match everything recursively, # unconditionally. self.matchrecursive = False # If True, avoid entering subdirectories, and return "unsure" for # everything. This is set to True when complex re patterns (potentially # including "/") are used. self.unsurerecursive = False # Patterns for matching paths in this directory. self._kindpats = [] # Glob patterns used to match parent directories of another glob # pattern. self._globdirpats = [] super(_tree, self).__init__(*args, **kwargs) def insert(self, path, matchrecursive=True, globpats=None, repats=None): """Insert a directory path to this tree. If matchrecursive is True, mark the directory as unconditionally include files and subdirs recursively. If globpats or repats are specified, append them to the patterns being applied at this directory. The tricky part is those patterns can match "x/y/z" and visit("x"), visit("x/y") need to return True, while we still want visit("x/a") to return False. """ if path == "": self.matchrecursive |= matchrecursive if globpats: # Need to match parent directories too. for pat in globpats: components = _globpatsplit(pat) parentpat = "" for comp in components: if parentpat: parentpat += "/" parentpat += comp if "/" in comp: # Giving up - fallback to slow paths. self.unsurerecursive = True self._globdirpats.append(parentpat) if any("**" in p for p in globpats): # Giving up - "**" matches paths including "/" self.unsurerecursive = True self._kindpats += [("glob", pat, "") for pat in globpats] if repats: if not all(map(_testrefastpath, repats)): # Giving up - fallback to slow paths. self.unsurerecursive = True self._kindpats += [("re", pat, "") for pat in repats] return subdir, rest = self._split(path) self.setdefault(subdir, _tree()).insert(rest, matchrecursive, globpats, repats) def visitdir(self, path): """Similar to matcher.visitdir""" path = normalizerootdir(path, "visitdir") if self.matchrecursive: return "all" elif self.unsurerecursive: return True elif path == "": return True if self._kindpats and self._compiledpats(path): # XXX: This is incorrect. But re patterns are already used in # production. We should kill them! # Need to test "if every string starting with 'path' matches". # Obviously it's impossible to test *every* string with the # standard regex API, therefore pick a random strange path to test # it approximately. if self._compiledpats("%s/*/_/-/0/*" % path): return "all" else: return True if self._globdirpats and self._compileddirpats(path): return True subdir, rest = self._split(path) subtree = self.get(subdir) if subtree is None: return False else: return subtree.visitdir(rest) @util.propertycache def _compiledpats(self): pat, matchfunc = _buildregexmatch(self._kindpats, "") return matchfunc @util.propertycache def _compileddirpats(self): pat, matchfunc = _buildregexmatch( [("glob", p, "") for p in self._globdirpats], "$" ) return matchfunc def _split(self, path): if "/" in path: subdir, rest = path.split("/", 1) else: subdir, rest = path, "" if not subdir: raise error.ProgrammingError("path cannot be absolute") return subdir, rest def _remainingpats(pat, prefix): """list of patterns with prefix stripped >>> _remainingpats("a/b/c", "") ['a/b/c'] >>> _remainingpats("a/b/c", "a") ['b/c'] >>> _remainingpats("a/b/c", "a/b") ['c'] >>> _remainingpats("a/b/c", "a/b/c") [] >>> _remainingpats("", "") [] """ if prefix: if prefix == pat: return [] else: assert pat[len(prefix)] == "/" return [pat[len(prefix) + 1 :]] else: if pat: return [pat] else: return [] def _buildvisitdir(kindpats): """Try to build an efficient visitdir function Return a visitdir function if it's built. Otherwise return None if there are unsupported patterns. >>> _buildvisitdir([('include', 'foo', '')]) >>> _buildvisitdir([('relglob', 'foo', '')]) >>> t = _buildvisitdir([ ... ('glob', 'a/b', ''), ... ('glob', 'c/*.d', ''), ... ('glob', 'e/**/*.c', ''), ... ('re', '^f/(?!g)', ''), # no "$", only match prefix ... ('re', '^h/(i|j)$', ''), ... ('glob', 'i/a*/b*/c*', ''), ... ('glob', 'i/a5/b7/d', ''), ... ('glob', 'j/**.c', ''), ... ]) >>> t('a') True >>> t('a/b') 'all' >>> t('a/b/c') 'all' >>> t('c') True >>> t('c/d') False >>> t('c/rc.d') 'all' >>> t('c/rc.d/foo') 'all' >>> t('e') True >>> t('e/a') True >>> t('e/a/b.c') True >>> t('e/a/b.d') True >>> t('f') True >>> t('f/g') False >>> t('f/g2') False >>> t('f/g/a') False >>> t('f/h') 'all' >>> t('f/h/i') 'all' >>> t('h/i') True >>> t('h/i/k') False >>> t('h/k') False >>> t('i') True >>> t('i/a1') True >>> t('i/b2') False >>> t('i/a/b2/c3') 'all' >>> t('i/a/b2/d4') False >>> t('i/a5/b7/d') 'all' >>> t('j/x/y') True >>> t('z') False """ tree = _tree() for kind, pat, _source in kindpats: if kind == "glob": components = [] for p in pat.split("/"): if "[" in p or "{" in p or "*" in p or "?" in p: break components.append(p) prefix = "/".join(components) matchrecursive = prefix == pat tree.insert( prefix, matchrecursive=matchrecursive, globpats=_remainingpats(pat, prefix), ) elif kind == "re": # Still try to get a plain prefix from the regular expression so we # can still have fast paths. if pat.startswith("^"): # "re" already matches from the beginning, unlike "relre" pat = pat[1:] components = [] for p in pat.split("/"): if re.escape(p) != p: # contains special characters break components.append(p) prefix = "/".join(components) tree.insert( prefix, matchrecursive=False, repats=_remainingpats(pat, prefix) ) else: # Unsupported kind return None return tree.visitdir class basematcher(object): def __init__(self, root, cwd, badfn=None, relativeuipath=True): self._root = root self._cwd = cwd if badfn is not None: self.bad = badfn self._relativeuipath = relativeuipath def __repr__(self): return "<%s>" % self.__class__.__name__ def __call__(self, fn): return self.matchfn(fn) def __iter__(self): for f in self._files: yield f # Callbacks related to how the matcher is used by dirstate.walk. # Subscribers to these events must monkeypatch the matcher object. def bad(self, f, msg): """Callback from dirstate.walk for each explicit file that can't be found/accessed, with an error message.""" # If an traversedir is set, it will be called when a directory discovered # by recursive traversal is visited. traversedir = None def abs(self, f): """Convert a repo path back to path that is relative to the root of the matcher.""" return f def rel(self, f): """Convert repo path back to path that is relative to cwd of matcher.""" return util.pathto(self._root, self._cwd, f) def uipath(self, f): """Convert repo path to a display path. If patterns or -I/-X were used to create this matcher, the display path will be relative to cwd. Otherwise it is relative to the root of the repo.""" return (self._relativeuipath and self.rel(f)) or self.abs(f) @propertycache def _files(self): return [] def files(self): """Explicitly listed files or patterns or roots: if no patterns or .always(): empty list, if exact: list exact files, if not .anypats(): list all files and dirs, else: optimal roots""" return self._files @propertycache def _fileset(self): return set(self._files) def exact(self, f): """Returns True if f is in .files().""" return f in self._fileset def matchfn(self, f): return False def visitdir(self, dir): """Decides whether a directory should be visited based on whether it has potential matches in it or one of its subdirectories. This is based on the match's primary, included, and excluded patterns. Returns the string 'all' if the given directory and all subdirectories should be visited. Otherwise returns True or False indicating whether the given directory should be visited. """ return True def always(self): """Matcher will match everything and .files() will be empty -- optimization might be possible.""" return False def isexact(self): """Matcher will match exactly the list of files in .files() -- optimization might be possible.""" return False def prefix(self): """Matcher will match the paths in .files() recursively -- optimization might be possible.""" return False def anypats(self): """None of .always(), .isexact(), and .prefix() is true -- optimizations will be difficult.""" return not self.always() and not self.isexact() and not self.prefix() class alwaysmatcher(basematcher): """Matches everything.""" def __init__(self, root, cwd, badfn=None, relativeuipath=False): super(alwaysmatcher, self).__init__( root, cwd, badfn, relativeuipath=relativeuipath ) def always(self): return True def matchfn(self, f): return True def visitdir(self, dir): return "all" def __repr__(self): return "<alwaysmatcher>" class nevermatcher(basematcher): """Matches nothing.""" def __init__(self, root, cwd, badfn=None): super(nevermatcher, self).__init__(root, cwd, badfn) # It's a little weird to say that the nevermatcher is an exact matcher # or a prefix matcher, but it seems to make sense to let callers take # fast paths based on either. There will be no exact matches, nor any # prefixes (files() returns []), so fast paths iterating over them should # be efficient (and correct). def isexact(self): return True def prefix(self): return True def visitdir(self, dir): return False def __repr__(self): return "<nevermatcher>" class gitignorematcher(basematcher): """Match files specified by ".gitignore"s""" def __init__(self, root, cwd, badfn=None, gitignorepaths=None): super(gitignorematcher, self).__init__(root, cwd, badfn) gitignorepaths = gitignorepaths or [] self._matcher = pathmatcher.gitignorematcher(root, gitignorepaths) def matchfn(self, f): # XXX: is_dir is set to True here for performance. # It should be set to whether "f" is actually a directory or not. return self._matcher.match_relative(f, True) def explain(self, f): return self._matcher.explain(f, True) def visitdir(self, dir): dir = normalizerootdir(dir, "visitdir") matched = self._matcher.match_relative(dir, True) if matched: # Everything in the directory is selected (ignored) return "all" else: # Not sure return True def __repr__(self): return "<gitignorematcher>" class treematcher(basematcher): """Match glob patterns with negative pattern support. Have a smarter 'visitdir' implementation. """ def __init__(self, root, cwd, badfn=None, rules=[]): super(treematcher, self).__init__(root, cwd, badfn) rules = list(rules) self._matcher = pathmatcher.treematcher(rules) self._rules = rules def matchfn(self, f): return self._matcher.matches(f) def visitdir(self, dir): matched = self._matcher.match_recursive(dir) if matched is None: return True elif matched is True: return "all" else: assert matched is False return False def __repr__(self): return "<treematcher rules=%r>" % self._rules def normalizerootdir(dir, funcname): if dir == ".": util.nouideprecwarn( "match.%s() no longer accepts '.', use '' instead." % funcname, "20190805" ) return "" return dir def _kindpatstoglobs(kindpats, recursive=False): """Attempt to convert 'kindpats' to glob patterns that can be used in a treematcher. kindpats should be already normalized to be relative to repo root. If recursive is True, `glob:a*` will match both `a1/b` and `a1`, otherwise `glob:a*` will only match `a1` but not `a1/b`. Return None if there are unsupported patterns (ex. regular expressions). """ if not _usetreematcher: return None globs = [] for kindpat in kindpats: kind, pat = kindpat[0:2] if kind == "re": # Attempt to convert the re pat to globs reglobs = _convertretoglobs(pat) if reglobs is not None: globs += reglobs else: return None elif kind == "glob": # The treematcher (man gitignore) does not support csh-style # brackets (ex. "{a,b,c}"). Expand the brackets to patterns. for subpat in pathmatcher.expandcurlybrackets(pat): normalized = pathmatcher.normalizeglob(subpat) if recursive: normalized = _makeglobrecursive(normalized) globs.append(normalized) elif kind == "path": if pat == ".": # Special case. Comes from `util.normpath`. pat = "" else: pat = pathmatcher.plaintoglob(pat) pat = _makeglobrecursive(pat) globs.append(pat) else: return None return globs def _makeglobrecursive(pat): """Make a glob pattern recursive by appending "/**" to it""" if pat.endswith("/") or not pat: return pat + "**" else: return pat + "/**" # re:x/(?!y/) # meaning: include x, but not x/y. _repat1 = re.compile(r"^\^?([\w._/]+)/\(\?\!([\w._/]+)/?\)$") # re:x/(?:.*/)?y # meaning: glob:x/**/y _repat2 = re.compile(r"^\^?([\w._/]+)/\(\?:\.\*/\)\?([\w._]+)(?:\(\?\:\/\|\$\))?$") def _convertretoglobs(repat): """Attempt to convert a regular expression pattern to glob patterns. A single regular expression pattern might be converted into multiple glob patterns. Return None if conversion is unsupported. >>> _convertretoglobs("abc*") is None True >>> _convertretoglobs("xx/yy/(?!zz/kk)") ['xx/yy/**', '!xx/yy/zz/kk/**'] >>> _convertretoglobs("x/y/(?:.*/)?BUCK") ['x/y/**/BUCK'] """ m = _repat1.match(repat) if m: prefix, excluded = m.groups() return ["%s/**" % prefix, "!%s/%s/**" % (prefix, excluded)] m = _repat2.match(repat) if m: prefix, name = m.groups() return ["%s/**/%s" % (prefix, name)] return None class patternmatcher(basematcher): def __init__(self, root, cwd, kindpats, ctx=None, badfn=None): super(patternmatcher, self).__init__(root, cwd, badfn) # kindpats are already normalized to be relative to repo-root. # Can we use tree matcher? rules = _kindpatstoglobs(kindpats, recursive=False) fallback = True if rules is not None: try: matcher = treematcher(root, cwd, badfn=badfn, rules=rules) # Replace self to 'matcher'. self.__dict__ = matcher.__dict__ self.__class__ = matcher.__class__ fallback = False except ValueError: # for example, Regex("Compiled regex exceeds size limit of 10485760 bytes.") pass if fallback: self._prefix = _prefix(kindpats) self._pats, self.matchfn = _buildmatch(ctx, kindpats, "$", root) self._files = _explicitfiles(kindpats) @propertycache def _dirs(self): return set(util.dirs(self._fileset)) def visitdir(self, dir): dir = normalizerootdir(dir, "visitdir") if self._prefix and dir in self._fileset: return "all" if not self._prefix: return True return ( dir in self._fileset or dir in self._dirs or any(parentdir in self._fileset for parentdir in util.finddirs(dir)) ) def prefix(self): return self._prefix def __repr__(self): return "<patternmatcher patterns=%r>" % self._pats class includematcher(basematcher): def __init__(self, root, cwd, kindpats, ctx=None, badfn=None): super(includematcher, self).__init__(root, cwd, badfn) # Can we use tree matcher? rules = _kindpatstoglobs(kindpats, recursive=True) fallback = True if rules is not None: try: matcher = treematcher(root, cwd, badfn=badfn, rules=rules) # Replace self to 'matcher'. self.__dict__ = matcher.__dict__ self.__class__ = matcher.__class__ fallback = False except ValueError: # for example, Regex("Compiled regex exceeds size limit of 10485760 bytes.") pass if fallback: self._pats, self.matchfn = _buildmatch(ctx, kindpats, "(?:/|$)", root) # prefix is True if all patterns are recursive, so certain fast paths # can be enabled. Unfortunately, it's too easy to break it (ex. by # using "glob:*.c", "re:...", etc). self._prefix = _prefix(kindpats) roots, dirs = _rootsanddirs(kindpats) # roots are directories which are recursively included. # If self._prefix is True, then _roots can have a fast path for # visitdir to return "all", marking things included unconditionally. # If self._prefix is False, then that optimization is unsound because # "roots" might contain entries that is not recursive (ex. roots will # include "foo/bar" for pattern "glob:foo/bar/*.c"). self._roots = set(roots) # dirs are directories which are non-recursively included. # That is, files under that directory are included. But not # subdirectories. self._dirs = set(dirs) # Try to use a more efficient visitdir implementation visitdir = _buildvisitdir(kindpats) if visitdir: self.visitdir = visitdir def visitdir(self, dir): dir = normalizerootdir(dir, "visitdir") if self._prefix and dir in self._roots: return "all" return ( dir in self._roots or dir in self._dirs or any(parentdir in self._roots for parentdir in util.finddirs(dir)) ) def __repr__(self): return "<includematcher includes=%r>" % self._pats class exactmatcher(basematcher): """Matches the input files exactly. They are interpreted as paths, not patterns (so no kind-prefixes). """ def __init__(self, root, cwd, files, badfn=None): super(exactmatcher, self).__init__(root, cwd, badfn) if isinstance(files, list): self._files = files else: self._files = list(files) matchfn = basematcher.exact @propertycache def _dirs(self): return set(util.dirs(self._fileset)) def visitdir(self, dir): dir = normalizerootdir(dir, "visitdir") return dir in self._dirs def isexact(self): return True def __repr__(self): return "<exactmatcher files=%r>" % self._files class differencematcher(basematcher): """Composes two matchers by matching if the first matches and the second does not. Well, almost... If the user provides a pattern like "-X foo foo", Mercurial actually does match "foo" against that. That's because exact matches are treated specially. So, since this differencematcher is used for excludes, it needs to special-case exact matching. The second matcher's non-matching-attributes (root, cwd, bad, traversedir) are ignored. TODO: If we want to keep the behavior described above for exact matches, we should consider instead treating the above case something like this: union(exact(foo), difference(pattern(foo), include(foo))) """ def __init__(self, m1, m2): super(differencematcher, self).__init__(m1._root, m1._cwd) self._m1 = m1 self._m2 = m2 self.bad = m1.bad self.traversedir = m1.traversedir def matchfn(self, f): return self._m1(f) and (not self._m2(f) or self._m1.exact(f)) @propertycache def _files(self): if self.isexact(): return [f for f in self._m1.files() if self(f)] # If m1 is not an exact matcher, we can't easily figure out the set of # files, because its files() are not always files. For example, if # m1 is "path:dir" and m2 is "rootfileins:.", we don't # want to remove "dir" from the set even though it would match m2, # because the "dir" in m1 may not be a file. return self._m1.files() def visitdir(self, dir): dir = normalizerootdir(dir, "visitdir") if not self._m2.visitdir(dir): return self._m1.visitdir(dir) if self._m2.visitdir(dir) == "all": # There's a bug here: If m1 matches file 'dir/file' and m2 excludes # 'dir' (recursively), we should still visit 'dir' due to the # exception we have for exact matches. return False return bool(self._m1.visitdir(dir)) def isexact(self): return self._m1.isexact() def __repr__(self): return "<differencematcher m1=%r, m2=%r>" % (self._m1, self._m2) def intersectmatchers(m1, m2): """Composes two matchers by matching if both of them match. The second matcher's non-matching-attributes (root, cwd, bad, traversedir) are ignored. """ if m1 is None or m2 is None: return m1 or m2 if m1.always(): m = copy.copy(m2) # TODO: Consider encapsulating these things in a class so there's only # one thing to copy from m1. m.bad = m1.bad m.traversedir = m1.traversedir m.abs = m1.abs m.rel = m1.rel m._relativeuipath |= m1._relativeuipath return m if m2.always(): m = copy.copy(m1) m._relativeuipath |= m2._relativeuipath return m return intersectionmatcher(m1, m2) class intersectionmatcher(basematcher): def __init__(self, m1, m2): super(intersectionmatcher, self).__init__(m1._root, m1._cwd) self._m1 = m1 self._m2 = m2 self.bad = m1.bad self.traversedir = m1.traversedir @propertycache def _files(self): if self.isexact(): m1, m2 = self._m1, self._m2 if not m1.isexact(): m1, m2 = m2, m1 return [f for f in m1.files() if m2(f)] # It neither m1 nor m2 is an exact matcher, we can't easily intersect # the set of files, because their files() are not always files. For # example, if intersecting a matcher "-I glob:foo.txt" with matcher of # "path:dir2", we don't want to remove "dir2" from the set. return self._m1.files() + self._m2.files() def matchfn(self, f): return self._m1(f) and self._m2(f) def visitdir(self, dir): dir = normalizerootdir(dir, "visitdir") visit1 = self._m1.visitdir(dir) if visit1 == "all": return self._m2.visitdir(dir) # bool() because visit1=True + visit2='all' should not be 'all' return bool(visit1 and self._m2.visitdir(dir)) def always(self): return self._m1.always() and self._m2.always() def isexact(self): return self._m1.isexact() or self._m2.isexact() def __repr__(self): return "<intersectionmatcher m1=%r, m2=%r>" % (self._m1, self._m2) class subdirmatcher(basematcher): """Adapt a matcher to work on a subdirectory only. The paths are remapped to remove/insert the path as needed: >>> from . import pycompat >>> m1 = match(b'root', b'', [b'a.txt', b'sub/b.txt']) >>> m2 = subdirmatcher(b'sub', m1) >>> bool(m2(b'a.txt')) False >>> bool(m2(b'b.txt')) True >>> bool(m2.matchfn(b'a.txt')) False >>> bool(m2.matchfn(b'b.txt')) True >>> m2.files() ['b.txt'] >>> m2.exact(b'b.txt') True >>> util.pconvert(m2.rel(b'b.txt')) 'sub/b.txt' >>> def bad(f, msg): ... print(b"%s: %s" % (f, msg)) >>> m1.bad = bad >>> m2.bad(b'x.txt', b'No such file') sub/x.txt: No such file >>> m2.abs(b'c.txt') 'sub/c.txt' """ def __init__(self, path, matcher): super(subdirmatcher, self).__init__(matcher._root, matcher._cwd) self._path = path self._matcher = matcher self._always = matcher.always() self._files = [ f[len(path) + 1 :] for f in matcher._files if f.startswith(path + "/") ] # If the parent repo had a path to this subrepo and the matcher is # a prefix matcher, this submatcher always matches. if matcher.prefix(): self._always = any(f == path for f in matcher._files) def bad(self, f, msg): self._matcher.bad(self._path + "/" + f, msg) def abs(self, f): return self._matcher.abs(self._path + "/" + f) def rel(self, f): return self._matcher.rel(self._path + "/" + f) def uipath(self, f): return self._matcher.uipath(self._path + "/" + f) def matchfn(self, f): # Some information is lost in the superclass's constructor, so we # can not accurately create the matching function for the subdirectory # from the inputs. Instead, we override matchfn() and visitdir() to # call the original matcher with the subdirectory path prepended. return self._matcher.matchfn(self._path + "/" + f) def visitdir(self, dir): dir = normalizerootdir(dir, "visitdir") if dir == "": dir = self._path else: dir = self._path + "/" + dir return self._matcher.visitdir(dir) def always(self): return self._always def prefix(self): return self._matcher.prefix() and not self._always def __repr__(self): return "<subdirmatcher path=%r, matcher=%r>" % (self._path, self._matcher) class unionmatcher(basematcher): """A matcher that is the union of several matchers. The non-matching-attributes (root, cwd, bad, traversedir) are taken from the first matcher. """ def __init__(self, matchers): m1 = matchers[0] super(unionmatcher, self).__init__(m1._root, m1._cwd) self.traversedir = m1.traversedir self._matchers = matchers def matchfn(self, f): for match in self._matchers: if match(f): return True return False def visitdir(self, dir): r = False for m in self._matchers: v = m.visitdir(dir) if v == "all": return v r |= v return r def __repr__(self): return "<unionmatcher matchers=%r>" % self._matchers class xormatcher(basematcher): """A matcher that is the xor of two matchers i.e. match returns true if there's at least one false and one true. The non-matching-attributes (root, cwd, bad, traversedir) are taken from the first matcher. """ def __init__(self, m1, m2): super(xormatcher, self).__init__(m1._root, m1._cwd) self.traversedir = m1.traversedir self.m1 = m1 self.m2 = m2 def matchfn(self, f): return bool(self.m1(f)) ^ bool(self.m2(f)) def visitdir(self, dir): m1dir = self.m1.visitdir(dir) m2dir = self.m2.visitdir(dir) # if both matchers return "all" then we know for sure we don't need # to visit this directory. Same if all matchers return False. In all # other case we have to visit a directory. if m1dir == "all" and m2dir == "all": return False if not m1dir and not m2dir: return False return True def __repr__(self): return "<xormatcher matchers=%r>" % self._matchers class recursivematcher(basematcher): """Make matchers recursive. If "a/b/c" matches, match "a/b/c/**". It is intended to be used by hgignore only. Other matchers would want to fix "visitdir" and "matchfn" to take parent directories into consideration. """ def __init__(self, matcher): self._matcher = matcher def matchfn(self, f): match = self._matcher return match(f) or any(map(match, util.dirs((f,)))) def visitdir(self, dir): if self(dir): return "all" return self._matcher.visitdir(dir) def __repr__(self): return "<recursivematcher %r>" % self._matcher def patkind(pattern, default=None): """If pattern is 'kind:pat' with a known kind, return kind.""" return _patsplit(pattern, default)[0] def _patsplit(pattern, default): """Split a string into the optional pattern kind prefix and the actual pattern.""" if ":" in pattern: kind, pat = pattern.split(":", 1) if kind in allpatternkinds: return kind, pat return default, pattern def _globre(pat): r"""Convert an extended glob string to a regexp string. >>> from . import pycompat >>> def bprint(s): ... print(s) >>> bprint(_globre(br'?')) . >>> bprint(_globre(br'*')) [^/]* >>> bprint(_globre(br'**')) .* >>> bprint(_globre(br'**/a')) (?:.*/)?a >>> bprint(_globre(br'a/**/b')) a/(?:.*/)?b >>> bprint(_globre(br'[a*?!^][^b][!c]')) [a*?!^][\^b][^c] >>> bprint(_globre(br'{a,b}')) (?:a|b) >>> bprint(_globre(br'.\*\?')) \.\*\? """ i, n = 0, len(pat) res = "" group = 0 escape = util.re.escape def peek(): return i < n and pat[i : i + 1] while i < n: c = pat[i : i + 1] i += 1 if c not in "*?[{},\\": res += escape(c) elif c == "*": if peek() == "*": i += 1 if peek() == "/": i += 1 res += "(?:.*/)?" else: res += ".*" else: res += "[^/]*" elif c == "?": res += "." elif c == "[": j = i if j < n and pat[j : j + 1] in "!]": j += 1 while j < n and pat[j : j + 1] != "]": j += 1 if j >= n: res += "\\[" else: stuff = pat[i:j].replace("\\", "\\\\") i = j + 1 if stuff[0:1] == "!": stuff = "^" + stuff[1:] elif stuff[0:1] == "^": stuff = "\\" + stuff res = "%s[%s]" % (res, stuff) elif c == "{": group += 1 res += "(?:" elif c == "}" and group: res += ")" group -= 1 elif c == "," and group: res += "|" elif c == "\\": p = peek() if p: i += 1 res += escape(p) else: res += escape(c) else: res += escape(c) return res def _regex(kind, pat, globsuffix): """Convert a (normalized) pattern of any kind into a regular expression. globsuffix is appended to the regexp of globs.""" if not pat and kind in ("glob", "relpath"): return "" if kind == "re": return pat if kind in ("path", "relpath"): if pat == ".": return "" return util.re.escape(pat) + "(?:/|$)" if kind == "rootfilesin": if pat == ".": escaped = "" else: # Pattern is a directory name. escaped = util.re.escape(pat) + "/" # Anything after the pattern must be a non-directory. return escaped + "[^/]+$" if kind == "relglob": return "(?:|.*/)" + _globre(pat) + globsuffix if kind == "relre": if pat.startswith("^"): return pat return ".*" + pat return _globre(pat) + globsuffix def _buildmatch(ctx, kindpats, globsuffix, root): """Return regexp string and a matcher function for kindpats. globsuffix is appended to the regexp of globs.""" matchfuncs = [] subincludes, kindpats = _expandsubinclude(kindpats, root) if subincludes: submatchers = {} def matchsubinclude(f): for prefix, matcherargs in subincludes: if f.startswith(prefix): mf = submatchers.get(prefix) if mf is None: mf = match(*matcherargs) submatchers[prefix] = mf if mf(f[len(prefix) :]): return True return False matchfuncs.append(matchsubinclude) fset, kindpats = _expandsets(kindpats, ctx) if fset: matchfuncs.append(fset.__contains__) regex = "" if kindpats: regex, mf = _buildregexmatch(kindpats, globsuffix) matchfuncs.append(mf) if len(matchfuncs) == 1: return regex, matchfuncs[0] else: return regex, lambda f: any(mf(f) for mf in matchfuncs) def _buildregexmatch(kindpats, globsuffix): """Build a match function from a list of kinds and kindpats, return regexp string and a matcher function.""" try: regex = "(?:%s)" % "|".join( [_regex(k, p, globsuffix) for (k, p, s) in kindpats] ) if len(regex) > 20000: raise OverflowError return regex, _rematcher(regex) except OverflowError: # We're using a Python with a tiny regex engine and we # made it explode, so we'll divide the pattern list in two # until it works l = len(kindpats) if l < 2: raise regexa, a = _buildregexmatch(kindpats[: l // 2], globsuffix) regexb, b = _buildregexmatch(kindpats[l // 2 :], globsuffix) return regex, lambda s: a(s) or b(s) except re.error: for k, p, s in kindpats: try: _rematcher("(?:%s)" % _regex(k, p, globsuffix)) except re.error: if s: raise error.Abort(_("%s: invalid pattern (%s): %s") % (s, k, p)) else: raise error.Abort(_("invalid pattern (%s): %s") % (k, p)) raise error.Abort(_("invalid pattern")) def _patternrootsanddirs(kindpats): """Returns roots and directories corresponding to each pattern. This calculates the roots and directories exactly matching the patterns and returns a tuple of (roots, dirs) for each. It does not return other directories which may also need to be considered, like the parent directories. """ r = [] d = [] for kind, pat, source in kindpats: if kind == "glob": # find the non-glob prefix root = [] for p in pat.split("/"): if "[" in p or "{" in p or "*" in p or "?" in p: break root.append(p) r.append("/".join(root)) elif kind in ("relpath", "path"): if pat == ".": pat = "" r.append(pat) elif kind in ("rootfilesin",): if pat == ".": pat = "" d.append(pat) else: # relglob, re, relre r.append("") return r, d def _roots(kindpats): """Returns root directories to match recursively from the given patterns.""" roots, dirs = _patternrootsanddirs(kindpats) return roots def _rootsanddirs(kindpats): """Returns roots and exact directories from patterns. roots are directories to match recursively, whereas exact directories should be matched non-recursively. The returned (roots, dirs) tuple will also include directories that need to be implicitly considered as either, such as parent directories. >>> _rootsanddirs( ... [(b'glob', b'g/h/*', b''), (b'glob', b'g/h', b''), ... (b'glob', b'g*', b'')]) (['g/h', 'g/h', ''], ['', 'g']) >>> _rootsanddirs( ... [(b'rootfilesin', b'g/h', b''), (b'rootfilesin', b'', b'')]) ([], ['g/h', '', '', 'g']) >>> _rootsanddirs( ... [(b'relpath', b'r', b''), (b'path', b'p/p', b''), ... (b'path', b'', b'')]) (['r', 'p/p', ''], ['', 'p']) >>> _rootsanddirs( ... [(b'relglob', b'rg*', b''), (b're', b're/', b''), ... (b'relre', b'rr', b'')]) (['', '', ''], ['']) """ r, d = _patternrootsanddirs(kindpats) # Append the parents as non-recursive/exact directories, since they must be # scanned to get to either the roots or the other exact directories. d.extend(sorted(util.dirs(d))) d.extend(sorted(util.dirs(r))) return r, d def _explicitfiles(kindpats): """Returns the potential explicit filenames from the patterns. >>> _explicitfiles([(b'path', b'foo/bar', b'')]) ['foo/bar'] >>> _explicitfiles([(b'rootfilesin', b'foo/bar', b'')]) [] """ # Keep only the pattern kinds where one can specify filenames (vs only # directory names). filable = [kp for kp in kindpats if kp[0] not in ("rootfilesin",)] return _roots(filable) def _prefix(kindpats): """Whether all the patterns match a prefix (i.e. recursively)""" for kind, pat, source in kindpats: if kind not in ("path", "relpath"): return False return True _commentre = None def readpatternfile(filepath, warn, sourceinfo=False): """parse a pattern file, returning a list of patterns. These patterns should be given to compile() to be validated and converted into a match function. trailing white space is dropped. the escape character is backslash. comments start with #. empty lines are skipped. lines can be of the following formats: syntax: regexp # defaults following lines to non-rooted regexps syntax: glob # defaults following lines to non-rooted globs re:pattern # non-rooted regular expression glob:pattern # non-rooted glob pattern # pattern of the current default type if sourceinfo is set, returns a list of tuples: (pattern, lineno, originalline). This is useful to debug ignore patterns. """ syntaxes = { "re": "relre:", "regexp": "relre:", "glob": "relglob:", "include": "include", "subinclude": "subinclude", } syntax = "relre:" patterns = [] fp = open(filepath, "rb") for lineno, line in enumerate(util.iterfile(fp), start=1): if "#" in line: global _commentre if not _commentre: _commentre = util.re.compile(br"((?:^|[^\\])(?:\\\\)*)#.*") # remove comments prefixed by an even number of escapes m = _commentre.search(line) if m: line = line[: m.end(1)] # fixup properly escaped comments that survived the above line = line.replace("\\#", "#") line = line.rstrip() if not line: continue if line.startswith("syntax:"): s = line[7:].strip() try: syntax = syntaxes[s] except KeyError: if warn: warn(_("%s: ignoring invalid syntax '%s'\n") % (filepath, s)) continue linesyntax = syntax for s, rels in pycompat.iteritems(syntaxes): if line.startswith(rels): linesyntax = rels line = line[len(rels) :] break elif line.startswith(s + ":"): linesyntax = rels line = line[len(s) + 1 :] break if sourceinfo: patterns.append((linesyntax + line, lineno, line)) else: patterns.append(linesyntax + line) fp.close() return patterns _usetreematcher = True def init(ui): global _usetreematcher _usetreematcher = ui.configbool("experimental", "treematcher")
facebookexperimental/eden
eden/hg-server/edenscm/mercurial/match.py
Python
gpl-2.0
53,143
import numpy as np from OpenGL.GL import * from OpenGL.GLU import * import time import freenect import calibkinect import pykinectwindow as wxwindow # I probably need more help with these! try: TEXTURE_TARGET = GL_TEXTURE_RECTANGLE except: TEXTURE_TARGET = GL_TEXTURE_RECTANGLE_ARB if not 'win' in globals(): win = wxwindow.Window(size=(640, 480)) def refresh(): win.Refresh() print type(win) if not 'rotangles' in globals(): rotangles = [0,0] if not 'zoomdist' in globals(): zoomdist = 1 if not 'projpts' in globals(): projpts = (None, None) if not 'rgb' in globals(): rgb = None def create_texture(): global rgbtex rgbtex = glGenTextures(1) glBindTexture(TEXTURE_TARGET, rgbtex) glTexImage2D(TEXTURE_TARGET,0,GL_RGB,640,480,0,GL_RGB,GL_UNSIGNED_BYTE,None) if not '_mpos' in globals(): _mpos = None @win.eventx def EVT_LEFT_DOWN(event): global _mpos _mpos = event.Position @win.eventx def EVT_LEFT_UP(event): global _mpos _mpos = None @win.eventx def EVT_MOTION(event): global _mpos if event.LeftIsDown(): if _mpos: (x,y),(mx,my) = event.Position,_mpos rotangles[0] += y-my rotangles[1] += x-mx refresh() _mpos = event.Position @win.eventx def EVT_MOUSEWHEEL(event): global zoomdist dy = event.WheelRotation zoomdist *= np.power(0.95, -dy) refresh() clearcolor = [0,0,0,0] @win.event def on_draw(): if not 'rgbtex' in globals(): create_texture() xyz, uv = projpts if xyz is None: return if not rgb is None: rgb_ = (rgb.astype(np.float32) * 4 + 70).clip(0,255).astype(np.uint8) glBindTexture(TEXTURE_TARGET, rgbtex) glTexSubImage2D(TEXTURE_TARGET, 0, 0, 0, 640, 480, GL_RGB, GL_UNSIGNED_BYTE, rgb_); glClearColor(*clearcolor) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glEnable(GL_DEPTH_TEST) # flush that stack in case it's broken from earlier glPushMatrix() glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60, 4/3., 0.3, 200) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def mouse_rotate(xAngle, yAngle, zAngle): glRotatef(xAngle, 1.0, 0.0, 0.0); glRotatef(yAngle, 0.0, 1.0, 0.0); glRotatef(zAngle, 0.0, 0.0, 1.0); glScale(zoomdist,zoomdist,1) glTranslate(0, 0,-3.5) mouse_rotate(rotangles[0], rotangles[1], 0); glTranslate(0,0,1.5) #glTranslate(0, 0,-1) # Draw some axes if 0: glBegin(GL_LINES) glColor3f(1,0,0); glVertex3f(0,0,0); glVertex3f(1,0,0) glColor3f(0,1,0); glVertex3f(0,0,0); glVertex3f(0,1,0) glColor3f(0,0,1); glVertex3f(0,0,0); glVertex3f(0,0,1) glEnd() # We can either project the points ourselves, or embed it in the opengl matrix if 0: dec = 4 v,u = mgrid[:480,:640].astype(np.uint16) points = np.vstack((u[::dec,::dec].flatten(), v[::dec,::dec].flatten(), depth[::dec,::dec].flatten())).transpose() points = points[points[:,2]<2047,:] glMatrixMode(GL_TEXTURE) glLoadIdentity() glMultMatrixf(calibkinect.uv_matrix().transpose()) glMultMatrixf(calibkinect.xyz_matrix().transpose()) glTexCoordPointers(np.array(points)) glMatrixMode(GL_MODELVIEW) glPushMatrix() glMultMatrixf(calibkinect.xyz_matrix().transpose()) glVertexPointers(np.array(points)) else: glMatrixMode(GL_TEXTURE) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glPushMatrix() glVertexPointerf(xyz) glTexCoordPointerf(uv) # Draw the points glPointSize(2) glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_TEXTURE_COORD_ARRAY) glEnable(TEXTURE_TARGET) glColor3f(1,1,1) glDrawElementsui(GL_POINTS, np.array(range(xyz.shape[0]))) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_TEXTURE_COORD_ARRAY) glDisable(TEXTURE_TARGET) glPopMatrix() # if 0: inds = np.nonzero(xyz[:,2]>-0.55) glPointSize(10) glColor3f(0,1,1) glEnableClientState(GL_VERTEX_ARRAY) glDrawElementsui(GL_POINTS, np.array(inds)) glDisableClientState(GL_VERTEX_ARRAY) if 0: # Draw only the points in the near plane glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_BLEND) glColor(0.9,0.9,1.0,0.8) glPushMatrix() glTranslate(0,0,-0.55) glScale(0.6,0.6,1) glBegin(GL_QUADS) glVertex3f(-1,-1,0); glVertex3f( 1,-1,0); glVertex3f( 1, 1,0); glVertex3f(-1, 1,0); glEnd() glPopMatrix() glDisable(GL_BLEND) glPopMatrix() # A silly loop that shows you can busy the ipython thread while opengl runs def playcolors(): while 1: global clearcolor clearcolor = [np.random.random(),0,0,0] time.sleep(0.1) refresh() # Update the point cloud from the shell or from a background thread! def update(dt=0): global projpts, rgb, depth depth,_ = freenect.sync_get_depth() rgb,_ = freenect.sync_get_video() q = depth X,Y = np.meshgrid(range(640),range(480)) # YOU CAN CHANGE THIS AND RERUN THE PROGRAM! # Point cloud downsampling d = 4 projpts = calibkinect.depth2xyzuv(q[::d,::d],X[::d,::d],Y[::d,::d]) refresh() def update_join(): update_on() try: _thread.join() except: update_off() def update_on(): global _updating if not '_updating' in globals(): _updating = False if _updating: return _updating = True from threading import Thread global _thread def _run(): while _updating: update() _thread = Thread(target=_run) _thread.start() def update_off(): global _updating _updating = False # Get frames in a loop and display with opencv def loopcv(): import cv while 1: cv.ShowImage('hi',get_depth().astype(np.uint8)) cv.WaitKey(10) update() #update_on()
Dining-Engineers/left-luggage-detection
misc/demo/ipython/demo_pclview.py
Python
gpl-2.0
5,742
using GitHubWin8Phone.Resources; namespace GitHubWin8Phone { /// <summary> /// Provides access to string resources. /// </summary> public class LocalizedStrings { private static AppResources _localizedResources = new AppResources(); public AppResources LocalizedResources { get { return _localizedResources; } } } }
davidkuhner/GitHubWin8
GitHubWin8Phone/LocalizedStrings.cs
C#
gpl-2.0
360
showWord(["np. ","Avoka, politisyen. Madanm prezidan Jean Bertrand Aristide." ])
georgejhunt/HaitiDictionary.activity
data/words/TwouyoMildr~ed_Trouillot.js
JavaScript
gpl-2.0
80
package org.erc.qmm.mq; import java.util.EventListener; /** * The listener interface for receiving messageReaded events. * The class that is interested in processing a messageReaded * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addMessageReadedListener<code> method. When * the messageReaded event occurs, that object's appropriate * method is invoked. * * @see MessageReadedEvent */ public interface MessageReadedListener extends EventListener { /** * Message readed. * * @param message the message */ void messageReaded(JMQMessage message); }
dubasdey/MQQueueMonitor
src/main/java/org/erc/qmm/mq/MessageReadedListener.java
Java
gpl-2.0
659
import re p = re.compile(r'(\w+) (\w+)(?P<sign>.*)', re.DOTALL) print re.DOTALL print "p.pattern:", p.pattern print "p.flags:", p.flags print "p.groups:", p.groups print "p.groupindex:", p.groupindex
solvery/lang-features
python/use_lib/re.4.py
Python
gpl-2.0
204
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Exception.php 20978 2010-02-08 15:35:25Z matthew $ */ /** * @category Zend * @package Zend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Qlick_Sauth_SocialException extends Exception { /** * @var null|Exception */ private $_previous = null; /** * Construct the exception * * @param string $msg * @param int $code * @param Exception $previous * @return void */ public function __construct($msg = '', $code = 0, Exception $previous = null) { if (version_compare(PHP_VERSION, '5.3.0', '<')) { parent::__construct($msg, (int) $code); $this->_previous = $previous; } else { parent::__construct($msg, (int) $code, $previous); } } /** * Overloading * * For PHP < 5.3.0, provides access to the getPrevious() method. * * @param string $method * @param array $args * @return mixed */ public function __call($method, array $args) { if ('getprevious' == strtolower($method)) { return $this->_getPrevious(); } return null; } /** * String representation of the exception * * @return string */ public function __toString() { if (version_compare(PHP_VERSION, '5.3.0', '<')) { if (null !== ($e = $this->getPrevious())) { return $e->__toString() . "\n\nNext " . parent::__toString(); } } return parent::__toString(); } /** * Returns previous Exception * * @return Exception|null */ protected function _getPrevious() { return $this->_previous; } }
whiteboss/motora
library/Qlick/Sauth/SocialException.php
PHP
gpl-2.0
2,575
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.ext.flac; import android.os.Handler; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.audio.AudioProcessor; import com.google.android.exoplayer2.audio.AudioRendererEventListener; import com.google.android.exoplayer2.audio.SimpleDecoderAudioRenderer; import com.google.android.exoplayer2.drm.DrmSessionManager; import com.google.android.exoplayer2.drm.ExoMediaCrypto; import com.google.android.exoplayer2.util.MimeTypes; /** * Decodes and renders audio using the native Flac decoder. */ public class LibflacAudioRenderer extends SimpleDecoderAudioRenderer { private static final int NUM_BUFFERS = 16; public LibflacAudioRenderer() { this(null, null); } /** * @param eventHandler A handler to use when delivering events to {@code eventListener}. May be * null if delivery of events is not required. * @param eventListener A listener of events. May be null if delivery of events is not required. * @param audioProcessors Optional {@link AudioProcessor}s that will process audio before output. */ public LibflacAudioRenderer( Handler eventHandler, AudioRendererEventListener eventListener, AudioProcessor... audioProcessors) { super(eventHandler, eventListener, audioProcessors); } @Override protected int supportsFormatInternal(DrmSessionManager<ExoMediaCrypto> drmSessionManager, Format format) { if (!MimeTypes.AUDIO_FLAC.equalsIgnoreCase(format.sampleMimeType)) { return FORMAT_UNSUPPORTED_TYPE; } else if (!supportsOutput(format.channelCount, C.ENCODING_PCM_16BIT)) { return FORMAT_UNSUPPORTED_SUBTYPE; } else if (!supportsFormatDrm(drmSessionManager, format.drmInitData)) { return FORMAT_UNSUPPORTED_DRM; } else { return FORMAT_HANDLED; } } @Override protected FlacDecoder createDecoder(Format format, ExoMediaCrypto mediaCrypto) throws FlacDecoderException { return new FlacDecoder( NUM_BUFFERS, NUM_BUFFERS, format.maxInputSize, format.initializationData); } }
CzBiX/Telegram
TMessagesProj/src/main/java/com/google/android/exoplayer2/ext/flac/LibflacAudioRenderer.java
Java
gpl-2.0
2,743
<?php /** * @package Windwalker.Framework * @subpackage class * * @copyright Copyright (C) 2012 Asikart. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * @author Generated by AKHelper - http://asikart.com */ // no direct access defined('_JEXEC') or die; /** * AKGrid class to dynamically generate HTML tables * * @package Windwalker.Framework * @subpackage class * @since 11.3 */ class AKGrid { /** * Array of columns * @var array * @since 11.3 */ protected $columns = array(); /** * Current active row * @var int * @since 11.3 */ protected $activeRow = 0; /** * Rows of the table (including header and footer rows) * @var array * @since 11.3 */ protected $rows = array(); /** * Header and Footer row-IDs * @var array * @since 11.3 */ protected $specialRows = array('header' => array(), 'footer' => array()); /** * Associative array of attributes for the table-tag * @var array * @since 11.3 */ protected $options; /** * Constructor for a AKGrid object * * @param array $options Associative array of attributes for the table-tag * * @since 11.3 */ public function __construct($options = array()) { $this->setTableOptions($options, true); } /** * Magic function to render this object as a table. * * @return string * * @since 11.3 */ public function __toString() { return $this->toString(); } /** * Method to set the attributes for a table-tag * * @param array $options Associative array of attributes for the table-tag * @param bool $replace Replace possibly existing attributes * * @return AKGrid This object for chaining * * @since 11.3 */ public function setTableOptions($options = array(), $replace = false) { if ($replace) { $this->options = $options; } else { $this->options = array_merge($this->options, $options); } return $this; } /** * Get the Attributes of the current table * * @return array Associative array of attributes * * @since 11.3 */ public function getTableOptions() { return $this->options; } /** * Add new column name to process * * @param string $name Internal column name * * @return AKGrid This object for chaining * * @since 11.3 */ public function addColumn($name) { $this->columns[] = $name; return $this; } /** * Returns the list of internal columns * * @return array List of internal columns * * @since 11.3 */ public function getColumns() { return $this->columns; } /** * Delete column by name * * @param string $name Name of the column to be deleted * * @return AKGrid This object for chaining * * @since 11.3 */ public function deleteColumn($name) { $index = array_search($name, $this->columns); if ($index !== false) { unset($this->columns[$index]); $this->columns = array_values($this->columns); } return $this; } /** * Method to set a whole range of columns at once * This can be used to re-order the columns, too * * @param array $columns List of internal column names * * @return AKGrid This object for chaining * * @since 11.3 */ public function setColumns($columns) { $this->columns = array_values($columns); return $this; } /** * Adds a row to the table and sets the currently * active row to the new row * * @param array $options Associative array of attributes for the row * @param int $special 1 for a new row in the header, 2 for a new row in the footer * * @return AKGrid This object for chaining * * @since 11.3 */ public function addRow($options = array(), $special = false) { $this->rows[]['_row'] = $options; $this->activeRow = count($this->rows) - 1; if ($special) { if ($special === 1) { $this->specialRows['header'][] = $this->activeRow; } else { $this->specialRows['footer'][] = $this->activeRow; } } return $this; } /** * Method to get the attributes of the currently active row * * @return array Associative array of attributes * * @since 11.3 */ public function getRowOptions() { return $this->rows[$this->activeRow]['_row']; } /** * Method to set the attributes of the currently active row * * @param array $options Associative array of attributes * * @return AKGrid This object for chaining * * @since 11.3 */ public function setRowOptions($options) { $this->rows[$this->activeRow]['_row'] = $options; return $this; } /** * Get the currently active row ID * * @return int ID of the currently active row * * @since 11.3 */ public function getActiveRow() { return $this->activeRow; } /** * Set the currently active row * * @param int $id ID of the row to be set to current * * @return AKGrid This object for chaining * * @since 11.3 */ public function setActiveRow($id) { $this->activeRow = (int) $id; return $this; } /** * Set cell content for a specific column for the * currently active row * * @param string $name Name of the column * @param string $content Content for the cell * @param array $option Associative array of attributes for the td-element * @param bool $replace If false, the content is appended to the current content of the cell * * @return AKGrid This object for chaining * * @since 11.3 */ public function setRowCell($name, $content, $option = array(), $replace = true) { if ($replace || !isset($this->rows[$this->activeRow][$name])) { $cell = new stdClass; $cell->options = $option; $cell->content = $content; $this->rows[$this->activeRow][$name] = $cell; } else { $this->rows[$this->activeRow][$name]->content .= $content; $this->rows[$this->activeRow][$name]->options = $option; } return $this; } /** * Get all data for a row * * @param int $id ID of the row to return * * @return array Array of columns of a table row * * @since 11.3 */ public function getRow($id = false) { if ($id === false) { $id = $this->activeRow; } if (isset($this->rows[(int) $id])) { return $this->rows[(int) $id]; } else { return false; } } /** * Get the IDs of all rows in the table * * @param int $special false for the standard rows, 1 for the header rows, 2 for the footer rows * * @return array Array of IDs * * @since 11.3 */ public function getRows($special = false) { if ($special) { if ($special === 1) { return $this->specialRows['header']; } else { return $this->specialRows['footer']; } } return array_diff(array_keys($this->rows), array_merge($this->specialRows['header'], $this->specialRows['footer'])); } /** * Delete a row from the object * * @param int $id ID of the row to be deleted * * @return AKGrid This object for chaining * * @since 11.3 */ public function deleteRow($id) { unset($this->rows[$id]); if (in_array($id, $this->specialRows['header'])) { unset($this->specialRows['header'][array_search($id, $this->specialRows['header'])]); } if (in_array($id, $this->specialRows['footer'])) { unset($this->specialRows['footer'][array_search($id, $this->specialRows['footer'])]); } if ($this->activeRow == $id) { end($this->rows); $this->activeRow = key($this->rows); } return $this; } /** * Render the HTML table * * @return string The rendered HTML table * * @since 11.3 */ public function toString() { $output = array(); $output[] = '<table' . $this->renderAttributes($this->getTableOptions()) . '>'; if (count($this->specialRows['header'])) { $output[] = $this->renderArea($this->specialRows['header'], 'thead', 'th'); } if (count($this->specialRows['footer'])) { $output[] = $this->renderArea($this->specialRows['footer'], 'tfoot'); } $ids = array_diff(array_keys($this->rows), array_merge($this->specialRows['header'], $this->specialRows['footer'])); if (count($ids)) { $output[] = $this->renderArea($ids); } $output[] = '</table>'; return implode('', $output); } /** * Render an area of the table * * @param array $ids IDs of the rows to render * @param string $area Name of the area to render. Valid: tbody, tfoot, thead * @param string $cell Name of the cell to render. Valid: td, th * * @return string The rendered table area * * @since 11.3 */ protected function renderArea($ids, $area = 'tbody', $cell = 'td') { $output = array(); $output[] = '<' . $area . ">\n"; foreach ($ids as $id) { $output[] = "\t<tr" . $this->renderAttributes($this->rows[$id]['_row']) . ">\n"; foreach ($this->getColumns() as $name) { if (isset($this->rows[$id][$name])) { $column = $this->rows[$id][$name]; $output[] = "\t\t<" . $cell . $this->renderAttributes($column->options) . '>' . $column->content . '</' . $cell . ">\n"; } } $output[] = "\t</tr>\n"; } $output[] = '</' . $area . '>'; return implode('', $output); } /** * Renders an HTML attribute from an associative array * * @param array $attributes Associative array of attributes * * @return string The HTML attribute string * * @since 11.3 */ protected function renderAttributes($attributes) { if (count((array) $attributes) == 0) { return ''; } $return = array(); foreach ($attributes as $key => $option) { $return[] = $key . '="' . $option . '"'; } return ' ' . implode(' ', $return); } }
ForAEdesWeb/AEW32
administrator/components/com_quickcontent/windwalker/html/grid.php
PHP
gpl-2.0
9,645
<?php class Metabox { public static $boxes = array(); /** * @static * @param $type * @param $options * @return Metabox */ public static function factory($type, $options = null) { $parts = explode('_', $type); array_walk( $parts, function(&$item){ $item = ucfirst($item); } ); $class = 'Metabox_'.implode('_', $parts); if(class_exists($class)) { if( ! isset($options['type']) ) { $options['type'] = $type; } return new $class($options); } return false; } /** * @static * @param $key * @return Metabox */ public static function get($key) { return (isset(self::$boxes[$key]) ? self::$boxes[$key] : null); } public static function attr($box, $attr) { return (isset(self::$boxes[$box]->$attr) ? self::$boxes[$box]->$attr : null); } }
vladcazacu/Wordpress-HMVC
wp-content/themes/hmvc/core/classes/metabox.php
PHP
gpl-2.0
805
<?php /** * General API for generating and formatting diffs - the differences between * two sequences of strings. * * The original PHP version of this code was written by Geoffrey T. Dairiki * <dairiki@dairiki.org>, and is used/adapted with his permission. * * Copyright 2004 Geoffrey T. Dairiki <dairiki@dairiki.org> * Copyright 2004-2010 The Horde Project (http://www.horde.org/) * * See the enclosed file COPYING for license information (LGPL). If you did * not receive this file, see http://opensource.org/licenses/lgpl-license.php. * * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> */ class Text_Diff { /** * Array of changes. * * @var array */ var $_edits; /** * Computes diffs between sequences of strings. * * @param string $engine Name of the diffing engine to use. 'auto' * will automatically select the best. * @param array $params Parameters to pass to the diffing engine. * Normally an array of two arrays, each * containing the lines from a file. */ function Text_Diff($engine, $params) { // Backward compatibility workaround. if (!is_string($engine)) { $params = array($engine, $params); $engine = 'auto'; } if ($engine == 'auto') { $engine = extension_loaded('xdiff') ? 'xdiff' : 'native'; } else { $engine = basename($engine); } // WP #7391 require_once dirname(__FILE__) . '/Diff/Engine/' . $engine . '.php'; $class = 'Text_Diff_Engine_' . $engine; $diff_engine = new $class(); $this->_edits = call_user_func_array(array($diff_engine, 'diff'), $params); } /** * Returns the array of differences. */ function getDiff() { return $this->_edits; } /** * returns the number of new (added) lines in a given diff. * * @since Text_Diff 1.1.0 * * @return integer The number of new lines */ function countAddedLines() { $count = 0; foreach ($this->_edits as $edit) { if (is_a($edit, 'Text_Diff_Op_add') || is_a($edit, 'Text_Diff_Op_change')) { $count += $edit->nfinal(); } } return $count; } /** * Returns the number of deleted (removed) lines in a given diff. * * @since Text_Diff 1.1.0 * * @return integer The number of deleted lines */ function countDeletedLines() { $count = 0; foreach ($this->_edits as $edit) { if (is_a($edit, 'Text_Diff_Op_delete') || is_a($edit, 'Text_Diff_Op_change')) { $count += $edit->norig(); } } return $count; } /** * Computes a reversed diff. * * Example: * <code> * $diff = new Text_Diff($lines1, $lines2); * $rev = $diff->reverse(); * </code> * * @return Text_Diff A Diff object representing the inverse of the * original diff. Note that we purposely don't return a * reference here, since this essentially is a clone() * method. */ function reverse() { if (version_compare(zend_version(), '2', '>')) { $rev = clone($this); } else { $rev = $this; } $rev->_edits = array(); foreach ($this->_edits as $edit) { $rev->_edits[] = $edit->reverse(); } return $rev; } /** * Checks for an empty diff. * * @return boolean True if two sequences were identical. */ function isEmpty() { foreach ($this->_edits as $edit) { if (!is_a($edit, 'Text_Diff_Op_copy')) { return false; } } return true; } /** * Computes the length of the Longest Common Subsequence (LCS). * * This is mostly for diagnostic purposes. * * @return integer The length of the LCS. */ function lcs() { $lcs = 0; foreach ($this->_edits as $edit) { if (is_a($edit, 'Text_Diff_Op_copy')) { $lcs += count($edit->orig); } } return $lcs; } /** * Gets the original set of lines. * * This reconstructs the $from_lines parameter passed to the constructor. * * @return array The original sequence of strings. */ function getOriginal() { $lines = array(); foreach ($this->_edits as $edit) { if ($edit->orig) { array_splice($lines, count($lines), 0, $edit->orig); } } return $lines; } /** * Gets the final set of lines. * * This reconstructs the $to_lines parameter passed to the constructor. * * @return array The sequence of strings. */ function getFinal() { $lines = array(); foreach ($this->_edits as $edit) { if ($edit->final) { array_splice($lines, count($lines), 0, $edit->final); } } return $lines; } /** * Removes trailing newlines from a line of text. This is meant to be used * with array_walk(). * * @param string $line The line to trim. * @param integer $key The index of the line in the array. Not used. */ static function trimNewlines(&$line, $key) { $line = str_replace(array("\n", "\r"), '', $line); } /** * Determines the location of the system temporary directory. * * @static * * @access protected * * @return string A directory name which can be used for temp files. * Returns false if one could not be found. */ function _getTempDir() { $tmp_locations = array('/tmp', '/var/tmp', 'c:\WUTemp', 'c:\temp', 'c:\windows\temp', 'c:\winnt\temp'); /* Try PHP's upload_tmp_dir directive. */ $tmp = ini_get('upload_tmp_dir'); /* Otherwise, try to determine the TMPDIR environment variable. */ if (!strlen($tmp)) { $tmp = getenv('TMPDIR'); } /* If we still cannot determine a value, then cycle through a list of * preset possibilities. */ while (!strlen($tmp) && count($tmp_locations)) { $tmp_check = array_shift($tmp_locations); if (@is_dir($tmp_check)) { $tmp = $tmp_check; } } /* If it is still empty, we have failed, so return false; otherwise * return the directory determined. */ return strlen($tmp) ? $tmp : false; } /** * Checks a diff for validity. * * This is here only for debugging purposes. */ function _check($from_lines, $to_lines) { if (serialize($from_lines) != serialize($this->getOriginal())) { trigger_error("Reconstructed original doesn't match", E_USER_ERROR); } if (serialize($to_lines) != serialize($this->getFinal())) { trigger_error("Reconstructed final doesn't match", E_USER_ERROR); } $rev = $this->reverse(); if (serialize($to_lines) != serialize($rev->getOriginal())) { trigger_error("Reversed original doesn't match", E_USER_ERROR); } if (serialize($from_lines) != serialize($rev->getFinal())) { trigger_error("Reversed final doesn't match", E_USER_ERROR); } $prevtype = null; foreach ($this->_edits as $edit) { if ($prevtype == get_class($edit)) { trigger_error("Edit sequence is non-optimal", E_USER_ERROR); } $prevtype = get_class($edit); } return true; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> */ class Text_MappedDiff extends Text_Diff { /** * Computes a diff between sequences of strings. * * This can be used to compute things like case-insensitve diffs, or diffs * which ignore changes in white-space. * * @param array $from_lines An array of strings. * @param array $to_lines An array of strings. * @param array $mapped_from_lines This array should have the same size * number of elements as $from_lines. The * elements in $mapped_from_lines and * $mapped_to_lines are what is actually * compared when computing the diff. * @param array $mapped_to_lines This array should have the same number * of elements as $to_lines. */ function Text_MappedDiff($from_lines, $to_lines, $mapped_from_lines, $mapped_to_lines) { assert(count($from_lines) == count($mapped_from_lines)); assert(count($to_lines) == count($mapped_to_lines)); parent::Text_Diff($mapped_from_lines, $mapped_to_lines); $xi = $yi = 0; for ($i = 0; $i < count($this->_edits); $i++) { $orig = &$this->_edits[$i]->orig; if (is_array($orig)) { $orig = array_slice($from_lines, $xi, count($orig)); $xi += count($orig); } $final = &$this->_edits[$i]->final; if (is_array($final)) { $final = array_slice($to_lines, $yi, count($final)); $yi += count($final); } } } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op { var $orig; var $final; function &reverse() { trigger_error('Abstract method', E_USER_ERROR); } function norig() { return $this->orig ? count($this->orig) : 0; } function nfinal() { return $this->final ? count($this->final) : 0; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op_copy extends Text_Diff_Op { function Text_Diff_Op_copy($orig, $final = false) { if (!is_array($final)) { $final = $orig; } $this->orig = $orig; $this->final = $final; } function &reverse() { $reverse = new Text_Diff_Op_copy($this->final, $this->orig); return $reverse; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op_delete extends Text_Diff_Op { function Text_Diff_Op_delete($lines) { $this->orig = $lines; $this->final = false; } function &reverse() { $reverse = new Text_Diff_Op_add($this->orig); return $reverse; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op_add extends Text_Diff_Op { function Text_Diff_Op_add($lines) { $this->final = $lines; $this->orig = false; } function &reverse() { $reverse = new Text_Diff_Op_delete($this->final); return $reverse; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op_change extends Text_Diff_Op { function Text_Diff_Op_change($orig, $final) { $this->orig = $orig; $this->final = $final; } function &reverse() { $reverse = new Text_Diff_Op_change($this->final, $this->orig); return $reverse; } }
ajspencer/NCSSM-SG-WordPress
wp-includes/Text/Diff.php
PHP
gpl-2.0
11,727
/* Stuart Bowman 2016 This class contains the graph nodes themselves, as well as helper functions for use by the generation class to better facilitate evaluation and breeding. It also contains the class definition for the nodes themselves, as well as the A* search implementation used by the genetic algorithm to check if a path can be traced between two given points on the maze. */ using UnityEngine; using System.Collections; using System.Collections.Generic; public class Graph { public Dictionary<int, Node> nodes; float AStarPathSuccess = 0.0f;//fraction of samples that could be maped to nodes and completed with AStar float AStarAvgPathLength = 0.0f;//average path length of successful paths public float getAStarPathSuccess() { return AStarPathSuccess; } public float getAStarAvgPathLength() { return AStarAvgPathLength; } public float getCompositeScore() { return AStarPathSuccess; }//a weighted, composite score of all evaluated attributes of this graph public int newNodeStartingID = 0; public Graph(int startingID) { newNodeStartingID = startingID; nodes = new Dictionary<int, Node>(); } public Graph(List<GameObject> floors, List<GameObject> walls, int initNumNodes = 20) { nodes = new Dictionary<int, Node>(); for (int i = 0; i < initNumNodes; i++) { int rndTile = Random.Range(0, floors.Count); //get the 2d bounding area for any floor tile MeshCollider mc = floors[rndTile].GetComponent<MeshCollider>(); Vector2 xyWorldSpaceBoundsBottomLeft = new Vector2(mc.bounds.center.x - mc.bounds.size.x/2, mc.bounds.center.z - mc.bounds.size.z/2); Vector2 rndPosInTile = new Vector2(Random.Range(0, mc.bounds.size.x), Random.Range(0, mc.bounds.size.z)); Vector2 rndWorldPos = xyWorldSpaceBoundsBottomLeft + rndPosInTile; Node n = addNewNode(rndWorldPos); } connectAllNodes(); } public Graph(Graph g)//deep copy constructor { nodes = new Dictionary<int, Node>(); //deep copy foreach (KeyValuePair<int, Node> entry in g.nodes) { //deep copy the node with the best score bool inherited = entry.Value.isNodeInheritedFromParent(); Node currentNode = new Node(new Vector2(entry.Value.pos.x, entry.Value.pos.y), entry.Value.ID, inherited); //don't bother copying the A* and heuristic stuff for each node, it's just going to be re-crunched later nodes.Add(currentNode.ID, currentNode); } AStarPathSuccess = g.getAStarPathSuccess(); AStarAvgPathLength = g.getAStarAvgPathLength(); } public static float normDistRand(float mean, float stdDev) { float u1 = Random.Range(0, 1.0f); float u2 = Random.Range(0, 1.0f); float randStdNormal = Mathf.Sqrt(-2.0f * Mathf.Log(u1) * Mathf.Sin(2.0f * 3.14159f * u2)); return mean + stdDev * randStdNormal; } public string getSummary() { string result = ""; result += nodes.Count + "\tNodes\t(" + getNumOfNewlyAddedNodes() + " new)\n"; result += getAStarPathSuccess() * 100 + "%\tA* Satisfaction\n"; result += getAStarAvgPathLength() + "\tUnit avg. A* Path\n"; return result; } int getNumOfNewlyAddedNodes() { int result = 0; foreach (KeyValuePair<int, Node> entry in nodes) { if (entry.Value.isNodeInheritedFromParent() == false) result++; } return result; } public void connectAllNodes() { foreach (KeyValuePair<int,Node> entry in nodes) { foreach (KeyValuePair<int, Node> entry2 in nodes) { if (entry.Value != entry2.Value) { if (!Physics.Linecast(new Vector3(entry.Value.pos.x, 2, entry.Value.pos.y), new Vector3(entry2.Value.pos.x, 2, entry2.Value.pos.y))) { entry.Value.connectTo(entry2.Value); } } } } } public int getFirstUnusedID() { for (int i = 0; i < nodes.Count; i++) { if (!nodes.ContainsKey(i)) return i; } return nodes.Count; } public int getMaxID() { int temp = 0; foreach (KeyValuePair<int, Node> entry in nodes) { if (entry.Value.ID > temp) temp = entry.Value.ID; } if (temp < newNodeStartingID) return newNodeStartingID; return temp; } public class Node { public int ID; public Vector2 pos; public List<Node> connectedNodes; bool inheritedFromParent; public Node Ancestor;//used in A* public float g, h;//public values for temporary use during searching and heuristic analysis public float f { get {return g + h; } private set { } } public bool isNodeInheritedFromParent() { return inheritedFromParent; } public Node(Vector2 position, int id, bool inherited) { connectedNodes = new List<Node>(); pos = position; ID = id; inheritedFromParent = inherited; } public void connectTo(Node node) { if (!connectedNodes.Contains(node)) { connectedNodes.Add(node); if (!node.connectedNodes.Contains(this)) { node.connectedNodes.Add(this); } } } public void disconnectFrom(Node n) { for (int i = 0; i < connectedNodes.Count; i++) { if (connectedNodes[i] == n) n.connectedNodes.Remove(this); } connectedNodes.Remove(n); } } public Node addNewNode(Vector2 pos) { int newID = this.getMaxID()+1;//get the new id from the maxID property Node tempNode = new Node(pos, newID, false); nodes.Add(newID, tempNode); return tempNode; } public Node addNewNode(Vector2 pos, int ID) { Node tempNode = new Node(pos, ID, false); nodes.Add(ID, tempNode); return tempNode; } public Node addNewNode(Vector2 pos, int ID, bool inherited) { Node tempNode = new Node(pos, ID, inherited); nodes.Add(ID, tempNode); return tempNode; } public void removeNode(int ID) { Node nodeToRemove = nodes[ID]; foreach (Node n in nodeToRemove.connectedNodes) { //remove symmetrical connections n.connectedNodes.Remove(nodeToRemove); } nodes.Remove(ID);//delete the actual node } public void printAdjMatrix() { foreach (KeyValuePair<int, Node> entry in nodes) { string connNodes = "Node: " + entry.Value.ID + "\nConn: "; foreach (Node n2 in entry.Value.connectedNodes) { connNodes += n2.ID + ", "; } Debug.Log(connNodes); } } public List<Node> AStar(int startingNodeKey, int endingNodeKey) { List<Node> ClosedSet = new List<Node>(); List<Node> OpenSet = new List<Node>(); foreach(KeyValuePair<int, Node> entry in nodes) { entry.Value.g = 99999;//set all g values to infinity entry.Value.Ancestor = null;//set all node ancestors to null } nodes[startingNodeKey].g = 0; nodes[startingNodeKey].h = Vector2.Distance(nodes[startingNodeKey].pos, nodes[endingNodeKey].pos); OpenSet.Add(nodes[startingNodeKey]); while (OpenSet.Count > 0 ) { float minscore = 99999; int minIndex = 0; for(int i = 0;i<OpenSet.Count;i++) { if (OpenSet[i].f < minscore) { minscore = OpenSet[i].f; minIndex = i; } } //deep copy the node with the best score Node currentNode = new Node(new Vector2(OpenSet[minIndex].pos.x, OpenSet[minIndex].pos.y), OpenSet[minIndex].ID, false); currentNode.g = OpenSet[minIndex].g; currentNode.h = OpenSet[minIndex].h; currentNode.Ancestor = OpenSet[minIndex].Ancestor; if (currentNode.ID == endingNodeKey) { //build the path list List<Node> fullPath = new List<Node>(); Node temp = currentNode; while (temp != null) { fullPath.Add(temp); temp = temp.Ancestor; } return fullPath; } //remove this node from the open set OpenSet.RemoveAt(minIndex); ClosedSet.Add(currentNode); //go through the list of nodes that are connected to the current node foreach(Node n in nodes[currentNode.ID].connectedNodes) { bool isInClosedSet = false; //check if it's already in the closed set for (int i = 0; i < ClosedSet.Count; i++) { if (ClosedSet[i].ID == n.ID) { isInClosedSet = true; break; } } if (isInClosedSet) continue; float tenativeG = currentNode.g + Vector2.Distance(n.pos, currentNode.pos); bool isInOpenSet = false; for (int i = 0; i < OpenSet.Count; i++) { if (OpenSet[i].ID == n.ID) isInOpenSet = true; } if (!isInOpenSet) OpenSet.Add(n); else if (tenativeG >= n.g) continue; n.Ancestor = currentNode; n.g = tenativeG; n.h = Vector2.Distance(n.pos, nodes[endingNodeKey].pos); } } //didn't find a path return new List<Node>(); } public void generateAStarSatisfaction(List<Vector2> startingPoint, List<Vector2> endingPoint) { int successfulPaths = 0; float avgPathLen = 0.0f; for (int i = 0; i < startingPoint.Count; i++) { Node startingNode = closestNodeToPoint(startingPoint[i]); if (startingNode == null) continue;//skip to next iteration if no starting node can be found Node endingNode = closestNodeToPoint(endingPoint[i]); if (endingNode == null) continue;//skip to next iteration if no ending node can be found List<Node> path = AStar(startingNode.ID, endingNode.ID); if (path.Count != 0)//if the path was successful { successfulPaths++; avgPathLen += path[path.Count - 1].g + Vector2.Distance(startingPoint[i], startingNode.pos) + Vector2.Distance(endingPoint[i], endingNode.pos); } } avgPathLen /= successfulPaths; //store results AStarAvgPathLength = avgPathLen; AStarPathSuccess = successfulPaths / (float)startingPoint.Count; } Node closestNodeToPoint(Vector2 point) { //find closest node to the given starting point List<Node> lineOfSightNodes = new List<Node>(); foreach (KeyValuePair<int, Node> entry in nodes) { if (!Physics.Linecast(new Vector3(point.x, 2, point.y), new Vector3(entry.Value.pos.x, 2, entry.Value.pos.y))) { lineOfSightNodes.Add(entry.Value); } } float minDist = 999999; int minIndex = 0; if (lineOfSightNodes.Count == 0) return null;//no nodes are line of sight to this point for (int j = 0; j < lineOfSightNodes.Count; j++) { float dist = Vector2.Distance(point, lineOfSightNodes[j].pos); if (dist < minDist) { minDist = dist; minIndex = j; } } return lineOfSightNodes[minIndex]; } }
stuartsoft/gngindiestudy
Assets/Scripts/Graph.cs
C#
gpl-2.0
12,517
<?php function migrate_blog() { /* * $tabRub[0] = "Annonces"; $tabRub[1] = "Partenariat"; $tabRub[2] = "Vie d'Anciela"; $tabRub[3] = "Autres"; * */ $categories = array('annonces','partenariat','anciela','autres'); $categoryNames = array('annonces'=>"Annonces",'partenariat'=>'Partenariats','anciela'=>"Vie d'anciela",'autres'=>'Autres'); foreach($categoryNames as $categorySlug => $categoryName) { wp_insert_term($categoryName, 'category', array('slug'=>$categorySlug)); } $db = mysqli_connect("localhost","root","","db161162332") or die("Error " . mysqli_error($link)); // Setup the author, slug, and title for the post $author_id = 1; $args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => null, // any parent ); $attachments = get_posts($args); $db->query('set names utf8'); $db->query("SET character_set_connection = 'UTF8'"); $db->query("SET character_set_client = 'UTF8'"); $db->query("SET character_set_results = 'UTF8'"); $result = $db->query("select * from `anc_info_blog`"); while($row = $result->fetch_array()) { $categoryIntId = ($row["rub_blog"]-1); $category = $categories[$categoryIntId]; $category = get_category_by_slug($category); if ($category) { $category = $category->term_id; } $title = stripslashes($row["titre_blog"]); $date = $row["date_pub_deb_blog"]; $content = stripslashes($row['texte_blog']); $img = $row['image_blog']; $align = $row['image_pos_blog'] == 0 ? 'center' : 'right'; if ($img) { foreach ($attachments as $post) { setup_postdata($post); the_title(); $mediaTitle = $post->post_title; $img = explode('.', $img)[0]; if ($mediaTitle == $img) { $id = $post->ID; $content = '[image id="'.$id.'" align="'.$align.'"]<br/>'.$content; } /*$dataToSave = array( 'ID' => $post->ID, 'post_title' => ); wp_update_post($dataToSave);*/ } } if (null == get_page_by_title($title, null, 'post')) { wp_insert_post( array( 'comment_status' => 'open', 'ping_status' => 'closed', 'post_author' => $author_id, 'post_title' => $title, 'post_status' => 'publish', 'post_type' => 'post', 'post_category' => array($category), 'post_date' => $date . ' 12:00:00', 'post_content' => $content ) ); } } mysqli_close($db); } // end migrate_blog //migrate_blog(); function migrate_events() { global $wpdb; $db = mysqli_connect("localhost","root","","db161162332") or die("Error " . mysqli_error($db)); // Setup the author, slug, and title for the post $author_id = 1; $db->query('set names utf8'); $db->query("SET character_set_connection = 'UTF8'"); $db->query("SET character_set_client = 'UTF8'"); $db->query("SET character_set_results = 'UTF8'"); $result = $db->query("select * from `anc_info_even_renc`"); $querystr = "SELECT meta_key FROM $wpdb->postmeta WHERE meta_value LIKE '%location%'"; $locationKey = $wpdb->get_results($querystr, OBJECT); if ($locationKey[0]) { $locationKey = $locationKey[0]->meta_key; } $querystr = "SELECT meta_key FROM $wpdb->postmeta WHERE meta_value LIKE '%beginDate%'"; $beginDateKey = $wpdb->get_results($querystr, OBJECT); if ($beginDateKey[0]) { $beginDateKey = $beginDateKey[0]->meta_key; } $querystr = "SELECT meta_key FROM $wpdb->postmeta WHERE meta_value LIKE '%endDate%'"; $endDateKey = $wpdb->get_results($querystr, OBJECT); if ($endDateKey[0]) { $endDateKey = $endDateKey[0]->meta_key; } $querystr = "SELECT meta_key FROM $wpdb->postmeta WHERE meta_value LIKE '%beginTime%'"; $beginTimeKey = $wpdb->get_results($querystr, OBJECT); if ($beginTimeKey[0]) { $beginTimeKey = $beginTimeKey[0]->meta_key; } $querystr = "SELECT meta_key FROM $wpdb->postmeta WHERE meta_value LIKE '%endTime%'"; $endTimeKey = $wpdb->get_results($querystr, OBJECT); if ($endTimeKey[0]) { $endTimeKey = $endTimeKey[0]->meta_key; } while ($row = $result->fetch_array()) { $title = stripslashes($row["titre_even_renc"]); $content = stripslashes($row['texte_even_renc'].'<br /><br />Intervenants : '.$row['intervenants_even_renc']); $location = stripslashes($row['lieu_even_renc']); $beginDate = $row['date_pub_deb_even_renc']; $endDate = $row['date_pub_fin_even_renc']; $timeStr = $row['horaire_even_renc']; $time = str_replace('h', ':', $timeStr); $time = explode(' ', $time); $beginTime = $time[0]; if (strlen($beginTime) == 3) { $beginTime = $beginTime . '00'; } $endTime = $time[2]; if (strlen($endTime) == 3) { $endTime = $endTime . '00'; } if (null == get_page_by_title($title, null, 'event')) { $postId = wp_insert_post( array( 'comment_status' => 'open', 'ping_status' => 'closed', 'post_author' => $author_id, 'post_title' => $title, 'post_status' => 'publish', 'post_type' => 'event', 'post_date' => $row['date_crea_even_renc'], 'post_content' => $content, ) ); $beginDate = str_replace('-','',$beginDate); $endDate = str_replace('-','',$endDate); if ($endDate == '00000000') { $endDate = $beginDate; } $acf = array( $locationKey => array('address' => $location), $beginTimeKey => $beginTime, $endTimeKey => $endTime, $beginDateKey => $beginDate, $endDateKey => $endDate ); foreach($acf as $k => $v ) { $f = apply_filters('acf/load_field', false, $k ); do_action('acf/update_value', $v, $postId, $f ); } } } mysqli_close($db); } // end migrate_events //migrate_events(); function image_shortcode($atts, $content = null) { extract( shortcode_atts( array( 'id' => '', 'align' => 'center', ), $atts ) ); if (isset($id)) { $url = wp_get_attachment_image_src($id, 'large')[0]; if ($align == 'center') { $output = '<p style="text-align:center;"><a href="'.$url.'""><img style="max-width:100%;" src="'.$url.'" /></a></p>'; } else { $output = '<a href="'.$url.'""><img style="max-width:100%;float:right;margin-left:20px;" src="'.$url.'" /></a>'; } return $output; } trigger_error($id." image not found", E_USER_WARNING); return ''; } add_shortcode('image','image_shortcode'); function setupPages() { $pages = array( "Découvrir Anciela", "Agenda des activités", "Blog", "Contact", "Anciela : Nos objectifs", "Anciela : Notre équipe", "Anciela : Devenir Bénévole", "Anciela : Nous soutenir", "Anciela : Actualités d'Anciela", "Démarches participatives : Collégiens et lycéens éco-citoyens", "Démarches participatives : Étudiants éco-citoyens", "Démarches participatives : Territoires de vie", "Démarches participatives : Animations ponctuelles", "Pépinière d'initiatives citoyennes : La démarche", "Pépinière d'initiatives citoyennes : Les cycles d'activités", "Pépinière d'initiatives citoyennes : Les initiatives accompagnées", "Pépinière d'initiatives citoyennes : Participez !", "Projets numériques : democratie-durable.info", "Projets numériques : ressources-ecologistes.org", "Projets internationaux : Notre démarche", "Projets internationaux : Jeunesse francophone pour un monde écologique et solidaire", "Projets internationaux : Nos partenaires", "Projets internationaux : Construire des projets avec nous ?", "Recherche : Esprit de la recherche", "Recherche : Partages et publications", "Recherche : Participez à la recherche !", "Recherche : Le Conseil scientifique", "Formations : Esprit des formations", "Formations : Formations ouvertes", "Formations : Service civique", "Formations : Formation et accompagnement des structures", "Nous rejoindre", "Réseaux, agréments et partenaires", "Ils parlent de nous", "Communiqués et logos", "Nos rapports d’activités", "Mentions légales", "Faire un don : pourquoi ? Comment ?", "Newsletter", "J'ai une idée !" ); foreach($pages as $pageTitle) { if (null == get_page_by_title($pageTitle, null, 'page')) { wp_insert_post( array( 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_author' => '1', 'post_title' => $pageTitle, 'post_status' => 'publish', 'post_type' => 'page' ) ); } } } // end setupPages //setupPages(); function setup_header_menu() { $menuName = 'header'; $exists = wp_get_nav_menu_object($menuName); if(!$exists){ $menuId = wp_update_nav_menu_object(0, array( 'menu-name' => $menuName, 'theme-location' => 'header' )); $entries = array( 'Découvrir Anciela' => '', 'Agenda des activités' => 'Agenda', 'Blog' => '', 'Contact' => '' ); foreach ($entries as $pageName => $linkTitle) { $page = get_page_by_title($pageName, null, 'page'); if (empty($linkTitle)) { $linkTitle = $pageName; } wp_update_nav_menu_item($menuId, 0, array( 'menu-item-title' => $linkTitle, 'menu-item-type' => 'post_type', 'menu-item-object' => 'page', 'menu-item-object-id' => $page->ID, 'menu-item-status' => 'publish')); } } } //setup_header_menu(); function setup_home_menu() { $menuName = 'home'; $exists = wp_get_nav_menu_object($menuName); if(!$exists){ $menuId = wp_update_nav_menu_object(0, array( 'menu-name' => $menuName, 'theme-location' => $menuName )); $entries = array( 'Anciela : Devenir Bénévole' => 'Devenir Bénévole', 'Faire un don : pourquoi ? Comment ?' => 'Dons citoyens', 'Newsletter' => '', "J'ai une idée" => "J'ai une idée !" ); foreach ($entries as $pageName => $linkTitle) { $page = get_page_by_title($pageName, null, 'page'); if (empty($linkTitle)) { $linkTitle = $pageName; } wp_update_nav_menu_item($menuId, 0, array( 'menu-item-title' => $linkTitle, 'menu-item-type' => 'post_type', 'menu-item-object' => 'page', 'menu-item-object-id' => $page->ID, 'menu-item-status' => 'publish')); } } } //setup_home_menu(); function setup_footer_menu() { $menuName = 'footer'; $exists = wp_get_nav_menu_object($menuName); if(!$exists){ $menuId = wp_update_nav_menu_object(0, array( 'menu-name' => $menuName, 'theme-location' => 'footer' )); $entries = array( 'Anciela : Notre équipe' => 'Notre équipe', 'Nous rejoindre' => '', "Réseaux, agréments et partenaires" => '', 'Ils parlent de nous' => '', "Communiqués et logos" => 'Communiqués & logos', "Nos rapports d’activités" => '', 'Mentions légales' => '' ); foreach ($entries as $pageName => $linkTitle) { $page = get_page_by_title($pageName, null, 'page'); if (empty($linkTitle)) { $linkTitle = $pageName; } wp_update_nav_menu_item($menuId, 0, array( 'menu-item-title' => $linkTitle, 'menu-item-type' => 'post_type', 'menu-item-object' => 'page', 'menu-item-object-id' => $page->ID, 'menu-item-status' => 'publish')); } } } //setup_footer_menu(); function setup_side_menu() { $menuName = 'side'; //wp_delete_nav_menu($menuName); $exists = wp_get_nav_menu_object($menuName); if(!$exists){ $menuId = wp_update_nav_menu_object(0, array( 'menu-name' => $menuName, 'theme-location' => $menuName )); $entries = array( 'Anciela' => array( 'Anciela : Nos objectifs' => 'Nos objectifs', 'Anciela : Notre équipe' => 'Notre équipe', 'Anciela : Devenir bénévole' => 'Devenir bénévole', 'Anciela : Nous soutenir' => 'Nous soutenir', 'Anciela : Actualités d\'Anciela' => 'Actualités d\'Anciela' ), 'Démarches participatives' => array( 'Démarches participatives : Collégiens et lycéens éco-citoyens' => 'Jeunes éco-citoyens', 'Démarches participatives : Étudiants éco-citoyens' => 'Étudiants éco-citoyens', 'Démarches participatives : Territoires de vie' => 'Territoires de vie', 'Démarches participatives : Animations ponctuelles' => 'Animations ponctuelles' ), 'Pépinière d\'initiatives' => array( 'Pépinière d\'initiatives citoyennes : La démarche' => 'La démarche', "Pépinière d'initiatives citoyennes : Les cycles d'activités" => "Les cycles d'activités", "Pépinière d'initiatives citoyennes : Les initiatives accompagnées" => 'Les initiatives', 'Pépinière d\'initiatives citoyennes : Participez !' => 'Participez !' ), 'Projets numériques' => array( 'Projets numériques : democratie-durable.info' => 'Démocratie Durable', 'Projets numériques : ressources-ecologistes.org' => 'Ressources écologistes' ), 'Projets internationaux' => array( "Projets internationaux : Notre démarche" => "Notre démarche", "Projets internationaux : Jeunesse francophone pour un monde écologique et solidaire" => "Jeunesse francophone", "Projets internationaux : Nos partenaires" => "Nos partenaires", "Projets internationaux : Construire des projets avec nous ?" => "Construire des projets<br/>avec nous ?" ), 'Recherche' => array( "Recherche : Esprit de la recherche" => "Esprit de la recherche", "Recherche : Partages et publications" => "Partages et publications", "Recherche : Participez à la recherche !" => "Participez à la recherche !", "Recherche : Le Conseil scientifique" => "Le Conseil scientifique" ), 'Formations' => array( 'Formations : Esprit des formations' => 'Esprit des formations', 'Formations : Formations ouvertes' => 'Formations ouvertes', 'Formations : Service civique' => 'Service civique', 'Formations : Formation et accompagnement des structures' => 'Formation et accompagnement<br/>des structures' ) ); foreach ($entries as $pageName => $data) { if (is_array($data)) { $parentItemId = wp_update_nav_menu_item($menuId, 0, array( 'menu-item-title' => $pageName, 'menu-item-url' => '', 'menu-item-status' => 'publish')); foreach($data as $childPageName => $childPageTitle) { $page = get_page_by_title($childPageName, null, 'page'); wp_update_nav_menu_item($menuId, 0, array( 'menu-item-title' => $childPageTitle, 'menu-item-parent-id' => $parentItemId, 'menu-item-type' => 'post_type', 'menu-item-object' => 'page', 'menu-item-object-id' => $page->ID, 'menu-item-status' => 'publish')); } } else { $page = get_page_by_title($pageName, null, 'page'); wp_update_nav_menu_item($menuId, 0, array( 'menu-item-title' => $pageName, 'menu-item-type' => 'post_type', 'menu-item-object' => 'page', 'menu-item-object-id' => $page->ID, 'menu-item-status' => 'publish')); } } } } //setup_side_menu(); function setup_menu_locations() { $headerMenu = wp_get_nav_menu_object('header'); $footerMenu = wp_get_nav_menu_object('footer'); $sideMenu = wp_get_nav_menu_object('side'); $homeMenu = wp_get_nav_menu_object('home'); set_theme_mod('nav_menu_locations', array( 'header' => $headerMenu->term_id, 'side' => $sideMenu->term_id, 'footer' => $footerMenu->term_id, 'home' => $homeMenu->term_id )); } //setup_menu_locations(); update_option('timezone_string', 'Europe/Paris'); function add_custom_taxonomies() { // Add new "Locations" taxonomy to Posts $taxonomy = 'articles'; if (!taxonomy_exists($taxonomy)) { register_taxonomy($taxonomy, 'post', array( 'hierarchical' => false, // This array of options controls the labels displayed in the WordPress Admin UI 'labels' => array( 'name' => _x('Types', 'taxonomy general name'), 'singular_name' => _x('Type d\'articles', 'taxonomy singular name'), 'search_items' => __('Chercher un type d\'articles'), 'all_items' => __('Tous les types d\'articles'), 'edit_item' => __('Modifier ce type d\'articles'), 'update_item' => __('Modifier ce type d\'articles'), 'add_new_item' => __('Ajouter un nouveau type d\'articles'), 'new_item_name' => __('Nouveau type d\'articles'), 'menu_name' => __('Types'), ), // Control the slugs used for this taxonomy 'rewrite' => array( 'with_front' => false, // Don't display the category base before "/locations/" 'hierarchical' => false // This will allow URL's like "/locations/boston/cambridge/" ), )); $array = array('Blog', 'Jeunes Éco-citoyens', 'Étudiants Éco-citoyens', 'Territoires de vie', 'Pépinière (démarche)', 'Démocratie Durable', 'Recherche', 'Formations', 'Projets internationaux', 'Projets numériques'); foreach($array as $page) { wp_insert_term($page, $taxonomy); } } } //add_custom_taxonomies(); function renameMedia() { $db = mysqli_connect("localhost","root","","db161162332") or die("Error " . mysqli_error($db)); // Setup the author, slug, and title for the post $author_id = 1; $db->query('set names utf8'); $db->query("SET character_set_connection = 'UTF8'"); $db->query("SET character_set_client = 'UTF8'"); $db->query("SET character_set_results = 'UTF8'"); $files = array(); $result = $db->query("select * from `anc_info_fichier`"); while ($row = $result->fetch_array()) { $fileId = strtolower(current(explode(".", $row['nom_file']))); $files[$fileId] = $row['libelle_file']; } $args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => null, // any parent ); $attachments = get_posts($args); if ($attachments) { foreach ($attachments as $post) { the_title(); wp_update_post(array('ID'=>$post->ID, 'post_title'=>$files[$post->post_name])); } } $db->close(); } //renameMedia(); function my_excerpt_length($length) { return 50; } add_filter('excerpt_length', 'my_excerpt_length'); if(!is_admin()) { wp_deregister_script('jquery'); wp_register_script('jquery', get_template_directory_uri() . '/lib/jquery/dist/jquery.min.js', array(), null, true); wp_register_script('momentjs-core', get_template_directory_uri() . '/lib/momentjs/min/moment.min.js', array(), null, true); wp_register_script('momentjs', get_template_directory_uri() . '/lib/momentjs/lang/fr.js', array('momentjs-core'), null, true); wp_register_script('underscorejs', get_template_directory_uri() . '/lib/underscore/underscore.js', array(), null, true); wp_register_script('clndr', get_template_directory_uri() . '/lib/clndr/clndr.min.js', array('jquery', 'momentjs', 'underscorejs'), null, true); wp_register_script('tooltipster', get_template_directory_uri() . '/lib/tooltipster/js/jquery.tooltipster.min.js', array(), null, true); wp_register_style('anciela-style', get_template_directory_uri() . '/style.css', array(), null); wp_register_style('tooltipster-style', get_template_directory_uri() . '/lib/tooltipster/css/tooltipster.css', array('anciela-style'), null); } wp_register_style('fontawesome', 'http://netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css', array('anciela-style'), null);
Anciela/anciela.info
wp-content/themes/anciela/inc/anciela-setup.php
PHP
gpl-2.0
22,406
#include "Input.h" #include "Core.h" #include "Memory.h" #include "Cpu.h" //Gameboy keys: //[Up][Left][Right][Down][A][B][Start][Select] //Mapped to standard keyboard keys: //[Up][Left][Right][Down][Z][X][Enter][RShift] //Mapped to standard Xbox controller buttons: //[Up][Left][Right][Down][A][X][Start][Select] // or // [B] Input::Input(QObject *parent, Memory& memory, Cpu& cpu) : QObject(parent), memory(memory), cpu(cpu) { QObject::connect(QGamepadManager::instance(), &QGamepadManager::gamepadButtonPressEvent, this, &Input::gamepadButtonPressed); QObject::connect(QGamepadManager::instance(), &QGamepadManager::gamepadButtonReleaseEvent, this, &Input::gamepadButtonReleased); } void Input::gamepadButtonPressed(int id, QGamepadManager::GamepadButton button, double value) { switch(button) { case QGamepadManager::ButtonA: padA = true; break; case QGamepadManager::ButtonB: case QGamepadManager::ButtonX: padB = true; break; case QGamepadManager::ButtonStart: padStart = true; break; case QGamepadManager::ButtonSelect: padSelect = false; break; case QGamepadManager::ButtonLeft: padLeft = true; break; case QGamepadManager::ButtonRight: padRight = true; break; case QGamepadManager::ButtonUp: padUp = true; break; case QGamepadManager::ButtonDown: padDown = true; break; } } void Input::gamepadButtonReleased(int id, QGamepadManager::GamepadButton button) { switch(button) { case QGamepadManager::ButtonA: padA = false; break; case QGamepadManager::ButtonB: case QGamepadManager::ButtonX: padB = false; break; case QGamepadManager::ButtonStart: padStart = false; break; case QGamepadManager::ButtonSelect: padSelect = false; break; case QGamepadManager::ButtonLeft: padLeft = false; break; case QGamepadManager::ButtonRight: padRight = false; break; case QGamepadManager::ButtonUp: padUp = false; break; case QGamepadManager::ButtonDown: padDown = false; break; } } Input::~Input() { QObject::disconnect(QGamepadManager::instance(), &QGamepadManager::gamepadButtonPressEvent, this, &Input::gamepadButtonPressed); QObject::disconnect(QGamepadManager::instance(), &QGamepadManager::gamepadButtonReleaseEvent, this, &Input::gamepadButtonReleased); } unsigned char Input::getKeyInput() { return memory.readMemory(0xFF00); } bool Input::isAnyKeyPressed() { return keyUp || keyDown || keyLeft || keyRight || keyStart || keySelect || keyA || keyB || padUp || padDown || padLeft || padRight || padStart || padSelect || padA || padB; } void Input::readInput() { unsigned char keyInput = getKeyInput(); bool interrupt = false; cpu.setStop(false); if (((keyInput & 0x10) >> 4) == 1) { if (keyA || padA) { //Z //A keyInput &= 0xFE; interrupt = true; } else { keyInput |= 0x01; } if (keyB || padB) { //X //B keyInput &= 0xFD; interrupt = true; } else { keyInput |= 0x02; } if (keySelect || padSelect) { //Control //Select keyInput &= 0xFB; interrupt = true; } else { keyInput |= 0x04; } if (keyStart || padStart) { //Enter //Start keyInput &= 0xF7; interrupt = true; } else { keyInput |= 0x08; } } else if (((keyInput & 0x20) >> 5) == 1)//(keyInput == 0x20) { if (!((keyRight || padRight) && (keyLeft || padLeft))) //Detect if both inputs are NOT enabled at once { if (keyRight || padRight) { keyInput &= 0xFE; interrupt = true; } else { keyInput |= 0x01; } if (keyLeft || padLeft) { keyInput &= 0xFD; interrupt = true; } else { keyInput |= 0x02; } } else //To solve issue of multiple key input on one axis we will ignore input when both left and right are pressed at the same time. { keyInput |= 0x01; keyInput |= 0x02; } if (!((keyUp || padUp) && (keyDown || padDown))) //Detect if both inputs are NOT enabled at once { if (keyUp || padUp) { keyInput &= 0xFB; interrupt = true; } else { keyInput |= 0x04; } if (keyDown || padDown) { keyInput &= 0xF7; interrupt = true; } else { keyInput |= 0x08; } } else //To solve issue of multiple key input on one axis we will ignore input when both left and right are pressed at the same time. { keyInput |= 0x04; keyInput |= 0x08; } } else { keyInput |= 0x01; keyInput |= 0x02; keyInput |= 0x04; keyInput |= 0x08; } //Bit 7 and 6 are always 1 keyInput |= 0x80; //Bit 7 keyInput |= 0x40; //Bit 6 if (interrupt) { memory.writeMemory(0xFF0F, (unsigned char)(memory.readMemory(0xFF0F) | 0x10)); } memory.writeMemory(0xFF00, keyInput); } void Input::setKeyInput(int keyCode, bool enabled) { cpu.setStop(false); switch (keyCode) { case 0: { keyUp = enabled; break; } case 1: { keyDown = enabled; break; } case 2: { keyLeft = enabled; break; } case 3: { keyRight = enabled; break; } case 4: { keyStart = enabled; break; } case 5: { keySelect = enabled; break; } case 6: { keyA = enabled; break; } case 7: { keyB = enabled; break; } } } bool Input::eventFilter(QObject *obj, QEvent *event) { bool keyPressed = event->type() == QEvent::KeyPress; bool keyReleased = event->type() == QEvent::KeyRelease; if (keyPressed || keyReleased) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); int key = keyEvent->key(); if (key == Qt::Key_Z) { setKeyInput(6, keyPressed); } if (key == Qt::Key_X) { setKeyInput(7, keyPressed); } if (key == Qt::Key_Return) { setKeyInput(4, keyPressed); } if (key == Qt::Key_Shift) { setKeyInput(5, keyPressed); } if (key == Qt::Key_Right) { setKeyInput(3, keyPressed); } if (key == Qt::Key_Left) { setKeyInput(2, keyPressed); } if (key == Qt::Key_Up) { setKeyInput(0, keyPressed); } if (key == Qt::Key_Down) { setKeyInput(1, keyPressed); } if (key == Qt::Key_F1 && keyReleased) { memory.createSaveFile(true); } } return QObject::eventFilter(obj, event); } void Input::resetInput() { keyRight = false; keyLeft = false; keyUp = false; keyDown = false; keySelect = false; keyStart = false; keyA = false; keyB = false; padRight = false; padLeft = false; padUp = false; padDown = false; padSelect = false; padStart = false; padA = false; padB = false; }
Daniel-McCarthy/GameBeak
GameBeak/src/Input.cpp
C++
gpl-2.0
8,311
<?php /** * Interactive image shortcode template */ ?> <div class="mkd-interactive-image <?php echo esc_attr($classes)?>"> <?php if($params['link'] != '') { ?> <a href="<?php echo esc_url($params['link'])?>"></a> <?php } ?> <?php echo wp_get_attachment_image($image,'full'); ?> <?php if($params['add_checkmark'] == 'yes') { ?> <div class="tick" <?php libero_mikado_inline_style($checkmark_position); ?>></div> <?php } ?> </div>
peerapat-pongnipakorn/somphoblaws
wp-content/themes/libero/framework/modules/shortcodes/interactive-image/templates/interactive-image-template.php
PHP
gpl-2.0
443
from models import Connection from django import forms class ConnectionForm(forms.ModelForm): class Meta: model = Connection exclude = ('d_object_id',)
CIGNo-project/CIGNo
cigno/mdtools/forms.py
Python
gpl-3.0
173
// created on 13/12/2002 at 22:07 using System; namespace xServer.Core.NAudio.Mixer { /// <summary> /// Custom Mixer control /// </summary> public class CustomMixerControl : MixerControl { internal CustomMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels) { this.mixerControl = mixerControl; this.mixerHandle = mixerHandle; this.mixerHandleType = mixerHandleType; this.nChannels = nChannels; this.mixerControlDetails = new MixerInterop.MIXERCONTROLDETAILS(); GetControlDetails(); } /// <summary> /// Get the data for this custom control /// </summary> /// <param name="pDetails">pointer to memory to receive data</param> protected override void GetDetails(IntPtr pDetails) { } // TODO: provide a way of getting / setting data } }
mirkoBastianini/Quasar-RAT
Server/Core/NAudio/Mixer/CustomMixerControl.cs
C#
gpl-3.0
873
package org.mivotocuenta.client.service; import org.mivotocuenta.server.beans.Conteo; import org.mivotocuenta.shared.UnknownException; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; @RemoteServiceRelativePath("servicegestionconteo") public interface ServiceGestionConteo extends RemoteService { Boolean insertarVoto(Conteo bean) throws UnknownException; }
jofrantoba/mivotocuenta
src/org/mivotocuenta/client/service/ServiceGestionConteo.java
Java
gpl-3.0
431
# -*- coding: utf-8 -*- # pylint: disable=too-many-lines,too-complex,too-many-branches # pylint: disable=too-many-statements,arguments-differ # needs refactoring, but I don't have the energy for anything # more than a superficial cleanup. #------------------------------------------------------------------------------- # Name: midi/__init__.py # Purpose: Access to MIDI library / music21 classes for dealing with midi data # # Authors: Christopher Ariza # Michael Scott Cuthbert # (Will Ware -- see docs) # # Copyright: Copyright © 2011-2013 Michael Scott Cuthbert and the music21 Project # Some parts of this module are in the Public Domain, see details. # License: LGPL or BSD, see license.txt #------------------------------------------------------------------------------- ''' Objects and tools for processing MIDI data. Converts from MIDI files to :class:`~MidiEvent`, :class:`~MidiTrack`, and :class:`~MidiFile` objects, and vice-versa. This module uses routines from Will Ware's public domain midi.py library from 2001 see http://groups.google.com/group/alt.sources/msg/0c5fc523e050c35e ''' import struct import sys import unicodedata # @UnresolvedImport # good midi reference: # http://www.sonicspot.com/guide/midifiles.html def is_num(usr_data): ''' check if usr_data is a number (float, int, long, Decimal), return boolean unlike `isinstance(usr_data, Number)` does not return True for `True, False`. Does not use `isinstance(usr_data, Number)` which is 6 times slower than calling this function (except in the case of Fraction, when it's 6 times faster, but that's rarer) Runs by adding 0 to the "number" -- so anything that implements add to a scalar works >>> is_num(3.0) True >>> is_num(3) True >>> is_num('three') False >>> is_num([2, 3, 4]) False True and False are NOT numbers: >>> is_num(True) False >>> is_num(False) False >>> is_num(None) False :rtype: bool ''' try: dummy = usr_data + 0 # pylint: disable=simplifiable-if-statement if usr_data is not True and usr_data is not False: return True else: return False except Exception: # pylint: disable=broad-except return False # pylint: disable=missing-docstring #------------------------------------------------------------------------------- class EnumerationException(Exception): pass class MidiException(Exception): pass #------------------------------------------------------------------------------- def char_to_binary(char): ''' Convert a char into its binary representation. Useful for debugging. >>> char_to_binary('a') '01100001' ''' ascii_value = ord(char) binary_digits = [] while ascii_value > 0: if (ascii_value & 1) == 1: binary_digits.append("1") else: binary_digits.append("0") ascii_value = ascii_value >> 1 binary_digits.reverse() binary = ''.join(binary_digits) zerofix = (8 - len(binary)) * '0' return zerofix + binary def ints_to_hex_string(int_list): ''' Convert a list of integers into a hex string, suitable for testing MIDI encoding. >>> # note on, middle c, 120 velocity >>> ints_to_hex_string([144, 60, 120]) b'\\x90<x' ''' # note off are 128 to 143 # note on messages are decimal 144 to 159 post = b'' for i in int_list: # B is an unsigned char # this forces values between 0 and 255 # the same as chr(int) post += struct.pack(">B", i) return post def get_number(midi_str, length): ''' Return the value of a string byte or bytes if length > 1 from an 8-bit string or (PY3) bytes object Then, return the remaining string or bytes object The `length` is the number of chars to read. This will sum a length greater than 1 if desired. Note that MIDI uses big-endian for everything. This is the inverse of Python's chr() function. >>> get_number('test', 0) (0, 'test') >>> get_number('test', 2) (29797, 'st') >>> get_number('test', 4) (1952805748, '') ''' summation = 0 if not is_num(midi_str): for i in range(length): midi_str_or_num = midi_str[i] if is_num(midi_str_or_num): summation = (summation << 8) + midi_str_or_num else: summation = (summation << 8) + ord(midi_str_or_num) return summation, midi_str[length:] else: mid_num = midi_str summation = mid_num - ((mid_num >> (8*length)) << (8*length)) big_bytes = mid_num - summation return summation, big_bytes def get_variable_length_number(midi_str): r''' Given a string of data, strip off a the first character, or all high-byte characters terminating with one whose ord() function is < 0x80. Thus a variable number of bytes might be read. After finding the appropriate termination, return the remaining string. This is necessary as DeltaTime times are given with variable size, and thus may be if different numbers of characters are used. (The ellipses below are just to make the doctests work on both Python 2 and Python 3 (where the output is in bytes).) >>> get_variable_length_number('A-u') (65, ...'-u') >>> get_variable_length_number('-u') (45, ...'u') >>> get_variable_length_number('u') (117, ...'') >>> get_variable_length_number('test') (116, ...'est') >>> get_variable_length_number('E@-E') (69, ...'@-E') >>> get_variable_length_number('@-E') (64, ...'-E') >>> get_variable_length_number('-E') (45, ...'E') >>> get_variable_length_number('E') (69, ...'') Test that variable length characters work: >>> get_variable_length_number(b'\xff\x7f') (16383, ...'') >>> get_variable_length_number('中xy') (210638584, ...'y') If no low-byte character is encoded, raises an IndexError >>> get_variable_length_number('中国') Traceback (most recent call last): MidiException: did not find the end of the number! ''' # from http://faydoc.tripod.com/formats/mid.htm # This allows the number to be read one byte at a time, and when you see # a msb of 0, you know that it was the last (least significant) byte of the number. summation = 0 if isinstance(midi_str, str): midi_str = midi_str.encode('utf-8') for i, byte in enumerate(midi_str): if not is_num(byte): byte = ord(byte) summation = (summation << 7) + (byte & 0x7F) if not byte & 0x80: try: return summation, midi_str[i+1:] except IndexError: break raise MidiException('did not find the end of the number!') def get_numbers_as_list(midi_str): ''' Translate each char into a number, return in a list. Used for reading data messages where each byte encodes a different discrete value. >>> get_numbers_as_list('\\x00\\x00\\x00\\x03') [0, 0, 0, 3] ''' post = [] for item in midi_str: if is_num(item): post.append(item) else: post.append(ord(item)) return post def put_number(num, length): ''' Put a single number as a hex number at the end of a string `length` bytes long. >>> put_number(3, 4) b'\\x00\\x00\\x00\\x03' >>> put_number(0, 1) b'\\x00' ''' lst = bytearray() for i in range(length): shift_bits = 8 * (length - 1 - i) this_num = (num >> shift_bits) & 0xFF lst.append(this_num) return bytes(lst) def put_variable_length_number(num): ''' >>> put_variable_length_number(4) b'\\x04' >>> put_variable_length_number(127) b'\\x7f' >>> put_variable_length_number(0) b'\\x00' >>> put_variable_length_number(1024) b'\\x88\\x00' >>> put_variable_length_number(8192) b'\\xc0\\x00' >>> put_variable_length_number(16383) b'\\xff\\x7f' >>> put_variable_length_number(-1) Traceback (most recent call last): MidiException: cannot put_variable_length_number() when number is negative: -1 ''' if num < 0: raise MidiException( 'cannot put_variable_length_number() when number is negative: %s' % num) lst = bytearray() while True: result, num = num & 0x7F, num >> 7 lst.append(result + 0x80) if num == 0: break lst.reverse() lst[-1] = lst[-1] & 0x7f return bytes(lst) def put_numbers_as_list(num_list): ''' Translate a list of numbers (0-255) into a bytestring. Used for encoding data messages where each byte encodes a different discrete value. >>> put_numbers_as_list([0, 0, 0, 3]) b'\\x00\\x00\\x00\\x03' If a number is < 0 then it wraps around from the top. >>> put_numbers_as_list([0, 0, 0, -3]) b'\\x00\\x00\\x00\\xfd' >>> put_numbers_as_list([0, 0, 0, -1]) b'\\x00\\x00\\x00\\xff' A number > 255 is an exception: >>> put_numbers_as_list([256]) Traceback (most recent call last): MidiException: Cannot place a number > 255 in a list: 256 ''' post = bytearray() for num in num_list: if num < 0: num = num % 256 # -1 will be 255 if num >= 256: raise MidiException("Cannot place a number > 255 in a list: %d" % num) post.append(num) return bytes(post) #------------------------------------------------------------------------------- class Enumeration(object): ''' Utility object for defining binary MIDI message constants. ''' def __init__(self, enum_list=None): if enum_list is None: enum_list = [] lookup = {} reverse_lookup = {} num = 0 unique_names = [] unique_values = [] for enum in enum_list: if isinstance(enum, tuple): enum, num = enum if not isinstance(enum, str): raise EnumerationException("enum name is not a string: " + enum) if not isinstance(num, int): raise EnumerationException("enum value is not an integer: " + num) if enum in unique_names: raise EnumerationException("enum name is not unique: " + enum) if num in unique_values: raise EnumerationException("enum value is not unique for " + enum) unique_names.append(enum) unique_values.append(num) lookup[enum] = num reverse_lookup[num] = enum num = num + 1 self.lookup = lookup self.reverse_lookup = reverse_lookup def __add__(self, other): lst = [] for k in self.lookup: lst.append((k, self.lookup[k])) for k in other.lookup: lst.append((k, other.lookup[k])) return Enumeration(lst) def hasattr(self, attr): if attr in self.lookup: return True return False def has_value(self, attr): if attr in self.reverse_lookup: return True return False def __getattr__(self, attr): if attr not in self.lookup: raise AttributeError return self.lookup[attr] def whatis(self, value): post = self.reverse_lookup[value] return post CHANNEL_VOICE_MESSAGES = Enumeration([ ("NOTE_OFF", 0x80), ("NOTE_ON", 0x90), ("POLYPHONIC_KEY_PRESSURE", 0xA0), ("CONTROLLER_CHANGE", 0xB0), ("PROGRAM_CHANGE", 0xC0), ("CHANNEL_KEY_PRESSURE", 0xD0), ("PITCH_BEND", 0xE0)]) CHANNEL_MODE_MESSAGES = Enumeration([ ("ALL_SOUND_OFF", 0x78), ("RESET_ALL_CONTROLLERS", 0x79), ("LOCAL_CONTROL", 0x7A), ("ALL_NOTES_OFF", 0x7B), ("OMNI_MODE_OFF", 0x7C), ("OMNI_MODE_ON", 0x7D), ("MONO_MODE_ON", 0x7E), ("POLY_MODE_ON", 0x7F)]) META_EVENTS = Enumeration([ ("SEQUENCE_NUMBER", 0x00), ("TEXT_EVENT", 0x01), ("COPYRIGHT_NOTICE", 0x02), ("SEQUENCE_TRACK_NAME", 0x03), ("INSTRUMENT_NAME", 0x04), ("LYRIC", 0x05), ("MARKER", 0x06), ("CUE_POINT", 0x07), ("PROGRAM_NAME", 0x08), # optional event is used to embed the # patch/program name that is called up by the immediately # subsequent Bank Select and Program Change messages. # It serves to aid the end user in making an intelligent # program choice when using different hardware. ("SOUND_SET_UNSUPPORTED", 0x09), ("MIDI_CHANNEL_PREFIX", 0x20), ("MIDI_PORT", 0x21), ("END_OF_TRACK", 0x2F), ("SET_TEMPO", 0x51), ("SMTPE_OFFSET", 0x54), ("TIME_SIGNATURE", 0x58), ("KEY_SIGNATURE", 0x59), ("SEQUENCER_SPECIFIC_META_EVENT", 0x7F)]) #------------------------------------------------------------------------------- class MidiEvent(object): ''' A model of a MIDI event, including note-on, note-off, program change, controller change, any many others. MidiEvent objects are paired (preceded) by :class:`~base.DeltaTime` objects in the list of events in a MidiTrack object. The `track` argument must be a :class:`~base.MidiTrack` object. The `type_` attribute is a string representation of a Midi event from the CHANNEL_VOICE_MESSAGES or META_EVENTS definitions. The `channel` attribute is an integer channel id, from 1 to 16. The `time` attribute is an integer duration of the event in ticks. This value can be zero. This value is not essential, as ultimate time positioning is determined by :class:`~base.DeltaTime` objects. The `pitch` attribute is only defined for note-on and note-off messages. The attribute stores an integer representation (0-127, with 60 = middle C). The `velocity` attribute is only defined for note-on and note-off messages. The attribute stores an integer representation (0-127). A note-on message with velocity 0 is generally assumed to be the same as a note-off message. The `data` attribute is used for storing other messages, such as SEQUENCE_TRACK_NAME string values. >>> mt = MidiTrack(1) >>> me1 = MidiEvent(mt) >>> me1.type_ = "NOTE_ON" >>> me1.channel = 3 >>> me1.time = 200 >>> me1.pitch = 60 >>> me1.velocity = 120 >>> me1 <MidiEvent NOTE_ON, t=200, track=1, channel=3, pitch=60, velocity=120> >>> me2 = MidiEvent(mt) >>> me2.type_ = "SEQUENCE_TRACK_NAME" >>> me2.time = 0 >>> me2.data = 'guitar' >>> me2 <MidiEvent SEQUENCE_TRACK_NAME, t=0, track=1, channel=None, data=b'guitar'> ''' def __init__(self, track, type_=None, time=None, channel=None): self.track = track self.type_ = type_ self.time = time self.channel = channel self._parameter1 = None # pitch or first data value self._parameter2 = None # velocity or second data value # data is a property... # if this is a Note on/off, need to store original # pitch space value in order to determine if this is has a microtone self.cent_shift = None # store a reference to a corresponding event # if a noteOn, store the note off, and vice versa # NTODO: We should make sure that we garbage collect this -- otherwise it's a memory # leak from a circular reference. # note: that's what weak references are for # unimplemented self.corresponding_event = None # store and pass on a running status if found self.last_status_byte = None self.sort_order = 0 self.update_sort_order() def update_sort_order(self): if self.type_ == 'PITCH_BEND': self.sort_order = -10 if self.type_ == 'NOTE_OFF': self.sort_order = -20 def __repr__(self): if self.track is None: track_index = None else: track_index = self.track.index return_str = ("<MidiEvent %s, t=%s, track=%s, channel=%s" % (self.type_, repr(self.time), track_index, repr(self.channel))) if self.type_ in ['NOTE_ON', 'NOTE_OFF']: attr_list = ["pitch", "velocity"] else: if self._parameter2 is None: attr_list = ['data'] else: attr_list = ['_parameter1', '_parameter2'] for attrib in attr_list: if getattr(self, attrib) is not None: return_str = return_str + ", " + attrib + "=" + repr(getattr(self, attrib)) return return_str + ">" def _set_pitch(self, value): self._parameter1 = value def _get_pitch(self): if self.type_ in ['NOTE_ON', 'NOTE_OFF']: return self._parameter1 else: return None pitch = property(_get_pitch, _set_pitch) def _set_velocity(self, value): self._parameter2 = value def _get_velocity(self): return self._parameter2 velocity = property(_get_velocity, _set_velocity) def _set_data(self, value): if value is not None and not isinstance(value, bytes): if isinstance(value, str): value = value.encode('utf-8') self._parameter1 = value def _get_data(self): return self._parameter1 data = property(_get_data, _set_data) def set_pitch_bend(self, cents, bend_range=2): ''' Treat this event as a pitch bend value, and set the ._parameter1 and ._parameter2 fields appropriately given a specified bend value in cents. The `bend_range` parameter gives the number of half steps in the bend range. >>> mt = MidiTrack(1) >>> me1 = MidiEvent(mt) >>> me1.set_pitch_bend(50) >>> me1._parameter1, me1._parameter2 (0, 80) >>> me1.set_pitch_bend(100) >>> me1._parameter1, me1._parameter2 (0, 96) >>> me1.set_pitch_bend(200) >>> me1._parameter1, me1._parameter2 (127, 127) >>> me1.set_pitch_bend(-50) >>> me1._parameter1, me1._parameter2 (0, 48) >>> me1.set_pitch_bend(-100) >>> me1._parameter1, me1._parameter2 (0, 32) ''' # value range is 0, 16383 # center should be 8192 cent_range = bend_range * 100 center = 8192 top_span = 16383 - center bottom_span = center if cents > 0: shift_scalar = cents / float(cent_range) shift = int(round(shift_scalar * top_span)) elif cents < 0: shift_scalar = cents / float(cent_range) # will be negative shift = int(round(shift_scalar * bottom_span)) # will be negative else: shift = 0 target = center + shift # produce a two-char value char_value = put_variable_length_number(target) data1, _ = get_number(char_value[0], 1) # need to convert from 8 bit to 7, so using & 0x7F data1 = data1 & 0x7F if len(char_value) > 1: data2, _ = get_number(char_value[1], 1) data2 = data2 & 0x7F else: data2 = 0 self._parameter1 = data2 self._parameter2 = data1 # data1 is msb here def _parse_channel_voice_message(self, midi_str): ''' >>> mt = MidiTrack(1) >>> me1 = MidiEvent(mt) >>> remainder = me1._parse_channel_voice_message(ints_to_hex_string([144, 60, 120])) >>> me1.channel 1 >>> remainder = me1._parse_channel_voice_message(ints_to_hex_string([145, 60, 120])) >>> me1.channel 2 >>> me1.type_ 'NOTE_ON' >>> me1.pitch 60 >>> me1.velocity 120 ''' # first_byte, channel_number, and second_byte define # characteristics of the first two chars # for first_byte: The left nybble (4 bits) contains the actual command, and the right nibble # contains the midi channel number on which the command will be executed. if is_num(midi_str[0]): first_byte = midi_str[0] else: first_byte = ord(midi_str[0]) channel_number = first_byte & 0xF0 if is_num(midi_str[1]): second_byte = midi_str[1] else: second_byte = ord(midi_str[1]) if is_num(midi_str[2]): third_byte = midi_str[2] else: third_byte = ord(midi_str[2]) self.channel = (first_byte & 0x0F) + 1 self.type_ = CHANNEL_VOICE_MESSAGES.whatis(channel_number) if (self.type_ == "PROGRAM_CHANGE" or self.type_ == "CHANNEL_KEY_PRESSURE"): self.data = second_byte return midi_str[2:] elif self.type_ == "CONTROLLER_CHANGE": # for now, do nothing with this data # for a note, str[2] is velocity; here, it is the control value self.pitch = second_byte # this is the controller id self.velocity = third_byte # this is the controller value return midi_str[3:] else: self.pitch = second_byte self.velocity = third_byte return midi_str[3:] def read(self, time, midi_str): ''' Parse the string that is given and take the beginning section and convert it into data for this event and return the now truncated string. The `time` value is the number of ticks into the Track at which this event happens. This is derived from reading data the level of the track. TODO: These instructions are inadequate. >>> # all note-on messages (144-159) can be found >>> 145 & 0xF0 # testing message type_ extraction 144 >>> 146 & 0xF0 # testing message type_ extraction 144 >>> (144 & 0x0F) + 1 # getting the channel 1 >>> (159 & 0x0F) + 1 # getting the channel 16 ''' if len(midi_str) < 2: # often what we have here are null events: # the string is simply: 0x00 print( 'MidiEvent.read(): got bad data string', 'time', time, 'str', repr(midi_str)) return '' # first_byte, message_type, and second_byte define # characteristics of the first two chars # for first_byte: The left nybble (4 bits) contains the # actual command, and the right nibble # contains the midi channel number on which the command will # be executed. if is_num(midi_str[0]): first_byte = midi_str[0] else: first_byte = ord(midi_str[0]) # detect running status: if the status byte is less than 128, its # not a status byte, but a data byte if first_byte < 128: if self.last_status_byte is not None: rsb = self.last_status_byte if is_num(rsb): rsb = bytes([rsb]) else: rsb = bytes([0x90]) # add the running status byte to the front of the string # and process as before midi_str = rsb + midi_str if is_num(midi_str[0]): first_byte = midi_str[0] else: first_byte = ord(midi_str[0]) else: self.last_status_byte = midi_str[0] message_type = first_byte & 0xF0 if is_num(midi_str[1]): second_byte = midi_str[1] else: second_byte = ord(midi_str[1]) if CHANNEL_VOICE_MESSAGES.has_value(message_type): return self._parse_channel_voice_message(midi_str) elif message_type == 0xB0 and CHANNEL_MODE_MESSAGES.has_value(second_byte): self.channel = (first_byte & 0x0F) + 1 self.type_ = CHANNEL_MODE_MESSAGES.whatis(second_byte) if self.type_ == "LOCAL_CONTROL": self.data = (ord(midi_str[2]) == 0x7F) elif self.type_ == "MONO_MODE_ON": self.data = ord(midi_str[2]) else: print('unhandled message:', midi_str[2]) return midi_str[3:] elif first_byte == 0xF0 or first_byte == 0xF7: self.type_ = {0xF0: "F0_SYSEX_EVENT", 0xF7: "F7_SYSEX_EVENT"}[first_byte] length, midi_str = get_variable_length_number(midi_str[1:]) self.data = midi_str[:length] return midi_str[length:] # SEQUENCE_TRACK_NAME and other MetaEvents are here elif first_byte == 0xFF: if not META_EVENTS.has_value(second_byte): print("unknown meta event: FF %02X" % second_byte) sys.stdout.flush() raise MidiException("Unknown midi event type_: %r, %r" % (first_byte, second_byte)) self.type_ = META_EVENTS.whatis(second_byte) length, midi_str = get_variable_length_number(midi_str[2:]) self.data = midi_str[:length] return midi_str[length:] else: # an uncaught message print( 'got unknown midi event type_', repr(first_byte), 'char_to_binary(midi_str[0])', char_to_binary(midi_str[0]), 'char_to_binary(midi_str[1])', char_to_binary(midi_str[1])) raise MidiException("Unknown midi event type_") def get_bytes(self): ''' Return a set of bytes for this MIDI event. ''' sysex_event_dict = {"F0_SYSEX_EVENT": 0xF0, "F7_SYSEX_EVENT": 0xF7} if CHANNEL_VOICE_MESSAGES.hasattr(self.type_): return_bytes = chr((self.channel - 1) + getattr(CHANNEL_VOICE_MESSAGES, self.type_)) # for writing note-on/note-off if self.type_ not in [ 'PROGRAM_CHANGE', 'CHANNEL_KEY_PRESSURE']: # this results in a two-part string, like '\x00\x00' try: data = chr(self._parameter1) + chr(self._parameter2) except ValueError: raise MidiException( "Problem with representing either %d or %d" % ( self._parameter1, self._parameter2)) elif self.type_ in ['PROGRAM_CHANGE']: try: data = chr(self.data) except TypeError: raise MidiException( "Got incorrect data for %return_bytes in .data: %return_bytes," % (self, self.data) + "cannot parse Program Change") else: try: data = chr(self.data) except TypeError: raise MidiException( ("Got incorrect data for %return_bytes in " ".data: %return_bytes, ") % (self, self.data) + "cannot parse Miscellaneous Message") return return_bytes + data elif CHANNEL_MODE_MESSAGES.hasattr(self.type_): return_bytes = getattr(CHANNEL_MODE_MESSAGES, self.type_) return_bytes = (chr(0xB0 + (self.channel - 1)) + chr(return_bytes) + chr(self.data)) return return_bytes elif self.type_ in sysex_event_dict: return_bytes = bytes([sysex_event_dict[self.type_]]) return_bytes = return_bytes + put_variable_length_number(len(self.data)) return return_bytes + self.data elif META_EVENTS.hasattr(self.type_): return_bytes = bytes([0xFF]) + bytes([getattr(META_EVENTS, self.type_)]) return_bytes = return_bytes + put_variable_length_number(len(self.data)) try: return return_bytes + self.data except (UnicodeDecodeError, TypeError): return return_bytes + unicodedata.normalize( 'NFKD', self.data).encode('ascii', 'ignore') else: raise MidiException("unknown midi event type_: %return_bytes" % self.type_) #--------------------------------------------------------------------------- def is_note_on(self): ''' return a boolean if this is a NOTE_ON message and velocity is not zero_ >>> mt = MidiTrack(1) >>> me1 = MidiEvent(mt) >>> me1.type_ = "NOTE_ON" >>> me1.velocity = 120 >>> me1.is_note_on() True >>> me1.is_note_off() False ''' return self.type_ == "NOTE_ON" and self.velocity != 0 def is_note_off(self): ''' Return a boolean if this is should be interpreted as a note-off message, either as a real note-off or as a note-on with zero velocity. >>> mt = MidiTrack(1) >>> me1 = MidiEvent(mt) >>> me1.type_ = "NOTE_OFF" >>> me1.is_note_on() False >>> me1.is_note_off() True >>> me2 = MidiEvent(mt) >>> me2.type_ = "NOTE_ON" >>> me2.velocity = 0 >>> me2.is_note_on() False >>> me2.is_note_off() True ''' if self.type_ == "NOTE_OFF": return True elif self.type_ == "NOTE_ON" and self.velocity == 0: return True return False def is_delta_time(self): ''' Return a boolean if this is a DeltaTime subclass. >>> mt = MidiTrack(1) >>> dt = DeltaTime(mt) >>> dt.is_delta_time() True ''' if self.type_ == "DeltaTime": return True return False def matched_note_off(self, other): ''' Returns True if `other` is a MIDI event that specifies a note-off message for this message. That is, this event is a NOTE_ON message, and the other is a NOTE_OFF message for this pitch on this channel. Otherwise returns False >>> mt = MidiTrack(1) >>> me1 = MidiEvent(mt) >>> me1.type_ = "NOTE_ON" >>> me1.velocity = 120 >>> me1.pitch = 60 >>> me2 = MidiEvent(mt) >>> me2.type_ = "NOTE_ON" >>> me2.velocity = 0 >>> me2.pitch = 60 >>> me1.matched_note_off(me2) True >>> me2.pitch = 61 >>> me1.matched_note_off(me2) False >>> me2.type_ = "NOTE_OFF" >>> me1.matched_note_off(me2) False >>> me2.pitch = 60 >>> me1.matched_note_off(me2) True >>> me2.channel = 12 >>> me1.matched_note_off(me2) False ''' if other.is_note_off: # might check velocity here too? if self.pitch == other.pitch and self.channel == other.channel: return True return False class DeltaTime(MidiEvent): ''' A :class:`~base.MidiEvent` subclass that stores the time change (in ticks) since the start or since the last MidiEvent. Pairs of DeltaTime and MidiEvent objects are the basic presentation of temporal data. The `track` argument must be a :class:`~base.MidiTrack` object. Time values are in integers, representing ticks. The `channel` attribute, inherited from MidiEvent is not used and set to None unless overridden (don't!). >>> mt = MidiTrack(1) >>> dt = DeltaTime(mt) >>> dt.time = 380 >>> dt <MidiEvent DeltaTime, t=380, track=1, channel=None> ''' def __init__(self, track, time=None, channel=None): MidiEvent.__init__(self, track, time=time, channel=channel) self.type_ = "DeltaTime" def read(self, oldstr): self.time, newstr = get_variable_length_number(oldstr) return self.time, newstr def get_bytes(self): midi_str = put_variable_length_number(self.time) return midi_str class MidiTrack(object): ''' A MIDI Track. Each track contains a list of :class:`~base.MidiChannel` objects, one for each channel. All events are stored in the `events` list, in order. An `index` is an integer identifier for this object. TODO: Better Docs >>> mt = MidiTrack(0) ''' def __init__(self, index): self.index = index self.events = [] self.length = 0 #the data length; only used on read() def read(self, midi_str): ''' Read as much of the string (representing midi data) as necessary; return the remaining string for reassignment and further processing. The string should begin with `MTrk`, specifying a Midi Track Creates and stores :class:`~base.DeltaTime` and :class:`~base.MidiEvent` objects. ''' time = 0 # a running counter of ticks if not midi_str[:4] == b"MTrk": raise MidiException('badly formed midi string: missing leading MTrk') # get the 4 chars after the MTrk encoding length, midi_str = get_number(midi_str[4:], 4) self.length = length # all event data is in the track str track_str = midi_str[:length] remainder = midi_str[length:] e_previous = None while track_str: # shave off the time stamp from the event delta_t = DeltaTime(self) # return extracted time, as well as remaining string d_time, track_str_candidate = delta_t.read(track_str) # this is the offset that this event happens at, in ticks time_candidate = time + d_time # pass self to event, set this MidiTrack as the track for this event event = MidiEvent(self) if e_previous is not None: # set the last status byte event.last_status_byte = e_previous.last_status_byte # some midi events may raise errors; simply skip for now try: track_str_candidate = event.read(time_candidate, track_str_candidate) except MidiException: # assume that track_str, after delta extraction, is still correct # set to result after taking delta time track_str = track_str_candidate continue # only set after trying to read, which may raise exception time = time_candidate track_str = track_str_candidate # remainder string # only append if we get this far self.events.append(delta_t) self.events.append(event) e_previous = event return remainder # remainder string after extracting track data def get_bytes(self): ''' returns a string of midi-data from the `.events` in the object. ''' # build str using MidiEvents midi_str = b"" for event in self.events: # this writes both delta time and message events try: event_bytes = event.get_bytes() int_array = [] for byte in event_bytes: if is_num(byte): int_array.append(byte) else: int_array.append(ord(byte)) event_bytes = bytes(bytearray(int_array)) midi_str = midi_str + event_bytes except MidiException as err: print("Conversion error for %s: %s; ignored." % (event, err)) return b"MTrk" + put_number(len(midi_str), 4) + midi_str def __repr__(self): return_str = "<MidiTrack %d -- %d events\n" % (self.index, len(self.events)) for event in self.events: return_str = return_str + " " + event.__repr__() + "\n" return return_str + " >" #--------------------------------------------------------------------------- def update_events(self): ''' We may attach events to this track before setting their `track` parameter. This method will move through all events and set their track to this track. ''' for event in self.events: event.track = self def has_notes(self): '''Return True/False if this track has any note-on/note-off pairs defined. ''' for event in self.events: if event.is_note_on(): return True return False def set_channel(self, value): '''Set the channel of all events in this Track. ''' if value not in range(1, 17): raise MidiException('bad channel value: %s' % value) for event in self.events: event.channel = value def get_channels(self): '''Get all channels used in this Track. ''' post = [] for event in self.events: if event.channel not in post: post.append(event.channel) return post def get_program_changes(self): '''Get all unique program changes used in this Track, sorted. ''' post = [] for event in self.events: if event.type_ == 'PROGRAM_CHANGE': if event.data not in post: post.append(event.data) return post class MidiFile(object): ''' Low-level MIDI file writing, emulating methods from normal Python files. The `ticks_per_quarter_note` attribute must be set before writing. 1024 is a common value. This object is returned by some properties for directly writing files of midi representations. ''' def __init__(self): self.file = None self.format = 1 self.tracks = [] self.ticks_per_quarter_note = 1024 self.ticks_per_second = None def open(self, filename, attrib="rb"): ''' Open a MIDI file path for reading or writing. For writing to a MIDI file, `attrib` should be "wb". ''' if attrib not in ['rb', 'wb']: raise MidiException('cannot read or write unless in binary mode, not:', attrib) self.file = open(filename, attrib) def open_file_like(self, file_like): '''Assign a file-like object, such as those provided by StringIO, as an open file object. >>> from io import StringIO >>> fileLikeOpen = StringIO() >>> mf = MidiFile() >>> mf.open_file_like(fileLikeOpen) >>> mf.close() ''' self.file = file_like def __repr__(self): return_str = "<MidiFile %d tracks\n" % len(self.tracks) for track in self.tracks: return_str = return_str + " " + track.__repr__() + "\n" return return_str + ">" def close(self): ''' Close the file. ''' self.file.close() def read(self): ''' Read and parse MIDI data stored in a file. ''' self.readstr(self.file.read()) def readstr(self, midi_str): ''' Read and parse MIDI data as a string, putting the data in `.ticks_per_quarter_note` and a list of `MidiTrack` objects in the attribute `.tracks`. ''' if not midi_str[:4] == b"MThd": raise MidiException('badly formated midi string, got: %s' % midi_str[:20]) # we step through the str src, chopping off characters as we go # and reassigning to str length, midi_str = get_number(midi_str[4:], 4) if length != 6: raise MidiException('badly formated midi string') midi_format_type, midi_str = get_number(midi_str, 2) self.format = midi_format_type if midi_format_type not in (0, 1): raise MidiException('cannot handle midi file format: %s' % format) num_tracks, midi_str = get_number(midi_str, 2) division, midi_str = get_number(midi_str, 2) # very few midi files seem to define ticks_per_second if division & 0x8000: frames_per_second = -((division >> 8) | -128) ticks_per_frame = division & 0xFF if ticks_per_frame not in [24, 25, 29, 30]: raise MidiException('cannot handle ticks per frame: %s' % ticks_per_frame) if ticks_per_frame == 29: ticks_per_frame = 30 # drop frame self.ticks_per_second = ticks_per_frame * frames_per_second else: self.ticks_per_quarter_note = division & 0x7FFF for i in range(num_tracks): trk = MidiTrack(i) # sets the MidiTrack index parameters midi_str = trk.read(midi_str) # pass all the remaining string, reassing self.tracks.append(trk) def write(self): ''' Write MIDI data as a file to the file opened with `.open()`. ''' self.file.write(self.writestr()) def writestr(self): ''' generate the midi data header and convert the list of midi_track objects in self_tracks into midi data and return it as a string_ ''' midi_str = self.write_m_thd_str() for trk in self.tracks: midi_str = midi_str + trk.get_bytes() return midi_str def write_m_thd_str(self): ''' convert the information in self_ticks_per_quarter_note into midi data header and return it as a string_''' division = self.ticks_per_quarter_note # Don't handle ticks_per_second yet, too confusing if (division & 0x8000) != 0: raise MidiException( 'Cannot write midi string unless self.ticks_per_quarter_note is a multiple of 1024') midi_str = b"MThd" + put_number(6, 4) + put_number(self.format, 2) midi_str = midi_str + put_number(len(self.tracks), 2) midi_str = midi_str + put_number(division, 2) return midi_str if __name__ == "__main__": import doctest doctest.testmod(optionflags=doctest.ELLIPSIS)
nihlaeth/voicetrainer
voicetrainer/midi.py
Python
gpl-3.0
42,017
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import testtools import openstack.cloud from openstack.cloud import meta from openstack.tests import fakes from openstack.tests.unit import base class TestVolume(base.TestCase): def test_attach_volume(self): server = dict(id='server001') vol = {'id': 'volume001', 'status': 'available', 'name': '', 'attachments': []} volume = meta.obj_to_munch(fakes.FakeVolume(**vol)) rattach = {'server_id': server['id'], 'device': 'device001', 'volumeId': volume['id'], 'id': 'attachmentId'} self.register_uris([ dict(method='POST', uri=self.get_mock_url( 'compute', 'public', append=['servers', server['id'], 'os-volume_attachments']), json={'volumeAttachment': rattach}, validate=dict(json={ 'volumeAttachment': { 'volumeId': vol['id']}}) )]) ret = self.cloud.attach_volume(server, volume, wait=False) self.assertEqual(rattach, ret) self.assert_calls() def test_attach_volume_exception(self): server = dict(id='server001') vol = {'id': 'volume001', 'status': 'available', 'name': '', 'attachments': []} volume = meta.obj_to_munch(fakes.FakeVolume(**vol)) self.register_uris([ dict(method='POST', uri=self.get_mock_url( 'compute', 'public', append=['servers', server['id'], 'os-volume_attachments']), status_code=404, validate=dict(json={ 'volumeAttachment': { 'volumeId': vol['id']}}) )]) with testtools.ExpectedException( openstack.cloud.OpenStackCloudURINotFound, "Error attaching volume %s to server %s" % ( volume['id'], server['id']) ): self.cloud.attach_volume(server, volume, wait=False) self.assert_calls() def test_attach_volume_wait(self): server = dict(id='server001') vol = {'id': 'volume001', 'status': 'available', 'name': '', 'attachments': []} volume = meta.obj_to_munch(fakes.FakeVolume(**vol)) vol['attachments'] = [{'server_id': server['id'], 'device': 'device001'}] vol['status'] = 'attached' attached_volume = meta.obj_to_munch(fakes.FakeVolume(**vol)) rattach = {'server_id': server['id'], 'device': 'device001', 'volumeId': volume['id'], 'id': 'attachmentId'} self.register_uris([ dict(method='POST', uri=self.get_mock_url( 'compute', 'public', append=['servers', server['id'], 'os-volume_attachments']), json={'volumeAttachment': rattach}, validate=dict(json={ 'volumeAttachment': { 'volumeId': vol['id']}})), dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={'volumes': [volume]}), dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={'volumes': [attached_volume]})]) # defaults to wait=True ret = self.cloud.attach_volume(server, volume) self.assertEqual(rattach, ret) self.assert_calls() def test_attach_volume_wait_error(self): server = dict(id='server001') vol = {'id': 'volume001', 'status': 'available', 'name': '', 'attachments': []} volume = meta.obj_to_munch(fakes.FakeVolume(**vol)) vol['status'] = 'error' errored_volume = meta.obj_to_munch(fakes.FakeVolume(**vol)) rattach = {'server_id': server['id'], 'device': 'device001', 'volumeId': volume['id'], 'id': 'attachmentId'} self.register_uris([ dict(method='POST', uri=self.get_mock_url( 'compute', 'public', append=['servers', server['id'], 'os-volume_attachments']), json={'volumeAttachment': rattach}, validate=dict(json={ 'volumeAttachment': { 'volumeId': vol['id']}})), dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={'volumes': [errored_volume]})]) with testtools.ExpectedException( openstack.cloud.OpenStackCloudException, "Error in attaching volume %s" % errored_volume['id'] ): self.cloud.attach_volume(server, volume) self.assert_calls() def test_attach_volume_not_available(self): server = dict(id='server001') volume = dict(id='volume001', status='error', attachments=[]) with testtools.ExpectedException( openstack.cloud.OpenStackCloudException, "Volume %s is not available. Status is '%s'" % ( volume['id'], volume['status']) ): self.cloud.attach_volume(server, volume) self.assertEqual(0, len(self.adapter.request_history)) def test_attach_volume_already_attached(self): device_id = 'device001' server = dict(id='server001') volume = dict(id='volume001', attachments=[ {'server_id': 'server001', 'device': device_id} ]) with testtools.ExpectedException( openstack.cloud.OpenStackCloudException, "Volume %s already attached to server %s on device %s" % ( volume['id'], server['id'], device_id) ): self.cloud.attach_volume(server, volume) self.assertEqual(0, len(self.adapter.request_history)) def test_detach_volume(self): server = dict(id='server001') volume = dict(id='volume001', attachments=[ {'server_id': 'server001', 'device': 'device001'} ]) self.register_uris([ dict(method='DELETE', uri=self.get_mock_url( 'compute', 'public', append=['servers', server['id'], 'os-volume_attachments', volume['id']]))]) self.cloud.detach_volume(server, volume, wait=False) self.assert_calls() def test_detach_volume_exception(self): server = dict(id='server001') volume = dict(id='volume001', attachments=[ {'server_id': 'server001', 'device': 'device001'} ]) self.register_uris([ dict(method='DELETE', uri=self.get_mock_url( 'compute', 'public', append=['servers', server['id'], 'os-volume_attachments', volume['id']]), status_code=404)]) with testtools.ExpectedException( openstack.cloud.OpenStackCloudURINotFound, "Error detaching volume %s from server %s" % ( volume['id'], server['id']) ): self.cloud.detach_volume(server, volume, wait=False) self.assert_calls() def test_detach_volume_wait(self): server = dict(id='server001') attachments = [{'server_id': 'server001', 'device': 'device001'}] vol = {'id': 'volume001', 'status': 'attached', 'name': '', 'attachments': attachments} volume = meta.obj_to_munch(fakes.FakeVolume(**vol)) vol['status'] = 'available' vol['attachments'] = [] avail_volume = meta.obj_to_munch(fakes.FakeVolume(**vol)) self.register_uris([ dict(method='DELETE', uri=self.get_mock_url( 'compute', 'public', append=['servers', server['id'], 'os-volume_attachments', volume.id])), dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={'volumes': [avail_volume]})]) self.cloud.detach_volume(server, volume) self.assert_calls() def test_detach_volume_wait_error(self): server = dict(id='server001') attachments = [{'server_id': 'server001', 'device': 'device001'}] vol = {'id': 'volume001', 'status': 'attached', 'name': '', 'attachments': attachments} volume = meta.obj_to_munch(fakes.FakeVolume(**vol)) vol['status'] = 'error' vol['attachments'] = [] errored_volume = meta.obj_to_munch(fakes.FakeVolume(**vol)) self.register_uris([ dict(method='DELETE', uri=self.get_mock_url( 'compute', 'public', append=['servers', server['id'], 'os-volume_attachments', volume.id])), dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={'volumes': [errored_volume]})]) with testtools.ExpectedException( openstack.cloud.OpenStackCloudException, "Error in detaching volume %s" % errored_volume['id'] ): self.cloud.detach_volume(server, volume) self.assert_calls() def test_delete_volume_deletes(self): vol = {'id': 'volume001', 'status': 'attached', 'name': '', 'attachments': []} volume = meta.obj_to_munch(fakes.FakeVolume(**vol)) self.register_uris([ dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={'volumes': [volume]}), dict(method='DELETE', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', volume.id])), dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={'volumes': []})]) self.assertTrue(self.cloud.delete_volume(volume['id'])) self.assert_calls() def test_delete_volume_gone_away(self): vol = {'id': 'volume001', 'status': 'attached', 'name': '', 'attachments': []} volume = meta.obj_to_munch(fakes.FakeVolume(**vol)) self.register_uris([ dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={'volumes': [volume]}), dict(method='DELETE', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', volume.id]), status_code=404)]) self.assertFalse(self.cloud.delete_volume(volume['id'])) self.assert_calls() def test_delete_volume_force(self): vol = {'id': 'volume001', 'status': 'attached', 'name': '', 'attachments': []} volume = meta.obj_to_munch(fakes.FakeVolume(**vol)) self.register_uris([ dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={'volumes': [volume]}), dict(method='POST', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', volume.id, 'action']), validate=dict( json={'os-force_delete': None})), dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={'volumes': []})]) self.assertTrue(self.cloud.delete_volume(volume['id'], force=True)) self.assert_calls() def test_set_volume_bootable(self): vol = {'id': 'volume001', 'status': 'attached', 'name': '', 'attachments': []} volume = meta.obj_to_munch(fakes.FakeVolume(**vol)) self.register_uris([ dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={'volumes': [volume]}), dict(method='POST', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', volume.id, 'action']), json={'os-set_bootable': {'bootable': True}}), ]) self.cloud.set_volume_bootable(volume['id']) self.assert_calls() def test_set_volume_bootable_false(self): vol = {'id': 'volume001', 'status': 'attached', 'name': '', 'attachments': []} volume = meta.obj_to_munch(fakes.FakeVolume(**vol)) self.register_uris([ dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={'volumes': [volume]}), dict(method='POST', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', volume.id, 'action']), json={'os-set_bootable': {'bootable': False}}), ]) self.cloud.set_volume_bootable(volume['id']) self.assert_calls() def test_list_volumes_with_pagination(self): vol1 = meta.obj_to_munch(fakes.FakeVolume('01', 'available', 'vol1')) vol2 = meta.obj_to_munch(fakes.FakeVolume('02', 'available', 'vol2')) self.register_uris([ dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={ 'volumes': [vol1], 'volumes_links': [ {'href': self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail'], qs_elements=['marker=01']), 'rel': 'next'}]}), dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail'], qs_elements=['marker=01']), json={ 'volumes': [vol2], 'volumes_links': [ {'href': self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail'], qs_elements=['marker=02']), 'rel': 'next'}]}), dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail'], qs_elements=['marker=02']), json={'volumes': []})]) self.assertEqual( [self.cloud._normalize_volume(vol1), self.cloud._normalize_volume(vol2)], self.cloud.list_volumes()) self.assert_calls() def test_list_volumes_with_pagination_next_link_fails_once(self): vol1 = meta.obj_to_munch(fakes.FakeVolume('01', 'available', 'vol1')) vol2 = meta.obj_to_munch(fakes.FakeVolume('02', 'available', 'vol2')) self.register_uris([ dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={ 'volumes': [vol1], 'volumes_links': [ {'href': self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail'], qs_elements=['marker=01']), 'rel': 'next'}]}), dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail'], qs_elements=['marker=01']), status_code=404), dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={ 'volumes': [vol1], 'volumes_links': [ {'href': self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail'], qs_elements=['marker=01']), 'rel': 'next'}]}), dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail'], qs_elements=['marker=01']), json={ 'volumes': [vol2], 'volumes_links': [ {'href': self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail'], qs_elements=['marker=02']), 'rel': 'next'}]}), dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail'], qs_elements=['marker=02']), json={'volumes': []})]) self.assertEqual( [self.cloud._normalize_volume(vol1), self.cloud._normalize_volume(vol2)], self.cloud.list_volumes()) self.assert_calls() def test_list_volumes_with_pagination_next_link_fails_all_attempts(self): vol1 = meta.obj_to_munch(fakes.FakeVolume('01', 'available', 'vol1')) uris = [] attempts = 5 for i in range(attempts): uris.extend([ dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={ 'volumes': [vol1], 'volumes_links': [ {'href': self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail'], qs_elements=['marker=01']), 'rel': 'next'}]}), dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail'], qs_elements=['marker=01']), status_code=404)]) self.register_uris(uris) # Check that found volumes are returned even if pagination didn't # complete because call to get next link 404'ed for all the allowed # attempts self.assertEqual( [self.cloud._normalize_volume(vol1)], self.cloud.list_volumes()) self.assert_calls() def test_get_volume_by_id(self): vol1 = meta.obj_to_munch(fakes.FakeVolume('01', 'available', 'vol1')) self.register_uris([ dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', '01']), json={'volume': vol1} ) ]) self.assertEqual( self.cloud._normalize_volume(vol1), self.cloud.get_volume_by_id('01')) self.assert_calls() def test_create_volume(self): vol1 = meta.obj_to_munch(fakes.FakeVolume('01', 'available', 'vol1')) self.register_uris([ dict(method='POST', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes']), json={'volume': vol1}, validate=dict(json={ 'volume': { 'size': 50, 'name': 'vol1', }})), dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={'volumes': [vol1]}), ]) self.cloud.create_volume(50, name='vol1') self.assert_calls() def test_create_bootable_volume(self): vol1 = meta.obj_to_munch(fakes.FakeVolume('01', 'available', 'vol1')) self.register_uris([ dict(method='POST', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes']), json={'volume': vol1}, validate=dict(json={ 'volume': { 'size': 50, 'name': 'vol1', }})), dict(method='GET', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', 'detail']), json={'volumes': [vol1]}), dict(method='POST', uri=self.get_mock_url( 'volumev2', 'public', append=['volumes', '01', 'action']), validate=dict( json={'os-set_bootable': {'bootable': True}})), ]) self.cloud.create_volume(50, name='vol1', bootable=True) self.assert_calls()
ctrlaltdel/neutrinator
vendor/openstack/tests/unit/cloud/test_volume.py
Python
gpl-3.0
22,754
# frozen_string_literal: true module ActiveJob # Returns the version of the currently loaded Active Job as a <tt>Gem::Version</tt> def self.gem_version Gem::Version.new VERSION::STRING end module VERSION MAJOR = 5 MINOR = 2 TINY = 6 PRE = nil STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end end
BeGe78/esood
vendor/bundle/ruby/3.0.0/gems/activejob-5.2.6/lib/active_job/gem_version.rb
Ruby
gpl-3.0
344
require 'y_support/all' # Places are basically glorified variables, with current contents (marking), and # default contents (default_marking). # class Place attr_reader :name, :default_marking attr_accessor :marking def initialize name, default_marking=0 @name, @default_marking = name, default_marking end def reset!; @marking = default_marking end end # Transitions specify how marking changes when the transition "fires" (activates). # "Arcs" attribute is a hash of { place => change } pairs. # class Transition attr_reader :name, :arcs def initialize( name, arcs: {} ) @name, @arcs = name, arcs end def fire! arcs.each { |place, change| place.marking = place.marking + change } end end A, B, C = Place.new( "A" ), Place.new( "B" ), Place.new( "C" ) # Marking of A is incremented by 1 AddA = Transition.new( "AddA", arcs: { A => 1 } ) # 1 piece of A dissociates into 1 piece of B and 1 piece of C DissocA = Transition.new( "DissocA", arcs: { A => -1, B => +1, C => +1 } ) [ A, B, C ].each &:reset! [ A, B, C ].map &:marking #=> [0, 0, 0] AddA.fire! [ A, B, C ].map &:marking #=> [1, 0, 0] DissocA.fire! [ A, B, C ].map &:marking #=> [0, 1, 1] require 'yaml' class Place def to_yaml YAML.dump( { name: name, default_marking: default_marking } ) end def to_ruby "Place( name: #{name}, default_marking: #{default_marking} )\n" end end puts A.to_yaml puts B.to_yaml puts C.to_yaml puts A.to_ruby puts B.to_ruby puts C.to_ruby class Transition def to_yaml YAML.dump( { name: name, arcs: arcs.modify { |k, v| [k.name, v] } } ) end def to_ruby "Transition( name: #{name}, default_marking: #{arcs.modify { |k, v| [k.name.to_sym, v] }} )\n" end end puts AddA.to_yaml puts DissocA.to_yaml puts AddA.to_ruby puts DissocA.to_ruby # Now save that to a file # and use Place.from_yaml YAML.load( yaml_place_string ) Transition.from_yaml YAML.load( yaml_transition_string ) # or YNelson::Manipulator.load( yaml: YAML.load( system_definition ) ) # then decorate #to_yaml and #to_ruby methods with Zz-structure-specific parts. class Zz def to_yaml super + "\n" + YAML.dump( { along: dump_connectivity() } ) end def to_ruby super + "\n" + "#{name}.along( #{dimension} ).posward #{along( dimension ).posward.name}\n" + "#{name}.along( #{dimension} ).negward #{along( dimension ).negward.name}" end end # etc.
boris-s/y_nelson
test/mongoid_example.rb
Ruby
gpl-3.0
2,409