repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
xbegault/clrh-idf
plugins/system/nnframework/fields/editor.php
1156
<?php /** * Element: Editor * Displays an HTML editor text field * * @package NoNumber Framework * @version 15.1.1 * * @author Peter van Westen <[email protected]> * @link http://www.nonumber.nl * @copyright Copyright © 2015 NoNumber All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ defined('_JEXEC') or die; class JFormFieldNN_Editor extends JFormField { public $type = 'Editor'; private $params = null; protected function getLabel() { return ''; } protected function getInput() { $this->params = $this->element->attributes(); $width = $this->get('width', '100%'); $height = $this->get('height', 400); $this->value = htmlspecialchars($this->value, ENT_COMPAT, 'UTF-8'); // Get an editor object. $editor = JFactory::getEditor(); $html = $editor->display($this->name, $this->value, $width, $height, true, $this->id); return $html . '<br clear="all" />'; } private function get($val, $default = '') { return (isset($this->params[$val]) && (string) $this->params[$val] != '') ? (string) $this->params[$val] : $default; } }
gpl-2.0
ceroberoz/fire-dragon-and-roar
application/modules/property_site/views/ipapa/admin/account.php
11079
<!-- Right side column. Contains the navbar and content of the page --> <aside class="right-side"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Dashboard <small>Manage Accounts</small> </h1> <ol class="breadcrumb"> <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li> <li class="active">Manage Accounts</li> </ol> </section> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box"> <div class="box-header"> <div class="modal fade" id="add" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Cancel</span></button> <h4 class="modal-title" id="myModalLabel">Add Account</h4> </div> <div class="modal-body"> <!-- <form role="form" class="block" action="<?php echo base_url();?>index.php/admin/home/add_account"> --> <?php echo form_open("admin/account/add");?> <div class="block-inner"> <div class="form-group"> <div class="row"> <div class="col-md-6"> <label>User Name</label> <?php echo form_error('username'); ?> <input placeholder="Full Name" name="username" type="text" class="form-control" value="<?php echo set_value('username');?>"> </div> <div class="col-md-6"> <label>Email</label> <?php echo form_error('email'); ?> <input name="email" type="text" class="form-control" value="<?php echo set_value('email');?>"> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-md-6"> <label>New Password</label> <?php echo form_error('password'); ?> <input name="password" type="password" class="form-control" value="<?php echo set_value('password');?>"> </div> <div class="col-md-6"> <label>Re-type New password</label> <?php echo form_error('password_confirm'); ?> <input name="password_confirm" type="password" class="form-control" value="<?php echo set_value('password_confirm');?>"> </div> </div> </div> <div class="form-group"> <label class="col-md-4 control-label" for="selectbasic">Select Group</label> <div class="col-md-4"> <select id="selectbasic" name="level" class="form-control"> <option value="1">Administrator</option> <!-- <option value="2">Registered User</option> --> <option value="2">Building Management</option> <option value="4">Marketing</option> <option value="5">SEO</option> <option value="6">Editor</option> <option value="">FRU</option> </select> </div> </div> </div> <div class="text-right"> <input type="reset" class="btn btn-default" data-dismiss="modal" value="Cancel"> <input type="submit" class="btn btn-success" value="Add Account"> </div> <?php echo form_close();?> </div> </div> </div> </div> <div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Cancel</span></button> <h4 class="modal-title" id="myModalLabel">Edit Account</h4> </div> <div class="modal-body"> </div> </div> </div> </div> </div><!-- /.box-header --> <div class="row pad col-sm-12 col-md-12"> <div class="col-md-8 col-sm-8 pull-left"> <button class="btn btn-info btn-sm" data-toggle="modal" data-target="#add" ><i class="ion ion-plus"></i> Add New</button> </div> <div class="col-md-4 col-sm-3 text-right"> <i class="fa fa-user-md blue"></i> <?php echo $descBM;?> BM &nbsp; &nbsp; <i class="fa fa-user orange"></i> <?php echo $descFRU;?> FRU &nbsp; &nbsp; <i class="fa fa-lock green"></i> <?php echo $descADM;?> Admin &nbsp; &nbsp; <i class="fa fa-users blue"></i> <?php echo $total;?> Total Users </div> </div><!-- /.row --> <div class="box-body table-responsive"> <table id="" class="table table-bordered table-striped"> <thead> <tr> <th>Status</th> <th><input type="checkbox" /></th> <th>Name</th> <th>Email</th> <th>Last Login</th> <th>Level</th> <th>Action</th> </tr> </thead> <tbody> <?php foreach($users as $user):?> <tr> <td><span class="label <?php if($user->active = '1'){echo "label-success";}else{echo "label-danger";}?>"> &nbsp; <?php if($user->active = '1'){echo "Active";}else{echo "Inactive";}?> &nbsp; </span></td> <td class="small-col"><input type="checkbox" /></td> <td><img class="circle-image" alt="user image" src="<?php echo base_url();?>/assets/ipapa/admin/img/default_user.png"> <?php echo $user->username;?></td> <td><?php echo $user->email;?></td> <td> <?php $epoch = $user->last_login;?> <?php $dt = new DateTime("@$epoch");?> <?php // echo $dt->format('Y-m-d H:i:s');?> <?php echo $dt->format('m-d-Y');?> </td> <td> <?php echo $user->description;?> </td> <td> <a href="<?php echo base_url();?>index.php/admin/account/edit/<?php echo $user->id;?>" class="btn-app"><i class="fa fa-edit"></i> Edit</a> &nbsp; <a onclick="return confirm('Are you sure you want to delete this item?');" href="<?php echo base_url();?>index.php/admin/account/delete/<?php echo $user->id;?>" class="btn-app"><i class="fa fa-minus-square"></i> Delete</a></td> </tr> <?php endforeach;?> <tr> </div> </tbody> <tfoot> </tfoot> </table> </div><!-- /.box-body --> </div><!-- /.box --> </div> </div> </section><!-- /.content --> </aside><!-- /.right-side --> </div><!-- ./wrapper --> <!-- jQuery 2.0.2 --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <!-- jQuery UI 1.10.3 --> <script src="<?php echo base_url();?>/assets/ipapa/admin/js/jquery-ui-1.10.3.min.js" type="text/javascript"></script> <!-- Bootstrap --> <script src="<?php echo base_url();?>/assets/ipapa/admin/js/bootstrap.min.js" type="text/javascript"></script> <!-- Ipapa App --> <script src="<?php echo base_url();?>/assets/ipapa/admin/js/Ipapa/app.js" type="text/javascript"></script> <script src="<?php echo base_url();?>/assets/ipapa/admin/js/plugins/datatables/jquery.dataTables.js" type="text/javascript"></script> <script src="<?php echo base_url();?>/assets/ipapa/admin/js/plugins/datatables/dataTables.bootstrap.js" type="text/javascript"></script> <!-- page script --> <script type="text/javascript"> $(function() { $("#accountlist-view").dataTable(); $('#example2').dataTable({ "bPaginate": true, "bLengthChange": false, "bFilter": false, "bSort": true, "bInfo": true, "bAutoWidth": false }); }); </script> </body> </html>
gpl-2.0
dknlght/dkodi
src/script.module.turtle/lib/snapvideo/Vimeo.py
2219
''' Created on Dec 24, 2011 @author: ajju ''' from BeautifulSoup import BeautifulStoneSoup from common import HttpUtils from common.DataObjects import VideoHostingInfo, VideoInfo, VIDEO_QUAL_SD, \ VIDEO_QUAL_HD_720 def getVideoHostingInfo(): video_hosting_info = VideoHostingInfo() video_hosting_info.set_video_hosting_image('http://cdn1.iconfinder.com/data/icons/Social_Networking_Icons_PNG/PNG/Vimeo.png') video_hosting_info.set_video_hosting_name('Vimeo') return video_hosting_info def retrieveVideoInfo(video_id): video_info = VideoInfo() video_info.set_video_hosting_info(getVideoHostingInfo()) video_info.set_video_id(video_id) try: video_info_link = 'http://www.vimeo.com/moogaloop/load/clip:' + str(video_id) soup = BeautifulStoneSoup(HttpUtils.HttpClient().getHtmlContent(url=video_info_link), convertEntities=BeautifulStoneSoup.XML_ENTITIES) referrerObj = soup.findChild(name='referrer') req_sig = referrerObj.findChild(name='request_signature').getText() req_sig_exp = referrerObj.findChild(name='request_signature_expires').getText() videoObj = soup.findChild(name='video') img_link = videoObj.findChild(name='thumbnail').getText() video_title = videoObj.findChild(name='caption').getText() qual = 'sd' video_link = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=H264,VP8,VP6&type=moogaloop_local&embed_location=" % (video_id, req_sig, req_sig_exp, qual) video_info.add_video_link(VIDEO_QUAL_SD, video_link) if(videoObj.findChild(name='ishd').getText() == '1'): qual = 'hd' video_link = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=H264,VP8,VP6&type=moogaloop_local&embed_location=" % (video_id, req_sig, req_sig_exp, qual) video_info.add_video_link(VIDEO_QUAL_HD_720, video_link) video_info.set_video_stopped(False) video_info.set_video_image(img_link) video_info.set_video_name(video_title) except: video_info.set_video_stopped(True) return video_info
gpl-2.0
lbehnke/hermesftp
src/main/java/com/apporiented/hermesftp/console/AbstractConsoleServlet.java
7646
/* * ------------------------------------------------------------------------------ * Hermes FTP Server * Copyright (c) 2005-2014 Lars Behnke * ------------------------------------------------------------------------------ * * This file is part of Hermes FTP Server. * * Hermes FTP Server 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. * * Hermes FTP Server 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 Hermes FTP Server; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ------------------------------------------------------------------------------ */ package com.apporiented.hermesftp.console; import java.io.IOException; import java.io.PrintWriter; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.apporiented.hermesftp.utils.IOUtils; import com.apporiented.hermesftp.utils.VarMerger; /** * Abstract super class of the servlets of the FTP console. * * @author Administrator */ public abstract class AbstractConsoleServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final int DEFAULT_REFRESH_SECONDS = 10; private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private static final NumberFormat NUM_FORMAT = new DecimalFormat("###,###,###,###,##0"); private static final Date APP_START = new Date(); private static final String TEXT_ENCODING = "UTF-8"; private String headerResourceName = "/console-header.html"; private String footerResourceName = "/console-footer.html"; private String contentResourceName; private int refreshInterval = DEFAULT_REFRESH_SECONDS; /** * {@inheritDoc} */ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String page = readPage(); VarMerger vm = new VarMerger(page); Properties p = new Properties(); p.putAll(System.getProperties()); p.putAll(IOUtils.getAppProperties()); p.putAll(getContentProperties()); p.put("current.date", "" + formatDate(new Date())); p.put("startup.date", "" + formatDate(APP_START)); p.put("refresh.interval", "" + getRefreshInterval()); vm.merge(p); page = vm.getText(); resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.write(page); } private String readPage() throws IOException { StringBuffer responseBuffer = new StringBuffer(); String part; part = IOUtils.loadTextResource(getHeaderResourceName(), TEXT_ENCODING); responseBuffer.append(part); part = IOUtils.loadTextResource(getContentResourceName(), TEXT_ENCODING); responseBuffer.append(part); part = IOUtils.loadTextResource(getFooterResourceName(), TEXT_ENCODING); responseBuffer.append(part); return responseBuffer.toString(); } /** * Creates an HTML table fied (TD element). * * @param sb The stringbuffer to write to. * @param value The value to fill. */ protected void fillField(StringBuffer sb, String value) { sb.append(ConsoleConstants.TD_START_TAG); sb.append(value); sb.append(ConsoleConstants.TD_END_TAG); } /** * Creates an HTML table fied (TD element). * * @param sb The stringbuffer to write to. * @param value The numeric value to fill. */ protected void fillNumField(StringBuffer sb, String value) { sb.append(ConsoleConstants.TD_START_TAG_NUM); sb.append(value); sb.append(ConsoleConstants.TD_END_TAG); } /** * Formats a date value. * * @param date The date to format. * @return The formatted date. */ protected String formatDate(Date date) { return DATE_FORMAT.format(date); } /** * Formats a numeric value. * * @param num The number to format. * @return The formatted number. */ protected String formatNum(Object num) { return NUM_FORMAT.format(num); } /** * Formats a long value. * * @param num The number to format. * @return The formatted number. */ protected String formatNum(long num) { return NUM_FORMAT.format(num); } /** * The content properties object. The properties object represents a mapping of placeholder keys * and their corresponding values. * * @return The properties. */ protected abstract Properties getContentProperties(); /** * Getter methode for property <code>contentResourceName</code>. * * @return Property <code>contentResourceName</code>. */ public String getContentResourceName() { return contentResourceName; } /** * Setter methode for property <code>contentResourceName</code>. * * @param contentResourceName Value for content resource name. */ public void setContentResourceName(String contentResourceName) { this.contentResourceName = contentResourceName; } /** * Getter methode for property <code>footerResourceName</code>. * * @return Property <code>footerResourceName</code>. */ public String getFooterResourceName() { return footerResourceName; } /** * Setter methode for property <code>footerResourceName</code>. * * @param footerResourceName Value for <code>footerResourceName</code>. */ public void setFooterResourceName(String footerResourceName) { this.footerResourceName = footerResourceName; } /** * Getter methode for property <code>headerResourceName</code>. * * @return Property <code>headerResourceName</code>. */ public String getHeaderResourceName() { return headerResourceName; } /** * Setter methode for property <code>headerResourceName</code>. * * @param headerResourceName Value for <code>headerResourceName</code>. */ public void setHeaderResourceName(String headerResourceName) { this.headerResourceName = headerResourceName; } /** * Getter methode for property <code>refreshInterval</code>. * * @return Property <code>refreshInterval</code>. */ public int getRefreshInterval() { return refreshInterval; } /** * Setter methode for property <code>refreshInterval</code>. * * @param refreshInterval Value for <code>refreshInterval</code>. */ public void setRefreshInterval(int refreshInterval) { this.refreshInterval = refreshInterval; } }
gpl-2.0
michael9999/bc-portal
wp-content/plugins/google-identity-toolkit/git/callback.php
382
<?php require_once('handler/gitCallbackHandler.php'); $inputEmail = isset($_GET['rp_input_email']) ? $_GET['rp_input_email'] : ''; $purpose = isset($_GET['rp_purpose']) ? $_GET['rp_purpose'] : ''; $url = gitUtil::getCurrentUrl(); $idpResponse = @file_get_contents('php://input'); $handler = new gitCallbackHandler($inputEmail, $purpose, $url, $idpResponse); $handler->execute();
gpl-2.0
seanwooj/Forage
wp-content/themes/forage/content.php
961
<?php /** * Content * * Displays content shown in the 'index.php' loop, default for 'standard' post format * * @package WordPress * @subpackage Foundation, for WordPress * @since Foundation, for WordPress 4.0 */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php if ( has_post_thumbnail()) : ?> <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" ><?php the_post_thumbnail(); ?></a> <?php endif; ?> <header> <hgroup> <h3><a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( __( 'Permalink to %s', 'foundation' ), the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h3> <?php if ( is_sticky() ) : ?><span class="right radius secondary label"><?php _e( 'Sticky', 'foundation' ); ?></span><?php endif; ?> <h6 class="georgia"><?php the_time(get_option('date_format')); ?></h6> </hgroup> </header> <?php the_excerpt(); ?> <hr> </article>
gpl-2.0
pdzion/fc-100
source/src/vm/mz700/quickdisk.cpp
11485
/* SHARP MZ-800 Emulator 'EmuZ-800' SHARP MZ-1500 Emulator 'EmuZ-1500' Skelton for retropc emulator Author : Takeda.Toshiya Date : 2011.02.17- [ quick disk ] */ #include "quickdisk.h" #include "../z80sio.h" #include "../../fileio.h" #define MZT_HEADER_SIZE 128 #define HEADER_SIZE 64 #define EVENT_RESTORE 0 #define EVENT_END 1 // 100usec #define PERIOD_RESTORE 100 // 1sec #define PERIOD_END 1000000 #define DATA_SYNC1 0x16 #define DATA_SYNC2 0x16 #define DATA_MARK 0xa5 #define DATA_CRC1 'C' #define DATA_CRC2 'R' #define DATA_CRC3 'C' #define DATA_BREAK 0x100 #define DATA_EMPTY 0x101 #define HEADER_BLOCK_ID 0 #define DATA_BLOCK_ID 1 void QUICKDISK::initialize() { insert = protect = false; home = true; } void QUICKDISK::release() { release_disk(); } void QUICKDISK::reset() { wrga = mton = true; sync = false; motor_on = false; accessed = false; restore_id = end_id = -1; set_insert(insert); set_protect(protect); set_home(true); } /* PROTECT -> CTSA H: write protected INSERT -> DCDA L: inserted HOME -> DCDB L: reach to head position H: reset, reach to end of disk, DTRB is L->H RTSA -> WRGA L: write disk / stop motor at the end of disk H: read disk DTRB -> MTON H->L: start motor H: stop motor at the end of disk */ #define REGISTER_RESTORE_EVENT() { \ if(restore_id == -1) { \ register_event(this, EVENT_RESTORE, PERIOD_RESTORE, false, &restore_id); \ } \ } #define CANCEL_RESTORE_EVENT() { \ if(restore_id != -1) { \ cancel_event(restore_id); \ restore_id = -1; \ } \ } #define REGISTER_END_EVENT() { \ if(end_id != -1) { \ cancel_event(end_id); \ } \ register_event(this, EVENT_END, PERIOD_END, false, &end_id); \ } #define CANCEL_END_EVENT() { \ if(end_id != -1) { \ cancel_event(end_id); \ end_id = -1; \ } \ } #define WRITE_BUFFER(v) { \ if(buffer_ptr < QUICKDISK_BUFFER_SIZE) { \ if(buffer[buffer_ptr] != v) { \ buffer[buffer_ptr] = v; \ modified = true; \ } \ buffer_ptr++; \ } \ } void QUICKDISK::write_signal(int id, uint32 data, uint32 mask) { bool next = ((data & mask) != 0); if(id == QUICKDISK_SIO_RTSA) { if(wrga && !next) { // start to write first_data = true; write_ptr = 0; } else if(!wrga && next) { // end to write write_crc(); } wrga = next; } else if(id == QUICKDISK_SIO_DTRB) { if(mton && !next) { // H->L: start motor if(motor_on && wrga) { // restart to send send_data(); REGISTER_END_EVENT(); } else { // start motor and restore to home position motor_on = true; REGISTER_RESTORE_EVENT(); CANCEL_END_EVENT(); } } else if(!mton && next) { // L->H: home signal is high set_home(true); } mton = next; } else if(id == QUICKDISK_SIO_SYNC) { // enter hunt/sync phase sync = next; if(sync) { // hack: start to send for verify if(!wrga) { write_crc(); wrga = true; } send_data(); } } else if(id == QUICKDISK_SIO_RXDONE) { // send next data send_data(); } else if(id == QUICKDISK_SIO_DATA || id == QUICKDISK_SIO_BREAK) { // write data if(!(motor_on && !wrga)) { return; } if(id == QUICKDISK_SIO_DATA) { if(first_data) { // write sync chars at the top of message WRITE_BUFFER(DATA_SYNC1); WRITE_BUFFER(DATA_SYNC2); first_data = false; } WRITE_BUFFER(data); write_ptr = buffer_ptr; } else if(id == QUICKDISK_SIO_BREAK) { write_crc(); WRITE_BUFFER(DATA_BREAK); first_data = true; write_ptr = 0; } accessed = true; if(buffer_ptr < QUICKDISK_BUFFER_SIZE) { REGISTER_END_EVENT(); } else { CANCEL_END_EVENT(); end_of_disk(); } } } uint32 QUICKDISK::read_signal(int ch) { // access lamp signal if(accessed) { accessed = false; return 1; } return 0; } void QUICKDISK::event_callback(int event_id, int err) { if(event_id == EVENT_RESTORE) { // reached to home position restore_id = -1; restore(); } else if(event_id == EVENT_END) { // reached to end of disk end_id = -1; end_of_disk(); } } void QUICKDISK::restore() { // reached to home position set_home(false); buffer_ptr = 0; // start to send send_data(); } void QUICKDISK::send_data() { if(!(motor_on && wrga) || restore_id != -1) { return; } retry: if(buffer_ptr < QUICKDISK_BUFFER_SIZE && buffer[buffer_ptr] != DATA_EMPTY) { if(buffer[buffer_ptr] == DATA_BREAK) { // wait until sio enters hunt/sync phase if(!sync) { return; } buffer_ptr++; goto retry; } // send data d_sio->write_signal(SIG_Z80SIO_RECV_CH0, buffer[buffer_ptr++], 0xff); accessed = true; REGISTER_END_EVENT(); } else { // reached to end of disk CANCEL_END_EVENT(); end_of_disk(); } } void QUICKDISK::write_crc() { if(!wrga && write_ptr != 0) { buffer_ptr = write_ptr; WRITE_BUFFER(DATA_CRC1); WRITE_BUFFER(DATA_CRC2); WRITE_BUFFER(DATA_CRC3); WRITE_BUFFER(0); // don't increment pointer !!! WRITE_BUFFER(DATA_BREAK); buffer_ptr--; } write_ptr = 0; } void QUICKDISK::end_of_disk() { // write crc write_crc(); // reached to end of disk if(mton || !wrga) { motor_on = false; } else { REGISTER_RESTORE_EVENT(); } set_home(true); } void QUICKDISK::set_insert(bool val) { // L=inserted d_sio->write_signal(SIG_Z80SIO_DCD_CH0, val ? 0 : 1, 1); insert = val; } void QUICKDISK::set_protect(bool val) { // H=protected d_sio->write_signal(SIG_Z80SIO_CTS_CH0, val ? 1 : 0, 1); protect = val; } void QUICKDISK::set_home(bool val) { if(home != val) { d_sio->write_signal(SIG_Z80SIO_DCD_CH1, val ? 1 : 0, 1); home = val; } } void QUICKDISK::open_disk(_TCHAR path[]) { // check current disk image if(insert) { if(_tcsicmp(file_path, path) == 0) { return; } // close current disk close_disk(); } memset(buffer, 0, sizeof(buffer)); // load disk image FILEIO* fio = new FILEIO(); if(fio->Fopen(path, FILEIO_READ_BINARY)) { _tcscpy(file_path, path); modified = false; fio->Fseek(0, FILEIO_SEEK_END); int remain = fio->Ftell(); fio->Fseek(0, FILEIO_SEEK_SET); int num_block = 0; int block_num_ptr = 0; // clear buffer memset(buffer, DATA_EMPTY, sizeof(buffer)); buffer_ptr = 0; // create block file buffer[buffer_ptr++] = DATA_BREAK; buffer[buffer_ptr++] = DATA_SYNC1; buffer[buffer_ptr++] = DATA_SYNC2; buffer[buffer_ptr++] = DATA_MARK; block_num_ptr = buffer_ptr; buffer[buffer_ptr++] = 0; // block number buffer[buffer_ptr++] = DATA_CRC1; buffer[buffer_ptr++] = DATA_CRC2; buffer[buffer_ptr++] = DATA_CRC3; buffer[buffer_ptr++] = 0; // dummy buffer[buffer_ptr++] = DATA_BREAK; while(remain >= MZT_HEADER_SIZE) { // load header uint8 header[MZT_HEADER_SIZE], ram[0x20000]; fio->Fread(header, MZT_HEADER_SIZE, 1); remain -= MZT_HEADER_SIZE; // load data int size = header[0x12] | (header[0x13] << 8); int offs = header[0x14] | (header[0x15] << 8); memset(ram, 0, sizeof(ram)); fio->Fread(ram + offs, size, 1); remain -= size; #if 0 // apply mz700win patch if(header[0x40] == 'P' && header[0x41] == 'A' && header[0x42] == 'T' && header[0x43] == ':') { int patch_ofs = 0x44; for(; patch_ofs < 0x80; ) { uint16 patch_addr = header[patch_ofs] | (header[patch_ofs + 1] << 8); patch_ofs += 2; if(patch_addr == 0xffff) { break; } int patch_len = header[patch_ofs++]; for(int i = 0; i < patch_len; i++) { ram[patch_addr + i] = header[patch_ofs++]; } } // clear patch data for(int i = 0x40; i < patch_ofs; i++) { header[i] = 0; } } #endif // copy header buffer[block_num_ptr] = ++num_block; buffer[buffer_ptr++] = DATA_SYNC1; buffer[buffer_ptr++] = DATA_SYNC2; buffer[buffer_ptr++] = DATA_MARK; buffer[buffer_ptr++] = HEADER_BLOCK_ID; buffer[buffer_ptr++] = HEADER_SIZE; buffer[buffer_ptr++] = 0; buffer[buffer_ptr++] = header[0]; // attribute for(int i = 0; i < 17; i++) { buffer[buffer_ptr++] = header[i + 1]; // file name } buffer[buffer_ptr++] = header[0x3e]; // lock buffer[buffer_ptr++] = header[0x3f]; // secret buffer[buffer_ptr++] = header[0x12]; // file size buffer[buffer_ptr++] = header[0x13]; buffer[buffer_ptr++] = header[0x14]; // load addr buffer[buffer_ptr++] = header[0x15]; buffer[buffer_ptr++] = header[0x16]; // exec addr buffer[buffer_ptr++] = header[0x17]; for(int i = 26; i < HEADER_SIZE; i++) { buffer[buffer_ptr++] = 0; // comment } buffer[buffer_ptr++] = DATA_CRC1; buffer[buffer_ptr++] = DATA_CRC2; buffer[buffer_ptr++] = DATA_CRC3; buffer[buffer_ptr++] = 0; // dummy buffer[buffer_ptr++] = DATA_BREAK; // copy data buffer[block_num_ptr] = ++num_block; buffer[buffer_ptr++] = DATA_SYNC1; buffer[buffer_ptr++] = DATA_SYNC2; buffer[buffer_ptr++] = DATA_MARK; buffer[buffer_ptr++] = DATA_BLOCK_ID; buffer[buffer_ptr++] = (uint8)(size & 0xff); buffer[buffer_ptr++] = (uint8)(size >> 8); for(int i = 0; i < size; i++) { buffer[buffer_ptr++] = ram[offs + i]; } buffer[buffer_ptr++] = DATA_CRC1; buffer[buffer_ptr++] = DATA_CRC2; buffer[buffer_ptr++] = DATA_CRC3; buffer[buffer_ptr++] = 0; // dummy buffer[buffer_ptr++] = DATA_BREAK; } set_insert(true); set_protect(fio->IsProtected(path)); set_home(true); fio->Fclose(); } delete fio; } void QUICKDISK::close_disk() { release_disk(); set_insert(false); set_protect(false); set_home(true); // cancel all events CANCEL_RESTORE_EVENT(); CANCEL_END_EVENT(); } void QUICKDISK::release_disk() { if(insert && !protect && modified) { // save blocks FILEIO* fio = new FILEIO(); if(fio->Fopen(file_path, FILEIO_WRITE_BINARY)) { int block_num = buffer[4]; buffer_ptr = 10; for(int i = 0; i < block_num; i++) { int id = buffer[buffer_ptr + 3] & 3; int size = buffer[buffer_ptr + 4] | (buffer[buffer_ptr + 5] << 8); buffer_ptr += 6; if(id == HEADER_BLOCK_ID) { // create mzt header uint8 header[MZT_HEADER_SIZE]; memset(header, 0, sizeof(header)); header[0x00] = (uint8)buffer[buffer_ptr + 0]; // attribute for(int i = 1; i <= 17; i++) { header[i] = (uint8)buffer[buffer_ptr + i]; // file name } header[0x3e] = (uint8)buffer[buffer_ptr + 18]; // lock header[0x3f] = (uint8)buffer[buffer_ptr + 19]; // lock header[0x12] = (uint8)buffer[buffer_ptr + 20]; // file size header[0x13] = (uint8)buffer[buffer_ptr + 21]; header[0x14] = (uint8)buffer[buffer_ptr + 22]; // load addr header[0x15] = (uint8)buffer[buffer_ptr + 23]; header[0x16] = (uint8)buffer[buffer_ptr + 24]; // exec addr header[0x17] = (uint8)buffer[buffer_ptr + 25]; fio->Fwrite(header, MZT_HEADER_SIZE, 1); } else { // data for(int i = 0; i < size; i++) { fio->Fputc(buffer[buffer_ptr + i]); } } buffer_ptr += size + 5; } fio->Fclose(); } delete fio; } }
gpl-2.0
iclosure/jframework
src/3rdpart/BCGCBPro/BCGPControlRenderer.cpp
28754
//******************************************************************************* // COPYRIGHT NOTES // --------------- // This is a part of the BCGControlBar Library // Copyright (C) 1998-2014 BCGSoft Ltd. // All rights reserved. // // This source code can be used, distributed or modified // only under terms and conditions // of the accompanying license agreement. //******************************************************************************* // // BCGPControlRenderer.cpp: implementation of the CBCGPControlRenderer class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "BCGPControlRenderer.h" #include "BCGPDrawManager.h" #include "BCGGlobals.h" #include "BCGPImageProcessing.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif CBCGPControlRendererParams::CBCGPControlRendererParams () { CommonInit (); } CBCGPControlRendererParams::~CBCGPControlRendererParams () { } CBCGPControlRendererParams::CBCGPControlRendererParams (UINT uiBmpResID, const CRect& rtImage, const CRect& rtCorners, const CRect& rtSides/* = CRect (0, 0, 0, 0)*/, const CRect& rtInner/* = CRect (0, 0, 0, 0)*/) { CommonInit (); SetResourceID (MAKEINTRESOURCE (uiBmpResID)); m_rectImage = rtImage; m_rectCorners = rtCorners; m_rectSides = rtSides; m_rectInter = rtInner; } CBCGPControlRendererParams::CBCGPControlRendererParams (LPCTSTR lpszBmpResID, const CRect& rtImage, const CRect& rtCorners, const CRect& rtSides/* = CRect (0, 0, 0, 0)*/, const CRect& rtInner/* = CRect (0, 0, 0, 0)*/) { CommonInit (); SetResourceID (lpszBmpResID); m_rectImage = rtImage; m_rectCorners = rtCorners; m_rectSides = rtSides; m_rectInter = rtInner; } CBCGPControlRendererParams::CBCGPControlRendererParams (UINT uiBmpResID, COLORREF clrTransparent, const CRect& rtImage, const CRect& rtCorners, const CRect& rtSides/* = CRect (0, 0, 0, 0)*/, const CRect& rtInner/* = CRect (0, 0, 0, 0)*/, BOOL bPreMultiplyCheck/* = TRUE*/) { CommonInit (); SetResourceID (MAKEINTRESOURCE (uiBmpResID)); m_rectImage = rtImage; m_rectCorners = rtCorners; m_rectSides = rtSides; m_rectInter = rtInner; m_clrTransparent = clrTransparent; m_bPreMultiplyCheck = bPreMultiplyCheck; } CBCGPControlRendererParams::CBCGPControlRendererParams (HBITMAP hBitmap, COLORREF clrTransparent, const CRect& rtImage, const CRect& rtCorners, const CRect& rtSides/* = CRect (0, 0, 0, 0)*/, const CRect& rtInner/* = CRect (0, 0, 0, 0)*/, BOOL bPreMultiplyCheck/* = TRUE*/) { CommonInit (); m_hBitmap = hBitmap; m_rectImage = rtImage; m_rectCorners = rtCorners; m_rectSides = rtSides; m_rectInter = rtInner; m_clrTransparent = clrTransparent; m_bPreMultiplyCheck = bPreMultiplyCheck; } CBCGPControlRendererParams::CBCGPControlRendererParams (LPCTSTR lpszBmpResID, COLORREF clrTransparent, const CRect& rtImage, const CRect& rtCorners, const CRect& rtSides/* = CRect (0, 0, 0, 0)*/, const CRect& rtInner/* = CRect (0, 0, 0, 0)*/, BOOL bPreMultiplyCheck/* = TRUE*/) { CommonInit (); SetResourceID (lpszBmpResID); m_rectImage = rtImage; m_rectCorners = rtCorners; m_rectSides = rtSides; m_rectInter = rtInner; m_clrTransparent = clrTransparent; m_bPreMultiplyCheck = bPreMultiplyCheck; } CBCGPControlRendererParams::CBCGPControlRendererParams (const CBCGPControlRendererParams& rSrc) { CommonInit (); (*this) = rSrc; } void CBCGPControlRendererParams::CommonInit () { m_uiBmpResID = 0; m_hBitmap = NULL; m_strBmpResID.Empty(); m_rectImage.SetRectEmpty (); m_rectCorners.SetRectEmpty (); m_rectSides.SetRectEmpty (); m_rectInter.SetRectEmpty (); m_clrTransparent = CLR_DEFAULT; m_bPreMultiplyCheck = TRUE; m_bMapTo3DColors = FALSE; m_clrBase = (COLORREF)-1; m_clrTarget = (COLORREF)-1; } HBITMAP CBCGPControlRendererParams::GetBitmap() const { return m_hBitmap; } LPCTSTR CBCGPControlRendererParams::GetResourceID () const { if (m_strBmpResID.IsEmpty ()) { return MAKEINTRESOURCE (m_uiBmpResID); } return m_strBmpResID; } void CBCGPControlRendererParams::SetResourceID (LPCTSTR lpszBmpResID) { if (IS_INTRESOURCE(lpszBmpResID)) { m_uiBmpResID = (UINT)((UINT_PTR)(lpszBmpResID)); } else { m_strBmpResID = lpszBmpResID; } } void CBCGPControlRendererParams::SetBaseColor (COLORREF clrBase, COLORREF clrTarget) { m_clrBase = clrBase; m_clrTarget = clrTarget; } CBCGPControlRendererParams& CBCGPControlRendererParams::operator = (const CBCGPControlRendererParams& rSrc) { m_uiBmpResID = rSrc.m_uiBmpResID; m_strBmpResID = rSrc.m_strBmpResID; m_hBitmap = rSrc.m_hBitmap; m_rectImage = rSrc.m_rectImage; m_rectCorners = rSrc.m_rectCorners; m_rectSides = rSrc.m_rectSides; m_rectInter = rSrc.m_rectInter; m_clrTransparent = rSrc.m_clrTransparent; m_bPreMultiplyCheck = rSrc.m_bPreMultiplyCheck; m_clrBase = rSrc.m_clrBase; m_clrTarget = rSrc.m_clrTarget; return *this; } static void RotateRect(CRect& rect, BOOL bCW) { if (bCW) { rect = CRect(rect.bottom, rect.left, rect.top, rect.right); } else { rect = CRect(rect.top, rect.right, rect.bottom, rect.left); } } void CBCGPControlRendererParams::Rotate (BOOL bCW) { RotateRect(m_rectImage, bCW); m_rectImage.NormalizeRect(); RotateRect(m_rectCorners, bCW); RotateRect(m_rectSides, bCW); RotateRect(m_rectInter, bCW); m_rectInter.NormalizeRect(); } IMPLEMENT_DYNCREATE(CBCGPControlRenderer, CObject) ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CBCGPControlRenderer::CBCGPControlRenderer() { m_bMirror = FALSE; m_bIsScaled = FALSE; } //********************************************************************************* CBCGPControlRenderer::~CBCGPControlRenderer() { CleanUp (); } ////////////////////////////////////////////////////////////////////// // Operations ////////////////////////////////////////////////////////////////////// BOOL CBCGPControlRenderer::Create (const CBCGPControlRendererParams& params, BOOL bFlipvert /*= FALSE*/) { CleanUp (); m_Params = params; LPCTSTR lpszResID = m_Params.GetResourceID (); HBITMAP hBitmap = m_Params.GetBitmap(); if (lpszResID != NULL || hBitmap != NULL) { m_Bitmap.SetImageSize (m_Params.m_rectImage.Size ()); m_Bitmap.SetPreMultiplyAutoCheck (m_Params.m_bPreMultiplyCheck); m_Bitmap.SetMapTo3DColors (m_Params.m_bMapTo3DColors); if (hBitmap == NULL) { m_Bitmap.LoadStr (lpszResID); } else { m_Bitmap.AddImage(hBitmap, TRUE); } if (bFlipvert) { m_Bitmap.MirrorVert (); } if (m_Params.m_clrTransparent != CLR_DEFAULT) { m_Bitmap.SetTransparentColor (m_Params.m_clrTransparent); } if (m_Params.m_clrBase != (COLORREF)-1 && m_Params.m_clrTarget != (COLORREF)-1) { m_Bitmap.AddaptColors (m_Params.m_clrBase, m_Params.m_clrTarget); } if (CBCGPToolBarImages::IsRTL () && m_Bitmap.GetImageWell () != NULL && m_Params.m_clrTransparent == CLR_DEFAULT) { BITMAP bmp; if (::GetObject (m_Bitmap.GetImageWell (), sizeof (BITMAP), &bmp) != 0) { if (bmp.bmBitsPixel == 32) { Mirror (); } } } if (m_Params.m_rectSides.IsRectNull ()) { m_Params.m_rectSides = m_Params.m_rectCorners; } if (m_Params.m_rectInter.IsRectNull ()) { m_Params.m_rectInter = CRect (CPoint (0, 0), m_Params.m_rectImage.Size ()); m_Params.m_rectInter.left += m_Params.m_rectCorners.left; m_Params.m_rectInter.top += m_Params.m_rectCorners.top; m_Params.m_rectInter.right -= m_Params.m_rectCorners.right; m_Params.m_rectInter.bottom -= m_Params.m_rectCorners.bottom; } if (bFlipvert) { long temp; temp = m_Params.m_rectCorners.top; m_Params.m_rectCorners.top = m_Params.m_rectCorners.bottom; m_Params.m_rectCorners.bottom = temp; temp = m_Params.m_rectSides.top; m_Params.m_rectSides.top = m_Params.m_rectSides.bottom; m_Params.m_rectSides.bottom = temp; long height = m_Params.m_rectImage.Height (); temp = m_Params.m_rectInter.top; m_Params.m_rectInter.top = height - m_Params.m_rectInter.bottom; m_Params.m_rectInter.bottom = height - temp; } } return TRUE; } //********************************************************************************* void CBCGPControlRenderer::Mirror () { if (m_Bitmap.Mirror ()) { m_bMirror = !m_bMirror; } } //********************************************************************************* void CBCGPControlRenderer::Rotate (BOOL bCW) { HBITMAP hBitmap = m_Bitmap.GetImageWell(); if (hBitmap == NULL) { return; } HBITMAP hBitmapR = BCGPRotateBitmap(hBitmap, bCW); if (hBitmapR == NULL) { return; } m_Params.Rotate (bCW); m_Bitmap.Clear(); m_Bitmap.SetImageSize (m_Params.m_rectImage.Size ()); m_Bitmap.SetPreMultiplyAutoCheck (m_Params.m_bPreMultiplyCheck); m_Bitmap.SetMapTo3DColors (m_Params.m_bMapTo3DColors); if (m_Params.m_clrTransparent != CLR_DEFAULT) { m_Bitmap.SetTransparentColor (m_Params.m_clrTransparent); } m_Bitmap.AddImage(hBitmapR, TRUE); ::DeleteObject(hBitmapR); } //********************************************************************************* void CBCGPControlRenderer::CleanUp () { m_Bitmap.Clear (); m_Bitmap.SetTransparentColor ((COLORREF)(-1)); CBCGPControlRendererParams emptyParams; m_Params = emptyParams; m_bMirror = FALSE; } //********************************************************************************* void CBCGPControlRenderer::Draw (CDC* pDC, CRect rect, UINT index, BYTE alphaSrc/* = 255*/) { CRect rectInter (rect); rectInter.left += m_Params.m_rectSides.left; rectInter.top += m_Params.m_rectSides.top; rectInter.right -= m_Params.m_rectSides.right; rectInter.bottom -= m_Params.m_rectSides.bottom; FillInterior (pDC, rectInter, index, alphaSrc); DrawFrame (pDC, rect, index, alphaSrc); } //********************************************************************************* void CBCGPControlRenderer::DrawFrame (CDC* pDC, CRect rect, UINT index, BYTE alphaSrc/* = 255*/) { struct XHVTypes { CBCGPToolBarImages::ImageAlignHorz horz; CBCGPToolBarImages::ImageAlignVert vert; }; XHVTypes corners[4] = { {CBCGPToolBarImages::ImageAlignHorzLeft , CBCGPToolBarImages::ImageAlignVertTop}, {CBCGPToolBarImages::ImageAlignHorzRight, CBCGPToolBarImages::ImageAlignVertTop}, {CBCGPToolBarImages::ImageAlignHorzLeft , CBCGPToolBarImages::ImageAlignVertBottom}, {CBCGPToolBarImages::ImageAlignHorzRight, CBCGPToolBarImages::ImageAlignVertBottom} }; XHVTypes sides[4] = { {CBCGPToolBarImages::ImageAlignHorzLeft , CBCGPToolBarImages::ImageAlignVertStretch}, {CBCGPToolBarImages::ImageAlignHorzRight , CBCGPToolBarImages::ImageAlignVertStretch}, {CBCGPToolBarImages::ImageAlignHorzStretch, CBCGPToolBarImages::ImageAlignVertTop}, {CBCGPToolBarImages::ImageAlignHorzStretch, CBCGPToolBarImages::ImageAlignVertBottom} }; CRect rectImage (m_Params.m_rectImage); int ind = index; if (m_Bitmap.GetCount () == 1) { rectImage.OffsetRect (0, m_Params.m_rectImage.Size ().cy * ind); ind = 0; } CRect rt (rect); CRect rectCorners (m_Params.m_rectCorners); CRect rectSides (m_Params.m_rectSides); rt.left += rectCorners.left; rt.top += rectCorners.top; rt.right -= rectCorners.right; rt.bottom -= rectCorners.bottom; if (rt.Width () > 0 || rt.Height () > 0) { if (rt.Height () > 0) { if (rectSides.left > 0) { CRect r (rt); r.left = rect.left; r.right = r.left + rectSides.left; CRect rectPart; if (m_bMirror) { rectPart = CRect (rectImage.right - rectSides.left, rectImage.top + rectCorners.top, rectImage.right, rectImage.bottom - rectCorners.bottom); } else { rectPart = CRect (rectImage.left, rectImage.top + rectCorners.top, rectImage.left + rectSides.left, rectImage.bottom - rectCorners.bottom); } m_Bitmap.DrawEx (pDC, r, ind, sides[0].horz, sides[0].vert, rectPart, alphaSrc); } if (rectSides.right > 0) { CRect r (rt); r.right = rect.right; r.left = r.right - rectSides.right; CRect rectPart; if (m_bMirror) { rectPart = CRect (rectImage.left, rectImage.top + rectCorners.top, rectImage.left + rectSides.right, rectImage.bottom - rectCorners.bottom); } else { rectPart = CRect (rectImage.right - rectSides.right, rectImage.top + rectCorners.top, rectImage.right, rectImage.bottom - rectCorners.bottom); } m_Bitmap.DrawEx (pDC, r, ind, sides[1].horz, sides[1].vert, rectPart, alphaSrc); } } if (rt.Width () > 0) { if (rectSides.top > 0) { CRect r (rt); r.top = rect.top; r.bottom = r.top + rectSides.top; CRect rectPart; if (m_bMirror) { rectPart = CRect (rectImage.left + rectCorners.right, rectImage.top, rectImage.right - rectCorners.left, rectImage.top + rectSides.top); } else { rectPart = CRect (rectImage.left + rectCorners.left, rectImage.top, rectImage.right - rectCorners.right, rectImage.top + rectSides.top); } m_Bitmap.DrawEx (pDC, r, ind, sides[2].horz, sides[2].vert, rectPart, alphaSrc); } if (rectSides.bottom > 0) { CRect r (rt); r.bottom = rect.bottom; r.top = r.bottom - rectSides.bottom; CRect rectPart; if (m_bMirror) { rectPart = CRect (rectImage.left + rectCorners.right, rectImage.bottom - rectSides.bottom, rectImage.right - rectCorners.left, rectImage.bottom); } else { rectPart = CRect (rectImage.left + rectCorners.left, rectImage.bottom - rectSides.bottom, rectImage.right - rectCorners.right, rectImage.bottom); } m_Bitmap.DrawEx (pDC, r, ind, sides[3].horz, sides[3].vert, rectPart, alphaSrc); } } if (rectCorners.left > 0 && rectCorners.top > 0) { CRect rectPart; if (m_bMirror) { rectPart = CRect (CPoint (rectImage.right - rectCorners.left, rectImage.top), CSize (rectCorners.left, rectCorners.top)); } else { rectPart = CRect (CPoint (rectImage.left, rectImage.top), CSize (rectCorners.left, rectCorners.top)); } m_Bitmap.DrawEx (pDC, rect, ind, corners[0].horz, corners[0].vert, rectPart, alphaSrc); } if (rectCorners.right > 0 && rectCorners.top > 0) { CRect rectPart; if (m_bMirror) { rectPart = CRect (CPoint (rectImage.left, rectImage.top), CSize (rectCorners.right, rectCorners.top)); } else { rectPart = CRect (CPoint (rectImage.right - rectCorners.right, rectImage.top), CSize (rectCorners.right, rectCorners.top)); } m_Bitmap.DrawEx (pDC, rect, ind, corners[1].horz, corners[1].vert, rectPart, alphaSrc); } if (rectCorners.left > 0 && rectCorners.bottom > 0) { CRect rectPart; if (m_bMirror) { rectPart = CRect (CPoint (rectImage.right - rectCorners.left, rectImage.bottom - rectCorners.bottom), CSize (rectCorners.left, rectCorners.bottom)); } else { rectPart = CRect (CPoint (rectImage.left, rectImage.bottom - rectCorners.bottom), CSize (rectCorners.left, rectCorners.bottom)); } m_Bitmap.DrawEx (pDC, rect, ind, corners[2].horz, corners[2].vert, rectPart, alphaSrc); } if (rectCorners.right > 0 && rectCorners.bottom > 0) { CRect rectPart; if (m_bMirror) { rectPart = CRect (CPoint (rectImage.left, rectImage.bottom - rectCorners.bottom), CSize (rectCorners.right, rectCorners.bottom)); } else { rectPart = CRect (CPoint (rectImage.right - rectCorners.right, rectImage.bottom - rectCorners.bottom), CSize (rectCorners.right, rectCorners.bottom)); } m_Bitmap.DrawEx (pDC, rect, ind, corners[3].horz, corners[3].vert, rectPart, alphaSrc); } } } //********************************************************************************* void CBCGPControlRenderer::FillInterior (CDC* pDC, CRect rect, CBCGPToolBarImages::ImageAlignHorz horz, CBCGPToolBarImages::ImageAlignVert vert, UINT index, BYTE alphaSrc/* = 255*/) { if (m_Params.m_rectInter.IsRectEmpty ()) { return; } CRect rectImage (m_Params.m_rectInter); if (m_bMirror) { rectImage.left = m_Params.m_rectImage.Size ().cx - m_Params.m_rectInter.right; rectImage.right = rectImage.left + m_Params.m_rectInter.Width (); } rectImage.OffsetRect (m_Params.m_rectImage.TopLeft ()); int ind = index; if (m_Bitmap.GetCount () == 1) { rectImage.OffsetRect (0, m_Params.m_rectImage.Size ().cy * ind); ind = 0; } m_Bitmap.DrawEx (pDC, rect, ind, horz, vert, rectImage, alphaSrc); } //********************************************************************************* void CBCGPControlRenderer::FillInterior (CDC* pDC, CRect rect, UINT index, BYTE alphaSrc/* = 255*/) { FillInterior (pDC, rect, CBCGPToolBarImages::ImageAlignHorzStretch, CBCGPToolBarImages::ImageAlignVertStretch, index, alphaSrc); } //********************************************************************************* void CBCGPControlRenderer::OnSysColorChange () { if (m_Bitmap.GetImageWell () != NULL) { m_Bitmap.OnSysColorChange (); } } //********************************************************************************* BOOL CBCGPControlRenderer::CopyTo (CBCGPControlRenderer& dest) { if (this == &dest) { return FALSE; } dest.CleanUp (); if (m_Bitmap.CopyTo (dest.m_Bitmap)) { dest.m_Params = m_Params; dest.m_bMirror = m_bMirror; return TRUE; } return FALSE; } //********************************************************************************* static void ResizeRect (CRect& rect, double dblScale) { int nWidth = rect.Width (); int nHeight = rect.Height (); rect.left = (int) (.5 + dblScale * rect.left); rect.top = (int) (.5 + dblScale * rect.top); rect.right = rect.left + (int) (.5 + dblScale * nWidth); rect.bottom = rect.top + (int) (.5 + dblScale * nHeight); } BOOL CBCGPControlRenderer::SmoothResize (double dblScale) { if (dblScale <= 1. || !m_Bitmap.SmoothResize (dblScale)) { return FALSE; } ResizeRect (m_Params.m_rectImage, dblScale); ResizeRect (m_Params.m_rectInter, dblScale); m_bIsScaled = TRUE; return TRUE; } IMPLEMENT_DYNCREATE(CBCGPShadowRenderer, CBCGPControlRenderer) CBCGPShadowRenderer::CBCGPShadowRenderer() : m_nDepth (0) , m_clrBase (0) , m_iMinBrightness(0) , m_iMaxBrightness(100) { } //********************************************************************************* CBCGPShadowRenderer::~CBCGPShadowRenderer() { } //********************************************************************************* BOOL CBCGPShadowRenderer::Create (const CBCGPControlRendererParams& /*params*/, BOOL /*bFlipvert*/ /*= FALSE*/) { return FALSE; } //********************************************************************************* BOOL CBCGPShadowRenderer::Create (int nDepth, COLORREF clrBase, int iMinBrightness/* = 0*/, int iMaxBrightness/* = 100*/, BOOL bCanMirror/* = TRUE*/, double dblSmooth/* = 1.0*/, double dblDarkRatio/* = 0.25*/) { if (IsValid() && m_nDepth == nDepth && m_clrBase == clrBase && m_iMinBrightness == iMinBrightness && m_iMaxBrightness == iMaxBrightness) { return TRUE; } CleanUp (); if (nDepth == 0 || iMaxBrightness == 0) { return FALSE; } m_nDepth = nDepth; m_clrBase = clrBase; m_iMinBrightness = iMinBrightness; m_iMaxBrightness = iMaxBrightness; if (m_clrBase == (COLORREF)-1) { clrBase = globalData.clrBarFace; } HBITMAP hBitmap = CBCGPDrawManager::PrepareShadowMask (nDepth, clrBase, iMinBrightness, iMaxBrightness, dblSmooth, dblDarkRatio); if (hBitmap == NULL) { return FALSE; } int nSize = nDepth < 2 ? 2 : nDepth; int nDestSize = nSize * 2 + 1; m_Params.m_rectImage = CRect (0, 0, nDestSize, nDestSize); m_Params.m_rectCorners = CRect (nSize, nSize, nSize, nSize); m_Params.m_rectSides = m_Params.m_rectCorners; m_Params.m_rectInter = CRect (CPoint (0, 0), m_Params.m_rectImage.Size ()); m_Params.m_rectInter.left += m_Params.m_rectCorners.left; m_Params.m_rectInter.top += m_Params.m_rectCorners.top; m_Params.m_rectInter.right -= m_Params.m_rectCorners.right; m_Params.m_rectInter.bottom -= m_Params.m_rectCorners.bottom; m_Bitmap.SetImageSize (m_Params.m_rectImage.Size ()); m_Bitmap.SetPreMultiplyAutoCheck (m_Params.m_bPreMultiplyCheck); m_Bitmap.SetMapTo3DColors (m_Params.m_bMapTo3DColors); m_Bitmap.AddImage (hBitmap, TRUE); ::DeleteObject (hBitmap); if (bCanMirror && CBCGPToolBarImages::IsRTL () && m_Bitmap.GetImageWell () != NULL) { Mirror (); } return m_Bitmap.GetCount () == 1; } //********************************************************************************* void CBCGPShadowRenderer::OnSysColorChange () { } //********************************************************************************* void CBCGPShadowRenderer::Draw (CDC* pDC, CRect rect, UINT index/* = 0*/, BYTE alphaSrc/* = 255*/) { if (128 <= alphaSrc) { CRect rectInter (rect); if (CBCGPToolBarImages::IsRTL ()) { rectInter.left += m_Params.m_rectSides.left; rectInter.right = rectInter.left + m_Params.m_rectSides.left; } else { rectInter.right -= m_Params.m_rectSides.right; rectInter.left = rectInter.right - m_Params.m_rectSides.right; } rectInter.bottom -= m_Params.m_rectSides.bottom; rectInter.top = rectInter.bottom - m_Params.m_rectSides.bottom; FillInterior (pDC, rectInter, index, alphaSrc); } DrawFrame (pDC, rect, index, alphaSrc); } //********************************************************************************* void CBCGPShadowRenderer::DrawFrame (CDC* pDC, CRect rect, UINT index/* = 0*/, BYTE alphaSrc/* = 255*/) { struct XHVTypes { CBCGPToolBarImages::ImageAlignHorz horz; CBCGPToolBarImages::ImageAlignVert vert; }; XHVTypes corners[4] = { {CBCGPToolBarImages::ImageAlignHorzLeft , CBCGPToolBarImages::ImageAlignVertTop}, {CBCGPToolBarImages::ImageAlignHorzRight, CBCGPToolBarImages::ImageAlignVertTop}, {CBCGPToolBarImages::ImageAlignHorzLeft , CBCGPToolBarImages::ImageAlignVertBottom}, {CBCGPToolBarImages::ImageAlignHorzRight, CBCGPToolBarImages::ImageAlignVertBottom} }; XHVTypes sides[4] = { {CBCGPToolBarImages::ImageAlignHorzLeft , CBCGPToolBarImages::ImageAlignVertStretch}, {CBCGPToolBarImages::ImageAlignHorzRight , CBCGPToolBarImages::ImageAlignVertStretch}, {CBCGPToolBarImages::ImageAlignHorzStretch, CBCGPToolBarImages::ImageAlignVertTop}, {CBCGPToolBarImages::ImageAlignHorzStretch, CBCGPToolBarImages::ImageAlignVertBottom} }; CRect rectImage (m_Params.m_rectImage); int ind = index; if (m_Bitmap.GetCount () == 1) { rectImage.OffsetRect (0, m_Params.m_rectImage.Size ().cy * ind); ind = 0; } CRect rt (rect); CRect rectCorners (m_Params.m_rectCorners); CRect rectSides (m_Params.m_rectSides); rt.left += rectCorners.left; rt.top += rectCorners.top; rt.right -= rectCorners.right; rt.bottom -= rectCorners.bottom; BOOL bRTL = CBCGPToolBarImages::IsRTL (); if (rt.Width () > 0 || rt.Height () > 0) { if (rt.Height () > 0) { if (bRTL && !m_bMirror) { if (rectSides.left > 0) { CRect r (rt); r.left = rect.left; r.right = r.left + rectSides.left; CRect rectPart (rectImage.left, rectImage.top + rectCorners.top, rectImage.left + rectSides.left, rectImage.bottom - rectCorners.bottom); m_Bitmap.DrawEx (pDC, r, ind, sides[0].horz, sides[0].vert, rectPart, alphaSrc); } } else { if (rectSides.right > 0) { CRect r (rt); r.right = rect.right; r.left = r.right - rectSides.right; CRect rectPart; if (m_bMirror) { rectPart = CRect (rectImage.left, rectImage.top + rectCorners.top, rectImage.left + rectSides.right, rectImage.bottom - rectCorners.bottom); } else { rectPart = CRect (rectImage.right - rectSides.right, rectImage.top + rectCorners.top, rectImage.right, rectImage.bottom - rectCorners.bottom); } m_Bitmap.DrawEx (pDC, r, ind, sides[1].horz, sides[1].vert, rectPart, alphaSrc); } } } if (rt.Width () > 0) { if (rectSides.bottom > 0) { CRect r (rt); r.bottom = rect.bottom; r.top = r.bottom - rectSides.bottom; CRect rectPart (rectImage.left + rectCorners.left, rectImage.bottom - rectSides.bottom, rectImage.right - rectCorners.right, rectImage.bottom); m_Bitmap.DrawEx (pDC, r, ind, sides[3].horz, sides[3].vert, rectPart, alphaSrc); } } if (bRTL && !m_bMirror) { if (rectCorners.left > 0 && rectCorners.top > 0) { CRect rectPart (CPoint (rectImage.left, rectImage.top), CSize (rectCorners.left, rectCorners.top)); m_Bitmap.DrawEx (pDC, rect, ind, corners[0].horz, corners[0].vert, rectPart, alphaSrc); } if (rectCorners.left > 0 && rectCorners.bottom > 0) { CRect rectPart = CRect (CPoint (rectImage.left, rectImage.bottom - rectCorners.bottom), CSize (rectCorners.left, rectCorners.bottom)); m_Bitmap.DrawEx (pDC, rect, ind, corners[2].horz, corners[2].vert, rectPart, alphaSrc); } if (rectCorners.right > 0 && rectCorners.bottom > 0) { CRect rectPart (CPoint (rectImage.right - rectCorners.right, rectImage.bottom - rectCorners.bottom), CSize (rectCorners.right, rectCorners.bottom)); m_Bitmap.DrawEx (pDC, rect, ind, corners[3].horz, corners[3].vert, rectPart, alphaSrc); } } else { if (rectCorners.right > 0 && rectCorners.top > 0) { CRect rectPart; if (m_bMirror) { rectPart = CRect (CPoint (rectImage.left, rectImage.top), CSize (rectCorners.right, rectCorners.top)); } else { rectPart = CRect (CPoint (rectImage.right - rectCorners.right, rectImage.top), CSize (rectCorners.right, rectCorners.top)); } m_Bitmap.DrawEx (pDC, rect, ind, corners[1].horz, corners[1].vert, rectPart, alphaSrc); } if (rectCorners.left > 0 && rectCorners.bottom > 0) { CRect rectPart; if (m_bMirror) { rectPart = CRect (CPoint (rectImage.right - rectCorners.left, rectImage.bottom - rectCorners.bottom), CSize (rectCorners.left, rectCorners.bottom)); } else { rectPart = CRect (CPoint (rectImage.left, rectImage.bottom - rectCorners.bottom), CSize (rectCorners.left, rectCorners.bottom)); } m_Bitmap.DrawEx (pDC, rect, ind, corners[2].horz, corners[2].vert, rectPart, alphaSrc); } if (rectCorners.right > 0 && rectCorners.bottom > 0) { CRect rectPart; if (m_bMirror) { rectPart = CRect (CPoint (rectImage.left, rectImage.bottom - rectCorners.bottom), CSize (rectCorners.right, rectCorners.bottom)); } else { rectPart = CRect (CPoint (rectImage.right - rectCorners.right, rectImage.bottom - rectCorners.bottom), CSize (rectCorners.right, rectCorners.bottom)); } m_Bitmap.DrawEx (pDC, rect, ind, corners[3].horz, corners[3].vert, rectPart, alphaSrc); } } } } //********************************************************************************* BOOL CBCGPShadowRenderer::CopyTo (CBCGPControlRenderer& dest) { if (this == &dest) { return FALSE; } if (CBCGPControlRenderer::CopyTo (dest)) { if (dest.IsKindOf (RUNTIME_CLASS (CBCGPShadowRenderer))) { CBCGPShadowRenderer& rDest = (CBCGPShadowRenderer&)dest; rDest.m_nDepth = m_nDepth; rDest.m_clrBase = m_clrBase; rDest.m_iMinBrightness = m_iMinBrightness; rDest.m_iMaxBrightness = m_iMaxBrightness; return TRUE; } } return FALSE; }
gpl-2.0
demiankatz/Geeby-Deeby
module/GeebyDeeby/src/GeebyDeeby/Controller/LinkController.php
2287
<?php /** * Link controller * * PHP version 5 * * Copyright (C) Demian Katz 2012. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category GeebyDeeby * @package Controller * @author Demian Katz <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://github.com/demiankatz/Geeby-Deeby Main Site */ namespace GeebyDeeby\Controller; /** * Link controller * * @category GeebyDeeby * @package Controller * @author Demian Katz <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://github.com/demiankatz/Geeby-Deeby Main Site */ class LinkController extends AbstractBase { /** * Link list * * @return mixed */ public function listAction() { // Get link group configuration: $config = $this->serviceLocator->get('config'); $groups = $config['geeby-deeby']['link_groups'] ?? []; $extra = $this->params()->fromRoute('extra'); $group = ($extra && isset($groups[$extra])) ? $groups[$extra] : false; // Initialize values: $table = $this->getDbTable('link'); // Retrieve the relevant links: $links = $table->getListByType( $group['typeMatch'] ?? null ); // Send back the details: return $this->createViewModel( [ 'links' => $links, 'title' => $group['title'] ?? 'Link List', 'desc' => $group['desc'] ?? '', 'typeTrim' => $group['typeTrim'] ?? 0, ] ); } }
gpl-2.0
nurulimamnotes/sistem-informasi-sekolah
jibas/kepegawaian/index.php
1138
<? /**[N]** * JIBAS Education Community * Jaringan Informasi Bersama Antar Sekolah * * @version: 3.2 (September 03, 2013) * @notes: JIBAS Education Community will be managed by Yayasan Indonesia Membaca (http://www.indonesiamembaca.net) * * Copyright (C) 2009 Yayasan Indonesia Membaca (http://www.indonesiamembaca.net) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License **[N]**/ ?> <? require_once('include/config.php'); session_name("_JIBAS_KEPEGAWAIAN__"); session_start(); if (isset($_SESSION['login'])) include("index2.php"); else include("login.php"); ?>
gpl-2.0
crotwell/sod
src/main/java/edu/sc/seis/sod/SimpleContentHandler.java
672
package edu.sc.seis.sod; import org.xml.sax.Attributes; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; /** * SimpleContentHandler.java * * * Created: Tue Jul 2 09:32:52 2002 * * @author Philip Crotwell */ public class SimpleContentHandler extends DefaultHandler { public SimpleContentHandler (XMLReader parser){ this.parser = parser; } public void startElement(String namespaceURI, String localName, String qName, Attributes atts) { System.out.println(localName); } XMLReader parser; }// SimpleContentHandler
gpl-2.0
etkirsch/gmusic
gmusic/model/events/PauseOrResume.py
166
from gmusic.model.Event import Event class PauseOrResume(Event): def __init__(self, sender): Event.__init__(self, sender) self.is_paused = False
gpl-2.0
padmanabhan-developer/Norway-GO
sites/all/modules/fb/contrib/fb_invite.js
7145
/** * @file * Javascript behaviors and helpers for fb_invite.module. */ FB_Invite = function(){}; /** * Drupal behaviors hook. * Called when page is loaded, or content added via javascript. */ (function ($) { Drupal.behaviors.fb_invite = { attach : function(context) { //jQuery(document).bind('fb_init', FB_Invite.fbBehaviors); // Login status event is produced by Facebook's JS SDK. jQuery(document).bind('fb_login_status', FB_Invite.fbStatusBehaviors); // These events produced by fb.js. jQuery(document).bind('fb_new_token', FB_Invite.fbNewToken); jQuery(document).bind('fb_token_invalid', FB_Invite.fbTokenInvalid); } }; })(jQuery); FB_Invite.friends = []; FB_Invite.users = []; FB_Invite.friendsRendered = 0; FB_Invite.usersRendered = 0; FB_Invite.renderIncrement = 300; // How many users to display at a time. FB_Invite.fbStatusBehaviors = function(event, response) { // Refresh any markup we've added to the page. if (response.status == 'connected') { // The token may not be new, but invoke our new token handler to render friend list. FB_Invite.fbNewToken(event, {access_token: response.authResponse.accessToken}); } } FB_Invite.fbTokenInvalid = function(event, data) { // Refresh any markup we've added to the page. jQuery('.fb_invite-friend').remove(); jQuery('.fb_invite-user').remove(); jQuery('.fb_invite-processed').removeClass('fb_invite-processed'); } /** * This callback is invoked after facebook API object FB is initialized. * * Here we query facebook for the current user's friends. The list * may be long, so we render them only as the page is scrolled down * far enough to see the bottom of the list. */ FB_Invite.fbNewToken = function(event, data) { jQuery('#fb_invite_friend_wrapper:not(fb_invite-processed)').each(function() { jQuery(this).addClass('fb_invite-processed'); jQuery(this).after('<div id=fb_invite_end_friends></div>'); // This tells us whether end of list is viewable. jQuery('#fb_invite_end_friends').attr('count', 0); jQuery(window).scroll(FB_Invite.renderFriends); /* FB.api('/fql', {q : 'SELECT uid, name, is_app_user, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND is_app_user = 0 ORDER BY name ASC'}, function(response) { FB_Invite.friends = response.data; FB_Invite.renderFriends(); }); */ FB_JS.fql('SELECT uid, name, is_app_user, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND is_app_user = 0 ORDER BY name ASC', { data : {access_token: data.access_token}, success : function(response) { FB_Invite.friends = response.data; FB_Invite.renderFriends(); }, error : function(response) { debugger; } }); }); jQuery('#fb_invite_user_wrapper:not(fb_invite-processed)').each(function() { jQuery(this).addClass('fb_invite-processed'); jQuery(this).after('<div id=fb_invite_end_users></div>'); // This tells us whether end of list is viewable. jQuery('#fb_invite_end_users').attr('count', 0); jQuery(window).scroll(FB_Invite.renderFriends); /* FB.api('/fql', {q : 'SELECT uid, name, is_app_user, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND is_app_user = 1 ORDER BY name ASC'}, function(response) { FB_Invite.users = response.data; FB_Invite.renderUsers(); }); */ FB_JS.fql('SELECT uid, name, is_app_user, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND is_app_user = 1 ORDER BY name ASC', { data : {access_token: data.access_token}, success: function(response) { FB_Invite.users = response.data; FB_Invite.renderUsers(); }, error : function(response) { debugger; } }); }); }; FB_Invite.renderFriends = function() { var endElement = jQuery('#fb_invite_end_friends'); while (typeof(FB_Invite.friends) != 'undefined' && FB_Invite.isScrolledIntoView(endElement) && endElement.attr('count') < FB_Invite.friends.length) { // Render each friend not an app user. for(var i = endElement.attr('count'); i < Math.min(FB_Invite.friends.length, endElement.attr('count') + FB_Invite.renderIncrement); i++) { var row = jQuery('#fb_invite_friend_template').clone(); var id = 'fb_invite_' + FB_Invite.friends[i].uid; row.attr('id', id); row.addClass('fb_invite-friend'); jQuery('.fb_invite_name', row).text(FB_Invite.friends[i].name); jQuery('img.fb_invite_img', row).attr('src', '//graph.facebook.com/' + FB_Invite.friends[i].uid + '/picture'); jQuery('input', row).click(FB_Invite.friends[i], FB_Invite.sendInvite); row.insertBefore(jQuery('#fb_invite_friend_template')).show(); } endElement.attr('count', i); } }; FB_Invite.renderUsers = function() { var endElement = jQuery('#fb_invite_end_users'); while (typeof(FB_Invite.users) != 'undefined' && FB_Invite.isScrolledIntoView(endElement) && endElement.attr('count') < FB_Invite.users.length) { // Render each friend who is an app user. for(var i = endElement.attr('count'); i < Math.min(FB_Invite.users.length, endElement.attr('count') + FB_Invite.renderIncrement); i++) { var row = jQuery('#fb_invite_user_template').clone(); var id = 'fb_invite_' + FB_Invite.users[i].uid; row.attr('id', id); row.addClass('fb_invite-user'); jQuery('.fb_invite_name', row).text(FB_Invite.users[i].name); jQuery('.fb_invite_user_link', row).attr('href', Drupal.settings.fb.base_url + '/fb_user/' + FB_Invite.users[i].uid); jQuery('img.fb_invite_img', row).attr('src', '//graph.facebook.com/' + FB_Invite.users[i].uid + '/picture'); jQuery('input', row).click(FB_Invite.users[i], FB_Invite.sendInvite); row.insertBefore(jQuery('#fb_invite_user_template')).show(); } endElement.attr('count', i); } }; FB_Invite.sendInvite = function(e) { FB.ui({method: 'send', name: Drupal.settings.fb_invite.site_name, link: Drupal.settings.fb_invite.link_url, to: e.data.uid }, FB_Invite.requestCallback); return false; }; FB_Invite.sendInviteMFS = function() { FB.ui({method: 'send', name: Drupal.settings.fb_invite.site_name, link: Drupal.settings.fb_invite.link_url, }, FB_Invite.requestCallback); }; FB_Invite.requestCallback = function(response) { // TODO Might make sense to invoke ajax event here. }; /** * http://stackoverflow.com/questions/487073/check-if-element-is-visible-after-scrolling */ FB_Invite.isScrolledIntoView = function(elem) { var docViewTop = jQuery(window).scrollTop(); var docViewBottom = docViewTop + jQuery(window).height(); var elemTop = jQuery(elem).offset().top; var elemBottom = elemTop + jQuery(elem).height(); return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)); }
gpl-2.0
brasadesign/wpecotemporadas
wp-content/plugins/post-status-notifier-lite/lib/IfwPsn/Vendor/Zend/Controller/Response/Abstract.php
21262
<?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 [email protected] so we can send you a copy immediately. * * @category Zend * @package IfwPsn_Vendor_Zend_Controller * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Abstract.php 911603 2014-05-10 10:58:23Z worschtebrot $ */ /** * IfwPsn_Vendor_Zend_Controller_Response_Abstract * * Base class for IfwPsn_Vendor_Zend_Controller responses * * @package IfwPsn_Vendor_Zend_Controller * @subpackage Response * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class IfwPsn_Vendor_Zend_Controller_Response_Abstract { /** * Body content * @var array */ protected $_body = array(); /** * Exception stack * @var Exception */ protected $_exceptions = array(); /** * Array of headers. Each header is an array with keys 'name' and 'value' * @var array */ protected $_headers = array(); /** * Array of raw headers. Each header is a single string, the entire header to emit * @var array */ protected $_headersRaw = array(); /** * HTTP response code to use in headers * @var int */ protected $_httpResponseCode = 200; /** * Flag; is this response a redirect? * @var boolean */ protected $_isRedirect = false; /** * Whether or not to render exceptions; off by default * @var boolean */ protected $_renderExceptions = false; /** * Flag; if true, when header operations are called after headers have been * sent, an exception will be raised; otherwise, processing will continue * as normal. Defaults to true. * * @see canSendHeaders() * @var boolean */ public $headersSentThrowsException = true; /** * Normalize a header name * * Normalizes a header name to X-Capitalized-Names * * @param string $name * @return string */ protected function _normalizeHeader($name) { $filtered = str_replace(array('-', '_'), ' ', (string) $name); $filtered = ucwords(strtolower($filtered)); $filtered = str_replace(' ', '-', $filtered); return $filtered; } /** * Set a header * * If $replace is true, replaces any headers already defined with that * $name. * * @param string $name * @param string $value * @param boolean $replace * @return IfwPsn_Vendor_Zend_Controller_Response_Abstract */ public function setHeader($name, $value, $replace = false) { $this->canSendHeaders(true); $name = $this->_normalizeHeader($name); $value = (string) $value; if ($replace) { foreach ($this->_headers as $key => $header) { if ($name == $header['name']) { unset($this->_headers[$key]); } } } $this->_headers[] = array( 'name' => $name, 'value' => $value, 'replace' => $replace ); return $this; } /** * Set redirect URL * * Sets Location header and response code. Forces replacement of any prior * redirects. * * @param string $url * @param int $code * @return IfwPsn_Vendor_Zend_Controller_Response_Abstract */ public function setRedirect($url, $code = 302) { $this->canSendHeaders(true); $this->setHeader('Location', $url, true) ->setHttpResponseCode($code); return $this; } /** * Is this a redirect? * * @return boolean */ public function isRedirect() { return $this->_isRedirect; } /** * Return array of headers; see {@link $_headers} for format * * @return array */ public function getHeaders() { return $this->_headers; } /** * Clear headers * * @return IfwPsn_Vendor_Zend_Controller_Response_Abstract */ public function clearHeaders() { $this->_headers = array(); return $this; } /** * Clears the specified HTTP header * * @param string $name * @return IfwPsn_Vendor_Zend_Controller_Response_Abstract */ public function clearHeader($name) { if (! count($this->_headers)) { return $this; } foreach ($this->_headers as $index => $header) { if ($name == $header['name']) { unset($this->_headers[$index]); } } return $this; } /** * Set raw HTTP header * * Allows setting non key => value headers, such as status codes * * @param string $value * @return IfwPsn_Vendor_Zend_Controller_Response_Abstract */ public function setRawHeader($value) { $this->canSendHeaders(true); if ('Location' == substr($value, 0, 8)) { $this->_isRedirect = true; } $this->_headersRaw[] = (string) $value; return $this; } /** * Retrieve all {@link setRawHeader() raw HTTP headers} * * @return array */ public function getRawHeaders() { return $this->_headersRaw; } /** * Clear all {@link setRawHeader() raw HTTP headers} * * @return IfwPsn_Vendor_Zend_Controller_Response_Abstract */ public function clearRawHeaders() { $this->_headersRaw = array(); return $this; } /** * Clears the specified raw HTTP header * * @param string $headerRaw * @return IfwPsn_Vendor_Zend_Controller_Response_Abstract */ public function clearRawHeader($headerRaw) { if (! count($this->_headersRaw)) { return $this; } $key = array_search($headerRaw, $this->_headersRaw); if ($key !== false) { unset($this->_headersRaw[$key]); } return $this; } /** * Clear all headers, normal and raw * * @return IfwPsn_Vendor_Zend_Controller_Response_Abstract */ public function clearAllHeaders() { return $this->clearHeaders() ->clearRawHeaders(); } /** * Set HTTP response code to use with headers * * @param int $code * @return IfwPsn_Vendor_Zend_Controller_Response_Abstract */ public function setHttpResponseCode($code) { if (!is_int($code) || (100 > $code) || (599 < $code)) { require_once IFW_PSN_LIB_ROOT . 'IfwPsn/Vendor/Zend/Controller/Response/Exception.php'; throw new IfwPsn_Vendor_Zend_Controller_Response_Exception('Invalid HTTP response code'); } if ((300 <= $code) && (307 >= $code)) { $this->_isRedirect = true; } else { $this->_isRedirect = false; } $this->_httpResponseCode = $code; return $this; } /** * Retrieve HTTP response code * * @return int */ public function getHttpResponseCode() { return $this->_httpResponseCode; } /** * Can we send headers? * * @param boolean $throw Whether or not to throw an exception if headers have been sent; defaults to false * @return boolean * @throws IfwPsn_Vendor_Zend_Controller_Response_Exception */ public function canSendHeaders($throw = false) { $ok = headers_sent($file, $line); if ($ok && $throw && $this->headersSentThrowsException) { require_once IFW_PSN_LIB_ROOT . 'IfwPsn/Vendor/Zend/Controller/Response/Exception.php'; throw new IfwPsn_Vendor_Zend_Controller_Response_Exception('Cannot send headers; headers already sent in ' . $file . ', line ' . $line); } return !$ok; } /** * Send all headers * * Sends any headers specified. If an {@link setHttpResponseCode() HTTP response code} * has been specified, it is sent with the first header. * * @return IfwPsn_Vendor_Zend_Controller_Response_Abstract */ public function sendHeaders() { // Only check if we can send headers if we have headers to send if (count($this->_headersRaw) || count($this->_headers) || (200 != $this->_httpResponseCode)) { $this->canSendHeaders(true); } elseif (200 == $this->_httpResponseCode) { // Haven't changed the response code, and we have no headers return $this; } $httpCodeSent = false; foreach ($this->_headersRaw as $header) { if (!$httpCodeSent && $this->_httpResponseCode) { header($header, true, $this->_httpResponseCode); $httpCodeSent = true; } else { header($header); } } foreach ($this->_headers as $header) { if (!$httpCodeSent && $this->_httpResponseCode) { header($header['name'] . ': ' . $header['value'], $header['replace'], $this->_httpResponseCode); $httpCodeSent = true; } else { header($header['name'] . ': ' . $header['value'], $header['replace']); } } if (!$httpCodeSent) { header('HTTP/1.1 ' . $this->_httpResponseCode); $httpCodeSent = true; } return $this; } /** * Set body content * * If $name is not passed, or is not a string, resets the entire body and * sets the 'default' key to $content. * * If $name is a string, sets the named segment in the body array to * $content. * * @param string $content * @param null|string $name * @return IfwPsn_Vendor_Zend_Controller_Response_Abstract */ public function setBody($content, $name = null) { if ((null === $name) || !is_string($name)) { $this->_body = array('default' => (string) $content); } else { $this->_body[$name] = (string) $content; } return $this; } /** * Append content to the body content * * @param string $content * @param null|string $name * @return IfwPsn_Vendor_Zend_Controller_Response_Abstract */ public function appendBody($content, $name = null) { if ((null === $name) || !is_string($name)) { if (isset($this->_body['default'])) { $this->_body['default'] .= (string) $content; } else { return $this->append('default', $content); } } elseif (isset($this->_body[$name])) { $this->_body[$name] .= (string) $content; } else { return $this->append($name, $content); } return $this; } /** * Clear body array * * With no arguments, clears the entire body array. Given a $name, clears * just that named segment; if no segment matching $name exists, returns * false to indicate an error. * * @param string $name Named segment to clear * @return boolean */ public function clearBody($name = null) { if (null !== $name) { $name = (string) $name; if (isset($this->_body[$name])) { unset($this->_body[$name]); return true; } return false; } $this->_body = array(); return true; } /** * Return the body content * * If $spec is false, returns the concatenated values of the body content * array. If $spec is boolean true, returns the body content array. If * $spec is a string and matches a named segment, returns the contents of * that segment; otherwise, returns null. * * @param boolean $spec * @return string|array|null */ public function getBody($spec = false) { if (false === $spec) { ob_start(); $this->outputBody(); return ob_get_clean(); } elseif (true === $spec) { return $this->_body; } elseif (is_string($spec) && isset($this->_body[$spec])) { return $this->_body[$spec]; } return null; } /** * Append a named body segment to the body content array * * If segment already exists, replaces with $content and places at end of * array. * * @param string $name * @param string $content * @return IfwPsn_Vendor_Zend_Controller_Response_Abstract */ public function append($name, $content) { if (!is_string($name)) { require_once IFW_PSN_LIB_ROOT . 'IfwPsn/Vendor/Zend/Controller/Response/Exception.php'; throw new IfwPsn_Vendor_Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")'); } if (isset($this->_body[$name])) { unset($this->_body[$name]); } $this->_body[$name] = (string) $content; return $this; } /** * Prepend a named body segment to the body content array * * If segment already exists, replaces with $content and places at top of * array. * * @param string $name * @param string $content * @return void */ public function prepend($name, $content) { if (!is_string($name)) { require_once IFW_PSN_LIB_ROOT . 'IfwPsn/Vendor/Zend/Controller/Response/Exception.php'; throw new IfwPsn_Vendor_Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")'); } if (isset($this->_body[$name])) { unset($this->_body[$name]); } $new = array($name => (string) $content); $this->_body = $new + $this->_body; return $this; } /** * Insert a named segment into the body content array * * @param string $name * @param string $content * @param string $parent * @param boolean $before Whether to insert the new segment before or * after the parent. Defaults to false (after) * @return IfwPsn_Vendor_Zend_Controller_Response_Abstract */ public function insert($name, $content, $parent = null, $before = false) { if (!is_string($name)) { require_once IFW_PSN_LIB_ROOT . 'IfwPsn/Vendor/Zend/Controller/Response/Exception.php'; throw new IfwPsn_Vendor_Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")'); } if ((null !== $parent) && !is_string($parent)) { require_once IFW_PSN_LIB_ROOT . 'IfwPsn/Vendor/Zend/Controller/Response/Exception.php'; throw new IfwPsn_Vendor_Zend_Controller_Response_Exception('Invalid body segment parent key ("' . gettype($parent) . '")'); } if (isset($this->_body[$name])) { unset($this->_body[$name]); } if ((null === $parent) || !isset($this->_body[$parent])) { return $this->append($name, $content); } $ins = array($name => (string) $content); $keys = array_keys($this->_body); $loc = array_search($parent, $keys); if (!$before) { // Increment location if not inserting before ++$loc; } if (0 === $loc) { // If location of key is 0, we're prepending $this->_body = $ins + $this->_body; } elseif ($loc >= (count($this->_body))) { // If location of key is maximal, we're appending $this->_body = $this->_body + $ins; } else { // Otherwise, insert at location specified $pre = array_slice($this->_body, 0, $loc); $post = array_slice($this->_body, $loc); $this->_body = $pre + $ins + $post; } return $this; } /** * Echo the body segments * * @return void */ public function outputBody() { $body = implode('', $this->_body); echo $body; } /** * Register an exception with the response * * @param Exception $e * @return IfwPsn_Vendor_Zend_Controller_Response_Abstract */ public function setException(Exception $e) { $this->_exceptions[] = $e; return $this; } /** * Retrieve the exception stack * * @return array */ public function getException() { return $this->_exceptions; } /** * Has an exception been registered with the response? * * @return boolean */ public function isException() { return !empty($this->_exceptions); } /** * Does the response object contain an exception of a given type? * * @param string $type * @return boolean */ public function hasExceptionOfType($type) { foreach ($this->_exceptions as $e) { if ($e instanceof $type) { return true; } } return false; } /** * Does the response object contain an exception with a given message? * * @param string $message * @return boolean */ public function hasExceptionOfMessage($message) { foreach ($this->_exceptions as $e) { if ($message == $e->getMessage()) { return true; } } return false; } /** * Does the response object contain an exception with a given code? * * @param int $code * @return boolean */ public function hasExceptionOfCode($code) { $code = (int) $code; foreach ($this->_exceptions as $e) { if ($code == $e->getCode()) { return true; } } return false; } /** * Retrieve all exceptions of a given type * * @param string $type * @return false|array */ public function getExceptionByType($type) { $exceptions = array(); foreach ($this->_exceptions as $e) { if ($e instanceof $type) { $exceptions[] = $e; } } if (empty($exceptions)) { $exceptions = false; } return $exceptions; } /** * Retrieve all exceptions of a given message * * @param string $message * @return false|array */ public function getExceptionByMessage($message) { $exceptions = array(); foreach ($this->_exceptions as $e) { if ($message == $e->getMessage()) { $exceptions[] = $e; } } if (empty($exceptions)) { $exceptions = false; } return $exceptions; } /** * Retrieve all exceptions of a given code * * @param mixed $code * @return void */ public function getExceptionByCode($code) { $code = (int) $code; $exceptions = array(); foreach ($this->_exceptions as $e) { if ($code == $e->getCode()) { $exceptions[] = $e; } } if (empty($exceptions)) { $exceptions = false; } return $exceptions; } /** * Whether or not to render exceptions (off by default) * * If called with no arguments or a null argument, returns the value of the * flag; otherwise, sets it and returns the current value. * * @param boolean $flag Optional * @return boolean */ public function renderExceptions($flag = null) { if (null !== $flag) { $this->_renderExceptions = $flag ? true : false; } return $this->_renderExceptions; } /** * Send the response, including all headers, rendering exceptions if so * requested. * * @return void */ public function sendResponse() { $this->sendHeaders(); if ($this->isException() && $this->renderExceptions()) { $exceptions = ''; foreach ($this->getException() as $e) { $exceptions .= $e->__toString() . "\n"; } echo $exceptions; return; } $this->outputBody(); } /** * Magic __toString functionality * * Proxies to {@link sendResponse()} and returns response value as string * using output buffering. * * @return string */ public function __toString() { ob_start(); $this->sendResponse(); return ob_get_clean(); } }
gpl-2.0
meijmOrg/Repo-test
freelance-admin/src/java/com/yh/admin/login/web/form/LoginForm.java
1298
package com.yh.admin.login.web.form; import org.apache.struts.validator.ValidatorForm; public class LoginForm extends ValidatorForm { /** * sid */ private static final long serialVersionUID = -4076373247406142615L; private String userCode; private String password; private String localeStr; private String systemCode; private String screenSize; public String getPassword() { return password; } public void setPassword(String password) { if (password != null) this.password = password.trim(); } public String getUserCode() { return userCode; } public void setUserCode(String username) { if (username != null) this.userCode = username.trim(); } public String getLocaleStr() { return localeStr; } public void setLocaleStr(String localeStr) { this.localeStr = localeStr; } public String toString() { StringBuffer str = new StringBuffer(); str.append("userName=" + userCode); str.append(",local=" + localeStr); return str.toString(); } public String getSystemCode() { return systemCode; } public void setSystemCode(String systemCode) { this.systemCode = systemCode; } public String getScreenSize() { return screenSize; } public void setScreenSize(String screenSize) { this.screenSize = screenSize; } }
gpl-2.0
wikimedia/mediawiki-extensions-OAuthAuthentication
utils/Config.php
1204
<?php namespace MediaWiki\Extensions\OAuthAuthentication; use MediaWiki\OAuthClient\ClientConfig; use MediaWiki\OAuthClient\Consumer; class Config { public static function getDefaultConfig() { global $wgOAuthAuthenticationConsumerKey, $wgOAuthAuthenticationConsumerSecret, $wgOAuthAuthenticationUrl, $wgOAuthAuthenticationCanonicalUrl, $wgOAuthAuthenticationValidateSSL; $validateSSL = false; if ( preg_match( '!^https://!i', $wgOAuthAuthenticationUrl ) ) { $validateSSL = $wgOAuthAuthenticationValidateSSL; } $config = new ClientConfig( $wgOAuthAuthenticationUrl, // url to use $validateSSL // do we validate the SSL certificate? Always use 'true' in production. ); if ( $wgOAuthAuthenticationCanonicalUrl ) { $config->canonicalServerUrl = $wgOAuthAuthenticationCanonicalUrl; } // Optional clean url here (i.e., to work with mobile), otherwise the // base url just has /authorize& added # $config->redirURL = 'http://en.wikipedia.beta.wmflabs.org/wiki/Special:OAuth/authorize?'; $consumer = new Consumer( $wgOAuthAuthenticationConsumerKey, $wgOAuthAuthenticationConsumerSecret ); $config->setConsumer( $consumer ); return $config; } }
gpl-2.0
adamfisk/littleshoot-client
common/bug-server/src/main/java/org/lastbamboo/common/bug/server/processors/MailBugProcessor.java
3153
package org.lastbamboo.common.bug.server.processors; import java.io.InputStream; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.servlet.http.HttpServletRequest; import org.springframework.mail.MailException; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessagePreparator; /** * Bug processor that sends e-mail to the appropriate recipients. */ public class MailBugProcessor implements BugProcessor { private final JavaMailSender m_mailSender; /** * Creates a new processor for sending e-mail about the bug. * * @param mailSender The class that sends the e-mails. */ public MailBugProcessor(final JavaMailSender mailSender) { this.m_mailSender = mailSender; } public void processBug(final InputStream is, final HttpServletRequest request) { final StringBuffer sb = new StringBuffer(); /* final Set entries = bugs.entrySet(); for (final Iterator iter = entries.iterator(); iter.hasNext();) { final Map.Entry entry = (Map.Entry) iter.next(); sb.append(entry.getKey()); sb.append("="); final String[] value = (String[]) entry.getValue(); for (int i = 0; i < value.length; i++) { sb.append(value[i]); sb.append(", "); } sb.append("\n"); } final String body = sb.toString(); final String[] version = (String[]) bugs.get("version"); if (version != null) { sendBody(body, "LittleShoot "+version[0]+" Bug"); } else { sendBody(body, "LittleShoot Unknown Version Bug"); } */ } private void sendBody(final String body, final String subject) { final MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(final MimeMessage mimeMessage) throws MessagingException { mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); mimeMessage.setFrom(new InternetAddress("[email protected]")); mimeMessage.setSubject(subject); mimeMessage.setText(body); } }; this.m_mailSender.send(preparator); try { this.m_mailSender.send(preparator); System.out.println("\n\n\nSent mail!!!!\n"); System.out.println(body); } catch (final MailException e) { //log it and go on System.err.println("Could not send mail:"+e.getMessage()); } } }
gpl-2.0
alexferrer/xcsoar_map_generator
lib/xcsoar/mapgen/waypoints/welt2000cup.py
1668
import os import subprocess from xcsoar.mapgen.waypoints.seeyou_reader import parse_seeyou_waypoints from xcsoar.mapgen.waypoints.seeyou_writer import write_seeyou_waypoints from xcsoar.mapgen.filelist import FileList def __get_database_file(dir_data): path = os.path.join(dir_data, 'welt2000', 'SEEYOU.CUP') # Create Welt2000 data folder if necessary if not os.path.exists(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) # Download the current file # (only if server file is newer than local file) url = 'http://www.segelflug.de/vereine/welt2000/download/SEEYOU.CUP' subprocess.check_call(['wget', '-N', '-P', os.path.dirname(path), url]) # Check if download succeeded if not os.path.exists(path): raise RuntimeError('Welt2000 cup database not found at {}'.format(path)) # Return path to the Welt2000 cup file return path def get_database(dir_data, bounds = None): # Get Welt2000 cup file path = __get_database_file(dir_data) # Parse Welt2000 cup file with open(path, "r") as f: # Return parsed WaypointList return parse_seeyou_waypoints(f, bounds) def __create_waypoint_file(database, dir_temp): print("Creating waypoints.cup with {} entries...".format(len(database))) # Create a Seeyou CUP file from the Welt2000 cup data path = os.path.join(dir_temp, 'waypoints.cup') write_seeyou_waypoints(database, path) return path def create(dir_data, dir_temp, bounds = None): database = get_database(dir_data, bounds) file = __create_waypoint_file(database, dir_temp) list = FileList() list.add(file, True) return list
gpl-2.0
MrNex/Game-Programming-Examples
GLFW/Collision Resolution/Minimum Translation Vector (Circle - 2D)/Minimum Translation Vector (Circle - 2D)/main.cpp
14736
/* Title: Detecting the Minimum Translation Vector (Circle - 2D) File Name: main.cpp Copyright © 2015 Original authors: Nicholas Gallagher Written under the supervision of David I. Schwartz, Ph.D., and supported by a professional development seed grant from the B. Thomas Golisano College of Computing & Information Sciences (https://www.rit.edu/gccis) at the Rochester Institute of Technology. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Description: This is a demonstration of detecting the minimum translation vector of two circles in 2D. There are Pink and Yellow wireframes of circles, when the circles overlap, the MVP will be drawn over the overlap distance indicating the intersection direction & magnitude between the two circles. The algorithm used is a modified version of the Separating Axis Theorem which is made much faster and more trivial because of both objects being circles. The only possible axis for intersection is the vector from the center of one circle to the other. Overlap over this axis is tested, if overlap is found, the axis is normalized to get the minimum translation vector. the amount of overlap is saved as the magnitude of the intersection. The user can move a circle using WASD. The user can also press spacebar to toggle the circle he/she is moving. References: PhysicsTimestep by Brockton Roth Base by Srinivasan Thiagarajan */ #include "GLIncludes.h" // Global data members #pragma region Base_data // This is your reference to your shader program. // This will be assigned with glCreateProgram(). // This program will run on your GPU. GLuint program; // These are your references to your actual compiled shaders GLuint vertex_shader; GLuint fragment_shader; // This is a reference to your uniform MVP matrix in your vertex shader GLuint uniMVP; GLuint uniHue; // Matrix for storing the View Projection transformation glm::mat4 VP; // This is a matrix to be sent to the shaders which can control global hue alteration glm::mat4 hue; // Reference to the window object being created by GLFW. GLFWwindow* window; struct Vertex { float x, y, z, r, g, b, a; }; //Struct for rendering struct Mesh { GLuint VBO; GLuint VAO; glm::mat4 translation; glm::mat4 rotation; glm::mat4 scale; int numVertices; struct Vertex* vertices; GLenum primitive; Mesh::Mesh(int numVert, struct Vertex* vert, GLenum primType) { glm::mat4 translation = glm::mat4(1.0f); glm::mat4 rotation = glm::mat4(1.0f); glm::mat4 scale = glm::mat4(1.0f); this->numVertices = numVert; this->vertices = new struct Vertex[this->numVertices]; memcpy(this->vertices, vert, this->numVertices * sizeof(struct Vertex)); this->primitive = primType; //Generate VAO glGenVertexArrays(1, &this->VAO); //bind VAO glBindVertexArray(VAO); //Generate VBO glGenBuffers(1, &this->VBO); //Configure VBO glBindBuffer(GL_ARRAY_BUFFER, this->VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(struct Vertex) * this->numVertices, this->vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(struct Vertex), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(struct Vertex), (void*)12); } Mesh::~Mesh(void) { delete[] this->vertices; glDeleteVertexArrays(1, &this->VAO); glDeleteBuffers(1, &this->VBO); } glm::mat4 Mesh::GetModelMatrix() { return translation * rotation * scale; } void Mesh::Draw(void) { //GEnerate the MVP for this model glm::mat4 MVP = VP * this->GetModelMatrix(); //Bind the VAO being drawn glBindVertexArray(this->VAO); // Set the uniform matrix in our shader to our MVP matrix for this mesh. glUniformMatrix4fv(uniMVP, 1, GL_FALSE, glm::value_ptr(MVP)); //Draw the mesh glDrawArrays(this->primitive, 0, this->numVertices); } }; //Struct for circle collider struct Circle { float radius; glm::vec3 center; //Default constructor, creates unit circle at origin Circle::Circle() { center = glm::vec3(0.0f); radius = 1.0f; } //PArameterized constructor, creates circle from given center and radius Circle::Circle(const glm::vec3& c, float r) { center = c; radius = r; } }; struct Mesh* circle1; struct Mesh* circle2; struct Circle* circle1Collider; struct Circle* circle2Collider; struct Circle* selectedCollider; glm::vec2 minimumTranslationVector; float overlap; bool collision = false; double time = 0.0; double timebase = 0.0; double accumulator = 0.0; double physicsStep = 0.012; // This is the number of milliseconds we intend for the physics to update. //Declaration of function which is called on key press. void OnKeyPress(GLFWwindow* window, int key, int scanCode, int action, int mods); #pragma endregion Base_data // Functions called only once every time the program is executed. #pragma region Helper_functions //Read shader source std::string readShader(std::string fileName) { std::string shaderCode; std::string line; std::ifstream file(fileName, std::ios::in); if (!file.good()) { std::cout << "Can't read file: " << fileName.data() << std::endl; return ""; } file.seekg(0, std::ios::end); shaderCode.resize((unsigned int)file.tellg()); file.seekg(0, std::ios::beg); file.read(&shaderCode[0], shaderCode.size()); file.close(); return shaderCode; } //Creates shader program GLuint createShader(std::string sourceCode, GLenum shaderType) { GLuint shader = glCreateShader(shaderType); const char *shader_code_ptr = sourceCode.c_str(); const int shader_code_size = sourceCode.size(); glShaderSource(shader, 1, &shader_code_ptr, &shader_code_size); glCompileShader(shader); GLint isCompiled = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled); if (isCompiled == GL_FALSE) { char infolog[1024]; glGetShaderInfoLog(shader, 1024, NULL, infolog); std::cout << "The shader failed to compile with the error:" << std::endl << infolog << std::endl; glDeleteShader(shader); } return shader; } // Initialization code void init() { // Initializes the glew library glewInit(); glEnable(GL_DEPTH_TEST); // Create shaders std::string vertShader = readShader("VertexShader.glsl"); std::string fragShader = readShader("FragmentShader.glsl"); vertex_shader = createShader(vertShader, GL_VERTEX_SHADER); fragment_shader = createShader(fragShader, GL_FRAGMENT_SHADER); program = glCreateProgram(); glAttachShader(program, vertex_shader); glAttachShader(program, fragment_shader); glLinkProgram(program); //Generate the View Projection matrix glm::mat4 view = glm::lookAt(glm::vec3(0.0f, 0.0f, 2.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 proj = glm::ortho(-1.0f,1.0f, -1.0f, 1.0f, 0.1f, 100.0f); VP = proj * view; //Create uniforms uniMVP = glGetUniformLocation(program, "MVP"); uniHue = glGetUniformLocation(program, "hue"); // Set options glFrontFace(GL_CCW); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Set key callback glfwSetKeyCallback(window, OnKeyPress); } #pragma endregion Helper_functions // Functions called between every frame. game logic #pragma region util_functions /// //Function which handles key-presses // //PArameters: // window: The window in focus during the key press // int: The key code // scanCode: The OS Scan code // action: GLFW_PRESS or GLFW_RELEASE // mods: Any modifier keys which were pressed. void OnKeyPress(GLFWwindow* window, int key, int scanCode, int action, int mods) { static const float movementSpeed = 0.1f; if(action == GLFW_PRESS) { if(key == GLFW_KEY_SPACE) { selectedCollider = selectedCollider == circle1Collider ? circle2Collider : circle1Collider; } if(key == GLFW_KEY_A) { selectedCollider->center.x -= movementSpeed; } if(key == GLFW_KEY_D) { selectedCollider->center.x += movementSpeed; } if(key == GLFW_KEY_W) { selectedCollider->center.y += movementSpeed; } if(key == GLFW_KEY_S) { selectedCollider->center.y -= movementSpeed; } } } /// //Checks for collision between two circles by seeing if the distance between them is less //than the sum of the radii. // //Parameters: // c1: The first circle to test // c2: The second circle to test // //Returns: // true if colliding, else false. bool CheckCollision(const Circle &c1, const Circle &c2, glm::vec2 &MTV, float &mag) { float dist = glm::length(c1.center - c2.center); if(dist < c1.radius + c2.radius) { //We have a collision, determine the Minimum Translation Vector MTV = glm::normalize(glm::vec2(c1.center - c2.center)); mag = (c1.radius + c2.radius) - dist; return true; } return false; } // This runs once every physics timestep. void update(float dt) { //Check for collision collision = CheckCollision(*circle1Collider, *circle2Collider, minimumTranslationVector, overlap); //Move appearance to new position circle1->translation = glm::translate(glm::mat4(1.0f), circle1Collider->center); circle2->translation = glm::translate(glm::mat4(1.0f), circle2Collider->center); } // This runs once every frame to determine the FPS and how often to call update based on the physics step. void checkTime() { // Get the current time. time = glfwGetTime(); // Get the time since we last ran an update. double dt = time - timebase; // If more time has passed than our physics timestep. if (dt > physicsStep) { timebase = time; // set new last updated time // Limit dt if (dt > 0.25) { dt = 0.25; } accumulator += dt; // Update physics necessary amount while (accumulator >= physicsStep) { update(physicsStep); accumulator -= physicsStep; } } } // This function runs every frame void renderScene() { // Clear the color buffer and the depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the screen to white glClearColor(0.0, 0.0, 0.0, 1.0); glLineWidth(1.0f); // Tell OpenGL to use the shader program you've created. glUseProgram(program); //Set hue uniform glUniformMatrix4fv(uniHue, 1, GL_FALSE, glm::value_ptr(hue)); // Draw the Gameobjects circle1->Draw(); circle2->Draw(); if(collision) { glm::mat4 mvp = VP * circle1->GetModelMatrix(); glUseProgram(0); glLineWidth(10.0f); //Draw the MTV between them glColor3f(1.0f, 1.0f, 1.0f); //Get the MTV's endpoints in world space glm::vec4 startPoint = glm::vec4(glm::vec2(circle1Collider->center), 0.11f, 1.0f) - glm::vec4(circle1Collider->radius * minimumTranslationVector, 0.0f, 0.0f); glm::vec4 endPoint = glm::vec4(glm::vec2(circle1Collider->center), 0.11f, 1.0f) - glm::vec4(circle1Collider->radius * minimumTranslationVector, 0.0f, 0.0f) + glm::vec4(overlap * minimumTranslationVector, 0.0f, 0.0f); startPoint = VP * startPoint; endPoint = VP * endPoint; //Draw glBegin(GL_LINES); glVertex3f(startPoint.x, startPoint.y, startPoint.z); glVertex3f(endPoint.x, endPoint.y, endPoint.z); glEnd(); } } #pragma endregion util_Functions void main() { glfwInit(); // Create a window window = glfwCreateWindow(800, 800, "Detecting the Minimum Translation Vector (Circle - 2D)", nullptr, nullptr); glfwMakeContextCurrent(window); glfwSwapInterval(0); // Initializes most things needed before the main loop init(); //Generate the circle mesh float circleScale = 0.15f; int numVertices = 72; struct Vertex circleVerts[72]; float stepSize = 2.0f * 3.14159 / (numVertices/3.0f); int vertexNumber = 0; for (int i = 0; i < numVertices; i++) { circleVerts[i].x = cosf(vertexNumber * stepSize); circleVerts[i].y = sinf(vertexNumber * stepSize); circleVerts[i].z = 0.0f; circleVerts[i].r = 1.0f; circleVerts[i].g = 1.0f; circleVerts[i].b = 0.0f; circleVerts[i].a = 1.0; ++i; ++vertexNumber; circleVerts[i].x = cosf(vertexNumber * stepSize); circleVerts[i].y = sinf(vertexNumber * stepSize); circleVerts[i].z = 0.0f; circleVerts[i].r = 1.0f; circleVerts[i].g = 1.0f; circleVerts[i].b = 0.0f; circleVerts[i].a = 1.0f; ++i; circleVerts[i].x = 0.0f; circleVerts[i].y = 0.0f; circleVerts[i].z = 0.0f; circleVerts[i].r = 1.0f; circleVerts[i].g = 1.0f; circleVerts[i].b = 0.0f; circleVerts[i].a = 1.0f; } //circle1 creation circle1 = new struct Mesh(numVertices, circleVerts, GL_TRIANGLES); //Alter mesh for circle2 for (int i = 0; i < numVertices; i++) { circleVerts[i].g = 0.0f; circleVerts[i].b = 1.0f; } //Circle2 creation circle2 = new struct Mesh(numVertices, circleVerts, GL_TRIANGLES); //Scale the circles circle1->scale = glm::scale(circle1->scale, glm::vec3(circleScale)); circle2->scale = glm::scale(circle2->scale, glm::vec3(circleScale)); //Generate the circles colliders circle1Collider = new Circle(glm::vec3(-0.75f, 0.0f, 0.2f), circleScale); circle2Collider = new Circle(glm::vec3(0.75f, 0.0f, 0.2f), circleScale); selectedCollider = circle1Collider; //Position circles circle1->translation = glm::translate(circle1->translation, circle1Collider->center); circle2->translation = glm::translate(circle2->translation, circle2Collider->center); //Print controls std::cout << "Controls:\nUse WASD to move the selected circle around the XY plane.\n"; std::cout << "Press spacebar to swap the selected circle.\n"; // Enter the main loop. while (!glfwWindowShouldClose(window)) { //Check time will update the programs clock and determine if & how many times the physics must be updated checkTime(); // Call the render function. renderScene(); // Swaps the back buffer to the front buffer // Remember, you're rendering to the back buffer, then once rendering is complete, you're moving the back buffer to the front so it can be displayed. glfwSwapBuffers(window); // Checks to see if any events are pending and then processes them. glfwPollEvents(); } // After the program is over, cleanup your data! glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); glDeleteProgram(program); // Note: If at any point you stop using a "program" or shaders, you should free the data up then and there. delete circle1; delete circle2; delete circle1Collider; delete circle2Collider; // Frees up GLFW memory glfwTerminate(); }
gpl-2.0
djangogirlscodecamp/curriculum
lesson_2/solutions/gross_pay_solution.py
1368
#2.3 Write a program to prompt the user for hours and rate per hour using raw_input to compute gross pay. #Use 35 hours and a rate of 2.75 per hour to test the program (the pay should be 96.25). #You should use raw_input to read a string and float() to convert the string to a number. #Do not worry about error checking or bad user data. #2.3 input을 사용하여 사용자의 시급과 근무시간을 바탕으로 급여를 계산하는 프로그램을 작성하여 보세요. #테스트를 위하여 35 시간과 2.75의 시급을 사용하세요. (급여는 96.25가 되어야 합니다.) #string을 읽어내기 위해서는 input을, string을 숫자로 바꾸기 위해서는 float()를 사용해야 합니다. #에러 확인이나 유저 데이터는 신경쓰지 않아도 됩니다. # This first line is provided for you #not checking for errors: hrs = input("Enter Hours:") pay = input("Enter Pay:") hrs = float(hrs) pay = float(pay) gross_pay = hrs*pay print(gross_pay) #checking input for errors # hrs = input("Enter Hours:") # if hrs.isdigit(): # pay = input("Enter Pay: ") # numpay = pay.split(".") # paystring = "".join(numpay) # if paystring.isdigit(): # hrs = float(hrs) # pay = float(pay) # gross_pay = hrs*pay # print(gross_pay) # else: # print("Pay isn't a valid number.") # else: # print("Hours isn't a valid number.")
gpl-2.0
SebDieBln/QGIS
python/plugins/processing/algs/qgis/Dissolve.py
6307
# -*- coding: utf-8 -*- """ *************************************************************************** Dissolve.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Victor Olaya' __date__ = 'August 2012' __copyright__ = '(C) 2012, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os from PyQt4.QtGui import QIcon from qgis.core import QgsFeature, QgsGeometry from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException from processing.core.parameters import ParameterVector from processing.core.parameters import ParameterBoolean from processing.core.parameters import ParameterTableField from processing.core.outputs import OutputVector from processing.tools import vector, dataobjects pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] class Dissolve(GeoAlgorithm): INPUT = 'INPUT' OUTPUT = 'OUTPUT' FIELD = 'FIELD' DISSOLVE_ALL = 'DISSOLVE_ALL' def getIcon(self): return QIcon(os.path.join(pluginPath, 'images', 'ftools', 'dissolve.png')) def defineCharacteristics(self): self.name = 'Dissolve' self.group = 'Vector geometry tools' self.addParameter(ParameterVector(Dissolve.INPUT, self.tr('Input layer'), [ParameterVector.VECTOR_TYPE_POLYGON, ParameterVector.VECTOR_TYPE_LINE])) self.addParameter(ParameterBoolean(Dissolve.DISSOLVE_ALL, self.tr('Dissolve all (do not use field)'), True)) self.addParameter(ParameterTableField(Dissolve.FIELD, self.tr('Unique ID field'), Dissolve.INPUT, optional=True)) self.addOutput(OutputVector(Dissolve.OUTPUT, self.tr('Dissolved'))) def processAlgorithm(self, progress): useField = not self.getParameterValue(Dissolve.DISSOLVE_ALL) fieldname = self.getParameterValue(Dissolve.FIELD) vlayerA = dataobjects.getObjectFromUri( self.getParameterValue(Dissolve.INPUT)) vproviderA = vlayerA.dataProvider() fields = vlayerA.fields() writer = self.getOutputFromName( Dissolve.OUTPUT).getVectorWriter(fields, vproviderA.geometryType(), vproviderA.crs()) outFeat = QgsFeature() features = vector.features(vlayerA) total = 100.0 / len(features) if not useField: first = True for current, inFeat in enumerate(features): progress.setPercentage(int(current * total)) if first: attrs = inFeat.attributes() tmpInGeom = QgsGeometry(inFeat.geometry()) if tmpInGeom.isGeosEmpty() or not tmpInGeom.isGeosValid(): continue outFeat.setGeometry(tmpInGeom) first = False else: tmpInGeom = QgsGeometry(inFeat.geometry()) if tmpInGeom.isGeosEmpty() or not tmpInGeom.isGeosValid(): continue tmpOutGeom = QgsGeometry(outFeat.geometry()) try: tmpOutGeom = QgsGeometry(tmpOutGeom.combine(tmpInGeom)) outFeat.setGeometry(tmpOutGeom) except: raise GeoAlgorithmExecutionException( self.tr('Geometry exception while dissolving')) outFeat.setAttributes(attrs) writer.addFeature(outFeat) else: fieldIdx = vlayerA.fieldNameIndex(fieldname) unique = vector.getUniqueValues(vlayerA, int(fieldIdx)) nFeat = len(unique) myDict = {} attrDict = {} for item in unique: myDict[unicode(item).strip()] = [] attrDict[unicode(item).strip()] = None unique = None for inFeat in features: attrs = inFeat.attributes() tempItem = attrs[fieldIdx] tmpInGeom = QgsGeometry(inFeat.geometry()) if tmpInGeom.isGeosEmpty() or not tmpInGeom.isGeosValid(): continue if attrDict[unicode(tempItem).strip()] == None: # keep attributes of first feature attrDict[unicode(tempItem).strip()] = attrs myDict[unicode(tempItem).strip()].append(tmpInGeom) features = None for key, value in myDict.items(): nElement += 1 progress.setPercentage(int(nElement * 100 / nFeat)) for i in range(len(value)): tmpInGeom = value[i] if i == 0: tmpOutGeom = tmpInGeom else: try: tmpOutGeom = QgsGeometry( tmpOutGeom.combine(tmpInGeom)) except: raise GeoAlgorithmExecutionException( self.tr('Geometry exception while dissolving')) outFeat.setGeometry(tmpOutGeom) outFeat.setAttributes(attrDict[key]) writer.addFeature(outFeat) del writer
gpl-2.0
WRdong/phalapi
vendor/phalapi/kernal/tests/src/Response/JsonResponse_Test.php
1073
<?php //require_once dirname(__FILE__) . '/bootstrap.php'; if (!class_exists('PhalApi\\Response\\JsonResponse')) { require dirname(__FILE__) . '/./src/Response/JsonResponse.php'; } /** * PhpUnderControl_PhalApi\Response\JsonResponse_Test * * 针对 ./src/Response/JsonResponse.php PhalApi\Response\JsonResponse 类的PHPUnit单元测试 * * @author: dogstar 20170708 */ class PhpUnderControl_PhalApiResponseJsonResponse_Test extends \PHPUnit_Framework_TestCase { public $phalApiResponseJsonResponse; protected function setUp() { parent::setUp(); $this->phalApiResponseJsonResponse = new PhalApi\Response\JsonResponse(); } protected function tearDown() { // 输出本次单元测试所执行的SQL语句 // var_dump(DI()->tracer->getSqls()); // 输出本次单元测试所涉及的追踪埋点 // var_dump(DI()->tracer->getSqls()); } public function testOutput() { $this->phalApiResponseJsonResponse->output(); $this->expectOutputRegex('/200/'); } }
gpl-2.0
CvO-Theory/apt
src/test/uniol/apt/analysis/synthesize/separation/BasicPureSeparationTest.java
1826
/*- * APT - Analysis of Petri Nets and labeled Transition systems * Copyright (C) 2014 Uli Schlachter * * 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. */ package uniol.apt.analysis.synthesize.separation; import uniol.apt.analysis.synthesize.PNProperties; import uniol.apt.analysis.synthesize.RegionUtility; import org.testng.annotations.Factory; /** @author Uli Schlachter */ public class BasicPureSeparationTest { static public class BasicPureSeparationFactory implements SeparationTestHelper.SeparationFactory { @Override public Separation createSeparation(RegionUtility utility, String[] locationMap) { return new BasicPureSeparation(utility, locationMap); } @Override public boolean supportsImpure() { return false; } @Override public Separation createSeparation(RegionUtility utility, PNProperties properties, String[] locationMap) throws UnsupportedPNPropertiesException { return new BasicPureSeparation(utility, properties, locationMap); } } @Factory public Object[] factory() { return SeparationTestHelper.factory(new BasicPureSeparationFactory()); } } // vim: ft=java:noet:sw=8:sts=8:ts=8:tw=120
gpl-2.0
Prosouth/DragonTale
Dragon Tale Tutorial/src/Main/Game.java
332
package Main; import javax.swing.JFrame; public class Game { public static void main(String[] args) { JFrame window = new JFrame("Dragon Tale"); window.setContentPane(new GamePanel()); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setResizable(false); window.pack(); window.setVisible(true); } }
gpl-2.0
javajoker/infoecos
src/com/infoecos/util/graph/Weight.java
105
package com.infoecos.util.graph; public class Weight { public final static Weight NA = new Weight(); }
gpl-2.0
Pengfei-Gao/source-Insight-3-for-centos7
SourceInsight3/NetFramework/ObjectDataSourceSelectingEventArgs.cs
700
public class ObjectDataSourceSelectingEventArgs : ObjectDataSourceMethodEventArgs { // Constructors public ObjectDataSourceSelectingEventArgs(System.Collections.Specialized.IOrderedDictionary inputParameters, System.Web.UI.DataSourceSelectArguments arguments, bool executingSelectCount) {} // Methods public Type GetType() {} public virtual string ToString() {} public virtual bool Equals(object obj) {} public virtual int GetHashCode() {} // Properties public System.Web.UI.DataSourceSelectArguments Arguments { get{} } public bool ExecutingSelectCount { get{} } public System.Collections.Specialized.IOrderedDictionary InputParameters { get{} } public bool Cancel { get{} set{} } }
gpl-2.0
emeryberger/eon
eon/src/edu/umass/eon/Lock.java
1463
/* * Created on Jul 8, 2005 * * To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package edu.umass.eflux; /** * @author emery, Jul 8, 2005 * Lock * */ public class Lock { public Lock (String n, int type) { scope = type & 3; variety = type & ~3; name = n; if (variety == 0) variety = 4; } public String getName () { return name; } public boolean isReader() { return variety == READER; } public boolean isWriter() { return variety == WRITER; } public boolean isConnection() { return scope == CONNECTION; } public boolean isProgram() { return scope == PROGRAM; } public boolean isSession() { return scope == SESSION; } public int hashCode() { return name.hashCode(); } public boolean equals(Object o) { if (o instanceof Lock) { Lock l = (Lock)o; return name.equals(l.getName()); } return false; } public String toString() { return name+ (isSession()?" session ":"")+ (isProgram()?" program ":""); } private String name; private int scope; private int variety; public static final int SESSION = 0; // 00 public static final int CONNECTION = 1; // 01 public static final int PROGRAM = 2; // 10 public static final int WRITER = 4; public static final int READER = 8; }
gpl-2.0
derv82/wifite2
wifite/model/pmkid_result.py
1901
#!/usr/bin/env python # -*- coding: utf-8 -*- from ..util.color import Color from .result import CrackResult class CrackResultPMKID(CrackResult): def __init__(self, bssid, essid, pmkid_file, key): self.result_type = 'PMKID' self.bssid = bssid self.essid = essid self.pmkid_file = pmkid_file self.key = key super(CrackResultPMKID, self).__init__() def dump(self): if self.essid: Color.pl('{+} %s: {C}%s{W}' % ('Access Point Name'.rjust(19), self.essid)) if self.bssid: Color.pl('{+} %s: {C}%s{W}' % ('Access Point BSSID'.rjust(19), self.bssid)) Color.pl('{+} %s: {C}%s{W}' % ('Encryption'.rjust(19), self.result_type)) if self.pmkid_file: Color.pl('{+} %s: {C}%s{W}' % ('PMKID File'.rjust(19), self.pmkid_file)) if self.key: Color.pl('{+} %s: {G}%s{W}' % ('PSK (password)'.rjust(19), self.key)) else: Color.pl('{!} %s {O}key unknown{W}' % ''.rjust(19)) def print_single_line(self, longest_essid): self.print_single_line_prefix(longest_essid) Color.p('{G}%s{W}' % 'PMKID'.ljust(5)) Color.p(' ') Color.p('Key: {G}%s{W}' % self.key) Color.pl('') def to_dict(self): return { 'type' : self.result_type, 'date' : self.date, 'essid' : self.essid, 'bssid' : self.bssid, 'key' : self.key, 'pmkid_file' : self.pmkid_file } if __name__ == '__main__': w = CrackResultPMKID('AA:BB:CC:DD:EE:FF', 'Test Router', 'hs/pmkid_blah-123213.16800', 'abcd1234') w.dump() w = CrackResultPMKID('AA:BB:CC:DD:EE:FF', 'Test Router', 'hs/pmkid_blah-123213.16800', 'Key') print('\n') w.dump() w.save() print(w.__dict__['bssid'])
gpl-2.0
jairojunior/mcollective-jboss-agent
util/jboss/digest_auth.rb
4420
require 'cgi' require 'digest' require 'monitor' require 'net/http' require 'securerandom' ## # An implementation of RFC 2617 Digest Access Authentication. # # http://www.rfc-editor.org/rfc/rfc2617.txt # # Here is a sample usage of DigestAuth on Net::HTTP: # # require 'uri' # require 'net/http' # require 'net/http/digest_auth' # # digest_auth = Net::HTTP::DigestAuth.new # # uri = URI.parse 'http://localhost:8000/' # uri.user = 'username' # uri.password = 'password' # # h = Net::HTTP.new uri.host, uri.port # # req = Net::HTTP::Get.new uri.request_uri # # res = h.request req # # res is a 401 response with a WWW-Authenticate header # # auth = digest_auth.auth_header uri, res['www-authenticate'], 'GET' # # # create a new request with the Authorization header # req = Net::HTTP::Get.new uri.request_uri # req.add_field 'Authorization', auth # # # re-issue request with Authorization # res = h.request req class Net::HTTP::DigestAuth include MonitorMixin ## # DigestAuth error class class Error < RuntimeError; end ## # Version of Net::HTTP::DigestAuth you are using VERSION = '1.4' ## # Creates a new DigestAuth header creator. def initialize(_ignored = :ignored) mon_initialize @nonce_count = -1 end ## # Creates a digest auth header for +uri+ from the +www_authenticate+ header # for HTTP method +method+. # # The result of this method should be sent along with the HTTP request as # the "Authorization" header. In Net::HTTP this will look like: # # request.add_field 'Authorization', digest_auth.auth_header # ... # # See Net::HTTP::DigestAuth for a complete example. # # IIS servers handle the "qop" parameter of digest authentication # differently so you may need to set +iis+ to true for such servers. def auth_header(uri, www_authenticate, method, iis = false) nonce_count = next_nonce user = CGI.unescape uri.user password = CGI.unescape uri.password www_authenticate =~ /^(\w+) (.*)/ challenge = Regexp.last_match(2) params = {} challenge.gsub(/(\w+)="(.*?)"/) { params[Regexp.last_match(1)] = Regexp.last_match(2) } challenge =~ /algorithm="?(.*?)"?([, ]|$)/ params['algorithm'] = Regexp.last_match(1) || 'MD5' if params['algorithm'] =~ /(.*?)(-sess)?$/ algorithm = case Regexp.last_match(1) when 'MD5' then Digest::MD5 when 'SHA1' then Digest::SHA1 when 'SHA2' then Digest::SHA2 when 'SHA256' then Digest::SHA256 when 'SHA384' then Digest::SHA384 when 'SHA512' then Digest::SHA512 when 'RMD160' then Digest::RMD160 else fail Error, "unknown algorithm \"#{Regexp.last_match(1)}\"" end sess = Regexp.last_match(2) end qop = params['qop'] cnonce = make_cnonce if qop || sess a1 = if sess [algorithm.hexdigest("#{user}:#{params['realm']}:#{password}"), params['nonce'], cnonce ].join ':' else "#{user}:#{params['realm']}:#{password}" end ha1 = algorithm.hexdigest a1 ha2 = algorithm.hexdigest "#{method}:#{uri.request_uri}" request_digest = [ha1, params['nonce']] request_digest.push(('%08x' % nonce_count), cnonce, qop) if qop request_digest << ha2 request_digest = request_digest.join ':' header = [ "Digest username=\"#{user}\"", "realm=\"#{params['realm']}\"", "algorithm=#{params['algorithm']}", if qop.nil? elsif iis "qop=\"#{qop}\"" else "qop=#{qop}" end, "uri=\"#{uri.request_uri}\"", "nonce=\"#{params['nonce']}\"", if qop [ "nc=#{'%08x' % @nonce_count}", "cnonce=\"#{cnonce}\"" ] end, "response=\"#{algorithm.hexdigest(request_digest)[0, 32]}\"", "opaque=\"#{params['opaque']}\"" if params.key? 'opaque' ].compact header.join ', ' end ## # Creates a client nonce value that is used across all requests based on the # current time, process id and a random number def make_cnonce Digest::MD5.hexdigest [ Time.now.to_i, $PROCESS_ID, SecureRandom.random_number(2**32) ].join ':' end def next_nonce synchronize do @nonce_count += 1 end end end
gpl-2.0
beardedkaktus/mannaggia_nocloud
mannaggia_nocloud.py
2273
#! /usr/bin/env python import re, random, time, argparse, subprocess, os #####var db = "santi_e_beati.txt" #the santi e beati db tts = "pico2wave -w" tts_opt = "--lang=it-IT" audiofile = "mannaggia.wav" #name of the audiofile that will be created player = "aplay -q" #audio player months = ["jan","feb","mar","apr","may","jun","jul","ago","sep","oct","nov","dec"] month31 = ["jan","mar","may","jul","ago","oct","dec"] month30 = ["apr","jun","sep","nov"] #####argparse: parser = argparse.ArgumentParser(prog="mannaggia-nocloud") parser = argparse.ArgumentParser(description='Mannaggiatore off-the-cloud, idea from github.com/LegolasTheElf/mannaggia') parser.add_argument('-w','--wait', help='wait time in seconds between one amnnaggia and the other',required=False,default=3) parser.add_argument('-d','--date', help='do the mannaggia for a specific date express like "1 jan" or 23 dec"',required=False) parser.add_argument('-r','--random', help='random day for santi e beati', action="store_true", default=False, required=False) args = parser.parse_args() #####random selection of month/day and manual selection of the day if args.random : rm = random.choice(months) if rm == "feb": today = str(random.choice(range(1,28))) + " " + rm if rm in month30 : today = str(random.choice(range(1,30))) + " " + rm if rm in month31 : today = str(random.choice(range(1,31))) + " " + rm else: if args.date is not None : today = args.date else : today = time.strftime("%d" + " " + "%b").lower().lstrip("0") print "Mannaggiament in progress for the day: " + today #debug: display the selected day #####search day line in db, split the santi e beati of the day in a list and delete the day from the list for line in open(db): if today in line: santig = line break santi = re.split('\:|\;|\.', santig) del santi[0] while True : randommannaggia = random.choice(santi)#.strip('\n') mannaggia = "Mannaggia a" + randommannaggia #builds the text of the mannaggia print mannaggia mannaggia_cmd = tts + ' ' + audiofile + ' ' + tts_opt + ' \" ' + mannaggia + '\" && ' + player + ' ' + audiofile subprocess.call(mannaggia_cmd, shell=True) #send command to os os.remove(audiofile) # time.sleep(args.wait) #wait for the spcified time
gpl-2.0
Schurwolle/apartments
wp-content/themes/catch-base/content-none.php
1139
<?php /** * The template part for displaying a message that posts cannot be found * * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package Catch Themes * @subpackage Catch Base * @since Catch Base 1.0 */ ?> <section class="no-results not-found"> <header class="page-header"> <h1 class="page-title"><?php _e( 'Nothing Found', 'catch-base' ); ?></h1> </header><!-- .page-header --> <div class="page-content"> <?php if ( is_home() && current_user_can( 'publish_posts' ) ) : ?> <p><?php printf( __( 'Ready to publish your first post? <a href="%1$s">Get started here</a>.', 'catch-base' ), esc_url( admin_url( 'post-new.php' ) ) ); ?></p> <?php elseif ( is_search() ) : ?> <p><?php _e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'catch-base' ); ?></p> <?php get_search_form(); ?> <?php else : ?> <p><?php _e( 'It seems we can&rsquo;t find what you&rsquo;re looking for. Perhaps searching can help.', 'catch-base' ); ?></p> <?php get_search_form(); ?> <?php endif; ?> </div><!-- .page-content --> </section><!-- .no-results -->
gpl-2.0
spirali/aislinn
tests/sendrecv/waitall2.cpp
565
/* * MPI_Waitall with empty lits of requests or containing MPI_REQUEST_NULL */ #include <mpi.h> #include <stdio.h> #include <string.h> int main(int argc, char **argv) { MPI_Init(&argc, &argv); MPI_Waitall(0, NULL, MPI_STATUSES_IGNORE); MPI_Request r[3]; r[0] = MPI_REQUEST_NULL; MPI_Waitall(1, r, MPI_STATUSES_IGNORE); int in = 1, out; MPI_Isend(&in, 1, MPI_INT, 0, 10, MPI_COMM_SELF, &r[0]); r[1] = MPI_REQUEST_NULL; MPI_Irecv(&out, 1, MPI_INT, 0, 10, MPI_COMM_SELF, &r[2]); MPI_Waitall(3, r, MPI_STATUSES_IGNORE); MPI_Finalize(); return 0; }
gpl-2.0
CvO-Theory/apt
src/test/uniol/apt/TestNetsForSeparation.java
8552
/*- * APT - Analysis of Petri Nets and labeled Transition systems * Copyright (C) 2012-2013 Members of the project group APT * * 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. */ package uniol.apt; import uniol.apt.adt.pn.Flow; import uniol.apt.adt.pn.PetriNet; import uniol.apt.adt.pn.Place; import uniol.apt.adt.pn.Transition; /** * Some test nets for testing separation module. * * @author Daniel * */ public class TestNetsForSeparation { private TestNetsForSeparation() { // nothing } public static PetriNet getStrongSeparableFromLecture() { PetriNet pn = new PetriNet(); Place p1 = pn.createPlace("p1"); Place p2 = pn.createPlace("p2"); Place p3 = pn.createPlace("p3"); Place p4 = pn.createPlace("p4"); p1.setInitialToken(4); p2.setInitialToken(0); p3.setInitialToken(2); Transition ta = pn.createTransition("ta"); Transition tt = pn.createTransition("tt"); pn.createFlow(p1, ta); pn.createFlow(ta, p2); pn.createFlow(p2, tt); pn.createFlow(p3, tt); pn.createFlow(tt, p4); return (pn); } public static PetriNet getStrongSeparableFromLectureWithoutToken() { PetriNet pn = new PetriNet(); Place p1 = pn.createPlace("p1"); Place p2 = pn.createPlace("p2"); Place p3 = pn.createPlace("p3"); Place p4 = pn.createPlace("p4"); p1.setInitialToken(0); p2.setInitialToken(0); p3.setInitialToken(0); Transition ta = pn.createTransition("ta"); Transition tt = pn.createTransition("tt"); pn.createFlow(p1, ta); pn.createFlow(ta, p2); pn.createFlow(p2, tt); pn.createFlow(p3, tt); pn.createFlow(tt, p4); return (pn); } public static PetriNet getWeakSeparableFromLecture() { PetriNet pnWeak = new PetriNet(); Place wp1 = pnWeak.createPlace("p1"); Place wp2 = pnWeak.createPlace("p2"); Place wp3 = pnWeak.createPlace("p3"); wp1.setInitialToken(2); wp2.setInitialToken(0); wp3.setInitialToken(0); Transition wta = pnWeak.createTransition("a"); Transition wtb = pnWeak.createTransition("b"); Transition wtc = pnWeak.createTransition("c"); pnWeak.createFlow(wp1, wta); pnWeak.createFlow(wta, wp2); pnWeak.createFlow(wta, wp3); pnWeak.createFlow(wp2, wtb); pnWeak.createFlow(wtb, wp3); pnWeak.createFlow(wp3, wtb); pnWeak.createFlow(wp3, wtc); return (pnWeak); } public static PetriNet getNoSeparableFromLecture() { PetriNet pnNo = new PetriNet(); Place noP1 = pnNo.createPlace("p1"); Place noP2 = pnNo.createPlace("p2"); Place noP3 = pnNo.createPlace("p3"); Place noP4 = pnNo.createPlace("p4"); noP1.setInitialToken(2); noP2.setInitialToken(2); noP3.setInitialToken(0); noP4.setInitialToken(0); Transition noTb = pnNo.createTransition("b"); Transition noTt = pnNo.createTransition("t"); Transition noTa = pnNo.createTransition("a"); pnNo.createFlow(noP1, noTb); pnNo.createFlow(noTb, noP3); pnNo.createFlow(noP2, noTt); pnNo.createFlow(noP3, noTt); pnNo.createFlow(noTt, noP4); pnNo.createFlow(noP4, noTa); pnNo.createFlow(noTa, noP3); return (pnNo); } public static PetriNet getNoSeparable() { PetriNet pnNon = new PetriNet(); Place nonP1 = pnNon.createPlace("p1"); Place nonP2 = pnNon.createPlace("p2"); Place nonP3 = pnNon.createPlace("p3"); nonP1.setInitialToken(2); nonP2.setInitialToken(0); nonP3.setInitialToken(0); Transition nonTa = pnNon.createTransition("a"); Transition nonTb = pnNon.createTransition("b"); pnNon.createFlow(nonP1, nonTa); pnNon.createFlow(nonTa, nonP2); pnNon.createFlow(nonP2, nonTb); pnNon.createFlow(nonP1, nonTb); pnNon.createFlow(nonTb, nonP3); return (pnNon); } public static PetriNet getSeparableCycle() { PetriNet pnC = new PetriNet(); Place cP1 = pnC.createPlace("p1"); Place cP2 = pnC.createPlace("p2"); cP1.setInitialToken(2); cP2.setInitialToken(0); Transition cTa = pnC.createTransition("a"); Transition cTb = pnC.createTransition("b"); pnC.createFlow(cP1, cTa); pnC.createFlow(cTa, cP2); pnC.createFlow(cP2, cTb); pnC.createFlow(cTb, cP1); return (pnC); } public static PetriNet getSeparableLine() { PetriNet pnC = new PetriNet(); Place cP1 = pnC.createPlace("p1"); Place cP2 = pnC.createPlace("p2"); Place cP3 = pnC.createPlace("p3"); cP1.setInitialToken(2); cP2.setInitialToken(0); cP3.setInitialToken(0); Transition cTa = pnC.createTransition("a"); Transition cTb = pnC.createTransition("b"); pnC.createFlow(cP1, cTa); pnC.createFlow(cTa, cP2); pnC.createFlow(cP2, cTb); pnC.createFlow(cTb, cP3); return (pnC); } public static PetriNet getSeparableTrivial() { PetriNet pn = new PetriNet(); pn.createTransition("ta"); return (pn); } /** * 6-initial marking. * 3-separable, but not 2-separable and not 6-separable * * @return PetriNet */ public static PetriNet getSeparableK3Not26() { PetriNet pn = new PetriNet(); Place s = pn.createPlace(); Place s1 = pn.createPlace(); s.setInitialToken(6); s1.setInitialToken(0); Transition ta1 = pn.createTransition("ta1"); Transition ta2 = pn.createTransition("ta2"); Transition tb = pn.createTransition("tb"); Flow arc = pn.createFlow(s, ta1); arc.setWeight(2); pn.createFlow(ta1, s1); pn.createFlow(s1, ta2); Flow arc2 = pn.createFlow(ta2, s); arc2.setWeight(2); pn.createFlow(s, tb); pn.createFlow(tb, s); return (pn); } /** * 6-initial marking. * 2-separable, but not 3-separable and not 6-separable * * @return PetriNet */ public static PetriNet getSeparableK2Not36() { PetriNet pn = new PetriNet(); Place s = pn.createPlace(); Place s1 = pn.createPlace(); s.setInitialToken(6); s1.setInitialToken(0); Transition ta1 = pn.createTransition("ta1"); Transition ta2 = pn.createTransition("ta2"); Transition tb = pn.createTransition("tb"); Flow arc = pn.createFlow(s, ta1); arc.setWeight(3); pn.createFlow(ta1, s1); pn.createFlow(s1, ta2); Flow arc2 = pn.createFlow(ta2, s); arc2.setWeight(3); pn.createFlow(s, tb); pn.createFlow(tb, s); return (pn); } /** * 2-initial marking. * alive, reversible, FC * not 2-separable * @return PetriNet */ public static PetriNet getNoSeparableLiveRevFC() { PetriNet pn = new PetriNet(); Place s1 = pn.createPlace(); Place s2 = pn.createPlace(); Place s3 = pn.createPlace(); Place s4 = pn.createPlace(); Place s5 = pn.createPlace(); s1.setInitialToken(2); s2.setInitialToken(0); s3.setInitialToken(0); s4.setInitialToken(0); s5.setInitialToken(2); Transition t1 = pn.createTransition("t1"); Transition t2 = pn.createTransition("t2"); Transition t3 = pn.createTransition("t3"); Transition t4 = pn.createTransition("t4"); Transition t5 = pn.createTransition("t5"); pn.createFlow(s1, t1); pn.createFlow(s4, t1); pn.createFlow(t1, s2); pn.createFlow(s2, t2); pn.createFlow(t2, s3); pn.createFlow(t2, s4); pn.createFlow(s5, t3); pn.createFlow(t3, s4); pn.createFlow(s1, t4); pn.createFlow(s4, t4); pn.createFlow(t4, s3); pn.createFlow(t4, s5); pn.createFlow(s3, t5); pn.createFlow(t5, s1); return (pn); } /** * 2-initial marking. * weakly 2-separable but not strongly, reversible, FC * "aacbbc" weakly but not strongly * * @return PetriNet */ public static PetriNet getWeakSeparable() { PetriNet pn = new PetriNet(); Place s1 = pn.createPlace(); Place s2 = pn.createPlace(); Place s3 = pn.createPlace(); s1.setInitialToken(0); s2.setInitialToken(2); s3.setInitialToken(0); Transition ta = pn.createTransition("ta"); Transition tb = pn.createTransition("tb"); Transition tc = pn.createTransition("tc"); pn.createFlow(s2, ta); pn.createFlow(ta, s1); pn.createFlow(ta, s3); pn.createFlow(s1, tb); pn.createFlow(s3, tb); pn.createFlow(tb, s3); pn.createFlow(s3, tc); return (pn); } } // vim: ft=java:noet:sw=8:sts=8:ts=8:tw=120
gpl-2.0
rajuniit/falgun-api
config/initializers/doorkeeper.rb
3516
Doorkeeper.configure do # Change the ORM that doorkeeper will use. # Currently supported options are :active_record, :mongoid2, :mongoid3, :mongo_mapper orm :mongoid3 # This block will be called to check whether the resource owner is authenticated or not. resource_owner_authenticator do #raise "Please configure doorkeeper resource_owner_authenticator block located in #{__FILE__}" # Put your resource owner authentication logic here. # Example implementation: # User.find_by_id(session[:user_id]) || redirect_to(new_user_session_url) current_user || warden.authenticate!(:scope => :user) end # If you want to restrict access to the web interface for adding oauth authorized applications, you need to declare the block below. # admin_authenticator do # # Put your admin authentication logic here. # # Example implementation: # Admin.find_by_id(session[:admin_id]) || redirect_to(new_admin_session_url) # end # Authorization Code expiration time (default 10 minutes). # authorization_code_expires_in 10.minutes # Access token expiration time (default 2 hours). # If you want to disable expiration, set this to nil. # access_token_expires_in 2.hours # Issue access tokens with refresh token (disabled by default) # use_refresh_token # Provide support for an owner to be assigned to each registered application (disabled by default) # Optional parameter :confirmation => true (default false) if you want to enforce ownership of # a registered application # Note: you must also run the rails g doorkeeper:application_owner generator to provide the necessary support # enable_application_owner :confirmation => false # Define access token scopes for your provider # For more information go to https://github.com/applicake/doorkeeper/wiki/Using-Scopes # default_scopes :public # optional_scopes :write, :update # Change the way client credentials are retrieved from the request object. # By default it retrieves first from the `HTTP_AUTHORIZATION` header, then # falls back to the `:client_id` and `:client_secret` params from the `params` object. # Check out the wiki for more information on customization # client_credentials :from_basic, :from_params # Change the way access token is authenticated from the request object. # By default it retrieves first from the `HTTP_AUTHORIZATION` header, then # falls back to the `:access_token` or `:bearer_token` params from the `params` object. # Check out the wiki for more information on customization # access_token_methods :from_bearer_authorization, :from_access_token_param, :from_bearer_param # Change the test redirect uri for client apps # When clients register with the following redirect uri, they won't be redirected to any server and the authorization code will be displayed within the provider # The value can be any string. Use nil to disable this feature. When disabled, clients must provide a valid URL # (Similar behaviour: https://developers.google.com/accounts/docs/OAuth2InstalledApp#choosingredirecturi) # # test_redirect_uri 'urn:ietf:wg:oauth:2.0:oob' # Under some circumstances you might want to have applications auto-approved, # so that the user skips the authorization step. # For example if dealing with trusted a application. # skip_authorization do |resource_owner, client| # client.superapp? or resource_owner.admin? # end # WWW-Authenticate Realm (default "Doorkeeper"). # realm "Doorkeeper" end
gpl-2.0
taconaut/ums-mlx
plugins/PlayCountWatcherPlugin/src/main/java/net/pms/plugin/startstoplistener/PlayCountWatcher.java
5604
package net.pms.plugin.startstoplistener; import java.io.IOException; import java.util.Date; import java.util.LinkedList; import java.util.Queue; import java.util.ResourceBundle; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.pms.dlna.DLNAMediaInfo; import net.pms.dlna.DLNAResource; import net.pms.dlna.RealFile; import net.pms.plugin.startstoplistener.pcw.configuration.GlobalConfiguration; import net.pms.plugin.startstoplistener.pcw.gui.GlobalConfigurationPanel; import net.pms.plugins.StartStopListener; import net.pms.util.PmsProperties; import net.pms.medialibrary.commons.interfaces.IMediaLibraryStorage; import net.pms.medialibrary.storage.MediaLibraryStorage; public class PlayCountWatcher implements StartStopListener { private static final Logger logger = LoggerFactory.getLogger(PlayCountWatcher.class); public static final ResourceBundle messages = ResourceBundle.getBundle("net.pms.plugin.startstoplistener.pcw.lang.messages"); private Queue<QueueItem> playCache = new LinkedList<QueueItem>(); private IMediaLibraryStorage storage; /** Holds only the project version. It's used to always use the maven build number to display the version in code */ private static final PmsProperties properties = new PmsProperties(); static { try { properties.loadFromResourceFile("/playcountwatcherplugin.properties", PlayCountWatcher.class); } catch (IOException e) { logger.error("Could not load playcountwatcherplugin.properties", e); } } /** The global configuration is shared amongst all plugin instances. */ private static final GlobalConfiguration globalConfig; static { globalConfig = new GlobalConfiguration(); try { globalConfig.load(); } catch (IOException e) { logger.error("Failed to load global configuration", e); } } /** GUI */ private GlobalConfigurationPanel pGlobalConfiguration; @Override public void donePlaying(DLNAMediaInfo media, DLNAResource resource) { if (logger.isDebugEnabled()) logger.debug("Done playing " + resource.getName()); // lazy-load the storage if (storage == null) { storage = MediaLibraryStorage.getInstance(); if (storage == null) return; } // update the play count if 80% of the file has been played. remove it from the cache anyway as it finished // playing // TODO: try to improve this behavior when pausing a stream int playLengthSec = 0; while (true) { QueueItem item = playCache.poll(); if (item == null) { break; } if (item.resourcId.equals(resource.getInternalId())) { if (resource instanceof RealFile) { playLengthSec = (int) (new Date().getTime() - item.startDate.getTime()) / 1000; break; } } } if (playLengthSec > 0) { String filePath = ((RealFile) resource).getFile().getAbsolutePath(); int fullLengthSec = (int) media.getDurationInSeconds(); int minPlayLogLength = (int) (fullLengthSec * ((double) globalConfig.getPercentPlayedRequired() / 100)); if (logger.isDebugEnabled()) logger.debug(String.format("Stopped playing %s (%s) after %s seconds. Min play length for loging %ss", resource.getName(), resource.getInternalId(), playLengthSec, minPlayLogLength)); if (playLengthSec > minPlayLogLength) { // TODO: insert the file with basic info (mencoder/ffmpeg but no plugins) if it hasn't been previously // inserted into the library storage.updatePlayCount(filePath, playLengthSec, new Date()); if (logger.isInfoEnabled()) logger.info(String.format("Updated play count for %s (%s) after %s seconds. Min play length for loging %ss", resource.getName(), resource.getInternalId(), playLengthSec, minPlayLogLength)); } } } @Override public void nowPlaying(DLNAMediaInfo media, DLNAResource resource) { if (logger.isDebugEnabled()) logger.debug(String.format("Started playing %s (%s)", resource.getName(), resource.getInternalId())); playCache.add(new QueueItem(resource.getInternalId(), new Date())); } @Override public JComponent getGlobalConfigurationPanel() { if (pGlobalConfiguration == null) { pGlobalConfiguration = new GlobalConfigurationPanel(globalConfig); } pGlobalConfiguration.applyConfig(); return pGlobalConfiguration; } @Override public String getName() { return messages.getString("PlayCountWatcher.Name"); } @Override public void shutdown() { playCache.clear(); } private class QueueItem { String resourcId; Date startDate; public QueueItem(String id, Date date) { resourcId = id; startDate = date; } } @Override public String getVersion() { return properties.get("project.version"); } @Override public Icon getPluginIcon() { return new ImageIcon(getClass().getResource("/playcountwatcher-32.png")); } @Override public String getShortDescription() { return messages.getString("PlayCountWatcher.ShortDescription"); } @Override public String getLongDescription() { return messages.getString("PlayCountWatcher.LongDescription"); } @Override public String getUpdateUrl() { return null; } @Override public String getWebSiteUrl() { return "http://www.ps3mediaserver.org/"; } @Override public void initialize() { } @Override public void saveConfiguration() { if (pGlobalConfiguration != null) { pGlobalConfiguration.updateConfiguration(globalConfig); try { globalConfig.save(); } catch (IOException e) { logger.error("Failed to save global configuration", e); } } } @Override public boolean isPluginAvailable() { return true; } }
gpl-2.0
joravlo/Actividad1D
archive-employees.php
2380
<?php /** * Services archives template * * @package Sydney */ //Toco este archivo get_header(); ?> <?php do_action('sydney_before_content'); ?> <div id="primary" class="content-area"> <main id="main" class="post-wrap roll-team no-carousel" role="main"> <?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> <?php //Get the custom field values $photo = get_post_meta( get_the_ID(), 'wpcf-photo', true ); $position = get_post_meta( get_the_ID(), 'wpcf-position', true ); $facebook = get_post_meta( get_the_ID(), 'wpcf-facebook', true ); $twitter = get_post_meta( get_the_ID(), 'wpcf-twitter', true ); $google = get_post_meta( get_the_ID(), 'wpcf-google-plus', true ); $link = get_post_meta( get_the_ID(), 'wpcf-custom-link', true ); ?> <div class="team-item col-md-4"> <div class="team-inner"> <?php if ( has_post_thumbnail() ) : ?> <div class="avatar"> <?php the_post_thumbnail('employees-image'); ?> </div> <?php endif; ?> </div> <div class="team-content"> <div class="name"> <?php if ($link == '') : ?> <?php the_title(); ?> <?php else : ?> <a href="<?php echo esc_url($link); ?>"><?php the_title(); ?></a> <?php endif; ?> </div> <div class="pos"><?php echo esc_html($position); ?></div> <ul class="team-social"> <?php if ($facebook != '') : ?> <li><a class="facebook" href="<?php echo esc_url($facebook); ?>" target="_blank"><i class="fa fa-facebook"></i></a></li> <?php endif; ?> <?php if ($twitter != '') : ?> <li><a class="twitter" href="<?php echo esc_url($twitter); ?>" target="_blank"><i class="fa fa-twitter"></i></a></li> <?php endif; ?> <?php if ($google != '') : ?> <li><a class="google" href="<?php echo esc_url($google); ?>" target="_blank"><i class="fa fa-google-plus"></i></a></li> <?php endif; ?> </ul> </div> </div><!-- /.team-item --> <?php endwhile; ?> <?php the_posts_navigation(); ?> <?php else : ?> <?php get_template_part( 'content', 'none' ); ?> <?php endif; ?> </main><!-- #main --> </div><!-- #primary --> <?php do_action('sydney_after_content'); ?> <?php get_footer(); ?>
gpl-2.0
vanilla-bear/julien
modules/ubercart/uc_tax/src/Entity/TaxRate.php
5000
<?php namespace Drupal\uc_tax\Entity; use Drupal\Core\Config\Entity\ConfigEntityBase; use Drupal\uc_tax\TaxRateInterface; /** * Defines a tax rate configuration entity. * * @ConfigEntityType( * id = "uc_tax_rate", * label = @Translation("Tax rate"), * label_singular = @Translation("tax rate"), * label_plural = @Translation("tax rates"), * label_count = @PluralTranslation( * singular = "@count tax rate", * plural = "@count tax rates", * ), * handlers = { * "access" = "Drupal\Core\Entity\EntityAccessControlHandler", * "list_builder" = "Drupal\uc_tax\TaxRateListBuilder", * "form" = { * "default" = "Drupal\uc_tax\Form\TaxRateForm", * "delete" = "Drupal\uc_tax\Form\TaxRateDeleteForm" * } * }, * entity_keys = { * "id" = "id", * "label" = "label", * "status" = "status", * "weight" = "weight" * }, * config_export = { * "id", * "label", * "weight", * "shippable", * "display_include", * "inclusion_text", * "product_types", * "line_item_types", * "plugin", * "settings", * }, * config_prefix = "rate", * admin_permission = "administer taxes", * links = { * "edit-form" = "/admin/store/config/tax/{uc_tax_rate}", * "enable" = "/admin/store/config/tax/{uc_tax_rate}/enable", * "disable" = "/admin/store/config/tax/{uc_tax_rate}/disable", * "delete-form" = "/admin/store/config/tax/{uc_tax_rate}/delete", * "clone" = "/admin/store/config/tax/{uc_tax_rate}/clone", * "collection" = "/admin/store/config/tax" * } * ) */ class TaxRate extends ConfigEntityBase implements TaxRateInterface { /** * The tax rate ID. * * @var string */ protected $id; /** * The tax rate label. * * @var string */ protected $label; /** * The tax rate. * * @var float */ protected $rate; /** * The tax rate weight. * * @var int */ protected $weight = 0; /** * Whether to display prices including tax. * * @var bool */ protected $display_include; /** * The text to display next to prices if tax is included. * * @var string */ protected $inclusion_text; /** * If the tax applies only to shippable products. * * @var string */ protected $shippable; /** * Line item types subject to this tax rate. * * @var string[] */ protected $line_item_types = []; /** * Product item types subject to this tax rate. * * @var string[] */ protected $product_types = []; /** * The tax rate plugin ID. * * @var string */ protected $plugin; /** * The tax rate plugin settings. * * @var array */ protected $settings = array(); /** * {@inheritdoc} */ public function getPlugin() { return \Drupal::service('plugin.manager.uc_tax.rate')->createInstance($this->plugin, $this->settings); } /** * {@inheritdoc} */ public function setId($id) { $this->id = $id; return $this; } /** * {@inheritdoc} */ public function getLabel() { return $this->label(); } /** * {@inheritdoc} */ public function setLabel($label) { $this->label = $label; return $this; } /** * {@inheritdoc} */ public function getRate() { return $this->rate; } /** * {@inheritdoc} */ public function setRate($rate) { $this->rate = $rate; return $this; } /** * {@inheritdoc} */ public function getProductTypes() { return $this->product_types; } /** * {@inheritdoc} */ public function setProductTypes(array $product_types) { $this->product_types = $product_types; return $this; } /** * {@inheritdoc} */ public function getLineItemTypes() { return $this->line_item_types; } /** * {@inheritdoc} */ public function setLineItemTypes(array $line_item_types) { $this->line_item_types = $line_item_types; return $this; } /** * {@inheritdoc} */ public function getWeight() { return $this->weight; } /** * {@inheritdoc} */ public function setWeight($weight) { $this->weight = $weight; return $this; } /** * {@inheritdoc} */ public function isIncludedInPrice() { return (bool) $this->display_include; } /** * {@inheritdoc} */ public function setIncludedInPrice($included) { $this->display_include = (bool) $included; return $this; } /** * {@inheritdoc} */ public function getInclusionText() { return $this->inclusion_text; } /** * {@inheritdoc} */ public function setInclusionText($inclusion_text) { $this->inclusion_text = $inclusion_text; return $this; } /** * {@inheritdoc} */ public function isForShippable() { return (bool) $this->shippable; } /** * {@inheritdoc} */ public function setForShippable($shippable) { $this->shippable = (bool) $shippable; return $this; } }
gpl-2.0
loveyoupeng/rt
apps/samples/Modena/src/main/java/modena/SamplePageHelpers.java
15270
/* * Copyright (c) 2008, 2015, Oracle and/or its affiliates. * All rights reserved. Use is subject to license terms. * * This file is available and licensed under the following license: * * 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 Oracle Corporation 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. */ package modena; import java.util.ArrayList; import java.util.List; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.css.PseudoClass; import javafx.geometry.Insets; import javafx.geometry.Orientation; import javafx.geometry.Pos; import javafx.geometry.Side; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.control.Accordion; import javafx.scene.control.Button; import javafx.scene.control.CheckMenuItem; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.RadioMenuItem; import javafx.scene.control.Pagination; import javafx.scene.control.SelectionMode; import javafx.scene.control.Separator; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.SplitPane; import javafx.scene.control.TabPane; import javafx.scene.control.Tab; import javafx.scene.control.TitledPane; import javafx.scene.control.TextField; import javafx.scene.control.ToolBar; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCharacterCombination; import javafx.scene.input.KeyCombination; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Line; import javafx.scene.shape.Rectangle; /** * Helper static methods for Sample Page */ public class SamplePageHelpers { static <T extends Node> T withState(T node, String state) { if (node != null && state != null) { // stop user from being able to change state node.setMouseTransparent(true); node.setFocusTraversable(false); // set state to chosen state final String[] pseudoClasses = (state).split("[\\s,]+"); for (String pseudoClass : pseudoClasses) { node.pseudoClassStateChanged(PseudoClass.getPseudoClass(pseudoClass), true); } } return node; } static <T extends Node> T withState(final T node, final String state, final String subNodeStyleClass, final String subNodeState) { withState(node, state); Platform.runLater(() -> withState(node.lookup(subNodeStyleClass), subNodeState)); return node; } private static final String[] LETTERS = new String[]{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}; static ObservableList<String> sampleItems() { return sampleItems(7); } static ObservableList<String> sampleItems(int numberOfItems) { ArrayList<String> items = new ArrayList<String>(); if (numberOfItems < 26) { for(int i=0; i<numberOfItems; i++) { items.add("Item "+LETTERS[i]); } } else { for(int i=0; i<numberOfItems; i++) { items.add("Item "+i); } } return FXCollections.observableArrayList(items); } static Node scrollPaneContent() { Line l1 = new Line(); l1.setEndX(200); l1.setEndY(200); l1.setStroke(Color.DODGERBLUE); Line l2 = new Line(); l2.setStartX(200); l2.setStartY(0); l2.setEndY(200); l2.setStroke(Color.DODGERBLUE); return new Group(new Rectangle(200, 200, Color.PALETURQUOISE), l1, l2); } static Node createTabPane(int numOfTabs, int prefWidth, int prefHeight, String firstTabText, boolean floating, boolean disableFirst, Side side) { TabPane tabPane = new TabPane(); tabPane.setSide(side); if (floating) tabPane.getStyleClass().add("floating"); for (int i=1; i<=numOfTabs; i++) { Tab tab = new Tab("Tab "+i); tab.setDisable(i==1 && disableFirst); tab.setContent(new Label((i==1 && firstTabText!=null)? firstTabText :"Tab "+i+" Content")); tabPane.getTabs().add(tab); } if (disableFirst) tabPane.getSelectionModel().select(1); tabPane.setPrefWidth(prefWidth); tabPane.setPrefHeight(prefHeight); return tabPane; } static Node wrapBdr(Node node) { StackPane sp = new StackPane(node); sp.setStyle("-fx-border-color: black; -fx-border-width: 3;"); return sp; } static ToolBar createToolBar(Side side, boolean overFlow, boolean disabled) { final boolean vertical = side == Side.LEFT || side == Side.RIGHT; ToolBar toolBar = new ToolBar(); if (vertical) toolBar.setOrientation(Orientation.VERTICAL); if (side == Side.BOTTOM) toolBar.getStyleClass().add("bottom"); if (side == Side.RIGHT) toolBar.getStyleClass().add("right"); if (disabled) toolBar.setDisable(true); toolBar.getItems().addAll( new Button("A"), new Button("B"), new Separator() ); if (vertical) { toolBar.getItems().addAll( new Button("C"), new Button("D") ); } else { Label searchLabel = new Label("Search:"); HBox searchBox = new HBox(10, searchLabel, new TextField()); searchBox.setAlignment(Pos.BASELINE_LEFT); toolBar.getItems().addAll(searchBox); } if (overFlow) { if (vertical) { toolBar.setPrefHeight(80); } else { toolBar.setPrefWidth(80); } } return toolBar; } static Accordion createAccordion() { Accordion accordian = new Accordion(); accordian.getPanes().addAll( new TitledPane("Title 1", new Label("Content\nLine2.")), new TitledPane("Title 2", new Label("Content\nLine2.")), new TitledPane("Title 3", new Label("Content\nLine2.")) ); return accordian; } static SplitPane createSplitPane(int numOfItems, boolean vertical, Node firstItem) { SplitPane splitPane = new SplitPane(); if(vertical) splitPane.setOrientation(Orientation.VERTICAL); if (firstItem != null) splitPane.getItems().add(firstItem); for (int i=1; i<=numOfItems; i++) { splitPane.getItems().add(new Label("Item "+i)); } splitPane.setPrefSize(150, 150); return splitPane; } static Pagination createPagination(int numOfPages, boolean bullet, boolean arrows) { Pagination pagination = new Pagination(numOfPages); if (bullet) pagination.getStyleClass().add("bullet"); if (!arrows) pagination.setStyle("-fx-arrows-visible:false;"); pagination.setPageFactory(param -> new Label("Page Label "+param)); return pagination; } static ListView<String> createListView(int numOfItems, boolean multipleSelection, boolean disable, boolean horiz) { ListView<String> listView = new ListView<String>(); if (horiz) listView.setOrientation(Orientation.HORIZONTAL); listView.setPrefHeight((24*7)+4); listView.setPrefWidth(horiz ? 200 : 140); listView.getItems().addAll(sampleItems(numOfItems)); listView.setDisable(disable); if (multipleSelection) { listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); listView.getSelectionModel().selectRange(1, 5); } else { listView.getSelectionModel().select(1); } return listView; } static MenuItem[] createMenuItems(int numberOfItems) { ArrayList<MenuItem> items = new ArrayList<MenuItem>(); if (numberOfItems < 26) { for(int i=0; i<numberOfItems; i++) { items.add(new MenuItem("Item "+LETTERS[i])); } } else { for(int i=0; i<numberOfItems; i++) { items.add(new MenuItem("Item "+i)); } } return items.toArray(new MenuItem[items.size()]); } static MenuBar createMenuBar() { final MenuBar mb = new MenuBar(); mb.getMenus().addAll( createMenu("File"), createMenu("Edit"), createMenu("View"), createMenu("Help") ); Platform.runLater(() -> new ArrayList<Node>(mb.lookupAll(".menu")).get(1).pseudoClassStateChanged(PseudoClass.getPseudoClass("hover"), true)); return mb; } static Menu createMenu(String name) { Menu m = new Menu(name); m.getStyleClass().add(name); m.getItems().addAll(createMenuContents()); return m; } static Node createContextMenu() { Button b = new Button("ContextMenu Right Click Me"); b.setContextMenu(new ContextMenu(createMenuContents())); return b; } static Node createInlineMenu(final boolean selectAll) { // create a context menu so we can put it inline in our test page final ContextMenu menu = new ContextMenu(createMenuContents()); // create a place holder container final StackPane contextMenu = new StackPane(); // show context menu then steal and place inline Platform.runLater(() -> { menu.show(contextMenu,-1000,-1000); menu.hide(); Platform.runLater(() -> { final Node menuContent = menu.getSkin().getNode(); contextMenu.getChildren().add(menuContent); menuContent.setMouseTransparent(true); // System.out.println("menuContent = " + menuContent); // System.out.println("menuContent.lookupAll(\".menu-item\") = " + menuContent.lookupAll(".menu-item")); // Platform.runLater(new Runnable() { // @Override public void run() { //// if (selectAll) { //// for (Node n: menuContent.lookupAll(".menu-item")) { //// n.pseudoClassStateChanged(PseudoClass.getPseudoClass("hover"), true); //// } //// } else { // new ArrayList<Node>(menuContent.lookupAll(".menu-item")).get(2) // .pseudoClassStateChanged(PseudoClass.getPseudoClass("hover"), true); //// } // } // }); }); }); return contextMenu; } static MenuItem[] createMenuContents() { List<MenuItem> menuItems = new ArrayList<>(); final Menu menu11 = new Menu("_New"); MenuItem menu12 = new MenuItem("_Open"); menu12.getStyleClass().add("OpenMenuItem"); menu12.setAccelerator(new KeyCharacterCombination("]", KeyCombination.SHIFT_DOWN, KeyCombination.META_DOWN)); Menu menu13 = new Menu("_Submenu"); MenuItem menu15 = new MenuItem("E_xit"); final String change[] = {"Change Text", "Change Back"}; final MenuItem menu16 = new MenuItem(change[0]); menu16.setAccelerator(KeyCombination.keyCombination("Shortcut+C")); menuItems.add(menu11); menuItems.add(menu12); menuItems.add(menu13); menuItems.add(menu16); menuItems.add(new SeparatorMenuItem()); menuItems.add(new CheckMenuItem("Check")); CheckMenuItem checkMenuItem = new CheckMenuItem("Check Selected"); checkMenuItem.setSelected(true); menuItems.add(checkMenuItem); menuItems.add(new SeparatorMenuItem()); menuItems.add(new RadioMenuItem("Radio")); RadioMenuItem radioMenuItem = new RadioMenuItem("Radio Selected"); radioMenuItem.setSelected(true); menuItems.add(radioMenuItem); menuItems.add(new SeparatorMenuItem()); menuItems.add(menu15); // --- Menu 11 submenu final MenuItem menu111 = new MenuItem("blah"); final MenuItem menu112 = new MenuItem("foo"); final CheckMenuItem menu113 = new CheckMenuItem("Show \"foo\" item"); menu113.setSelected(true); menu113.selectedProperty().addListener(valueModel -> { menu112.setVisible(menu113.isSelected()); System.err.println("MenuItem \"foo\" is now " + (menu112.isVisible() ? "" : "not") + " visible."); }); menu11.getItems().addAll(menu111, menu112, menu113); // --- Menu 13 submenu MenuItem menu131 = new MenuItem("Item _1"); MenuItem menu132 = new MenuItem("Item _2"); menu13.getItems().addAll(menu131, menu132); return menuItems.toArray(new MenuItem[menuItems.size()]); } static final Image recorder48 = new Image(SamplePageHelpers.class.getResource("recorder-icon-48.png").toExternalForm()); static ImageView createGraphic() { return new ImageView(recorder48); } static Node createGreyButton(double percentageGrey) { int grey = (int)(percentageGrey*255); int percentage = (int)(percentageGrey * 100); StackPane sp = new StackPane(); sp.setStyle("-fx-base: rgba("+grey+","+grey+","+grey+",1); -fx-background-color: -fx-background;"); sp.setPadding(new Insets(8)); sp.getChildren().add(new Button(percentage+"%")); return sp; } }
gpl-2.0
dotcastle/sql-dependency-provider
SqlDependencies/DC.Data.SqlDependencies/Common/Helper.cs
13461
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading; using DC.Data.SqlDependencies.Properties; namespace DC.Data.SqlDependencies { /// <summary> /// Helper class /// </summary> internal static class Helper { private static readonly object _syncLock = new object(); private static readonly Dictionary<string, int> _refCounts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); #region External Access /// <summary> /// Ensures that the required db objects exist /// </summary> /// <param name="dependencyParams">Dependency parameters</param> public static void CreateSqlObjects(SqlDependencyParams dependencyParams) { // Create connection using (new MonitorLock(_syncLock)) using (var conn = new SqlConnection(dependencyParams.ConnectionString)) { // Open EnsureOpenConnection(conn); // Take a backup of ref counts var backupRefCounts = new Dictionary<string, int>(_refCounts); // Transaction using (var trans = conn.BeginTransaction(IsolationLevel.Serializable)) { // Enclose to rollback uncommitted transaction var transCommitted = false; try { // Changes table EnsureChangeHolderTable(conn, trans, dependencyParams); // Ensure Table Triggers for all monitored tables EnsureTableTriggers(conn, trans, dependencyParams); // Commit trans.Commit(); transCommitted = true; } finally { if (!transCommitted) { // Rollback db trans.Rollback(); // Rollback Ref Counts _refCounts.Clear(); backupRefCounts.ToList().ForEach(kv => _refCounts[kv.Key] = kv.Value); } } } } } /// <summary> /// Ensures that the required db objects are deleted /// </summary> /// <param name="dependencyParams">Dependency parameters</param> public static void DeleteSqlObjects(SqlDependencyParams dependencyParams) { // Create connection using (new MonitorLock(_syncLock)) using (var conn = new SqlConnection(dependencyParams.ConnectionString)) { // Open EnsureOpenConnection(conn); // Take a backup of ref counts var backupRefCounts = new Dictionary<string, int>(_refCounts); // Transaction using (var trans = conn.BeginTransaction(IsolationLevel.Serializable)) { // Enclose to rollback uncommitted transaction var transCommitted = false; try { // Delete Table Triggers for all monitored tables DeleteTableTriggers(conn, trans, dependencyParams); // Delete Changes table DeleteChangeHolderTable(conn, trans, dependencyParams); // Commit trans.Commit(); transCommitted = true; } finally { if (!transCommitted) { // Rollback db trans.Rollback(); // Rollback Ref Counts _refCounts.Clear(); backupRefCounts.ToList().ForEach(kv => _refCounts[kv.Key] = kv.Value); } } } } } #endregion #region Helpers /// <summary> /// Checks if the connection is open. If not, tries to open the connection /// </summary> /// <param name="connection">Connection object</param> /// <param name="maxTries">Number of times a connection will be tried</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public static void EnsureOpenConnection(DbConnection connection, int maxTries = 5) { // Validate if (connection == null) { throw new ArgumentNullException(nameof(connection)); } if (maxTries < 0) { maxTries = 5; } var numTries = 0; Exception previousException = null; while (true) { // Check State if ((connection.State == ConnectionState.Open) || (connection.State == ConnectionState.Executing) || (connection.State == ConnectionState.Fetching)) { return; } else if (connection.State == ConnectionState.Connecting) { Thread.Sleep(250); continue; } // Check if retries exceeded if (numTries >= maxTries) { #if USETRANSLATIONS throw new InvalidOperationException(Translations.Default["SText_DatabaseConnectionCouldNotBeOpened"], previousException); #else throw new InvalidOperationException(Resources.SText_DatabaseConnectionCouldNotBeOpened, previousException); #endif } // Delay if (numTries > 0) { Thread.Sleep(1000); } try { // Open connection.Open(); } catch (InvalidOperationException) { // Data source/server not specified error. Cannot retry throw; } catch (SqlException ex) { // Check password error if ((ex.Number == 18487) || (ex.Number == 18488)) { // Password expired. Cannot retry throw; } // Save exception previousException = ex; } catch (Exception ex) { // Continue on all other errors // Save exception previousException = ex; } finally { numTries += 1; } } } /// <summary> /// Check if a table exists /// </summary> [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")] internal static bool TableExists(SqlConnection connection, SqlTransaction trans, SqlDependencyQualifiedObjectName table) { var commandText = string.Format(CultureInfo.InvariantCulture, "SELECT COUNT(*) FROM [sys].[tables] WHERE [object_id] = OBJECT_ID('{0}')", table); using (var cmd = new SqlCommand(commandText, connection)) { cmd.CommandType = CommandType.Text; cmd.Transaction = trans; return Convert.ToInt32(cmd.ExecuteScalar(), CultureInfo.InvariantCulture) > 0; } } /// <summary> /// Check if a trigger exists /// </summary> [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")] internal static bool TriggerExists(SqlConnection connection, SqlTransaction trans, SqlDependencyQualifiedObjectName trigger) { var commandText = string.Format(CultureInfo.InvariantCulture, "SELECT COUNT(*) FROM [sys].[triggers] WHERE [object_id] = OBJECT_ID('{0}')", trigger); using (var cmd = new SqlCommand(commandText, connection)) { cmd.CommandType = CommandType.Text; cmd.Transaction = trans; return Convert.ToInt32(cmd.ExecuteScalar(), CultureInfo.InvariantCulture) > 0; } } /// <summary> /// Gets a nullable field value from the data reader /// </summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public static TValue? GetNullableFieldValue<TValue>(DbDataReader dataReader, string fieldName) where TValue: struct { object fieldValue = dataReader[fieldName]; if (Convert.IsDBNull(fieldValue) || (fieldValue == null)) { return null; } try { return (TValue) fieldValue; } catch { return (TValue) Convert.ChangeType(fieldValue, typeof (TValue), CultureInfo.CurrentCulture); } } /// <summary> /// Increments the object ref count /// </summary> private static int IncrementRefCount(string objectName) { int refCount; if (!_refCounts.TryGetValue(objectName, out refCount)) { _refCounts[objectName] = refCount = 1; } else { _refCounts[objectName] = refCount += 1; } return refCount; } /// <summary> /// Decrements the object ref count /// </summary> private static int DecrementRefCount(string objectName) { int refCount; if (_refCounts.TryGetValue(objectName, out refCount) && (refCount > 0)) { _refCounts[objectName] = refCount -= 1; } return refCount; } #endregion #region Sql Objects /// <summary> /// Ensures changes holder table exists /// </summary> [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")] private static void EnsureChangeHolderTable(SqlConnection conn, SqlTransaction trans, SqlDependencyParams dependencyParams) { var cmdText = string.Format(CultureInfo.InvariantCulture, @"IF NOT EXISTS (SELECT 1 FROM [sys].[tables] WHERE [object_id] = OBJECT_ID('{0}')) BEGIN CREATE TABLE {0} ( [ObjectId] [int] NOT NULL, [ObjectName] [nvarchar](128) NOT NULL, [LastInsertDate] [datetimeoffset](7) NULL, [LastUpdateDate] [datetimeoffset](7) NULL, [LastDeleteDate] [datetimeoffset](7) NULL, CONSTRAINT [PK_{1}] PRIMARY KEY CLUSTERED ([ObjectId] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]; CREATE UNIQUE NONCLUSTERED INDEX [IX_{1}] ON {0} ([ObjectName] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON); END", dependencyParams.Options.ChangeHolderTable, dependencyParams.Options.ChangeHolderTable.Name); // Execute using (var cmd = new SqlCommand(cmdText, conn)) { // Process EnsureOpenConnection(conn); // Properties cmd.CommandType = CommandType.Text; cmd.Transaction = trans; // Execute cmd.ExecuteNonQuery(); } // Increment ref count IncrementRefCount(dependencyParams.Options.ChangeHolderTable); } /// <summary> /// Deletes changes holder table /// </summary> [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")] private static void DeleteChangeHolderTable(SqlConnection conn, SqlTransaction trans, SqlDependencyParams dependencyParams) { var refCount = DecrementRefCount(dependencyParams.Options.ChangeHolderTable); if (refCount <= 0) { var cmdText = string.Format(CultureInfo.InvariantCulture, @"IF EXISTS (SELECT 1 FROM [sys].[tables] WHERE [object_id] = OBJECT_ID('{0}')) DROP TABLE {0};", dependencyParams.Options.ChangeHolderTable); // Execute using (var cmd = new SqlCommand(cmdText, conn)) { // Process EnsureOpenConnection(conn); // Properties cmd.CommandType = CommandType.Text; cmd.Transaction = trans; // Execute cmd.ExecuteNonQuery(); } } } /// <summary> /// Ensures table triggers /// </summary> [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")] private static void EnsureTableTriggers(SqlConnection conn, SqlTransaction trans, SqlDependencyParams dependencyParams) { // Format for each table var cmdTextFormat = @"CREATE TRIGGER {0} ON {1} AFTER INSERT, UPDATE, DELETE AS BEGIN SET NOCOUNT ON; -- Insert a record in changes table for this table IF NOT EXISTS (SELECT 1 FROM {2} WHERE [ObjectId] = OBJECT_ID('{1}')) INSERT INTO {2} VALUES (OBJECT_ID('{1}'), '{1}', NULL, NULL, NULL); -- Update the record appropriately IF EXISTS (SELECT 1 FROM INSERTED) IF EXISTS (SELECT 1 FROM DELETED) UPDATE {2} SET [LastUpdateDate] = SYSDATETIMEOFFSET() WHERE ([ObjectId] = OBJECT_ID('{1}')); ELSE UPDATE {2} SET [LastInsertDate] = SYSDATETIMEOFFSET() WHERE ([ObjectId] = OBJECT_ID('{1}')); ELSE IF EXISTS (SELECT 1 FROM DELETED) UPDATE {2} SET [LastDeleteDate] = SYSDATETIMEOFFSET() WHERE ([ObjectId] = OBJECT_ID('{1}')); END"; // Create dependencyParams.Tables.ForEach(t => { var trigger = dependencyParams.Options.GetTableTrigger(t); if (!TriggerExists(conn, trans, trigger)) { var cmdText = string.Format(CultureInfo.InvariantCulture, cmdTextFormat, trigger, t, dependencyParams.Options.ChangeHolderTable); // Execute using (var cmd = new SqlCommand(cmdText, conn)) { // Process EnsureOpenConnection(conn); // Properties cmd.CommandType = CommandType.Text; cmd.Transaction = trans; // Execute cmd.ExecuteNonQuery(); } } }); // Increment ref counts dependencyParams.Tables.ForEach(t => IncrementRefCount(dependencyParams.Options.GetTableTrigger(t))); } /// <summary> /// Deletes table triggers /// </summary> [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")] private static void DeleteTableTriggers(SqlConnection conn, SqlTransaction trans, SqlDependencyParams dependencyParams) { // Delete for all dependencyParams.Tables.ForEach(t => { // Trigger var tableTrigger = dependencyParams.Options.GetTableTrigger(t); // Decrement ref count var refCount = DecrementRefCount(tableTrigger); // Delete if ref count is 0 if (refCount <= 0) { // Delete var cmdText = string.Format(CultureInfo.InvariantCulture, @"IF EXISTS (SELECT 1 FROM [sys].[triggers] WHERE [object_id] = OBJECT_ID('{0}')) DROP TRIGGER {0};", tableTrigger); // Execute using (var cmd = new SqlCommand(cmdText, conn)) { // Process EnsureOpenConnection(conn); // Properties cmd.CommandType = CommandType.Text; cmd.Transaction = trans; // Execute cmd.ExecuteNonQuery(); } } }); } #endregion } }
gpl-2.0
AllFamous/singapore-wine-vault
wp-content/themes/singapore-wine-vault/sidebar.php
226
<!-- sidebar --> <aside class="sidebar" role="complementary"> <div class="sidebar-widget"> <?php if(!function_exists('dynamic_sidebar') || !dynamic_sidebar('right-sidebar')) ?> </div> </aside> <!-- /sidebar -->
gpl-2.0
solopaulo/yosane
yosane-service/src/main/java/au/com/twobit/yosane/service/dw/config/EmailConfiguration.java
2519
package au.com.twobit.yosane.service.dw.config; import java.util.List; import com.google.common.collect.Lists; public class EmailConfiguration { private boolean sslEnabled = false; private String smtpHost; private int smtpPort = -1; private String username; private String password; private String defaultSubject = "Here is your scanned image from Yosane"; private String defaultSender = "[email protected]"; private String defaultSenderName = "Yosane Scanner Emails"; private String defaultRecipient; private boolean startTls = false; private List<String> recipients = Lists.newArrayList(); public List<String> getRecipients() { return recipients; } public void setRecipients(List<String> recipients) { this.recipients = recipients; } public String getDefaultSubject() { return defaultSubject; } public void setDefaultSubject(String defaultSubject) { this.defaultSubject = defaultSubject; } public boolean isSslEnabled() { return sslEnabled; } public void setSslEnabled(boolean useSSL) { this.sslEnabled = useSSL; } public String getSmtpHost() { return smtpHost; } public void setSmtpHost(String mailHost) { this.smtpHost = mailHost; } public int getSmtpPort() { return smtpPort; } public void setSmtpPort(int mailPort) { this.smtpPort = mailPort; } public String getUsername() { return username; } public void setUsername(String mailUser) { this.username = mailUser; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isStartTls() { return startTls; } public void setStartTls(boolean startTls) { this.startTls = startTls; } public String getDefaultRecipient() { return defaultRecipient; } public void setDefaultRecipient(String defaultRecipient) { this.defaultRecipient = defaultRecipient; } public String getDefaultSender() { return defaultSender; } public void setDefaultSender(String defaultSender) { this.defaultSender = defaultSender; } public String getDefaultSenderName() { return defaultSenderName; } public void setDefaultSenderName(String defaultSenderName) { this.defaultSenderName = defaultSenderName; } }
gpl-2.0
hexbinary/landing
src/main/java/oscar/oscarEncounter/oscarConsultationRequest/config/pageUtil/EctConShowAllInstitutionsAction.java
2033
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package oscar.oscarEncounter.oscarConsultationRequest.config.pageUtil; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class EctConShowAllInstitutionsAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { EctConShowAllInstitutionsForm showAllInstitutionsForm = (EctConShowAllInstitutionsForm)form; String id = showAllInstitutionsForm.getId(); String name = showAllInstitutionsForm.getName(); request.setAttribute("id", id); request.setAttribute("name", name); return mapping.findForward("success"); } }
gpl-2.0
devthuan/lotteryhcm
templates/xskt/js/site.js
7003
; /* * Format functions * by Thuy */ ;(function(W, D, $) { $.extend({ 'version': '1.2' , 'isBlank': function(str) { return (typeof(str) == 'undefined' || str == null || $.trim(str) == ''); } , 'isEmail': function(str) { return str.search(/^[\w\.=-]+@[\w\.-]+\.[\w]{2,9}$/) != -1; } , 'isPhone': function(str) { return str.search(/^(\+[1-9][0-9]*(\([0-9]*\)|-[0-9]*-))?[0]?[1-9][0-9\- ]*$/) != -1; } , 'isNum': function(str) { return str.search(/^[0-9]+$/) != -1; } , 'URLNoCache': function(url) { if (url == null) { return ''; } url = url.toString(); if ($.trim(url) == '') { return ''; } var sequence = String(Math.random()).replace('0.', ''); var params = url.split('rnd='); if (params.length == 2) { var rnds = params[1].split('&'); return params[0] + 'rnd=' + sequence + (rnds.length == 2 ? '&' + rnds[1] : ''); } else { return url + (url.indexOf('?') == -1 ? '?' : '&') + 'rnd=' + sequence; } } , 'goTo': function(url) { W.location.href = url; } }); $.fn.extend({ 'scrollTo': function(selector) { this.scrollTop( $(selector).offset().top - this.offset().top + this.scrollTop() ); return this; } , 'noWrap': function() { this.each(function() { $(this).html($(this).text().replace(/\s+/g, '&nbsp;')); }); return this; } /* special input validation */ , 'formcontrol': function() { this.each(function() { $(this).val($(this).data('default')).wrapAll('<span />'); if ($(this).data('require') != 'none') { $(this).data('valid', 'failed'); } else { $(this).data('valid', 'checked'); } $(this).attr('title', $(this).data('warning')).bind({ 'focus': function() { $(this).focusin(); } , 'blur': function() { $(this).focusout(); } /*, 'keyup change': function() { $(this).validate(); }*/ }); }); } , 'focusin': function() { this.each(function() { if ($.trim($(this).val()) == $(this).data('default') || $.isBlank($(this).val())) { $(this) .val('') .data('valid', 'checked') .removeClass('required') .removeAttr('title') .next() .remove(); } }); return this; } , 'focusout': function() { this.each(function() { $(this).val($.trim($(this).val())); if ($.isBlank($(this).val())) { $(this) .val($(this).data('default')) .removeClass('required'); } $(this).validate(); }); return this; } , 'validate': function() { this.each(function() { var val = $.trim($(this).val()); switch ($(this).data('require')) { case 'required': if ($.isBlank(val) || val == $(this).data('default')) { $(this) .data('valid', 'failed') .addClass('required') .attr('title', $(this).data('warning')); if ($(this).next().length == 0) { $('<span />', { 'text': $(this).data('warning') }).insertAfter(this); } } else { $(this) .data('valid', 'checked') .removeClass('required') .removeAttr('title') .next() .remove(); } break; case 'email': if (!$.isEmail(val)) { $(this) .data('valid', 'failed') .addClass('required') .attr('title', $(this).data('warning')); if ($(this).next().length == 0) { $('<span />', { 'text': $(this).data('warning') }).insertAfter(this); } } else { $(this) .data('valid', 'checked') .removeClass('required') .removeAttr('title') .next() .remove(); } break; } }); return this; } , 'formcheck': function() { var valid = true; this.each(function() { if ($(this).data('valid') == 'failed') { valid = false; $(this).addClass('required'); } }); return valid; } }); })(window, document, jQuery); ;(function(W, D, $) { ;({ 'sysparam' : { 'version': '1.0' , 'null': null } , 'init_Interface': function(s) { /* TOP MENU */ $('#header li a').noWrap(); $('#header li').bind({ 'mouseenter': function() { var ul = $(this).find('>ul'); if (ul.length == 0) { return; } ul.css('display', 'block'); } , 'mouseleave': function() { var ul = $(this).find('>ul'); if (ul.length == 0) { return; } ul.css('display', 'none'); } }); /* DATE PICKER */ $('#datepicker').datepicker({ dateFormat: 'dd/mm/yy' }); /* CITY PICKER */ $('#citypicker').click(function(evt) { var btn = $(this); var div = $('.city-picker-div'); if (div.length == 0) { div = $('<ul />', { 'class': 'city-picker-div' , 'html': function() { var html = ''; $.each(btn.data('cities').split(','), function(index, value) { html += '<li>'; html += '<a href="' + value + '">' + value + '</a>'; html += '</li>'; }); return html; } }).insertAfter(btn); } div.find('a').click(function(evt) { evt.preventDefault(); btn.val($(this).text()); }); div.css('display', 'block'); }); $(D).click(function(evt) { if ($(evt.target).hasClass('city-picker-div') || $(evt.target).attr('id') == 'citypicker') { return; } $('.city-picker-div').css('display', 'none'); }); /* JS SCROLLBAR */ $('.scroll-pane').jScrollPane({ 'mouseWheelSpeed': 20 }); /* MARQUEE */ $('#marquee marquee').marquee('pointer').mouseover(function () { $(this).trigger('stop'); }).mouseout(function () { $(this).trigger('start'); }).mousemove(function (event) { if ($(this).data('drag') == true) { this.scrollLeft = $(this).data('scrollX') + ($(this).data('x') - event.clientX); } }).mousedown(function (event) { $(this).data('drag', true).data('x', event.clientX).data('scrollX', this.scrollLeft); }).mouseup(function () { $(this).data('drag', false); }); //$('marquee').marquee(); } , 'init_Forms': function(s) { $('.contact-form input[type=text], .contact-form textarea').formcontrol(); $('.contact-form').submit(function(evt) { if ($(this).find('input[type=text]').formcheck() === false) { evt.preventDefault(); // alert('Xin vui lòng nhập các thông tin yêu cầu!'); return; } }); } , 'initialize': function() { var scope = this; $(D).ready(function() { $.each(scope, function(fn_name, fn) { if (String(fn_name).indexOf('init_') == 0) { try { (scope[fn_name])(scope); } catch (err) {}; } }); }); } }).initialize(); })(window, window.document, jQuery);
gpl-2.0
georgejhunt/HaitiDictionary.activity
data/words/gr~ek.js
83
showWord(["","1. moun ki fè nan peyi Lagrès. 2. n. Grèp, sak pou koule kafe." ])
gpl-2.0
chisimba/modules
award/templates/content/addbargainingunit_tpl.php
12517
<?php // security check - must be included in all scripts if(!$GLOBALS['kewl_entry_point_run']){ die("You cannot view this page directly"); } // end security check /** * @package LRS Admin */ /** * add bargaining unit template for the LRS Wages * This template is used to add a new bargainging unit. All dropdowns must be selected to continue * Author Brent van Rensburg */ //Load classes $this->loadClass('button', 'htmlelements'); $this->loadClass('htmltable', 'htmlelements'); $this->loadClass('label', 'htmlelements'); $this->loadClass('form', 'htmlelements'); $this->loadClass('link', 'htmlelements'); $this->loadClass('textinput', 'htmlelements'); $this->loadClass('textarea', 'htmlelements'); $this->loadClass('checkBox', 'htmlelements'); //create heading $header = $this->getObject('htmlheading','htmlelements'); $header->type = 2; if(isset($unitId)) { $header->str = $this->objLanguage->languageText('mod_lrs_Edit_Unit_header', 'award'); $objAddUnitForm = new form('lrsadmin', $this->uri(array('action'=>'updatebargainingunit', 'unitId'=>$unitId, 'selected'=>'init_10'))); } else { $header->str = $this->objLanguage->languageText('mod_lrs_Add_Unit_header', 'award'); $objAddUnitForm = new form('lrsadmin', $this->uri(array('action'=>'updatebargainingunit', 'selected'=>'init_10'))); } $objAddUnitForm->addToForm($header->show()); //Create a table for the header $objAddUnitTable = new htmlTable('lrsadmin'); $objAddUnitTable->cellspacing = 2; $lblbargainingUnit = new label($this->objLanguage->languageText('mod_lrs_confirm_unit_Type', 'award'), NULL); $lbltradeUnionType = new label($this->objLanguage->languageText('mod_lrs_trade_union_Type', 'award'), NULL); $lblpartyBranch = new label($this->objLanguage->languageText('mod_lrs_branch_Type', 'award'), NULL); $lblregion = new label($this->objLanguage->languageText('mod_lrs_region_Type', 'award'), NULL); $lbldistrict = new label($this->objLanguage->languageText('mod_lrs_district_Type', 'award'), NULL); $lblunitNotes = new label($this->objLanguage->languageText('mod_lrs_unit_Notes', 'award'), NULL); $lblsicMajorDiv = $this->objLanguage->languageText('mod_lrs_sicMajDiv', 'award'); $lblsicDiv = $this->objLanguage->languageText('mod_lrs_sicDiv', 'award'); $lblsicMajGrp = $this->objLanguage->languageText('mod_lrs_sicMajGrp', 'award'); $lblsicGrp = $this->objLanguage->languageText('mod_lrs_sicGroup', 'award'); $lblindustryCatagory = new label($this->objLanguage->languageText('mod_lrs_industry_cat_Type', 'award'), NULL); //Message to be displayed when a rule is broken $msgtradeUnionType = $this->objLanguage->languageText('mod_lrs_trade_union_msg', 'award'); $msgpartyBranch = $this->objLanguage->languageText('mod_lrs_branch_msg', 'award'); $msgindustryCatagory = $this->objLanguage->languageText('mod_lrs_industry_cat_msg', 'award'); $msgregion = $this->objLanguage->languageText('mod_lrs_region_msg', 'award'); $msgdistrict = $this->objLanguage->languageText('mod_lrs_district_msg', 'award'); $msgMajorDiv = $this->objLanguage->languageText('mod_lrs_majorDiv_msg', 'award'); $msgDiv = $this->objLanguage->languageText('mod_lrs_div_msg', 'award'); $defaultDrop = $this->objLanguage->languageText('mod_lrs_default_drop', 'award'); $setNotes = ''; if(isset($unitId)) { $unitRow = $this->objDbUnit->getRow('id', $unitId); $unit = $unitRow['name']; $unitBranchRow = $this->objUnitBranch->getRow('unitid', $unitId); $branchRow = $this->objDbBranch->getRow('id', $unitBranchRow['branchid']); $bargUnitSicRow = $this->objUnitSic->getRow('unitid', $unitId); $setParty = $branchRow['partyid']; $setBranch = $unitBranchRow['branchid']; $setMajDiv = $bargUnitSicRow['major_divid']; $setDiv = $bargUnitSicRow['divid']; $setMajorGroup = $bargUnitSicRow['major_groupid']; $setGroup = $bargUnitSicRow['groupid']; $setSubGroup = $bargUnitSicRow['sub_groupid']; $setNotes = $unitRow['notes']; $sql = "SELECT id, regionid FROM tbl_award_unit_region WHERE unitid = '$unitId'"; $regionInfo = $this->objRegion->getArray($sql); $setRegion = current($regionInfo); } //get parties $parties = $this->objDbParty->getAll("ORDER BY abbreviation ASC"); $unitBox = new textinput('unit', $unit); $objAddUnitTable->startHeaderRow(); $objAddUnitTable->addHeaderCell($lblbargainingUnit->show()); $objAddUnitTable->addHeaderCell($unitBox->show()); $objAddUnitTable->endHeaderRow(); //use javascript and xajax to filter the next dropdown according to the selection $dropUnionType = new dropdown('tradeUnionType'); $dropUnionType->extra = " onchange = \"javascript:populatePB(this.value)\""; $dropUnionType->addOption('-1',$defaultDrop); $dropUnionType->addFromDB($parties, 'abbreviation', 'id'); $dropUnionType->setSelected('-1'); if(isset($unitId)) { $dropUnionType->setSelected($setParty); } $objAddUnitTable->startRow(); $objAddUnitTable->addCell($lbltradeUnionType->show(), NULL, "", NULL, 'odd'); $objAddUnitTable->addCell($dropUnionType->show()); $objAddUnitTable->endRow(); $dropBranchName = new dropdown('branch'); $dropBranchName->addOption('-1',$defaultDrop); if(isset($unitId)) { $content = $this->objDbBranch->getAll("WHERE partyid = '$setParty' ORDER BY name ASC"); $dropBranchName->addFromDB($content, 'name', 'id'); $dropBranchName->setSelected($setBranch); } else { $dropBranchName->extra = "disabled"; $dropBranchName->setSelected(-1); } $objAddUnitTable->startRow(); $objAddUnitTable->addCell($lblpartyBranch->show(), NULL, "", NULL, 'odd'); $objAddUnitTable->addCell("<div id='myDiv_input_branch'>".$dropBranchName->show()."</div>"); $objAddUnitTable->endRow(); $objSicMajDiv = $this->getObject('dbsicmajordiv','awardapi'); $sicMajDivs = $objSicMajDiv->getAll("ORDER BY description ASC"); $dropSicMajDiv = new dropdown('majorDiv'); $dropSicMajDiv->extra = " onchange = \"javascript:populateSicDiv(this.value)\""; //default selected option for drodown $dropSicMajDiv->addOption('-1',$defaultDrop); $dropSicMajDiv->setSelected('-1'); $dropSicMajDiv->addFromDB($sicMajDivs, 'description', 'id'); if(isset($unitId)) { $dropSicMajDiv->setSelected($setMajDiv); } $objAddUnitTable->startRow(); $objAddUnitTable->addCell($lblsicMajorDiv, NULL, "", NULL, 'odd'); $objAddUnitTable->addCell($dropSicMajDiv->show()); $objAddUnitTable->endRow(); $objSicDiv = $this->getObject('dbsicdiv','awardapi'); $dropSicDiv = new dropdown('div'); $dropSicDiv->addOption('-1',$defaultDrop); if(isset($unitId)) { $content = $objSicDiv->getAll("WHERE major_divid = '$setMajDiv' ORDER BY description ASC"); $dropSicDiv->extra = "onchange = \"javascript:populateSicMajGrp(this.value)\""; foreach ($content as $c) { //The description in the dropdown cannot exceed 55 characters if (strlen($c['description']) > 55) { $c['description'] = substr($c['description'],0,52).'...'; } $dropSicDiv->addOption($c['id'],$c['description']); } $dropSicDiv->setSelected($setDiv); } else { $dropSicDiv->extra = "disabled"; $dropSicDiv->setSelected('-1'); } $objAddUnitTable->startRow(); $objAddUnitTable->addCell($lblsicDiv, NULL, "", NULL, 'odd'); $objAddUnitTable->addCell("<div id='myDiv_input_div'>".$dropSicDiv->show()."</div>"); $objAddUnitTable->endRow(); $objSicMajGrp = $this->getObject('dbsicmajorgroup','awardapi'); $dropSicMajGrp = new dropdown('majGrp'); $dropSicMajGrp->addOption('-1',$defaultDrop); if(isset($unitId)) { $content = $objSicMajGrp->getAll("WHERE divid = '$setDiv' ORDER BY description ASC"); $dropSicMajGrp->extra = "onchange = \"javascript:populateSicGrp(this.value)\""; foreach ($content as $c) { //The description in the dropdown cannot exceed 55 characters if (strlen($c['description']) > 55) { $c['description'] = substr($c['description'],0,52).'...'; } $dropSicMajGrp->addOption($c['id'],$c['description']); } $dropSicMajGrp->setSelected($setMajorGroup); } else { $dropSicMajGrp->extra = "disabled"; $dropSicMajGrp->setSelected(-1); } $objAddUnitTable->startRow(); $objAddUnitTable->addCell($lblsicMajGrp, NULL, "", NULL, 'odd'); $objAddUnitTable->addCell("<div id='myDiv_input_majGrp'>".$dropSicMajGrp->show()."</div>"); $objAddUnitTable->endRow(); $objSicGrp = $this->getObject('dbsicgroup','awardapi'); $dropSicGrp = new dropdown('grp'); $dropSicGrp->addOption('-1',$defaultDrop); if(isset($unitId)) { $content = $objSicGrp->getAll("WHERE major_groupid = '$setMajorGroup' ORDER BY description ASC"); $dropSicGrp->extra = "onchange = \"javascript:populateSicSubGrp(this.value)\""; foreach ($content as $c) { //The description in the dropdown cannot exceed 55 characters if (strlen($c['description']) > 55) { $c['description'] = substr($c['description'],0,52).'...'; } $dropSicGrp->addOption($c['id'],$c['description']); } $dropSicGrp->setSelected($setGroup); } else { $dropSicGrp->extra = "disabled"; $dropSicGrp->setSelected('-1'); } $objAddUnitTable->startRow(); $objAddUnitTable->addCell($lblsicGrp, NULL, "", NULL, 'odd'); $objAddUnitTable->addCell("<div id='myDiv_input_grp'>".$dropSicGrp->show()."</div>"); $objAddUnitTable->endRow(); $objSicSubGrp = $this->getObject('dbsicsubgroup','awardapi'); $dropSicSub = new dropdown('subGrp'); $dropSicSub->addOption('-1',$defaultDrop); if(isset($unitId)) { $content = $objSicSubGrp->getAll("WHERE groupid = '$setGroup' ORDER BY description ASC"); foreach ($content as $c) { //The description in the dropdown cannot exceed 55 characters if (strlen($c['description']) > 55) { $c['description'] = substr($c['description'],0,52).'...'; } $dropSicSub->addOption($c['id'],$c['description']); } $dropSicSub->setSelected($setSubGroup); } else { $dropSicSub->extra = "disabled"; $dropSicSub->setSelected('-1'); } $objAddUnitTable->startRow(); $objAddUnitTable->addCell($lblindustryCatagory->show(), NULL, "", NULL, 'odd'); $objAddUnitTable->addCell("<div id='myDiv_input_subGrp'>".$dropSicSub->show()."</div>"); $objAddUnitTable->endRow(); $region = $this->objDbRegion->getAll("ORDER BY name ASC"); //use javascript and xajax to filter the next dropdown according to the selection $dropRegion = new dropdown('region'); $dropRegion->addOption('-1',$defaultDrop); $dropRegion->addFromDB($region, 'name', 'id'); $dropRegion->setSelected('-1'); if(isset($unitId)) { $dropRegion->setSelected($setRegion['regionid']); } $objAddUnitTable->startRow(); $objAddUnitTable->addCell($lblregion->show(), NULL, "", NULL, 'odd'); $objAddUnitTable->addCell($dropRegion->show()); $objAddUnitTable->endRow(); /*if(isset($unitId)) { if($unitRow['active'] == 1){ $setDisplay = false; } else { $setDisplay = true; } $expired = new checkBox("expired", null, $setDisplay); $objAddUnitTable->startRow(); $objAddUnitTable->addCell($this->objLanguage->languageText('mod_lrs_edit_expired', 'award'),'','','','odd'); $objAddUnitTable->addCell($expired->show()); $objAddUnitTable->endRow(); }*/ $txtunitNotes = new textarea('unitNotes',$setNotes); $objAddUnitTable->startRow(); $objAddUnitTable->addCell($lblunitNotes->show(), NULL, NULL, NULL, 'odd'); $objAddUnitTable->addCell($txtunitNotes->show()); $objAddUnitTable->endRow(); //once the submit button is selected a javascript function is called to validate that all the dropdowns have been selected $btnSubmit = new button('submitUnit'); $btnSubmit->setToSubmit(); $btnSubmit->setValue($this->objLanguage->languageText("word_submit")); if(isset($unitId)) { $btnCancel = new button('cancel'); $location = $this->uri(array('action'=>'bargainingunitoverview', 'id'=>$unitId, 'selected'=>'init_10')); $btnCancel->setOnClick("javascript:window.location='$location'"); $btnCancel->setValue($this->objLanguage->languageText("word_back")); } else { $btnCancel = new button('cancel'); $location = $this->uri(array('action'=>'start', 'selected'=>'init_10')); $btnCancel->setOnClick("javascript:window.location='$location'"); $btnCancel->setValue(' '.$this->objLanguage->languageText("word_back").' '); } if(isset($unitId)) { $txthiddenRegion = new textinput('regionId', $setRegion['id'], 'hidden'); $objAddUnitTable->startRow(); $objAddUnitTable->addCell($txthiddenRegion->show()); $objAddUnitTable->addCell("<br />"); $objAddUnitTable->endRow(); } $objAddUnitTable->startRow(); $objAddUnitTable->addCell($btnSubmit->show().' '.$btnCancel->show()); $objAddUnitTable->addCell("<br />"); $objAddUnitTable->endRow(); $objAddUnitForm->addToForm($objAddUnitTable->show()); $script = $this->getResourceUri('wageadmin.js'); $this->appendArrayVar('headerParams', "<script type='text/javascript' src='$script'></script>"); echo $objAddUnitForm->show(); ?>
gpl-2.0
dpogorelov/gitcc4j_ver2
src/main/java/gitcc/cc/DirDiffUtil.java
1558
package gitcc.cc; import gitcc.cc.CCFile.Status; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class DirDiffUtil { private boolean delete; public DirDiffUtil() {} public DirDiffUtil(boolean delete) { this.delete = delete; } public List<CCFile> diff(String root, File a, File b) { Set<String> d1 = getFiles(a); Set<String> d2 = getFiles(b); return diff(root, d1, d2); } public List<CCFile> diff(String root, Set<String> d1, Set<String> d2) { List<CCFile> files = new ArrayList<CCFile>(); Set<String> d3 = new HashSet<String>(d2); d3.removeAll(d1); for (String s : d3) { files.add(new CCFile(rel(root, s), "", Status.Added)); } d1.removeAll(d2); for (String s : d1) { files.add(new CCFile(rel(root, s), "", Status.Deleted)); } return files; } private String rel(String root, String s) { return root + "\\" + s; } private Set<String> getFiles(File f) { try { return _getFiles(f); } catch (Exception e) { throw new RuntimeException(e); } } private Set<String> _getFiles(File f) throws Exception { Set<String> files = new HashSet<String>(); BufferedReader r = new BufferedReader(new FileReader(f)); r.readLine(); r.readLine(); for (String line; (line = r.readLine()) != null;) { String[] s = line.split(":"); files.add(s[1].substring(0, Integer.parseInt(s[0]))); } r.close(); if (delete) { f.delete(); } return files; } }
gpl-2.0
jfwells/wp-united
WordPress Plugin/wp-united/extras/quickpoll/widget.php
7673
<?php /** * * @package WP-United * @version $Id: 0.9.1.5 2012/12/28 John Wells (Jhong) Exp $ * @copyright (c) 2006-2013 wp-united.com * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @author John Wells * * The polls widget * */ class WPU_Forum_Polls_Widget extends WP_Widget { private $parentExtra = false, $addedPollScript = false; public function __construct() { global $wpUnited; $this->parentExtra = $wpUnited->get_extra('quickpoll'); if(!is_object($this->parentExtra)) { return; } $widget_ops = array('classname' => 'wp-united-forum-polls', 'description' => __('Displays a selected poll from your forum. Users must have the relevant permissions to view and/or vote on the poll.', 'wp-united') ); parent::__construct('wp-united-forum-polls', __('WP-United Forum Quick Poll', 'wp-united'), $widget_ops);//$this->WP_Widget } public function widget($args, $instance) { global $wpUnited, $phpbbForum; extract($args, EXTR_SKIP); $title = empty($instance['title']) ? '&nbsp;' : apply_filters('widget_title', $instance['title']); $pollId = $instance['pollId']; $hideIfNoPerms = $instance['hideIfNoPerms']; $showTopicLink = $instance['showTopicLink']; $nativeCSS = $instance['nativeCSS']; $template = $instance['useTemplate']; if($template == 'guess') { $template = $phpbbForum->guess_style_type(); } $poll = $this->parentExtra->get_poll($pollId, $showTopicLink, $template); if((($poll == '') && $hideIfNoPerms) || is_admin()) { return; } if (!empty($poll) && is_active_widget(false, false, $this->id_base) && !$wpUnited->should_do_action('template-w-in-p') && !$nativeCSS) { wpu_add_board_styles(false); } $poll = ($poll == '') ? __('You do not have permission to view this poll', 'wp-united') : $poll; $isleClass = ($nativeCSS) ? 'wpunative' : 'wpuisle'; $linkClass = ($showTopicLink) ? 'wpushowlink ' : ''; $isleClass = $linkClass . $isleClass; echo $before_widget; echo $before_title . $title . $after_title; ?> <div class="wpuldg" style="display: none;position: relative; padding-top: 12px;"> <?php _e('Loading.', 'wp-united'); ?> <?php _e('Please wait...', 'wp-united'); ?> <img src="<?php _e($wpUnited->get_plugin_url()); ?>images/settings/wpuldg.gif" /> </div> <div class="wpuquickpoll <?php echo $isleClass; ?> textwidget wpupoll-<?php echo $pollId; ?>"><div class="<?php echo $isleClass; ?>2"> <?php echo $poll; ?> </div></div> <?php $this->add_poll_script(); echo $after_widget; } public function update($new_instance, $old_instance) { //save the widget $instance = $old_instance; $instance['title'] = strip_tags(stripslashes($new_instance['title'])); $instance['pollId'] = (int)($new_instance['pollId']); $instance['hideIfNoPerms'] = (strip_tags(stripslashes($new_instance['hideIfNoPerms'])) == 'ok')? 1 : 0; $instance['showTopicLink'] = (strip_tags(stripslashes($new_instance['showTopicLink'])) == 'ok')? 1 : 0; $instance['nativeCSS'] = (strip_tags(stripslashes($new_instance['nativeCSS'])) == 'ok')? 1 : 0; $instance['useTemplate'] = (string)strip_tags(stripslashes($new_instance['useTemplate'])); if(trim($instance['useTemplate']) == '') { $instance['useTemplate'] == 'prosilver'; } return $instance; } public function form($instance) { //widget form $instance = wp_parse_args( (array) $instance, array( 'title' => __('Quick Poll', 'wp-united'), 'pollId' => 0, 'hideIfNoPerms' => 1, 'showTopicLink' => 1, 'nativeCSS' => 0, 'useTemplate' => 'guess' )); $title = strip_tags($instance['title']); $hideIfNoPerms = (!empty($instance['hideIfNoPerms'])) ? 'checked="checked"' : ''; $showTopicLink = (!empty($instance['showTopicLink'])) ? 'checked="checked"' : ''; $nativeCSS = (!empty($instance['nativeCSS'])) ? 'checked="checked"' : ''; $template = ((string)$instance['useTemplate']); if(empty($template)) { $template = 'guess'; } $pollId = $instance['pollId']; $polls = $this->parentExtra->get_poll_list(); ?> <p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title: ', 'wp-united'); ?> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></label></p> <p> <label for="<?php echo $this->get_field_id('pollId'); ?>"><?php _e('Select a poll: ', 'wp-united'); ?></label><br /> <select name="<?php echo $this->get_field_name('pollId'); ?>" id="<?php echo $this->get_field_name('pollId'); ?>"> <option value="0">--- <?php _e('No poll selected', 'wp-united'); ?> ---</option> <?php foreach($polls as $pollIndex => $pollData) { $isSelected = ($pollData['topic_id'] == $pollId) ? ' selected="selected" ' : ''; $pollText = sprintf(__("'%1\$s', in topic: '%2\$s'", 'wp-united'), $pollData['poll_title'], $pollData['topic_title']); $pollText = (strlen($pollText) > 38) ? substr($pollText, 0, 38) . '&hellip;' : $pollText; echo '<option value="' . $pollData['topic_id'] . '"' . $isSelected . '>' . $pollText . '</option>'; } ?> </select> </p> <p><input id="<?php echo $this->get_field_id('hideIfNoPerms'); ?>" name="<?php echo $this->get_field_name('hideIfNoPerms'); ?>" type="checkbox" value="ok" <?php echo $hideIfNoPerms ?> /> <label for="<?php echo $this->get_field_id('hideIfNoPerms'); ?>"><?php _e('Hide widget if the user has no permissions to view this poll?', 'wp-united'); ?></label></p> <p><input id="<?php echo $this->get_field_id('showTopicLink'); ?>" name="<?php echo $this->get_field_name('showTopicLink'); ?>" type="checkbox" value="ok" <?php echo $showTopicLink ?> /> <label for="<?php echo $this->get_field_id('showTopicLink'); ?>"><?php _e('Show a link to the poll topic?', 'wp-united'); ?></label></p> <p> <label for="<?php echo $this->get_field_id('useTemplate'); ?>"><?php _e('Use template: ', 'wp-united'); ?></label><br /> <select name="<?php echo $this->get_field_name('useTemplate'); ?>" id="<?php echo $this->get_field_name('useTemplate'); ?>"> <option value="guess" <?php if($template == 'guess'){ ?>selected="selected"<?php } ?>><?php _e('Make best guess for user', 'wp-united'); ?></option> <option value="prosilver" <?php if($template == 'prosilver') { ?>selected="selected"<?php } ?>><?php _e('Force prosilver', 'wp-united'); ?></option> <option value="subsilver2" <?php if($template == 'subsilver2') { ?>selected="selected"<?php } ?>><?php _e('Force subsilver2', 'wp-united'); ?></option> </select> </p> <p><input id="<?php echo $this->get_field_id('nativeCSS'); ?>" name="<?php echo $this->get_field_name('nativeCSS'); ?>" type="checkbox" value="ok" <?php echo $nativeCSS ?> /> <label for="<?php echo $this->get_field_id('nativeCSS'); ?>"><?php _e("Don't add CSS, I will style this myself", 'wp-united'); ?></label></p> <?php } public function add_poll_script() { global $wpUnited; if($this->addedPollScript) { return; } $this->addedPollScript = true; $pollNonce = wp_create_nonce('wpu-poll-submit'); wp_enqueue_script( 'wpu-poll', $wpUnited->get_plugin_url() . 'extras/quickpoll/js/poll.js', array( 'jquery-effects-core', 'jquery' ), $wpUnited->get_version(), false ); ?> <script type="text/javascript">//<![CDATA[ var wpuPollNonce = '<?php echo $pollNonce; ?>'; var wpuHomeURL = '<?php echo $wpUnited->get_wp_home_url(); ?>'; // ]]> </script> <?php } } // Done. End of file.
gpl-2.0
dsiekiera/modified-bs4
admin/includes/modules/content_manager_products.php
18117
<?php /* -------------------------------------------------------------- $Id: content_manager_products.php 10543 2017-01-02 08:51:27Z Tomcraft $ modified eCommerce Shopsoftware http://www.modified-shop.org Copyright (c) 2009 - 2013 [www.modified-shop.org] Released under the GNU General Public License --------------------------------------------------------------*/ defined('_VALID_XTC') or die('Direct Access to this location is not allowed.'); if (!$action) { // products content // load products_ids into array $products_id_query=xtc_db_query("SELECT DISTINCT pc.products_id, pd.products_name FROM ".TABLE_PRODUCTS_CONTENT." pc, ".TABLE_PRODUCTS_DESCRIPTION." pd WHERE pd.products_id=pc.products_id AND pd.language_id='".(int)$_SESSION['languages_id']."'"); $products_ids=array(); while ($products_id_data=xtc_db_fetch_array($products_id_query)) { $products_ids[]=array('id'=>$products_id_data['products_id'], 'name'=>$products_id_data['products_name']); } // while ?> <div class="pageHeadingTaba pdg2 flt-l"><a onclick="this.blur();" href="<?php echo xtc_href_link(FILENAME_CONTENT_MANAGER); ?>"><?php echo HEADING_CONTENT; ?></a></div> <div class="pageHeadingTab pdg2 flt-l"><?php echo HEADING_PRODUCTS_CONTENT; ?></div> <div class="borderTab"> <?php $total_space_media_products = xtc_spaceUsed(DIR_FS_CATALOG.'media/products/'); // DokuMan - 2011-09-06 - sum up correct filesize avoiding global variable echo '<div class="main clear">'.USED_SPACE.xtc_format_filesize($total_space_media_products).'</div><br />'; ?> <table class="tableCenter"> <tr class="dataTableHeadingRow"> <td class="dataTableHeadingContent nobr txta-c"><?php echo TABLE_HEADING_PRODUCTS_ID; ?></td> <td class="dataTableHeadingContent"><?php echo TABLE_HEADING_PRODUCTS; ?></td> </tr> <?php for ($i=0,$n=sizeof($products_ids); $i<$n; $i++) { echo '<tr class="dataTableRow" onmouseover="this.className=\'dataTableRowOver\'" onmouseout="this.className=\'dataTableRow\'">' . "\n"; ?> <td class="dataTableContent_products txta-c" style="width:5%"><?php echo $products_ids[$i]['id']; ?></td> <td class="dataTableContent_products"><b> <?php echo xtc_image(DIR_WS_CATALOG.'images/icons/arrow.gif'); ?> <a href="<?php echo xtc_href_link(FILENAME_CONTENT_MANAGER,'pID='.$products_ids[$i]['id'].$setparam);?>"><?php echo $products_ids[$i]['name']; ?></a></b> </td> </tr> <?php if ($_GET['pID']) { // display content elements $content_query=xtc_db_query("SELECT content_id, content_name, content_file, content_link, languages_id, file_comment, content_read FROM ".TABLE_PRODUCTS_CONTENT." WHERE products_id='".$_GET['pID']."' ORDER BY content_name"); $content_array = array(); while ($content_data = xtc_db_fetch_array($content_query)) { $content_array[]=array('id'=> $content_data['content_id'], 'name'=> $content_data['content_name'], 'file'=> $content_data['content_file'], 'link'=> $content_data['content_link'], 'comment'=> $content_data['file_comment'], 'languages_id'=> $content_data['languages_id'], 'read'=> $content_data['content_read']); } // while content data if ($_GET['pID']==$products_ids[$i]['id']){ ?> <tr> <td class="dataTableContent"></td> <td class="dataTableContent"> <table class="tableCenter"> <tr class="dataTableHeadingRow"> <td class="dataTableHeadingContent nobr txta-c" style="width:2%" ><?php echo TABLE_HEADING_PRODUCTS_CONTENT_ID; ?></td> <td class="dataTableHeadingContent nobr" style="width:2%" >&nbsp;</td> <td class="dataTableHeadingContent nobr" style="width:5%" ><?php echo TABLE_HEADING_LANGUAGE; ?></td> <td class="dataTableHeadingContent nobr" style="width:15%" ><?php echo TABLE_HEADING_CONTENT_NAME; ?></td> <td class="dataTableHeadingContent nobr" style="width:30%" ><?php echo TABLE_HEADING_CONTENT_FILE; ?></td> <td class="dataTableHeadingContent nobr" style="width:1%" ><?php echo TABLE_HEADING_CONTENT_FILESIZE; ?></td> <td class="dataTableHeadingContent nobr txta-c" style="width:20%" ><?php echo TABLE_HEADING_CONTENT_LINK; ?></td> <td class="dataTableHeadingContent nobr" style="width:5%" ><?php echo TABLE_HEADING_CONTENT_HITS; ?></td> <td class="dataTableHeadingContent nobr" style="width:20%" ><?php echo TABLE_HEADING_CONTENT_ACTION; ?></td> </tr> <?php for ($ii=0,$nn=sizeof($content_array); $ii<$nn; $ii++) { echo '<tr class="dataTableRow" onmouseover="this.className=\'dataTableRowOver\'" onmouseout="this.className=\'dataTableRow\'">' . "\n"; ?> <td class="dataTableContent txta-c"><?php echo $content_array[$ii]['id']; ?> </td> <td class="dataTableContent txta-c"> <?php if ($content_array[$ii]['file']!='') { echo xtc_image('../'. DIR_WS_IMAGES.'icons/filetype/icon_'.str_replace('.','',strstr($content_array[$ii]['file'],'.')).'.gif'); //web28 - 2010-09-03 - change path } else { echo xtc_image('../'. DIR_WS_IMAGES.'icons/filetype/icon_link.gif'); //web28 - 2010-09-03 - change path } for ($xx=0,$zz=sizeof($languages); $xx<$zz;$xx++){ if ($languages[$xx]['id']==$content_array[$ii]['languages_id']) { $lang_dir=$languages[$xx]['directory']; break; } } ?> </td> <td class="dataTableContent txta-c"><?php echo xtc_image(DIR_WS_CATALOG.'lang/'.$lang_dir.'/admin/images/icon.gif'); ?></td> <td class="dataTableContent"><?php echo $content_array[$ii]['name']; ?></td> <td class="dataTableContent"><?php echo $content_array[$ii]['file']; ?></td> <td class="dataTableContent txta-c"><?php echo xtc_filesize($content_array[$ii]['file']); ?></td> <td class="dataTableContent txta-c"> <?php if ($content_array[$ii]['link']!='') { echo '<a href="'.$content_array[$ii]['link'].'" target="new">'.$content_array[$ii]['link'].'</a>'; } ?> &nbsp; </td> <td class="dataTableContent txta-c"><?php echo $content_array[$ii]['read']; ?></td> <td class="dataTableContent"> <a href="<?php echo xtc_href_link(FILENAME_CONTENT_MANAGER,'special=delete_product&coID='.$content_array[$ii]['id'].'&pID='.$products_ids[$i]['id'].'&set='.$set); ?>" onclick="return confirmLink('<?php echo DELETE_ENTRY; ?>', '', this)"> <?php echo xtc_image(DIR_WS_ICONS.'delete.gif', ICON_DELETE,'','','style="cursor:pointer" onclick="return confirmLink(\''. DELETE_ENTRY .'\', \'\' ,this)"').' '.TEXT_DELETE.'</a>&nbsp;&nbsp;'; ?> <a href="<?php echo xtc_href_link(FILENAME_CONTENT_MANAGER,'action=edit_products_content&coID='.$content_array[$ii]['id'].$setparam); ?>"> <?php echo xtc_image(DIR_WS_ICONS.'icon_edit.gif', ICON_EDIT,'','','style="cursor:pointer"').' '.TEXT_EDIT.'</a>'; // display preview button if filetype in array $allowed_filetypes = array('.gif','.jpg','.png','.html','.htm','.txt','.bmp'); if (in_array(substr($content_array[$ii]['file'], 0, strrpos($content_array[$ii]['file'], '.') - 1), $allowed_filetypes)) { ?> <a style="cursor:pointer" onclick="javascript:window.open('<?php echo xtc_href_link(FILENAME_CONTENT_PREVIEW,'pID=media&coID='.$content_array[$ii]['id']); ?>', 'popup', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no, width=640, height=600')"> <?php echo xtc_image(DIR_WS_ICONS.'preview.gif', ICON_PREVIEW,'','',' style="cursor:pointer"').'&nbsp;&nbsp;'.TEXT_PREVIEW.'</a>'; } ?> </td> </tr> <?php } // for content_array echo ' </table>'; echo ' </td>'; echo '</tr>'; } } // for } ?> </table> </div> <?php } else { switch ($action) { case 'edit_products_content': case 'new_products_content': if ($action =='edit_products_content') { $content_query=xtc_db_query("SELECT content_id, products_id, group_ids, content_name, content_file, content_link, languages_id, file_comment, content_read FROM ".TABLE_PRODUCTS_CONTENT." WHERE content_id='".$g_coID."' LIMIT 1"); //DokuMan - 2011-05-13 - added LIMIT 1 $content=xtc_db_fetch_array($content_query); } // get products names. $products_query=xtc_db_query("SELECT products_id, products_name FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE language_id='".(int)$_SESSION['languages_id']."' ORDER BY products_name"); // Tomcraft - 2010-09-15 - Added default sort order to products_name for product-content in content-manager $products_array=array(); while ($products_data=xtc_db_fetch_array($products_query)) { $products_array[]=array('id' => $products_data['products_id'], 'text' => $products_data['products_name']); } // get languages $languages_array = array(); for ($i = 0, $n = sizeof($languages); $i < $n; $i++) { if ($languages[$i]['id']==$content['languages_id']) { $languages_selected=$languages[$i]['code']; $languages_id=$languages[$i]['id']; } $languages_array[] = array('id' => $languages[$i]['code'], 'text' => $languages[$i]['name']); } // get used content files $content_files_query=xtc_db_query("SELECT DISTINCT content_name, content_file FROM ".TABLE_PRODUCTS_CONTENT." WHERE content_file!=''"); $content_files=array(); while ($content_files_data=xtc_db_fetch_array($content_files_query)) { $content_files[]=array('id' => $content_files_data['content_file'], 'text' => $content_files_data['content_name']); } // add default value to array $default_array[]=array('id' => 'default','text' => TEXT_SELECT); $default_value='default'; $content_files=array_merge($default_array,$content_files); // mask for product content ?> <div style="width:99%; margin:5px;"> <div class="pageHeading"><br /><?php echo HEADING_PRODUCTS_CONTENT; ?><br /></div> <div class="main"><?php echo TEXT_CONTENT_DESCRIPTION; ?></div> <?php if ($action !='new_products_content') { echo xtc_draw_form('edit_content',FILENAME_CONTENT_MANAGER, xtc_get_all_get_params(array('action')) . 'action=edit_products_content&id=update_product&coID='.$g_coID,'post','enctype="multipart/form-data"').xtc_draw_hidden_field('coID',$g_coID); } else { echo xtc_draw_form('edit_content',FILENAME_CONTENT_MANAGER, xtc_get_all_get_params(array('action')) . 'action=edit_products_content&id=insert_product','post','enctype="multipart/form-data"'); } ?> <table class="tableConfig borderall"> <tr> <td class="dataTableConfig col-left"><?php echo TEXT_PRODUCT; ?></td> <td class="dataTableConfig col-single-right"><?php echo ((isset($_GET['pID'])) ? xtc_get_products_name($_GET['pID']) . xtc_draw_hidden_field('product', (int)$_GET['pID']) : xtc_draw_pull_down_menu('product',$products_array,$content['products_id'])); ?></td> </tr> <tr> <td class="dataTableConfig col-left"><?php echo TEXT_LANGUAGE; ?></td> <td class="dataTableConfig col-single-right"><?php echo xtc_draw_pull_down_menu('language_code',$languages_array,$languages_selected); ?></td> </tr> <?php if (GROUP_CHECK=='true') { $customers_statuses_array = xtc_get_customers_statuses(); $customers_statuses_array=array_merge(array(array('id'=>'all','text'=>TXT_ALL)),$customers_statuses_array); ?> <td class="dataTableConfig col-left"><?php echo ENTRY_CUSTOMERS_STATUS; ?></td> <td class="dataTableConfig col-single-right"> <div class="customers-groups"> <?php for ($i=0;$n=sizeof($customers_statuses_array),$i<$n;$i++) { $checked = false; if (strstr($content['group_ids'],'c_'.$customers_statuses_array[$i]['id'].'_group')) { $checked = true; } echo xtc_draw_checkbox_field('groups[]', $customers_statuses_array[$i]['id'], $checked).' '.$customers_statuses_array[$i]['text'].'<br />'; } ?> </div> </td> </tr> <?php } ?> <tr> <td class="dataTableConfig col-left"><?php echo TEXT_TITLE_FILE; ?></td> <td class="dataTableConfig col-single-right"><?php echo xtc_draw_input_field('cont_title',$content['content_name'],'size="60"'); ?></td> </tr> <tr> <td class="dataTableConfig col-left"><?php echo TEXT_LINK; ?></td> <td class="dataTableConfig col-single-right"><?php echo xtc_draw_input_field('cont_link',$content['content_link'],'size="60"'); ?></td> </tr> <tr> <td class="dataTableConfig col-left"><?php echo TEXT_FILE_DESC; ?></td> <td class="dataTableConfig col-single-right"><?php echo xtc_draw_textarea_field('file_comment','','100','30',$content['file_comment']); ?></td> </tr> <tr> <td class="dataTableConfig col-left"><?php echo TEXT_CHOOSE_FILE; ?></td> <td class="dataTableConfig col-single-right"><?php echo xtc_draw_pull_down_menu('select_file',$content_files,$default_value); ?><?php echo ' '.TEXT_CHOOSE_FILE_DESC; ?></td> </tr> <tr> <td class="dataTableConfig col-left"><?php echo TEXT_UPLOAD_FILE; ?></td> <td class="dataTableConfig col-single-right"><?php echo xtc_draw_file_field('file_upload').' '.TEXT_UPLOAD_FILE_LOCAL; ?></td> </tr> <?php if ($content['content_file']!='') { ?> <tr> <td class="dataTableConfig col-left"><?php echo TEXT_FILENAME; ?></td> <td class="dataTableConfig col-single-right"><?php echo xtc_draw_hidden_field('file_name',$content['content_file']).xtc_image('../'. DIR_WS_IMAGES. 'icons/filetype/icon_'.str_replace('.','',strstr($content['content_file'],'.')).'.gif').$content['content_file']; //DokuMan - 2011-09-06 - change path ?></td> </tr> <?php } ?> </table> <div class="flt-r mrg5 pdg2"> <?php echo '<input type="submit" class="button" onclick="this.blur();" value="' . BUTTON_SAVE . '"/>'; ?> </div> <div class="flt-r mrg5 pdg2"> <a class="button" onclick="this.blur();" href="<?php echo xtc_href_link(FILENAME_CONTENT_MANAGER, xtc_get_all_get_params(array('action'))); ?>"><?php echo BUTTON_BACK; ?></a> </div> </form> </div> <?php break; } }
gpl-2.0
leenooks/phpLDAPadmin
lib/hooks.php
6884
<?php /** * Functions related to hooks management. * * 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 * * @author Benjamin Drieu <[email protected]> and AlcÃ?ve * @package phpLDAPadmin */ /** * Compares two arrays by numerically comparing their 'prority' * value. Standard `cmp-like' function. * * @param a First element to compare. * @param b Second element to compare. * * @return -1 if priority of first element is smaller than second * element priority. 1 otherwise. */ function sort_array_by_priority($a,$b) { if (defined('DEBUG_ENABLED') && DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS')) debug_log('Entered (%%)',257,0,__FILE__,__LINE__,__METHOD__,$fargs); return (($a['priority'] < $b['priority']) ? -1 : 1 ); } /** * Runs procedures attached to a hook. * * @param hook_name Name of hook to run. * @param args Array of optional arguments set by phpldapadmin. It is normally in a form known by call_user_func_array() : * * <pre>[ 'server_id' => 0, * 'dn' => 'uid=epoussa,ou=tech,o=corp,o=fr' ]</pre> * * @return true if all procedures returned true, false otherwise. */ function run_hook($hook_name,$args) { if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS')) debug_log('Entered (%%)',257,0,__FILE__,__LINE__,__METHOD__,$fargs); $hooks = isset($_SESSION[APPCONFIG]) ? $_SESSION[APPCONFIG]->hooks : array(); if (! count($hooks) || ! array_key_exists($hook_name,$hooks)) { if (DEBUG_ENABLED) debug_log('Returning, HOOK not defined (%s)',257,0,__FILE__,__LINE__,__METHOD__,$hook_name); return true; } $rollbacks = array(); reset($hooks[$hook_name]); /* Execution of procedures attached is done using a numeric order * since all procedures have been attached to the hook with a * numerical weight. */ foreach ($hooks[$hook_name] as $key=>$hook) { if (DEBUG_ENABLED) debug_log('Calling HOOK Function (%s)(%s)',257,0,__FILE__,__LINE__,__METHOD__, $hook['hook_function'],$args); array_push($rollbacks,$hook['rollback_function']); $result = call_user_func_array($hook['hook_function'],$args); if (DEBUG_ENABLED) debug_log('Called HOOK Function (%s)',257,0,__FILE__,__LINE__,__METHOD__, $hook['hook_function']); /* If a procedure fails (identified by a false return), its optional rollback is executed with * the same arguments. After that, all rollbacks from * previously executed procedures are executed in the reverse * order. */ if (! is_null($result) && $result == false) { if (DEBUG_ENABLED) debug_log('HOOK Function [%s] return (%s)',257,0,__FILE__,__LINE__,__METHOD__, $hook['hook_function'],$result); while ($rollbacks) { $rollback = array_pop($rollbacks); if ($rollback != false) { if (DEBUG_ENABLED) debug_log('HOOK Function Rollback (%s)',257,0,__FILE__,__LINE__,__METHOD__, $rollback); call_user_func_array($rollback,$args); } } return false; } } return true; } /** * Adds a procedure to a hook for later execution. * * @param hook_name Name of the hook. * @param hook_function Name of the php function called upon hook trigger. * @param priority Numeric priority. Lowest means procedure will be executed before. * @param rollback_function Name of the php rollback function called upon failure. */ function add_hook($hook_name,$hook_function,$priority=0,$rollback_function=null) { if (defined('DEBUG_ENABLED') && DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS')) debug_log('Entered (%%)',257,0,__FILE__,__LINE__,__METHOD__,$fargs); # First, see if the hook function exists. if (! function_exists($hook_function)) { system_message(array( 'title'=>_('Hook function does not exist'), 'body'=>sprintf('Hook name: %s<br/>Hook function: %s',$hook_name,$hook_function), 'type'=>'warn')); return; } if (! array_key_exists($hook_name,$_SESSION[APPCONFIG]->hooks)) $_SESSION[APPCONFIG]->hooks[$hook_name] = array(); remove_hook($hook_name,$hook_function,-1,null); array_push($_SESSION[APPCONFIG]->hooks[$hook_name],array( 'priority' => $priority, 'hook_function' => $hook_function, 'rollback_function' => $rollback_function)); uasort($_SESSION[APPCONFIG]->hooks[$hook_name],'sort_array_by_priority'); } /** * Removes a procedure from a hook, based on a filter. * * @param hook_name Name of the hook. * @param priority Numeric priority. If set, all procedures of that priority will be removed. * @param hook_function Name of the procedure function. If set, all procedures that call this function will be removed. * @param rollback_function Name of the php rollback function called upon failure. If set, all * procedures that call this function as a rollback will be removed. */ function remove_hook($hook_name,$hook_function,$priority,$rollback_function) { if (defined('DEBUG_ENABLED') && DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS')) debug_log('Entered (%%)',257,0,__FILE__,__LINE__,__METHOD__,$fargs); if (array_key_exists($hook_name,$_SESSION[APPCONFIG]->hooks)) { reset($_SESSION[APPCONFIG]->hooks[$hook_name]); foreach ($_SESSION[APPCONFIG]->hooks[$hook_name] as $key=>$hook) { if (($priority >= 0 && $priority == $hook['priority']) || ($hook_function && $hook_function == $hook['hook_function']) || ($rollback_function && $rollback_function == $hook['rollback_function'])) { unset($_SESSION[APPCONFIG]->hooks[$hook_name][$key]); } } } } /** * Removes all procedures from a hook. * * @param hook_name Name of hook to clear. */ function clear_hooks($hook_name) { if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS')) debug_log('Entered (%%)',257,0,__FILE__,__LINE__,__METHOD__,$fargs); if (array_key_exists($hook_name,$_SESSION[APPCONFIG]->hooks)) unset($_SESSION[APPCONFIG]->hooks[$hook_name]); } $hooks = array(); # Evaluating user-made hooks if (is_dir(HOOKSDIR.'functions')) { $hooks['dir'] = dir(HOOKSDIR.'functions'); while ($hooks['file'] = $hooks['dir']->read()) { $script = sprintf('%s/%s/%s',HOOKSDIR,'functions',$hooks['file']); if (is_file($script) && preg_match('/php[0-9]?$/',$hooks['file'])) require_once $script; } $hooks['dir']->close(); } ?>
gpl-2.0
alex174/SeniorResearch
java/vendor/jfreechart-0.7.2/source/com/jrefinery/chart/StackedHorizontalBarRenderer.java
6462
/* ======================================= * JFreeChart : a Java Chart Class Library * ======================================= * * Project Info: http://www.jrefinery.com/jfreechart; * Project Lead: David Gilbert ([email protected]); * * (C) Copyright 2000-2002, by Simba Management Limited and Contributors. * * 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. * * --------------------------------- * StackedHorizontalBarRenderer.java * --------------------------------- * (C) Copyright 2001, 2002, by Simba Management Limited. * * Original Author: David Gilbert (for Simba Management Limited); * Contributor(s): -; * * $Id: StackedHorizontalBarRenderer.java,v 1.7 2002/01/29 13:56:21 mungady Exp $ * * Changes * ------- * 22-Oct-2001 : Version 1 (DG); * Renamed DataSource.java --> Dataset.java etc. (DG); * 23-Oct-2001 : Changed intro and trail gaps on bar plots to use percentage of available space * rather than a fixed number of units (DG); * 15-Nov-2001 : Modified to allow for null data values (DG); * 13-Dec-2001 : Initial tooltip implementation (DG); * */ package com.jrefinery.chart; import java.awt.*; import java.awt.geom.*; import com.jrefinery.data.*; /** * A renderer that draws horizontal bars that are "stacked" on top of one another. */ public class StackedHorizontalBarRenderer extends HorizontalBarRenderer { /** * Constructs a new StackedHorizontalBarRenderer. */ public StackedHorizontalBarRenderer() { } /** * Returns a flag (always false for this renderer) to indicate whether or not there are * gaps between items in the plot. */ public boolean hasItemGaps() { return false; } /** * Returns the number of "bar widths" per category. * <P> * For this style of rendering, there is only one bar per category. */ public int barWidthsPerCategory(CategoryDataset data) { return 1; } /** * Draws a bar for a specific item. * @param g2 The graphics device. * @param dataArea The plot area. * @param plot The plot. * @param valueAxis The range axis. * @param data The data. * @param series The series number (zero-based index). * @param category The category. * @param categoryIndex The category number (zero-based index). * @param zeroToJava2D The data value zero translated into Java2D space. * @param itemWidth The width of one bar. * @param categorySpan The width of all items in one category. * @param categoryGapSpan The width of all category gaps. * @param itemSpan The width of all items. * @param itemGapSpan The width of all item gaps. */ public Shape drawBar(Graphics2D g2, Rectangle2D dataArea, BarPlot plot, ValueAxis valueAxis, CategoryDataset data, int series, Object category, int categoryIndex, double translatedZero, double itemWidth, double categorySpan, double categoryGapSpan, double itemSpan, double itemGapSpan) { Shape result = null; // RECT X double positiveBase = 0.0; double negativeBase = 0.0; for (int i=0; i<series; i++) { Number v = data.getValue(i, category); if (v!=null) { double d = v.doubleValue(); if (d>0) positiveBase = positiveBase+d; else negativeBase = negativeBase+d; } } Number value = data.getValue(series, category); if (value!=null) { double xx = value.doubleValue(); double translatedBase; double translatedValue; double rectX; if (xx>0) { translatedBase = valueAxis.translateValueToJava2D(positiveBase, dataArea); translatedValue = valueAxis.translateValueToJava2D(positiveBase+xx, dataArea); rectX = Math.min(translatedBase, translatedValue); } else { translatedBase = valueAxis.translateValueToJava2D(negativeBase, dataArea); translatedValue = valueAxis.translateValueToJava2D(negativeBase+xx, dataArea); rectX = Math.min(translatedBase, translatedValue); } // Y double rectY = dataArea.getY() // intro gap + dataArea.getHeight()*plot.getIntroGapPercent() // bars in completed categories + (categoryIndex*categorySpan/data.getCategoryCount()); if (data.getCategoryCount()>1) { // add gaps between completed categories rectY = rectY + (categoryIndex*categoryGapSpan/(data.getCategoryCount()-1)); } // RECT WIDTH double rectWidth = Math.abs(translatedValue-translatedBase); // Supplied as a parameter as it is constant // rect HEIGHT double rectHeight = itemWidth; Rectangle2D bar = new Rectangle2D.Double(rectX, rectY, rectWidth, rectHeight); Paint seriesPaint = plot.getSeriesPaint(series); g2.setPaint(seriesPaint); g2.fill(bar); if (itemWidth>3) { g2.setStroke(plot.getSeriesStroke(series)); g2.setPaint(plot.getSeriesOutlinePaint(series)); g2.draw(bar); } result = bar; } return result; } }
gpl-2.0
muromec/qtopia-ezx
examples/content/filtering/filterdemo.cpp
3187
/**************************************************************************** ** ** This file is part of the Qtopia Opensource Edition Package. ** ** Copyright (C) 2008 Trolltech ASA. ** ** Contact: Qt Extended Information ([email protected]) ** ** This file may be used under the terms of the GNU General Public License ** versions 2.0 as published by the Free Software Foundation and appearing ** in the file LICENSE.GPL included in the packaging of this file. ** ** Please review the following information to ensure GNU General Public ** Licensing requirements will be met: ** http://www.fsf.org/licensing/licenses/info/GPLv2.html. ** ** ****************************************************************************/ #include "filterdemo.h" #include <QSoftMenuBar> #include <QKeyEvent> /*! Constructs a FilterDemo widget which is a child of \a parent and has the given window \a flags. */ FilterDemo::FilterDemo( QWidget *parent, Qt::WindowFlags flags ) : QListView( parent ) , index( 0 ) { setWindowFlags( flags ); setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); setModel( new QContentSetModel( &contentSet, this ) ); QSoftMenuBar::menuFor( this ); QSoftMenuBar::setLabel( this, Qt::Key_Select, QSoftMenuBar::NoLabel ); QSoftMenuBar::setLabel( this, Qt::Key_Back, QSoftMenuBar::Next ); nextFilter(); } /*! Responds to a key press \a event. If the key pressed is the back key move to the next filter and accept the event. If it's another key, or the last filter has been displayed delegate the key handling to QListView. */ void FilterDemo::keyPressEvent( QKeyEvent *event ) { if ( event->key() == Qt::Key_Back && nextFilter() ) { event->accept(); } else { QListView::keyPressEvent( event ); } } /*! Apply the next set of filters. If a filter has been applied returns true, otherwise if there are no filters remaining returns false. */ bool FilterDemo::nextFilter() { switch( index++ ) { // Filter for all applications. case 0: contentSet.setCriteria( QContentFilter( QContent::Application ) ); return true; // Restrict the existing filter to only display content in the 'Games' category. case 1: contentSet.addCriteria( QContentFilter::Category, "Games", QContentFilter::And ); return true; // Filter for documents with the 'image/jpeg' or 'image/png' MIME type. case 2: contentSet.setCriteria( QContentFilter::MimeType, "image/jpeg" ); contentSet.addCriteria( QContentFilter::mimeType( "image/png" ), QContentFilter::Or ); contentSet.addCriteria( QContentFilter( QContent::Document ), QContentFilter::And ); return true; // Extend the existing filter to also include applications in the 'Games' category. case 3: contentSet.addCriteria( QContentFilter( QContent::Application ) & QContentFilter::category( "Games" ) , QContentFilter::Or ); QSoftMenuBar::setLabel( this, Qt::Key_Back, QSoftMenuBar::Back ); return true; default: return false; } }
gpl-2.0
alainsanguinetti/ebc
scripts/Robot.py
3719
#!/usr/bin/env python """ This file defines the robot object as seen from the controller point of view. It is a representation of a robot in the simulation """ from Component import Component from Task import Task import rospy from ebc.msg import Event from ebc.msg import Task as TaskMsg import sys import json class Robot ( Component ): """ The Robot class is a representation of a robot """ def loadConfig( self ): """ This method load the config file """ config_file_n = rospy.get_param( 'config_file_name' ) try: self.config = json.load( open ( config_file_n, 'r' ) ) except: e = sys.exc_info()[0] self.display("Error opening config file. %s" % e) raise def sectorLength( self ): """ This method returns length of a sector for a certain id """ for sector in self.config['graph']['sectors']: if sector ['id']== self.sector_id: return sector['length'] def controller_event_callback ( self, message ): """ This method is called when the robot receives a message from the controller """ # Handle the different kind of event self.display( "ctrlr_evnt_callback: " + str(message.robot_id) + " " + str(message.event) ) self.display( "robot state: " + str( self.id ) + " " + str( self.length ) ) if self.task: if self.id == message.robot_id and self.length == 0 and message.event==Event.G: self.length = self.sectorLength() self.event_publisher.publish( Event( self.id, Event.B ) ) return def task_cb( self, message ): """ Handles the arrival of task messages """ self.display ( str( message.robot_id ) + " " + message.sectors ) # Store the message as the current task if message.robot_id == self.id: self.task = Task( message.sectors ) self.display( "Received a task" ) self.sector_id = self.task.sectors[ 0 ] self.length = self.sectorLength() def setup ( self ): """ Creates the subscribers and publishers and all needed variables (with self.name_of_the_variable) """ # Get our robot id self.loadConfig() self.name = rospy.get_name() self.id = int(filter(str.isdigit, self.name)) # Creates the publisher for events of the robot self.event_publisher = rospy.Publisher( rospy.get_name(), Event ) # Creates the subscriber for events from the controller and link them to the callback self.controller_subscriber = rospy.Subscriber ( rospy.get_param( 'controller_name' ), Event, self.controller_event_callback ) # Subscriber for task messages self.task = [] self.task_sub = rospy.Subscriber( "/tasks", TaskMsg, self.task_cb, queue_size=10 ) # Publisher for the state of the robot self.length = 0 return def loopHook ( self ): """ This method will be called repetetively while the robot is on """ s=0 id = self.id # simulate the robot moving if it is in moving state IF it has permission if self.length == 0: self.event_publisher.publish( Event( self.id, Event.EOS ) ) elif self.length > 0 : self.length -= 1 # wait a bit if it is in waiting state # publish the state of the robot rospy.sleep(1) return if __name__ == "__main__": robot = Robot ( "robot" ) robot.start() robot.loop(0.1)
gpl-2.0
ia-toki/judgels-sandalphon
app/org/iatoki/judgels/sandalphon/models/entities/ProblemModel_.java
608
package org.iatoki.judgels.sandalphon.models.entities; import org.iatoki.judgels.play.models.entities.AbstractJudgelsModel_; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor") @StaticMetamodel(ProblemModel.class) public abstract class ProblemModel_ extends AbstractJudgelsModel_ { public static volatile SingularAttribute<ProblemModel, String> name; public static volatile SingularAttribute<ProblemModel, String> additionalNote; }
gpl-2.0
md-5/jdk10
src/hotspot/share/runtime/vmOperations.hpp
16358
/* * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_RUNTIME_VMOPERATIONS_HPP #define SHARE_RUNTIME_VMOPERATIONS_HPP #include "classfile/javaClasses.hpp" #include "memory/allocation.hpp" #include "oops/oop.hpp" #include "runtime/thread.hpp" #include "runtime/threadSMR.hpp" #include "code/codeCache.hpp" // The following classes are used for operations // initiated by a Java thread but that must // take place in the VMThread. #define VM_OP_ENUM(type) VMOp_##type, // Note: When new VM_XXX comes up, add 'XXX' to the template table. #define VM_OPS_DO(template) \ template(None) \ template(Cleanup) \ template(ThreadStop) \ template(ThreadDump) \ template(PrintThreads) \ template(FindDeadlocks) \ template(ClearICs) \ template(ForceSafepoint) \ template(ForceAsyncSafepoint) \ template(DeoptimizeFrame) \ template(DeoptimizeAll) \ template(ZombieAll) \ template(Verify) \ template(PrintJNI) \ template(HeapDumper) \ template(DeoptimizeTheWorld) \ template(CollectForMetadataAllocation) \ template(GC_HeapInspection) \ template(GenCollectFull) \ template(GenCollectFullConcurrent) \ template(GenCollectForAllocation) \ template(ParallelGCFailedAllocation) \ template(ParallelGCSystemGC) \ template(G1CollectForAllocation) \ template(G1CollectFull) \ template(G1Concurrent) \ template(G1TryInitiateConcMark) \ template(ZMarkStart) \ template(ZMarkEnd) \ template(ZRelocateStart) \ template(ZVerify) \ template(HandshakeOneThread) \ template(HandshakeAllThreads) \ template(HandshakeFallback) \ template(EnableBiasedLocking) \ template(BulkRevokeBias) \ template(PopulateDumpSharedSpace) \ template(JNIFunctionTableCopier) \ template(RedefineClasses) \ template(UpdateForPopTopFrame) \ template(SetFramePop) \ template(GetOwnedMonitorInfo) \ template(GetObjectMonitorUsage) \ template(GetCurrentContendedMonitor) \ template(GetStackTrace) \ template(GetMultipleStackTraces) \ template(GetAllStackTraces) \ template(GetThreadListStackTraces) \ template(GetFrameCount) \ template(GetFrameLocation) \ template(ChangeBreakpoints) \ template(GetOrSetLocal) \ template(GetCurrentLocation) \ template(EnterInterpOnlyMode) \ template(ChangeSingleStep) \ template(HeapWalkOperation) \ template(HeapIterateOperation) \ template(ReportJavaOutOfMemory) \ template(JFRCheckpoint) \ template(ShenandoahFullGC) \ template(ShenandoahInitMark) \ template(ShenandoahFinalMarkStartEvac) \ template(ShenandoahFinalEvac) \ template(ShenandoahInitTraversalGC) \ template(ShenandoahFinalTraversalGC) \ template(ShenandoahInitUpdateRefs) \ template(ShenandoahFinalUpdateRefs) \ template(ShenandoahDegeneratedGC) \ template(Exit) \ template(LinuxDllLoad) \ template(RotateGCLog) \ template(WhiteBoxOperation) \ template(JVMCIResizeCounters) \ template(ClassLoaderStatsOperation) \ template(ClassLoaderHierarchyOperation) \ template(DumpHashtable) \ template(DumpTouchedMethods) \ template(MarkActiveNMethods) \ template(PrintCompileQueue) \ template(PrintClassHierarchy) \ template(ThreadSuspend) \ template(ThreadsSuspendJVMTI) \ template(ICBufferFull) \ template(ScavengeMonitors) \ template(PrintMetadata) \ template(GTestExecuteAtSafepoint) \ template(JFROldObject) \ class VM_Operation : public StackObj { public: enum VMOp_Type { VM_OPS_DO(VM_OP_ENUM) VMOp_Terminating }; private: Thread* _calling_thread; long _timestamp; VM_Operation* _next; VM_Operation* _prev; // The VM operation name array static const char* _names[]; public: VM_Operation() : _calling_thread(NULL), _timestamp(0), _next(NULL), _prev(NULL) {} // VM operation support (used by VM thread) Thread* calling_thread() const { return _calling_thread; } void set_calling_thread(Thread* thread); long timestamp() const { return _timestamp; } void set_timestamp(long timestamp) { _timestamp = timestamp; } // Called by VM thread - does in turn invoke doit(). Do not override this void evaluate(); // evaluate() is called by the VMThread and in turn calls doit(). // If the thread invoking VMThread::execute((VM_Operation*) is a JavaThread, // doit_prologue() is called in that thread before transferring control to // the VMThread. // If doit_prologue() returns true the VM operation will proceed, and // doit_epilogue() will be called by the JavaThread once the VM operation // completes. If doit_prologue() returns false the VM operation is cancelled. virtual void doit() = 0; virtual bool doit_prologue() { return true; }; virtual void doit_epilogue() {}; // Linking VM_Operation *next() const { return _next; } VM_Operation *prev() const { return _prev; } void set_next(VM_Operation *next) { _next = next; } void set_prev(VM_Operation *prev) { _prev = prev; } // Configuration. Override these appropriately in subclasses. virtual VMOp_Type type() const = 0; virtual bool allow_nested_vm_operations() const { return false; } virtual void oops_do(OopClosure* f) { /* do nothing */ }; // An operation can either be done inside a safepoint // or concurrently with Java threads running. virtual bool evaluate_at_safepoint() const { return true; } // Debugging virtual void print_on_error(outputStream* st) const; virtual const char* name() const { return _names[type()]; } static const char* name(int type) { assert(type >= 0 && type < VMOp_Terminating, "invalid VM operation type"); return _names[type]; } #ifndef PRODUCT void print_on(outputStream* st) const { print_on_error(st); } #endif }; class VM_None: public VM_Operation { const char* _reason; public: VM_None(const char* reason) : _reason(reason) {} const char* name() const { return _reason; } VMOp_Type type() const { return VMOp_None; } void doit() {}; }; class VM_Cleanup: public VM_Operation { public: VMOp_Type type() const { return VMOp_Cleanup; } void doit() {}; }; class VM_ClearICs: public VM_Operation { private: bool _preserve_static_stubs; public: VM_ClearICs(bool preserve_static_stubs) { _preserve_static_stubs = preserve_static_stubs; } void doit(); VMOp_Type type() const { return VMOp_ClearICs; } }; // empty vm op, evaluated just to force a safepoint class VM_ForceSafepoint: public VM_Operation { public: void doit() {} VMOp_Type type() const { return VMOp_ForceSafepoint; } }; // empty vm op, when forcing a safepoint to suspend a thread class VM_ThreadSuspend: public VM_ForceSafepoint { public: VMOp_Type type() const { return VMOp_ThreadSuspend; } }; // empty vm op, when forcing a safepoint to suspend threads from jvmti class VM_ThreadsSuspendJVMTI: public VM_ForceSafepoint { public: VMOp_Type type() const { return VMOp_ThreadsSuspendJVMTI; } }; // empty vm op, when forcing a safepoint due to inline cache buffers being full class VM_ICBufferFull: public VM_ForceSafepoint { public: VMOp_Type type() const { return VMOp_ICBufferFull; } }; // Base class for invoking parts of a gtest in a safepoint. // Derived classes provide the doit method. // Typically also need to transition the gtest thread from native to VM. class VM_GTestExecuteAtSafepoint: public VM_Operation { public: VMOp_Type type() const { return VMOp_GTestExecuteAtSafepoint; } protected: VM_GTestExecuteAtSafepoint() {} }; class VM_MarkActiveNMethods: public VM_Operation { public: VM_MarkActiveNMethods() {} VMOp_Type type() const { return VMOp_MarkActiveNMethods; } void doit(); bool allow_nested_vm_operations() const { return true; } }; // Deopt helper that can deoptimize frames in threads other than the // current thread. Only used through Deoptimization::deoptimize_frame. class VM_DeoptimizeFrame: public VM_Operation { friend class Deoptimization; private: JavaThread* _thread; intptr_t* _id; int _reason; VM_DeoptimizeFrame(JavaThread* thread, intptr_t* id, int reason); public: VMOp_Type type() const { return VMOp_DeoptimizeFrame; } void doit(); bool allow_nested_vm_operations() const { return true; } }; #ifndef PRODUCT class VM_DeoptimizeAll: public VM_Operation { private: Klass* _dependee; public: VM_DeoptimizeAll() {} VMOp_Type type() const { return VMOp_DeoptimizeAll; } void doit(); bool allow_nested_vm_operations() const { return true; } }; class VM_ZombieAll: public VM_Operation { public: VM_ZombieAll() {} VMOp_Type type() const { return VMOp_ZombieAll; } void doit(); bool allow_nested_vm_operations() const { return true; } }; #endif // PRODUCT class VM_Verify: public VM_Operation { public: VMOp_Type type() const { return VMOp_Verify; } void doit(); }; class VM_PrintThreads: public VM_Operation { private: outputStream* _out; bool _print_concurrent_locks; bool _print_extended_info; public: VM_PrintThreads() : _out(tty), _print_concurrent_locks(PrintConcurrentLocks), _print_extended_info(false) {} VM_PrintThreads(outputStream* out, bool print_concurrent_locks, bool print_extended_info) : _out(out), _print_concurrent_locks(print_concurrent_locks), _print_extended_info(print_extended_info) {} VMOp_Type type() const { return VMOp_PrintThreads; } void doit(); bool doit_prologue(); void doit_epilogue(); }; class VM_PrintJNI: public VM_Operation { private: outputStream* _out; public: VM_PrintJNI() { _out = tty; } VM_PrintJNI(outputStream* out) { _out = out; } VMOp_Type type() const { return VMOp_PrintJNI; } void doit(); }; class VM_PrintMetadata : public VM_Operation { private: outputStream* const _out; const size_t _scale; const int _flags; public: VM_PrintMetadata(outputStream* out, size_t scale, int flags) : _out(out), _scale(scale), _flags(flags) {}; VMOp_Type type() const { return VMOp_PrintMetadata; } void doit(); }; class DeadlockCycle; class VM_FindDeadlocks: public VM_Operation { private: bool _concurrent_locks; DeadlockCycle* _deadlocks; outputStream* _out; ThreadsListSetter _setter; // Helper to set hazard ptr in the originating thread // which protects the JavaThreads in _deadlocks. public: VM_FindDeadlocks(bool concurrent_locks) : _concurrent_locks(concurrent_locks), _deadlocks(NULL), _out(NULL), _setter() {}; VM_FindDeadlocks(outputStream* st) : _concurrent_locks(true), _deadlocks(NULL), _out(st) {}; ~VM_FindDeadlocks(); DeadlockCycle* result() { return _deadlocks; }; VMOp_Type type() const { return VMOp_FindDeadlocks; } void doit(); }; class ThreadDumpResult; class ThreadSnapshot; class ThreadConcurrentLocks; class VM_ThreadDump : public VM_Operation { private: ThreadDumpResult* _result; int _num_threads; GrowableArray<instanceHandle>* _threads; int _max_depth; bool _with_locked_monitors; bool _with_locked_synchronizers; void snapshot_thread(JavaThread* java_thread, ThreadConcurrentLocks* tcl); public: VM_ThreadDump(ThreadDumpResult* result, int max_depth, // -1 indicates entire stack bool with_locked_monitors, bool with_locked_synchronizers); VM_ThreadDump(ThreadDumpResult* result, GrowableArray<instanceHandle>* threads, int num_threads, // -1 indicates entire stack int max_depth, bool with_locked_monitors, bool with_locked_synchronizers); VMOp_Type type() const { return VMOp_ThreadDump; } void doit(); bool doit_prologue(); void doit_epilogue(); }; class VM_Exit: public VM_Operation { private: int _exit_code; static volatile bool _vm_exited; static Thread * volatile _shutdown_thread; static void wait_if_vm_exited(); public: VM_Exit(int exit_code) { _exit_code = exit_code; } static int wait_for_threads_in_native_to_block(); static int set_vm_exited(); static bool vm_exited() { return _vm_exited; } static Thread * shutdown_thread() { return _shutdown_thread; } static void block_if_vm_exited() { if (_vm_exited) { wait_if_vm_exited(); } } VMOp_Type type() const { return VMOp_Exit; } void doit(); }; class VM_PrintCompileQueue: public VM_Operation { private: outputStream* _out; public: VM_PrintCompileQueue(outputStream* st) : _out(st) {} VMOp_Type type() const { return VMOp_PrintCompileQueue; } void doit(); }; #if INCLUDE_SERVICES class VM_PrintClassHierarchy: public VM_Operation { private: outputStream* _out; bool _print_interfaces; bool _print_subclasses; char* _classname; public: VM_PrintClassHierarchy(outputStream* st, bool print_interfaces, bool print_subclasses, char* classname) : _out(st), _print_interfaces(print_interfaces), _print_subclasses(print_subclasses), _classname(classname) {} VMOp_Type type() const { return VMOp_PrintClassHierarchy; } void doit(); }; #endif // INCLUDE_SERVICES #endif // SHARE_RUNTIME_VMOPERATIONS_HPP
gpl-2.0
projectestac/jclic
src/core/edu/xtec/jclic/media/JMFAudioPlayer.java
2472
/* * File : JMFAudioPlayer.java * Created : 25-may-2002 19:27 * By : fbusquets * * JClic - Authoring and playing system for educational activities * * Copyright (C) 2000 - 2018 Francesc Busquets & Departament * d'Educacio de la Generalitat de Catalunya * * 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 (see the LICENSE file). */ package edu.xtec.jclic.media; import edu.xtec.jclic.bags.MediaBag; import edu.xtec.util.ExtendedByteArrayInputStream; /** * @author Francesc Busquets ([email protected]) * @version 1.0 */ public class JMFAudioPlayer implements AudioPlayer { protected javax.media.Player player; public static final javax.media.Time zeroTime = new javax.media.Time(0L); /** Creates new JMFAudioPlayer */ public JMFAudioPlayer() { player = null; } public boolean setDataSource(Object source) throws Exception { close(); if (source instanceof ExtendedByteArrayInputStream) { player = javax.media.Manager.createPlayer(new ByteDataSource((ExtendedByteArrayInputStream) source)); } else if (source instanceof String) { javax.media.MediaLocator ml = new javax.media.MediaLocator((String) source); javax.media.protocol.DataSource dataSource = javax.media.Manager.createDataSource(ml); player = javax.media.Manager.createPlayer(dataSource); } return player != null; } public void realize(String fileName, MediaBag mediaBag) throws Exception { if (fileName != null) setDataSource(mediaBag.getMediaDataSource(fileName)); if (player != null) player.realize(); } public void close() { if (player != null) { player.close(); player = null; } } public void play() { try { stop(); player.setMediaTime(zeroTime); player.start(); } catch (Exception ex) { System.err.println("Error playing system sound:\n" + ex); } } public void stop() { if (player != null && player.getState() >= javax.media.Player.Started) player.stop(); } }
gpl-2.0
tbruinsma/ArpScan
ArpSweep/ArpSweep.cpp
496
/* Copyright (c) Constantine V. Sharlaimov */ /* ArpSweep.cpp : Implementation of DLL Exports. */ #include "stdafx.h" #include "resource.h" // The module attribute causes DllMain, DllRegisterServer and DllUnregisterServer to be automatically implemented for you [ module(dll, uuid = "{049F9861-0AC4-4FC3-9E7D-DEB15387682C}", name = "ArpSweep", helpstring = "ArpSweep 1.0", resource_name = "IDR_ARPSWEEP") ] class CArpSweepModule { public: // Override CAtlDllModuleT members };
gpl-2.0
AncientKemet/Ancient-Kemet-Utility
akgl/Units/GLTypes/Extensions/UI/Sprites/Sprite.java
489
package akgl.Units.GLTypes.Extensions.UI.Sprites; import akgl.Units.Geometry.HardCodedGeometry.Quad2DGenerator; /** * @author Robert Kollar */ public class Sprite extends BaseSprite { @Override public void SetupSprite() { } @Override public Bounds2D getBounds() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void OnPreRender() { } }
gpl-2.0
Startappz/ICurl
ICurl/src/com/moshx/icurl/ICurl.java
4650
package com.moshx.icurl; import java.util.HashMap; import java.util.Locale; public class ICurl { @SuppressWarnings("unused") private static void main(String[] args) { ICurl ac = new ICurl("www.google.com"); ac.setHeader("mail", "[email protected]"); ac.setHeader("userId", "7DDDgfsdf"); ac.setParameter("mm", "add&"); ac.setParameter("u", 12444); ac.setParameter("m", 2002); ac.setCookie("cookie1", "value1"); ac.setCookie("cookie2", "val2"); ac.enableResponseLogging().enableVerbose(); ac.setTimeOut(100); ac.setType(Type.POST); System.out.println(ac.toCurl()); } public enum Type { GET("GET"), POST("POST"), DELETE("DELETE"), PUT("PUT"); public final String name; private Type(String name) { this.name = name; } } private final String mUrl; private final HashMap<String, String> mHeaders = new HashMap<>(); private final HashMap<String, Object> mParameters = new HashMap<>(); private final HashMap<String, Object> mCookies = new HashMap<>(); private static final String FORMATTED_HEADER = "-H \"%s: %s\" "; private static final String FORMATTED_URL = "\"%s\" "; private static final String FORMATTED_PARM = "%s=%s&"; private boolean responseLogging = false; private boolean verbose = false; private String basicAuthentication = null; private Type mType = Type.GET; private long mTimeOut = 30000l; public ICurl(String mUrl) { super(); this.mUrl = mUrl; } public ICurl setType(Type t) { mType = t; return this; } public ICurl setHeader(String k, String v) { mHeaders.put(k, v); return this; } public ICurl setHeaders(HashMap<String, String> hs) { if (hs != null && hs.size() > 0) { mHeaders.putAll(hs); } return this; } public ICurl setParameter(String k, Object v) { mParameters.put(k, v); return this; } public ICurl setParameters(HashMap<String, Object> ps) { if (ps != null && ps.size() > 0) { mParameters.putAll(ps); } return this; } public ICurl setCookie(String k, Object v) { mCookies.put(k, v); return this; } public ICurl setCookies(HashMap<String, Object> cs) { if (cs != null && cs.size() > 0) { mCookies.putAll(cs); } return this; } public ICurl setTimeOut(long mTimeOut) { this.mTimeOut = mTimeOut; return this; } public ICurl enableResponseLogging() { responseLogging = true; return this; } public ICurl enableVerbose() { verbose = true; return this; } public ICurl setBasicAuthentication(String username, String password) { basicAuthentication = username + ":" + password; return this; } public ICurl setBasicAuthentication(String auth) { basicAuthentication = auth; return this; } public String toCurl() { StringBuilder builder = new StringBuilder(); builder.append("curl "); addTimeOut(builder); addHeaders(builder); addParameters(builder); addCookies(builder); addExtraParms(builder); addType(builder); addUrl(builder); return builder.toString(); } // ############################################################## // INTERNAL METHODS // ############################################################## private void addHeaders(StringBuilder builder) { if (!mHeaders.isEmpty()) { for (String key : mHeaders.keySet()) { builder.append(String.format(Locale.US, FORMATTED_HEADER, key, mHeaders.get(key))); } } } private void addParameters(StringBuilder builder) { if (!mParameters.isEmpty()) { builder.append("-d \""); for (String key : mParameters.keySet()) { builder.append(String.format(Locale.US, FORMATTED_PARM, key, mParameters.get(key).toString())); } builder.deleteCharAt(builder.length() - 1).append("\" "); } } private void addCookies(StringBuilder builder) { if (mCookies.size() > 0) { builder.append("-c \""); for (String key : mCookies.keySet()) { builder.append(String.format(Locale.US, FORMATTED_PARM, key, mCookies.get(key).toString())); } builder.deleteCharAt(builder.length() - 1).append("\" "); } } private void addExtraParms(StringBuilder builder) { if (responseLogging) { builder.append("-i "); } if (verbose) { builder.append("-v "); } if (basicAuthentication != null) { builder.append("-u \"").append(basicAuthentication).append(" "); } } private void addType(StringBuilder builder) { builder.append("-X ").append(mType.name).append(' '); } private void addUrl(StringBuilder builder) { builder.append(String.format(Locale.US, FORMATTED_URL, mUrl)); } private void addTimeOut(StringBuilder builder) { if (mTimeOut != 30000l) { builder.append("--max-time ").append(mTimeOut).append(" "); } } }
gpl-2.0
tacoder/Virtual-Codechef-Contests
contest/IOPC2014/IOPC14B.php
4571
<?php require("../../includes/header.php"); ?><h1>Add and Compute Path</h1><div class="content"> <p>In the kingdom of Baratheons, there is a strict hierarchy in the army. The leader of the army is the king under whose command are a set of soldiers. Each soldier commands a certain section of army, that is there are certain soldiers under him who may be commanding some more soldiers, and the similar hierarchical structure is followed downwards, till the lowest rank of soldiers. Note that if soldier <strong>A</strong> commands soldier <strong>B</strong> and <strong>B</strong> commands <strong>C</strong>, then <strong>C</strong> also comes under the purview of <strong>A</strong>, however it will be said that <strong>B</strong> is under the direct command of <strong>A</strong> and <strong>C</strong> is under the direct command of <strong>B</strong>. Also note that each soldier has a unique hierarchical path to the king.<br /><br /></p> <p>The army commission, a different body, may decide to give certain units of power to a particular section of the army. To do this, the commission gives <strong>K</strong> units of power to the soldier commanding a section, which is cloned and each soldier under his command, including himself, receives <strong>K</strong> units of power. Remember, initially all soldiers have <strong>zero</strong> units of power.<br /><br /></p> <p>In times of war, a team of soldiers may be selected from across sections. The team is selected in the following way: given two soldiers <strong>A</strong> and <strong>B</strong>, all the soldiers in the path through the hierarchical structure from <strong>A</strong> to <strong>B</strong>, are included in the team. For such a team, you have to calculate the total power of the team. <br /></p> <h3>Input Format</h3> <p>First line contains three space separated integers <strong>N</strong>, <strong>K</strong> and <strong>R</strong>.<br /><br /> N represents the number of soldiers<br /><br /> <strong>R</strong> represents the id of the king.<br /><br /></p> <p>Next <strong>N-1</strong> lines describes the hierarchical structure. Each line consists of two integers <strong>A</strong> and <strong>B</strong>, signifying that soldier <strong>B</strong> is under the direct command of soldier <strong>A</strong>.<br /><br /><br /> <strong>K</strong> following lines represent operations of the following types.<br />For a query operation, the first character is <strong>Q</strong>, followed by two space separated integers <strong>X</strong> and <strong>Y</strong>.<br />For an update operation, the first character is <strong>U</strong>, followed by two space separated integers <strong>S</strong> and <strong>T</strong>, such that the soldier <strong>S</strong> is given <strong>T</strong> units of power to be cloned and distributed to soldiers under his command.<br /></p> <h3>Output Format</h3> <p>For each query operation, output the total power of all soldiers in the path through the hierarchical structure from <strong>X</strong> to <strong>Y</strong>.<br /></p> <h3>Constraints</h3> <ul> <li>1 ≤ N ≤ 1e5 </li> <li>1 ≤ K ≤ 1e5 </li> <li>1 ≤ X,Y,S ≤ 1e5 </li> <li>Absolute(T) ≤ 1000 </li> </ul> <p><br /></p> <h3>Sample Input</h3> <p>5 3 1<br /><br /> 1 2<br /><br /> 1 3<br /><br /> 3 4<br /><br /> 3 5<br /><br /> U 3 5<br /><br /> Q 4 5<br /><br /> Q 4 1<br /></p> <h3>Sample Output</h3> <p>15<br /><br /> 10<br /></p> <h3>Explanation</h3> <p>Initially all soldiers have 0 power. When the update operation is executed, soldiers 3, 4 and 5 get 5 units of power.<br /><br /> For the first query, all soldiers in the path from 4 to 5 are added up, i.e, power(4) + power(3) + power(5) = 15, is given as output.<br /><br /> For second query, all soldiers in the path from 4 to 1 are added up, i.e., power(4) + power(3) + power(1) = 10, is given as output.<br /></p> </div><table cellspacing="0" cellpadding="0" align="left"> <tr> <td width="14%">Author:</td> <td><a href="/users/iopc_admin">iopc_admin</a></td> </tr> <tr> <td width="14%">Date Added:</td> <td>2-02-2014</td> </tr> <tr> <td width="14%">Time Limit:</td> <td>2 sec</td> </tr> <tr> <td width="14%">Source Limit:</td> <td>50000 Bytes</td> </tr> <tr> <td width="14%">Languages:</td> <td>C, CPP 4.3.2, CPP 4.8.1, GO, JAVA</td> </tr> </table> <?php require("../../includes/footer.php"); ?>
gpl-2.0
parloma/robotcontrol
python/my_fun.py
9658
#Collection of fundamental functions import xml.etree.ElementTree as ET import numpy import glob from collections import Counter from sklearn.cross_validation import * import sys #Our novel second classification layer def joints2dist(joints): dist = [] for i in range(0,len(joints)): for j in range(i+1,len(joints)): dist.append(numpy.linalg.norm(joints[i]-joints[j])) return dist def compute_dists(file_path): tree = ET.parse(file_path) root = tree.getroot() t = [] for child in root: t.append(numpy.array([float(x) for x in child.find('coords').text.split()])) dist = [] for i in range(0,len(t)): for j in range(i+1,len(t)): dist.append(numpy.linalg.norm(t[i]-t[j])) return dist #Automatically create patterns and label to parse input files def create_patterns(paths): patt = [] for p in paths: patt.append(compute_dists(p)) return patt def create_labels(paths): Y = [] for p in paths: Y.append(p.split('/')[9][0]) return Y #Training against patterns (input data) and a priori labels (Y) def train_obj(path_training_set, classifier_obj): paths = [] SIGN_LIST = ['A','B','C','D','F','I','L','O','R','S1','U','V','W','X','Y'] for sign in SIGN_LIST: paths += glob.glob(path_training_set+'*/'+sign+'/*.xml') X = create_patterns(paths) Y = create_labels(paths) print Counter(Y) #print Y classifier_obj = classifier_obj.fit(X,Y) return classifier_obj #Testing against patterns (input data) and a priori labels (Y) def test_obj(path_test, classifier_obj): paths = glob.glob(path_test+'*/*/*.xml') X = create_patterns(paths) Y = create_labels(paths) print "Debug Paths" cY = Counter(Y) classified = classifier_obj.predict(X).tolist() cC = Counter(classified) print "Debug Classified" print cY print cC print len(classified) result = {'total': {'correct':0, 'tot':len(Y)}} for world in cY: result[world] = {'correct':0, 'tot':cY[world], 'found':cC[world]} for i in range(0, len(classified)): if classified[i] == Y[i]: result['total']['correct']+=1 result[Y[i]]['correct']+=1 for key in result.keys(): if key!='total': print "%10s\t\t%d/%d (%d)\t\t%0.2f%s" % (key, result[key]['correct'], result[key]['tot'], result[key]['found'], float(result[key]['correct'])/result[key]['tot']*100,'%') key = 'total' print "\n%10s\t\t%d/%d\t\t\t%0.2f%s\n\n" % (key, result[key]['correct'], result[key]['tot'], float(result[key]['correct'])/result[key]['tot']*100, '%') def conf_only_test_obj(path_test, classifier_obj): paths = glob.glob(path_test+'*/*/*.xml') Z = create_patterns(paths) W = create_labels(paths) print "OK Paths" cY = Counter(W) classified = classifier_obj.predict(Z).tolist() cC = Counter(classified) print "OK test" result = {'total': {'correct':0, 'tot':len(W)}} matrix= {'total': {'A':0,'B':0,'C':0,'D':0,'E':0,'F':0,'H':0,'I':0,'K':0,'L':0,'M':0,'N':0,'O':0,'P1':0,'P2':0,'Q':0,'R':0,'S1':0,'S2':0,'T':0,'U':0,'V':0,'W':0,'X':0,'Y':0}} for word in cY: result[word] = {'correct':0, 'tot':cY[word], 'found':cC[word]} matrix[word] = {'A':0,'B':0,'C':0,'D':0,'E':0,'F':0,'H':0,'I':0,'K':0,'L':0,'M':0,'N':0,'O':0,'P1':0,'P2':0,'Q':0,'R':0,'S1':0,'S2':0,'T':0,'U':0,'V':0,'W':0,'X':0,'Y':0} for i in range(0, len(classified)): if classified[i] == W[i]: result['total']['correct']+=1 result[W[i]]['correct']+=1 matrix[W[i]][classified[i]]+=1 for key in result.keys(): if key!='total': print "%10s\t\t%d/%d (%d)\t\t%0.2f%s" % (key, result[key]['correct'], result[key]['tot'], result[key]['found'], float(result[key]['correct'])/result[key]['tot']*100,'%') key = 'total' print "\n%10s\t\t%d/%d\t\t\t%0.2f%s\n\n" % (key, result[key]['correct'], result[key]['tot'], float(result[key]['correct'])/result[key]['tot']*100, '%') #print matrix sign=['A','B','C','D','E','F','H','I','K','L','M','N','O','P1','P2','Q','R','S1','S2','T','U','V','W','X','Y'] f = open("fileNEW.txt", "w") for i in sign: for j in sign: print >>f, ' %d' %matrix[i][j] f.close() def conf_test_obj(path_train, path_test, classifier_obj): paths = glob.glob(path_train+'*/*/*.xml') X = create_patterns(paths) Y = create_labels(paths) paths = glob.glob(path_test+'*/*/*.xml') Z = create_patterns(paths) W = create_labels(paths) print "OK Paths" cY = Counter(Y) classified = classifier_obj.fit(X,Y).predict(Z).tolist() cC = Counter(classified) print "OK Classified" result = {'total': {'correct':0, 'tot':len(Y)}} matrix= {'total': {'A':0,'B':0,'C':0,'D':0,'E':0,'F':0,'H':0,'I':0,'K':0,'L':0,'M':0,'N':0,'O':0,'P1':0,'P2':0,'Q':0,'R':0,'S1':0,'S2':0,'T':0,'U':0,'V':0,'W':0,'X':0,'Y':0}} for word in cY: result[word] = {'correct':0, 'tot':cY[word], 'found':cC[word]} matrix[word] = {'A':0,'B':0,'C':0,'D':0,'E':0,'F':0,'H':0,'I':0,'K':0,'L':0,'M':0,'N':0,'O':0,'P1':0,'P2':0,'Q':0,'R':0,'S1':0,'S2':0,'T':0,'U':0,'V':0,'W':0,'X':0,'Y':0} for i in range(0, len(classified)): if classified[i] == W[i]: result['total']['correct']+=1 result[W[i]]['correct']+=1 matrix[W[i]][classified[i]]+=1 for key in result.keys(): if key!='total': print "%10s\t\t%d/%d (%d)\t\t%0.2f%s" % (key, result[key]['correct'], result[key]['tot'], result[key]['found'], float(result[key]['correct'])/result[key]['tot']*100,'%') key = 'total' print "\n%10s\t\t%d/%d\t\t\t%0.2f%s\n\n" % (key, result[key]['correct'], result[key]['tot'], float(result[key]['correct'])/result[key]['tot']*100, '%') #print matrix sign=['A','B','C','D','E','F','H','I','K','L','M','N','O','P1','P2','Q','R','S1','S2','T','U','V','W','X','Y'] f = open("fileNEW.txt", "w") for i in sign: for j in sign: print >>f, ' %d' %matrix[i][j] f.close() #Cross validation def cross_test_obj(path_test, classifier_obj):#classifier NOT already fitted! paths = glob.glob(path_test+'*/*/*.xml') X = numpy.asarray(create_patterns(paths)) Y = numpy.asarray(create_labels(paths)) #print X #print Y #print "Debug Paths" #Different paths of cross validation from sklearn library #cv = StratifiedKFold(y, k=6) cv = LeavePOut(len(Y), 500) #cv = LeaveOneOut(len(Y), indices=True) #print "Debug cv" #print cv for i, (train, test) in enumerate(cv): #print "Debug Train" #print train #print "Debug Test" #print test if i < 10: cY = Counter(Y) #for j in enumerate(train): #classifiedTMP = classifier_obj.fit(X[j], Y[j]) #for j in enumerate(test): ##classified = classifiedTMP.predict(X[j]).tolist() #classified = classifiedTMP.predict(X[j]).tolist() classified = classifier_obj.fit(X[train], Y[train]).predict(X[test]).tolist() #print classified cC = Counter(classified) result = {'total': {'correct':0, 'tot':len(Y)}} for world in cY: result[world] = {'correct':0, 'tot':cY[world], 'found':cC[world]} for i in range(0, len(classified)): if classified[i] == Y[i]: result['total']['correct']+=1 result[Y[i]]['correct']+=1 partial = 0 for key in result.keys(): if key!='total': print "%10s\t\t%d/%d (%d)\t\t%0.2f%s" % (key, result[key]['correct'], result[key]['tot'], result[key]['found'], float(result[key]['correct'])/(0.001+result[key]['found'])*100,'%') partial = partial + result[key]['found'] if partial == 0: partial = 0.001 key = 'total' #print "\n%10s\t\t%d/%d\t\t\t%0.2f%s\n\n" % (key, result[key]['correct'], result[key]['tot'], float(result[key]['correct'])/result[key]['tot']*100, '%') print "\n%10s\t\t%d/%d\t\t\t%0.2f%s\n\n" % (key, result[key]['correct'], partial, float(result[key]['correct'])/partial*100, '%') #Support functions for cross validation def create_training_set_cross(path_test): paths = glob.glob(path_test+'*/*/*.xml') X = numpy.asarray(create_patterns(paths)) return X def create_test_set_cross(path_test): paths = glob.glob(path_test+'*/*/*.xml') Y = numpy.asarray(create_labels(paths)) return Y def cross_test_objXY(path_test, classifier_obj, X, Y):#classifier NOT already fitted! #print X #print Y #print "Debug Paths" #cv = StratifiedKFold(y, k=6) cv = LeavePOut(len(Y), 500) #cv = LeaveOneOut(len(Y), indices=True) #print "Debug cv" #print cv for i, (train, test) in enumerate(cv): #print "Debug Train" #print train #print "Debug Test" #print test if i < 5: cY = Counter(Y) #for j in enumerate(train): #classifiedTMP = classifier_obj.fit(X[j], Y[j]) #for j in enumerate(test): ##classified = classifiedTMP.predict(X[j]).tolist() #classified = classifiedTMP.predict(X[j]).tolist() classified = classifier_obj.fit(X[train], Y[train]).predict(X[test]).tolist() #print classified cC = Counter(classified) result = {'total': {'correct':0, 'tot':len(Y)}} for world in cY: result[world] = {'correct':0, 'tot':cY[world], 'found':cC[world]} for i in range(0, len(classified)): if classified[i] == Y[i]: result['total']['correct']+=1 result[Y[i]]['correct']+=1 partial = 0 for key in result.keys(): if key!='total': print "%10s\t\t%d/%d (%d)\t\t%0.2f%s" % (key, result[key]['correct'], result[key]['tot'], result[key]['found'], float(result[key]['correct'])/(0.001+result[key]['found'])*100,'%') partial = partial + result[key]['found'] if partial == 0: partial = 0.001 key = 'total' #print "\n%10s\t\t%d/%d\t\t\t%0.2f%s\n\n" % (key, result[key]['correct'], result[key]['tot'], float(result[key]['correct'])/result[key]['tot']*100, '%') print "\n%10s\t\t%d/%d\t\t\t%0.2f%s\n\n" % (key, result[key]['correct'], partial, float(result[key]['correct'])/partial*100, '%') else: return if __name__=="__main__": train_obj(sys.argv[1], '')
gpl-2.0
vidonme/webapp
js/pageif.js
4431
var g_CurLibId = 0; var g_CommercialVideoId = 1; var g_PersonalVideoId = 2; var g_CurLibraryType = "commercial"; var g_CurDeletePathWaitforConfirm = {}; //´æÒѾ­Ñ¡ÖÐɾ³ýµÄ·¾¶li¶ÔÏó $(function() { RequestGetLibraries("all"); $("#addCommercialPath").click(function() { g_CurLibId = g_CommercialVideoId; g_CurLibraryType = "commercial"; var title = $.i18n.prop('index_17'); $("#popaddVideoH3").text(title); ShowPageManageLibPath(g_CurLibId); }) $("#addPermediaPath").click(function() { g_CurLibId = g_PersonalVideoId; g_CurLibraryType = "personal"; var title = $.i18n.prop('index_18'); $("#popaddVideoH3").text(title); ShowPageManageLibPath(g_CurLibId); }) $("#addPathbtn").click(function() { showdiv(".addPath", 2); AccessPageLibraryPath(g_CurLibraryType); }) $("#btnMngPathOK").click(function() { close_box('.addVideo', 1); RefreshMediaLibrary(g_CurLibraryType); }) $("#btnCfmDeletePathOK").click(function() { confirmDeletePath(); $('#selectedPath li').removeClass("even"); $('#selectedPath li:even').addClass("even"); }) //Ò³ÃæÉ¾³ý·¾¶ $("#selectedPath").delegate('.delete', "click", function() { g_CurDeletePathWaitforConfirm = $(this).parent(); showdiv(".confirmDelete", 2); $("#deletePath").text($(this).parent().find(".showpath").text()); //$(this).parent().remove(); }) }) function cbSetLibraryID(data, mediatype) { if (data && data.result && data.result.libraries && (data.result.libraries.length > 0)) { $.each($(data.result.libraries), jQuery.proxy(function(i, item) { switch (item.type) { case "commercial": g_CommercialVideoId = item.LibraryId; return; case "personal": g_PersonalVideoId = item.LibraryId; return; default: rerurn; } }, this)); } } //==================ManageLibraryPath Div====================== function ShowPageManageLibPath(libid) { showdiv('.addVideo', 1); g_CurLibId = libid; RequestLibraryPaths(libid); } function cbHandleLibraryPaths(data) { var msg = ""; if (!checkResponse(data)) return; $("#selectedPath").html(""); var FolderCnt = data.result.paths.length; (FolderCnt)? (msg = $.i18n.prop('index_51')) : (msg = $.i18n.prop('index_52')); $("#addPathbtn").text(msg); if(!FolderCnt){ msg = $.i18n.prop('index_16'); var itemhtml = '<li index="' + 0 + '"><span class="showpath">' + msg + '</span></li>' $("#selectedPath").append(itemhtml); return; } $.each($(data.result.paths), jQuery.proxy(function(i, item) { var pid = item.PathId; var path = item.path; var itemhtml = '<li index="' + pid + '"><span class="delete"></span><span class="showpath">' + path + '</span></li>' $("#selectedPath").append(itemhtml); $('#selectedPath li:even').addClass("even"); }, this)); } function cbHandleAddLibraryPath(data){ if (!checkResponse(data)){ // var errmsg = $.i18n.prop('index_187'); // alert(errmsg); return; } var len= $("#selectedPath li").length; var index = $("#selectedPath li").attr("index"); if (len == 1 && index == 0) { $("#selectedPath").html(""); } var mediapath = $("#addSrcPath").val(); if (!mediapath) return; var pathid = data.result.PathId; var html = '<li index="' + pathid + '"><span class="delete"></span><span class="showpath">' + mediapath + '</span></li>' $("#selectedPath").append(html); $('#selectedPath li:even').addClass("even"); close_box('.addPath', 2); } //Ö÷Ò³Ôö¼Ó·¾¶ function commitAddOneLibPath() { var mediapath = $("#addSrcPath").val(); if (!mediapath) return; RequestAddLibraryPath(g_CurLibId, mediapath); } //==================È·ÈÏɾ³ý·¾¶DIV============================== function cbHandleDeleteLibraryPath(data){ if (data && data.result.ret == true) { return; } else { PopupAlert(data.result.err); } } function confirmDeletePath() { var pid = g_CurDeletePathWaitforConfirm.attr("index"); var mediapath = g_CurDeletePathWaitforConfirm.text(); //alert("pid="+pid+",mediapath="+mediapath); if (pid != "0") { RequestDeleteLibraryPath(g_CurLibId, pid) } g_CurDeletePathWaitforConfirm.remove(); close_box('.confirmDelete', 2); }
gpl-2.0
ForensicTools/MetaVisualization-474_2135-Barber
src/metaviz/process.py
1943
#!/usr/bin/python import sys import exiftool import MySQLdb as mdb import hashlib # Change 'yourpassword' to your mysql password con = mdb.connect('localhost', 'root', 'yourpassword', 'MetaViz'); #sys.stderr = open('/dev/null', 'w') image_dir = "uploaded/" files = sys.argv files = files[1:] hashes = []; def key_exists(key): with con: cur = con.cursor() sql = "SHOW COLUMNS FROM images LIKE " + "\'" + key + "\'" cur.execute(sql) result = cur.fetchall() if len(result) > 0: if key == result[0][0]: return True else: return False def get_hashes(): with con: cur = con.cursor() sql = "SELECT hash FROM images" cur.execute(sql) result = cur.fetchall() return result def hashimage(image): with open(image) as hash_me: data = hash_me.read() img_hash = hashlib.sha256(data).hexdigest() return img_hash for x in xrange(len(files)): files[x] = image_dir + files[x]#.strip("'") for image in files: with con: cur = con.cursor() imagehash = hashimage(image) sql_statement = "SELECT hash FROM images WHERE \'" + str(imagehash) +"\' IN (SELECT hash FROM images)" check = cur.execute(sql_statement) if check == 0: sql = "INSERT INTO images (Hash) VALUES (\'" + imagehash + '\')' cur.execute(sql) sql2 = "UPDATE images SET Name =\'" + str(image[9:]) + "\' WHERE hash=\'" + imagehash + "\'" cur.execute(sql2) else: # Remove from list of files files.remove(image) hashes.append(imagehash) if len(files)>0: with exiftool.ExifTool() as et: metadata = et.get_metadata_batch(files) i=0 for d in metadata: with con: cur = con.cursor() keys = list(d) for key in keys: value = d[key] key=key.split(':', 1)[-1] key=key.replace('/','1') if key_exists(key): sql = "UPDATE images SET " + key + "=\'" + str(value) + "\' WHERE hash=\'" + hashes[i] + "\'" cur.execute(sql) print hashes
gpl-2.0
cuongnd/banhangonline88_joomla
media/foundry/2.1/scripts_/joomla.js
993
dispatch.to("Foundry/2.1 Core Plugins").at(function($, manifest) { /** * joomla * Abstraction layer for Joomla client-side API. * https://github.com/foundry-modules/joomla * * Copyright (c) 2012 Jason Ramos * www.stackideas.com * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ var parser = { squeezebox: function() { return ($.joomlaVersion > 1.5) ? window.parent.SqueezeBox : window.parent.document.getElementById('sbox-window'); } }; var self = $.Joomla = function(method, args) { // Overriding function if ($.isFunction(args)) { var fn = args; if ($.joomlaVersion > 1.5) { window.Joomla[method] = fn; } else { window[method] = fn; }; return; } // Calling function var method = parser[method] || (($.joomlaVersion > 1.5) ? window.Joomla[method] : window[method]); if ($.isFunction(method)) { return method.apply(window, args); } }; }); // dispatch: end
gpl-2.0
ccompiler4pic32/pic32-gcc
libstdc++-v3/src/wlocale-inst.cc
8843
// Locale support -*- C++ -*- // Copyright (C) 1999, 2000, 2001, 2002, 2003, 2006, 2009 // Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This 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 General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. // // ISO C++ 14882: 22.1 Locales // #include <bits/c++config.h> #ifdef _GLIBCXX_USE_WCHAR_T #define C wchar_t #include "locale-inst.cc" // XXX GLIBCXX_ABI Deprecated #if defined _GLIBCXX_LONG_DOUBLE_COMPAT #define _GLIBCXX_LDBL_COMPAT(dbl, ldbl) \ extern "C" void ldbl (void) __attribute__ ((alias (#dbl), weak)) _GLIBCXX_LDBL_COMPAT(_ZNKSt17__gnu_cxx_ldbl1287num_getIwSt19istreambuf_iteratorIwSt11char_traitsIwEEE14_M_extract_intIjEES4_S4_S4_RSt8ios_baseRSt12_Ios_IostateRT_, _ZNKSt7num_getIwSt19istreambuf_iteratorIwSt11char_traitsIwEEE14_M_extract_intIjEES3_S3_S3_RSt8ios_baseRSt12_Ios_IostateRT_); _GLIBCXX_LDBL_COMPAT(_ZNKSt17__gnu_cxx_ldbl1287num_getIwSt19istreambuf_iteratorIwSt11char_traitsIwEEE14_M_extract_intIlEES4_S4_S4_RSt8ios_baseRSt12_Ios_IostateRT_, _ZNKSt7num_getIwSt19istreambuf_iteratorIwSt11char_traitsIwEEE14_M_extract_intIlEES3_S3_S3_RSt8ios_baseRSt12_Ios_IostateRT_); _GLIBCXX_LDBL_COMPAT(_ZNKSt17__gnu_cxx_ldbl1287num_getIwSt19istreambuf_iteratorIwSt11char_traitsIwEEE14_M_extract_intImEES4_S4_S4_RSt8ios_baseRSt12_Ios_IostateRT_, _ZNKSt7num_getIwSt19istreambuf_iteratorIwSt11char_traitsIwEEE14_M_extract_intImEES3_S3_S3_RSt8ios_baseRSt12_Ios_IostateRT_); _GLIBCXX_LDBL_COMPAT(_ZNKSt17__gnu_cxx_ldbl1287num_getIwSt19istreambuf_iteratorIwSt11char_traitsIwEEE14_M_extract_intItEES4_S4_S4_RSt8ios_baseRSt12_Ios_IostateRT_, _ZNKSt7num_getIwSt19istreambuf_iteratorIwSt11char_traitsIwEEE14_M_extract_intItEES3_S3_S3_RSt8ios_baseRSt12_Ios_IostateRT_); _GLIBCXX_LDBL_COMPAT(_ZNKSt17__gnu_cxx_ldbl1287num_getIwSt19istreambuf_iteratorIwSt11char_traitsIwEEE14_M_extract_intIxEES4_S4_S4_RSt8ios_baseRSt12_Ios_IostateRT_, _ZNKSt7num_getIwSt19istreambuf_iteratorIwSt11char_traitsIwEEE14_M_extract_intIxEES3_S3_S3_RSt8ios_baseRSt12_Ios_IostateRT_); _GLIBCXX_LDBL_COMPAT(_ZNKSt17__gnu_cxx_ldbl1287num_getIwSt19istreambuf_iteratorIwSt11char_traitsIwEEE14_M_extract_intIyEES4_S4_S4_RSt8ios_baseRSt12_Ios_IostateRT_, _ZNKSt7num_getIwSt19istreambuf_iteratorIwSt11char_traitsIwEEE14_M_extract_intIyEES3_S3_S3_RSt8ios_baseRSt12_Ios_IostateRT_); _GLIBCXX_LDBL_COMPAT(_ZNKSt17__gnu_cxx_ldbl1287num_putIwSt19ostreambuf_iteratorIwSt11char_traitsIwEEE13_M_insert_intIlEES4_S4_RSt8ios_basewT_, _ZNKSt7num_putIwSt19ostreambuf_iteratorIwSt11char_traitsIwEEE13_M_insert_intIlEES3_S3_RSt8ios_basewT_); _GLIBCXX_LDBL_COMPAT(_ZNKSt17__gnu_cxx_ldbl1287num_putIwSt19ostreambuf_iteratorIwSt11char_traitsIwEEE13_M_insert_intImEES4_S4_RSt8ios_basewT_, _ZNKSt7num_putIwSt19ostreambuf_iteratorIwSt11char_traitsIwEEE13_M_insert_intImEES3_S3_RSt8ios_basewT_); _GLIBCXX_LDBL_COMPAT(_ZNKSt17__gnu_cxx_ldbl1287num_putIwSt19ostreambuf_iteratorIwSt11char_traitsIwEEE13_M_insert_intIxEES4_S4_RSt8ios_basewT_, _ZNKSt7num_putIwSt19ostreambuf_iteratorIwSt11char_traitsIwEEE13_M_insert_intIxEES3_S3_RSt8ios_basewT_); _GLIBCXX_LDBL_COMPAT(_ZNKSt17__gnu_cxx_ldbl1287num_putIwSt19ostreambuf_iteratorIwSt11char_traitsIwEEE13_M_insert_intIyEES4_S4_RSt8ios_basewT_, _ZNKSt7num_putIwSt19ostreambuf_iteratorIwSt11char_traitsIwEEE13_M_insert_intIyEES3_S3_RSt8ios_basewT_); _GLIBCXX_LDBL_COMPAT(_ZNKSt17__gnu_cxx_ldbl1287num_putIwSt19ostreambuf_iteratorIwSt11char_traitsIwEEE15_M_insert_floatIdEES4_S4_RSt8ios_basewcT_, _ZNKSt7num_putIwSt19ostreambuf_iteratorIwSt11char_traitsIwEEE15_M_insert_floatIdEES3_S3_RSt8ios_basewcT_); _GLIBCXX_LDBL_COMPAT(_ZNKSt7num_putIwSt19ostreambuf_iteratorIwSt11char_traitsIwEEE15_M_insert_floatIdEES3_S3_RSt8ios_basewcT_, _ZNKSt7num_putIwSt19ostreambuf_iteratorIwSt11char_traitsIwEEE15_M_insert_floatIeEES3_S3_RSt8ios_basewcT_); _GLIBCXX_LDBL_COMPAT(_ZNKSt17__gnu_cxx_ldbl1289money_getIwSt19istreambuf_iteratorIwSt11char_traitsIwEEE10_M_extractILb0EEES4_S4_S4_RSt8ios_baseRSt12_Ios_IostateRSs, _ZNKSt9money_getIwSt19istreambuf_iteratorIwSt11char_traitsIwEEE10_M_extractILb0EEES3_S3_S3_RSt8ios_baseRSt12_Ios_IostateRSs); _GLIBCXX_LDBL_COMPAT(_ZNKSt17__gnu_cxx_ldbl1289money_getIwSt19istreambuf_iteratorIwSt11char_traitsIwEEE10_M_extractILb1EEES4_S4_S4_RSt8ios_baseRSt12_Ios_IostateRSs, _ZNKSt9money_getIwSt19istreambuf_iteratorIwSt11char_traitsIwEEE10_M_extractILb1EEES3_S3_S3_RSt8ios_baseRSt12_Ios_IostateRSs); _GLIBCXX_LDBL_COMPAT(_ZNKSt17__gnu_cxx_ldbl1289money_putIwSt19ostreambuf_iteratorIwSt11char_traitsIwEEE9_M_insertILb0EEES4_S4_RSt8ios_basewRKSbIwS3_SaIwEE, _ZNKSt9money_putIwSt19ostreambuf_iteratorIwSt11char_traitsIwEEE9_M_insertILb0EEES3_S3_RSt8ios_basewRKSbIwS2_SaIwEE); _GLIBCXX_LDBL_COMPAT(_ZNKSt17__gnu_cxx_ldbl1289money_putIwSt19ostreambuf_iteratorIwSt11char_traitsIwEEE9_M_insertILb1EEES4_S4_RSt8ios_basewRKSbIwS3_SaIwEE, _ZNKSt9money_putIwSt19ostreambuf_iteratorIwSt11char_traitsIwEEE9_M_insertILb1EEES3_S3_RSt8ios_basewRKSbIwS2_SaIwEE); #endif // _GLIBCXX_LONG_DOUBLE_COMPAT #if _GLIBCXX_C_LOCALE_GNU /* Because of a bad cross-compilation fallback in a configure test, Sourcery G++ toolchains for GNU/Linux targets formerly used the "generic" locale model in libstdc++. Improve compatibility with those toolchains by exporting symbol aliases under the "generic" names for the "gnu" functions. */ #define _GLIBCXX_LOCALE_COMPAT(generic, gnu) \ extern "C" void generic (void) __attribute__ ((alias (#gnu), weak)) #ifdef _GLIBCXX_SIZE_T_IS_UINT _GLIBCXX_LOCALE_COMPAT (_ZNSt10moneypunctIwLb0EEC1EPiPKcj, _ZNSt10moneypunctIwLb0EEC1EP15__locale_structPKcj); _GLIBCXX_LOCALE_COMPAT (_ZNSt10moneypunctIwLb0EEC2EPiPKcj, _ZNSt10moneypunctIwLb0EEC2EP15__locale_structPKcj); _GLIBCXX_LOCALE_COMPAT (_ZNSt10moneypunctIwLb1EEC1EPiPKcj, _ZNSt10moneypunctIwLb1EEC1EP15__locale_structPKcj); _GLIBCXX_LOCALE_COMPAT (_ZNSt10moneypunctIwLb1EEC2EPiPKcj, _ZNSt10moneypunctIwLb1EEC2EP15__locale_structPKcj); _GLIBCXX_LOCALE_COMPAT (_ZNSt11__timepunctIwEC1EPiPKcj, _ZNSt11__timepunctIwEC1EP15__locale_structPKcj); _GLIBCXX_LOCALE_COMPAT (_ZNSt11__timepunctIwEC2EPiPKcj, _ZNSt11__timepunctIwEC2EP15__locale_structPKcj); _GLIBCXX_LOCALE_COMPAT (_ZNSt7collateIwEC1EPij, _ZNSt7collateIwEC1EP15__locale_structj); _GLIBCXX_LOCALE_COMPAT (_ZNSt7collateIwEC2EPij, _ZNSt7collateIwEC2EP15__locale_structj); _GLIBCXX_LOCALE_COMPAT (_ZNSt8messagesIwEC1EPiPKcj, _ZNSt8messagesIwEC1EP15__locale_structPKcj); _GLIBCXX_LOCALE_COMPAT (_ZNSt8messagesIwEC2EPiPKcj, _ZNSt8messagesIwEC2EP15__locale_structPKcj); _GLIBCXX_LOCALE_COMPAT (_ZNSt8numpunctIwEC1EPij, _ZNSt8numpunctIwEC1EP15__locale_structj); _GLIBCXX_LOCALE_COMPAT (_ZNSt8numpunctIwEC2EPij, _ZNSt8numpunctIwEC2EP15__locale_structj); #else _GLIBCXX_LOCALE_COMPAT (_ZNSt10moneypunctIwLb0EEC1EPiPKcm, _ZNSt10moneypunctIwLb0EEC1EP15__locale_structPKcm); _GLIBCXX_LOCALE_COMPAT (_ZNSt10moneypunctIwLb0EEC2EPiPKcm, _ZNSt10moneypunctIwLb0EEC2EP15__locale_structPKcm); _GLIBCXX_LOCALE_COMPAT (_ZNSt10moneypunctIwLb1EEC1EPiPKcm, _ZNSt10moneypunctIwLb1EEC1EP15__locale_structPKcm); _GLIBCXX_LOCALE_COMPAT (_ZNSt10moneypunctIwLb1EEC2EPiPKcm, _ZNSt10moneypunctIwLb1EEC2EP15__locale_structPKcm); _GLIBCXX_LOCALE_COMPAT (_ZNSt11__timepunctIwEC1EPiPKcm, _ZNSt11__timepunctIwEC1EP15__locale_structPKcm); _GLIBCXX_LOCALE_COMPAT (_ZNSt11__timepunctIwEC2EPiPKcm, _ZNSt11__timepunctIwEC2EP15__locale_structPKcm); _GLIBCXX_LOCALE_COMPAT (_ZNSt7collateIwEC1EPim, _ZNSt7collateIwEC1EP15__locale_structm); _GLIBCXX_LOCALE_COMPAT (_ZNSt7collateIwEC2EPim, _ZNSt7collateIwEC2EP15__locale_structm); _GLIBCXX_LOCALE_COMPAT (_ZNSt8messagesIwEC1EPiPKcm, _ZNSt8messagesIwEC1EP15__locale_structPKcm); _GLIBCXX_LOCALE_COMPAT (_ZNSt8messagesIwEC2EPiPKcm, _ZNSt8messagesIwEC2EP15__locale_structPKcm); _GLIBCXX_LOCALE_COMPAT (_ZNSt8numpunctIwEC1EPim, _ZNSt8numpunctIwEC1EP15__locale_structm); _GLIBCXX_LOCALE_COMPAT (_ZNSt8numpunctIwEC2EPim, _ZNSt8numpunctIwEC2EP15__locale_structm); #endif #endif #endif
gpl-2.0
lamsfoundation/lams
lams_common/src/java/org/lamsfoundation/lams/index/IndexLinkBean.java
2747
/**************************************************************** * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) * ============================================================= * License Information: http://lamsfoundation.org/licensing/lams/2.0/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2.0 * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA * * http://www.gnu.org/licenses/gpl.txt * **************************************************************** */ package org.lamsfoundation.lams.index; /** * @version * * <p> * <a href="IndexLinkBean.java.html"><i>View Source</i></a> * </p> * * @author <a href="mailto:[email protected]">Fei Yang</a> * * Created at 10:12:09 on 14/06/2006 */ public class IndexLinkBean { private String name; private String url; private String style; private String tooltip; private String id; public IndexLinkBean(String name, String url, String style, String tooltip) { super(); this.name = name; this.url = url; this.style = style; this.tooltip = tooltip; this.id = name != null ? name.replace('.', '-') : null; } public IndexLinkBean(String name, String url) { this.name = name; this.url = url; this.id = name != null ? name.replace('.', '-') : null; } /** * @return Returns the name. */ public String getName() { return name; } /** * @param name * The name to set. */ public void setName(String name) { this.name = name; this.id = name != null ? name.replace('.', '-') : null; } /** * @return Returns the url. */ public String getUrl() { return url; } /** * @param url * The url to set. */ public void setUrl(String url) { this.url = url; } public String getStyle() { return style; } public void setStyle(String style) { this.style = style; } public String getTooltip() { return tooltip; } public void setTooltip(String tooltip) { this.tooltip = tooltip; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
gpl-2.0
andela-ooshodi/django-bucketlist-application
djangobucketlist/bucketlist/urls.py
1260
""" URL config for accessing views of the bucketlist app """ from django.conf.urls import url from bucketlist.views import view_authentication, view_buckets urlpatterns = [ url(r'^$', view_authentication.IndexView.as_view(), name='index'), url(r'^login$', view_authentication.LoginView.as_view(), name='login'), url(r'^logout$', 'django.contrib.auth.views.logout', {'next_page': '/'}), url(r'^register$', view_authentication.RegistrationView.as_view(), name='register'), url(r'^bucketlist$', view_buckets.BucketListView.as_view(), name='bucketlist'), url(r'^bucketlist/(?P<bucketlistid>[0-9]+)/edit$', view_buckets.BucketListEditView.as_view(), name='bucketlistedit'), url(r'^bucketlist/(?P<bucketlistid>[0-9]+)/delete$', view_buckets.BucketListDeleteView.as_view(), name='bucketlistdelete'), url(r'^bucketlist/(?P<bucketlistid>[0-9]+)/bucketitems$', view_buckets.BucketItemView.as_view(), name='bucketitem'), url(r'^bucketitem/(?P<bucketitemid>[0-9]+)/edit$', view_buckets.BucketItemEditView.as_view(), name='bucketitemedit'), url(r'^bucketitem/(?P<bucketitemid>[0-9]+)/delete$', view_buckets.BucketItemDeleteView.as_view(), name='bucketitemdelete'), ]
gpl-2.0
digijin/space-station-sim
flow-typed/npm/babel-loader_vx.x.x.js
1871
// flow-typed signature: b5b9382dc5715df97e371240cf2afddc // flow-typed version: <<STUB>>/babel-loader_v^6.2.4/flow_v0.38.0 /** * This is an autogenerated libdef stub for: * * 'babel-loader' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'babel-loader' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'babel-loader/lib/fs-cache' { declare module.exports: any; } declare module 'babel-loader/lib/index' { declare module.exports: any; } declare module 'babel-loader/lib/resolve-rc' { declare module.exports: any; } declare module 'babel-loader/lib/utils/exists' { declare module.exports: any; } declare module 'babel-loader/lib/utils/read' { declare module.exports: any; } declare module 'babel-loader/lib/utils/relative' { declare module.exports: any; } // Filename aliases declare module 'babel-loader/lib/fs-cache.js' { declare module.exports: $Exports<'babel-loader/lib/fs-cache'>; } declare module 'babel-loader/lib/index.js' { declare module.exports: $Exports<'babel-loader/lib/index'>; } declare module 'babel-loader/lib/resolve-rc.js' { declare module.exports: $Exports<'babel-loader/lib/resolve-rc'>; } declare module 'babel-loader/lib/utils/exists.js' { declare module.exports: $Exports<'babel-loader/lib/utils/exists'>; } declare module 'babel-loader/lib/utils/read.js' { declare module.exports: $Exports<'babel-loader/lib/utils/read'>; } declare module 'babel-loader/lib/utils/relative.js' { declare module.exports: $Exports<'babel-loader/lib/utils/relative'>; }
gpl-2.0
vongdeptaydep/vongdeotaydep
wp-content/plugins/rit-core/inc/widgets/widget-facebook.php
8248
<?php /** * RIT Core Plugin * @package RIT Core * @version 2.0.2 * @author Zootemplate * @link http://www.zootemplate.com * @copyright Copyright (c) 2015 Zootemplate * @license GPL v2 */ if (!class_exists('RITFacebook')) { class RITFacebook extends WP_Widget { public function __construct() { parent::__construct('facebook_widget', 'RIT Facebook', array('description' => esc_html__('Facebook Social widget', RIT_TEXT_DOMAIN),)); } public function form($instance) { $title = isset($instance['title']) ? $instance['title'] : esc_html__('Facebook widget', RIT_TEXT_DOMAIN); $width = isset($instance['width']) ? $instance['width'] : 255; $color = isset($instance['color']) ? $instance['color'] : 'dark'; $stream = isset($instance['stream']) ? $instance['stream'] : 'false'; $faces = isset($instance['faces']) ? $instance['faces'] : 'true'; $url = isset($instance['url']) ? $instance['url'] : ''; $header = isset($instance['header']) ? $instance['header'] : 'false'; ?> <p> <label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php esc_html_e('Title:', RIT_TEXT_DOMAIN); ?></label> <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text" value="<?php echo esc_attr($title); ?>"/> </p> <p> <label for="<?php echo esc_attr($this->get_field_id('url')); ?>"><?php esc_html_e('Facebook Name: ( facebook.com/ * Type into field * )', RIT_TEXT_DOMAIN); ?></label> <input class="widefat" id="<?php echo esc_attr($this->get_field_id('url')); ?>" name="<?php echo esc_attr($this->get_field_name('url')); ?>" type="text" value="<?php echo esc_attr($url); ?>"/> </p> <p> <label for="<?php echo esc_attr($this->get_field_id('width')); ?>"><?php esc_html_e('Width(px):', RIT_TEXT_DOMAIN); ?></label> <input class="widefat" id="<?php echo esc_attr($this->get_field_id('width')); ?>" name="<?php echo esc_attr($this->get_field_name('width')); ?>" type="text" value="<?php echo esc_attr($width); ?>"/> </p> <p> <label for="<?php echo esc_attr($this->get_field_id('color')); ?>"><?php esc_html_e('Color scheme:', RIT_TEXT_DOMAIN); ?></label> <select id="<?php echo esc_attr($this->get_field_id('color')); ?>" name="<?php echo esc_attr($this->get_field_name('color')); ?>" value="<?php echo esc_attr($color); ?>"> <option value='light' <?php if (esc_attr($color) == 'light') echo 'selected'; ?>>Light</option> <option value='dark' <?php if (esc_attr($color) == 'dark') echo 'selected'; ?>>Dark</option> </select> </p> <p> <label for="<?php echo esc_attr($this->get_field_id('stream')); ?>"><?php esc_html_e('Show stream:', RIT_TEXT_DOMAIN); ?></label> <select id="<?php echo esc_attr($this->get_field_id('stream')); ?>" name="<?php echo esc_attr($this->get_field_name('stream')); ?>" value="<?php echo esc_attr($stream); ?>"> <option value='true' <?php if (esc_attr($stream) == 'true') echo 'selected'; ?>>Yes</option> <option value='false' <?php if (esc_attr($stream) == 'false') echo 'selected'; ?>>No</option> </select> </p> <p> <label for="<?php echo esc_attr($this->get_field_id('faces')); ?>"><?php esc_html_e('Show faces:', RIT_TEXT_DOMAIN); ?></label> <select id="<?php echo esc_attr($this->get_field_id('faces')); ?>" name="<?php echo esc_attr($this->get_field_name('faces')); ?>" value="<?php echo esc_attr($faces); ?>"> <option value='true' <?php if (esc_attr($faces) == 'true') echo 'selected'; ?>>Yes</option> <option value='false' <?php if (esc_attr($faces) == 'false') echo 'selected'; ?>>No</option> </select> </p> <p> <label for="<?php echo esc_attr($this->get_field_id('header')); ?>"><?php esc_html_e('Show header:', RIT_TEXT_DOMAIN); ?></label> <select id="<?php echo esc_attr($this->get_field_id('header')); ?>" name="<?php echo esc_attr($this->get_field_name('header')); ?>" value="<?php echo esc_attr($header); ?>"> <option value='true' <?php if (esc_attr($header) == 'true') echo 'selected'; ?>>Yes</option> <option value='false' <?php if (esc_attr($header) == 'false') echo 'selected'; ?>>No</option> </select> </p> <?php } public function update($new_instance, $old_instance) { $instance = array(); $instance['title'] = strip_tags($new_instance['title']); $instance['color'] = strip_tags($new_instance['color']); $instance['stream'] = strip_tags($new_instance['stream']); $instance['width'] = strip_tags($new_instance['width']); $instance['faces'] = strip_tags($new_instance['faces']); $instance['url'] = strip_tags($new_instance['url']); $instance['header'] = strip_tags($new_instance['header']); return $instance; } public function widget($args, $instance) { wp_enqueue_script('Evatheme_facebook_widget_script'); extract($args); $title = apply_filters('widget_title', $instance['title']); $width = $instance['width']; $color = $instance['color']; $stream = $instance['stream']; $faces = $instance['faces']; $url = $instance['url']; $header = $instance['header']; echo htmlspecialchars_decode(esc_html($before_widget)); if ($title) { echo htmlspecialchars_decode(esc_html($before_title . $title . $after_title)); } ?> <div class="facebookOuter"> <div class="facebookInner"> <div class="fb-like-box" data-width="<?php echo esc_attr($width); ?>" data-height="300" data-href="http://www.facebook.com/<?php echo esc_attr($url); ?>" data-colorscheme="<?php echo esc_attr($color); ?>" data-show-border="false" data-show-faces="<?php echo esc_attr($faces); ?>" data-stream="<?php echo esc_attr($stream); ?>" data-header="<?php echo esc_attr($header); ?>"> </div> </div> </div> <div id="fb-root"></div> <script> (function (d, s, id) { "use strict"; 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> <?php echo htmlspecialchars_decode(esc_html($after_widget)); } } } add_action('widgets_init', 'rit_facebook_load_widgets'); function rit_facebook_load_widgets() { register_widget('RITFacebook'); }
gpl-2.0
AshamaneProject/AshamaneCore
src/server/scripts/Kalimdor/zone_azuremyst_isle.cpp
24405
/* * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Azuremyst_Isle SD%Complete: 75 SDComment: Quest support: 9283, 9537, 9582, 9554, ? (special flight path, proper model for mount missing). Injured Draenei cosmetic only, 9582. SDCategory: Azuremyst Isle EndScriptData */ /* ContentData npc_draenei_survivor npc_engineer_spark_overgrind npc_injured_draenei npc_magwin go_ravager_cage npc_death_ravager EndContentData */ #include "ScriptMgr.h" #include "CellImpl.h" #include "GridNotifiersImpl.h" #include "Log.h" #include "MotionMaster.h" #include "ObjectAccessor.h" #include "ScriptedEscortAI.h" #include "ScriptedGossip.h" #include "TemporarySummon.h" /*###### ## npc_draenei_survivor ######*/ enum draeneiSurvivor { SAY_THANK_FOR_HEAL = 0, SAY_ASK_FOR_HELP = 1, SPELL_IRRIDATION = 35046, SPELL_STUNNED = 28630, EVENT_CAN_ASK_FOR_HELP = 1, EVENT_THANK_PLAYER = 2, EVENT_RUN_AWAY = 3 }; Position const CrashSite = { -4115.25f, -13754.75f }; class npc_draenei_survivor : public CreatureScript { public: npc_draenei_survivor() : CreatureScript("npc_draenei_survivor") { } struct npc_draenei_survivorAI : public ScriptedAI { npc_draenei_survivorAI(Creature* creature) : ScriptedAI(creature) { Initialize(); } void Initialize() { _playerGUID.Clear(); _canAskForHelp = true; _canUpdateEvents = false; _tappedBySpell = false; } void Reset() override { Initialize(); _events.Reset(); DoCastSelf(SPELL_IRRIDATION, true); me->AddUnitFlag(UNIT_FLAG_PVP_ATTACKABLE); me->AddUnitFlag(UNIT_FLAG_IN_COMBAT); me->SetHealth(me->CountPctFromMaxHealth(10)); me->SetStandState(UNIT_STAND_STATE_SLEEP); } void EnterCombat(Unit* /*who*/) override { } void MoveInLineOfSight(Unit* who) override { if (_canAskForHelp && who->GetTypeId() == TYPEID_PLAYER && me->IsFriendlyTo(who) && me->IsWithinDistInMap(who, 25.0f)) { //Random switch between 4 texts Talk(SAY_ASK_FOR_HELP); _events.ScheduleEvent(EVENT_CAN_ASK_FOR_HELP, Seconds(16), Seconds(20)); _canAskForHelp = false; _canUpdateEvents = true; } } void SpellHit(Unit* caster, const SpellInfo* spell) override { if (spell->SpellFamilyFlags[2] & 0x80000000 && !_tappedBySpell) { _events.Reset(); _tappedBySpell = true; _canAskForHelp = false; _canUpdateEvents = true; me->RemoveUnitFlag(UNIT_FLAG_PVP_ATTACKABLE); me->SetStandState(UNIT_STAND_STATE_STAND); _playerGUID = caster->GetGUID(); if (Player* player = caster->ToPlayer()) player->KilledMonsterCredit(me->GetEntry()); me->SetFacingToObject(caster); DoCastSelf(SPELL_STUNNED, true); _events.ScheduleEvent(EVENT_THANK_PLAYER, Seconds(4)); } } void UpdateAI(uint32 diff) override { if (!_canUpdateEvents) return; _events.Update(diff); while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_CAN_ASK_FOR_HELP: _canAskForHelp = true; _canUpdateEvents = false; break; case EVENT_THANK_PLAYER: me->RemoveAurasDueToSpell(SPELL_IRRIDATION); if (Player* player = ObjectAccessor::GetPlayer(*me, _playerGUID)) Talk(SAY_THANK_FOR_HEAL, player); _events.ScheduleEvent(EVENT_RUN_AWAY, Seconds(10)); break; case EVENT_RUN_AWAY: me->GetMotionMaster()->Clear(); me->GetMotionMaster()->MovePoint(0, me->GetPositionX() + (std::cos(me->GetAngle(CrashSite)) * 28.0f), me->GetPositionY() + (std::sin(me->GetAngle(CrashSite)) * 28.0f), me->GetPositionZ() + 1.0f); me->DespawnOrUnsummon(Seconds(4)); break; default: break; } } } private: EventMap _events; bool _canUpdateEvents; bool _tappedBySpell; bool _canAskForHelp; ObjectGuid _playerGUID; }; CreatureAI* GetAI(Creature* creature) const override { return new npc_draenei_survivorAI(creature); } }; /*###### ## npc_engineer_spark_overgrind ######*/ enum Overgrind { SAY_TEXT = 0, SAY_EMOTE = 1, ATTACK_YELL = 2, QUEST_GNOMERCY = 9537, FACTION_HOSTILE = 14, SPELL_DYNAMITE = 7978 }; class npc_engineer_spark_overgrind : public CreatureScript { public: npc_engineer_spark_overgrind() : CreatureScript("npc_engineer_spark_overgrind") { } struct npc_engineer_spark_overgrindAI : public ScriptedAI { npc_engineer_spark_overgrindAI(Creature* creature) : ScriptedAI(creature) { Initialize(); NormFaction = creature->GetFaction(); NpcFlags = (uint32)creature->m_unitData->NpcFlags[0]; } void Initialize() { DynamiteTimer = 8000; EmoteTimer = urand(120000, 150000); if (me->GetAreaId() == AREA_AZUREMYST_ISLE_TRAITOR_COVE || me->GetAreaId() == AREA_AZUREMYST_ISLE_SILVERMYST_ISLE) IsTreeEvent = true; else IsTreeEvent = false; } void Reset() override { Initialize(); me->SetFaction(NormFaction); me->AddNpcFlag(NPCFlags(NpcFlags)); } void EnterCombat(Unit* who) override { Talk(ATTACK_YELL, who); } bool GossipSelect(Player* player, uint32 /*menuId*/, uint32 /*gossipListId*/) override { CloseGossipMenuFor(player); me->SetFaction(FACTION_HOSTILE); me->Attack(player, true); return false; } void UpdateAI(uint32 diff) override { if (!me->IsInCombat() && !IsTreeEvent) { if (EmoteTimer <= diff) { Talk(SAY_TEXT); Talk(SAY_EMOTE); EmoteTimer = urand(120000, 150000); } else EmoteTimer -= diff; } else if (IsTreeEvent) return; if (!UpdateVictim()) return; if (DynamiteTimer <= diff) { DoCastVictim(SPELL_DYNAMITE); DynamiteTimer = 8000; } else DynamiteTimer -= diff; DoMeleeAttackIfReady(); } private: uint32 NormFaction; uint32 NpcFlags; uint32 DynamiteTimer; uint32 EmoteTimer; bool IsTreeEvent; }; CreatureAI* GetAI(Creature* creature) const override { return new npc_engineer_spark_overgrindAI(creature); } }; /*###### ## npc_injured_draenei ######*/ class npc_injured_draenei : public CreatureScript { public: npc_injured_draenei() : CreatureScript("npc_injured_draenei") { } struct npc_injured_draeneiAI : public ScriptedAI { npc_injured_draeneiAI(Creature* creature) : ScriptedAI(creature) { } void Reset() override { me->AddUnitFlag(UNIT_FLAG_IN_COMBAT); me->SetHealth(me->CountPctFromMaxHealth(15)); switch (urand(0, 1)) { case 0: me->SetStandState(UNIT_STAND_STATE_SIT); break; case 1: me->SetStandState(UNIT_STAND_STATE_SLEEP); break; } } void EnterCombat(Unit* /*who*/) override { } void MoveInLineOfSight(Unit* /*who*/) override { } void UpdateAI(uint32 /*diff*/) override { } }; CreatureAI* GetAI(Creature* creature) const override { return new npc_injured_draeneiAI(creature); } }; /*###### ## npc_magwin ######*/ enum Magwin { SAY_START = 0, SAY_AGGRO = 1, SAY_PROGRESS = 2, SAY_END1 = 3, SAY_END2 = 4, EMOTE_HUG = 5, NPC_COWLEN = 17311, SAY_COWLEN = 0, EVENT_ACCEPT_QUEST = 1, EVENT_START_ESCORT = 2, EVENT_STAND = 3, EVENT_TALK_END = 4, EVENT_COWLEN_TALK = 5, QUEST_A_CRY_FOR_HELP = 9528, FACTION_QUEST = 113 }; class npc_magwin : public CreatureScript { public: npc_magwin() : CreatureScript("npc_magwin") { } struct npc_magwinAI : public npc_escortAI { npc_magwinAI(Creature* creature) : npc_escortAI(creature) { } void Reset() override { _events.Reset(); } void EnterCombat(Unit* who) override { Talk(SAY_AGGRO, who); } void QuestAccept(Player* player, Quest const* quest) override { if (quest->GetQuestId() == QUEST_A_CRY_FOR_HELP) { _player = player->GetGUID(); _events.ScheduleEvent(EVENT_ACCEPT_QUEST, Seconds(2)); } } void WaypointReached(uint32 waypointId) override { if (Player* player = GetPlayerForEscort()) { switch (waypointId) { case 17: Talk(SAY_PROGRESS, player); break; case 28: player->GroupEventHappens(QUEST_A_CRY_FOR_HELP, me); _events.ScheduleEvent(EVENT_TALK_END, Seconds(2)); SetRun(true); break; case 29: if (Creature* cowlen = me->FindNearestCreature(NPC_COWLEN, 50.0f, true)) Talk(EMOTE_HUG, cowlen); Talk(SAY_END2, player); break; } } } void UpdateEscortAI(uint32 diff) override { _events.Update(diff); if (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_ACCEPT_QUEST: if (Player* player = ObjectAccessor::GetPlayer(*me, _player)) Talk(SAY_START, player); me->SetFaction(FACTION_QUEST); _events.ScheduleEvent(EVENT_START_ESCORT, Seconds(1)); break; case EVENT_START_ESCORT: if (Player* player = ObjectAccessor::GetPlayer(*me, _player)) npc_escortAI::Start(true, false, player->GetGUID()); _events.ScheduleEvent(EVENT_STAND, Seconds(2)); break; case EVENT_STAND: // Remove kneel standstate. Using a separate delayed event because it causes unwanted delay before starting waypoint movement. me->SetStandState(UNIT_STAND_STATE_STAND); break; case EVENT_TALK_END: if (Player* player = ObjectAccessor::GetPlayer(*me, _player)) Talk(SAY_END1, player); _events.ScheduleEvent(EVENT_COWLEN_TALK, Seconds(2)); break; case EVENT_COWLEN_TALK: if (Creature* cowlen = me->FindNearestCreature(NPC_COWLEN, 50.0f, true)) cowlen->AI()->Talk(SAY_COWLEN); break; } } npc_escortAI::UpdateEscortAI(diff); } private: EventMap _events; ObjectGuid _player; }; CreatureAI* GetAI(Creature* creature) const override { return new npc_magwinAI(creature); } }; /*###### ## npc_geezle ######*/ enum Geezle { QUEST_TREES_COMPANY = 9531, SPELL_TREE_DISGUISE = 30298, GEEZLE_SAY_1 = 0, SPARK_SAY_2 = 3, SPARK_SAY_3 = 4, GEEZLE_SAY_4 = 1, SPARK_SAY_5 = 5, SPARK_SAY_6 = 6, GEEZLE_SAY_7 = 2, EMOTE_SPARK = 7, NPC_SPARK = 17243, GO_NAGA_FLAG = 181694 }; Position const SparkPos = {-5029.91f, -11291.79f, 8.096f, 0.0f}; class npc_geezle : public CreatureScript { public: npc_geezle() : CreatureScript("npc_geezle") { } struct npc_geezleAI : public ScriptedAI { npc_geezleAI(Creature* creature) : ScriptedAI(creature) { Initialize(); } void Initialize() { SparkGUID.Clear(); Step = 0; EventStarted = false; SayTimer = 0; } ObjectGuid SparkGUID; uint8 Step; uint32 SayTimer; bool EventStarted; void Reset() override { Initialize(); StartEvent(); } void EnterCombat(Unit* /*who*/) override { } void StartEvent() { Step = 0; EventStarted = true; if (Creature* Spark = me->SummonCreature(NPC_SPARK, SparkPos, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 1000)) { SparkGUID = Spark->GetGUID(); Spark->setActive(true); Spark->RemoveNpcFlag(UNIT_NPC_FLAG_GOSSIP); } SayTimer = 8000; } uint32 NextStep(uint8 step) { Creature* Spark = ObjectAccessor::GetCreature(*me, SparkGUID); if (!Spark) return 99999999; switch (step) { case 0: Spark->GetMotionMaster()->MovePoint(0, -5080.70f, -11253.61f, 0.56f); me->GetMotionMaster()->MovePoint(0, -5092.26f, -11252, 0.71f); return 9000; case 1: DespawnNagaFlag(true); Spark->AI()->Talk(EMOTE_SPARK); return 1000; case 2: Talk(GEEZLE_SAY_1, Spark); Spark->SetInFront(me); me->SetInFront(Spark); return 5000; case 3: Spark->AI()->Talk(SPARK_SAY_2); return 7000; case 4: Spark->AI()->Talk(SPARK_SAY_3); return 8000; case 5: Talk(GEEZLE_SAY_4, Spark); return 8000; case 6: Spark->AI()->Talk(SPARK_SAY_5); return 9000; case 7: Spark->AI()->Talk(SPARK_SAY_6); return 8000; case 8: Talk(GEEZLE_SAY_7, Spark); return 2000; case 9: me->GetMotionMaster()->MoveTargetedHome(); Spark->GetMotionMaster()->MovePoint(0, SparkPos); CompleteQuest(); return 9000; case 10: Spark->DisappearAndDie(); DespawnNagaFlag(false); me->DisappearAndDie(); default: return 99999999; } } // will complete Tree's company quest for all nearby players that are disguised as trees void CompleteQuest() { float radius = 50.0f; std::list<Player*> players; Trinity::AnyPlayerInObjectRangeCheck checker(me, radius); Trinity::PlayerListSearcher<Trinity::AnyPlayerInObjectRangeCheck> searcher(me, players, checker); Cell::VisitWorldObjects(me, searcher, radius); for (std::list<Player*>::const_iterator itr = players.begin(); itr != players.end(); ++itr) if ((*itr)->GetQuestStatus(QUEST_TREES_COMPANY) == QUEST_STATUS_INCOMPLETE && (*itr)->HasAura(SPELL_TREE_DISGUISE)) (*itr)->KilledMonsterCredit(NPC_SPARK); } void DespawnNagaFlag(bool despawn) { std::list<GameObject*> FlagList; me->GetGameObjectListWithEntryInGrid(FlagList, GO_NAGA_FLAG, 100.0f); if (!FlagList.empty()) { for (std::list<GameObject*>::const_iterator itr = FlagList.begin(); itr != FlagList.end(); ++itr) { if (despawn) (*itr)->SetLootState(GO_JUST_DEACTIVATED); else (*itr)->Respawn(); } } else TC_LOG_ERROR("scripts", "SD2 ERROR: FlagList is empty!"); } void UpdateAI(uint32 diff) override { if (SayTimer <= diff) { if (EventStarted) SayTimer = NextStep(Step++); } else SayTimer -= diff; } }; CreatureAI* GetAI(Creature* creature) const override { return new npc_geezleAI(creature); } }; enum RavegerCage { NPC_DEATH_RAVAGER = 17556, SPELL_REND = 13443, SPELL_ENRAGING_BITE = 30736, QUEST_STRENGTH_ONE = 9582 }; class go_ravager_cage : public GameObjectScript { public: go_ravager_cage() : GameObjectScript("go_ravager_cage") { } bool OnGossipHello(Player* player, GameObject* go) override { go->UseDoorOrButton(); if (player->GetQuestStatus(QUEST_STRENGTH_ONE) == QUEST_STATUS_INCOMPLETE) { if (Creature* ravager = go->FindNearestCreature(NPC_DEATH_RAVAGER, 5.0f, true)) { ravager->RemoveUnitFlag(UNIT_FLAG_NON_ATTACKABLE); ravager->SetReactState(REACT_AGGRESSIVE); ravager->AI()->AttackStart(player); } } return true; } }; class npc_death_ravager : public CreatureScript { public: npc_death_ravager() : CreatureScript("npc_death_ravager") { } struct npc_death_ravagerAI : public ScriptedAI { npc_death_ravagerAI(Creature* creature) : ScriptedAI(creature) { Initialize(); } void Initialize() { RendTimer = 30000; EnragingBiteTimer = 20000; } uint32 RendTimer; uint32 EnragingBiteTimer; void Reset() override { Initialize(); me->AddUnitFlag(UNIT_FLAG_NON_ATTACKABLE); me->SetReactState(REACT_PASSIVE); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; if (RendTimer <= diff) { DoCastVictim(SPELL_REND); RendTimer = 30000; } else RendTimer -= diff; if (EnragingBiteTimer <= diff) { DoCastVictim(SPELL_ENRAGING_BITE); EnragingBiteTimer = 15000; } else EnragingBiteTimer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return new npc_death_ravagerAI(creature); } }; /*######## ## Quest: The Prophecy of Akida ########*/ enum BristlelimbCage { QUEST_THE_PROPHECY_OF_AKIDA = 9544, NPC_STILLPINE_CAPITIVE = 17375, GO_BRISTELIMB_CAGE = 181714, CAPITIVE_SAY = 0, POINT_INIT = 1, EVENT_DESPAWN = 1, }; class npc_stillpine_capitive : public CreatureScript { public: npc_stillpine_capitive() : CreatureScript("npc_stillpine_capitive") { } struct npc_stillpine_capitiveAI : public ScriptedAI { npc_stillpine_capitiveAI(Creature* creature) : ScriptedAI(creature) { Initialize(); } void Initialize() { _playerGUID.Clear(); _movementComplete = false; } void Reset() override { if (GameObject* cage = me->FindNearestGameObject(GO_BRISTELIMB_CAGE, 5.0f)) { cage->SetLootState(GO_JUST_DEACTIVATED); cage->SetGoState(GO_STATE_READY); } _events.Reset(); Initialize(); } void StartMoving(Player* owner) { if (owner) { Talk(CAPITIVE_SAY, owner); _playerGUID = owner->GetGUID(); } Position pos = me->GetNearPosition(3.0f, 0.0f); me->GetMotionMaster()->MovePoint(POINT_INIT, pos); } void MovementInform(uint32 type, uint32 id) override { if (type != POINT_MOTION_TYPE || id != POINT_INIT) return; if (Player* _player = ObjectAccessor::GetPlayer(*me, _playerGUID)) _player->KilledMonsterCredit(me->GetEntry(), me->GetGUID()); _movementComplete = true; _events.ScheduleEvent(EVENT_DESPAWN, 3500); } void UpdateAI(uint32 diff) override { if (!_movementComplete) return; _events.Update(diff); if (_events.ExecuteEvent() == EVENT_DESPAWN) me->DespawnOrUnsummon(); } private: ObjectGuid _playerGUID; EventMap _events; bool _movementComplete; }; CreatureAI* GetAI(Creature* creature) const override { return new npc_stillpine_capitiveAI(creature); } }; class go_bristlelimb_cage : public GameObjectScript { public: go_bristlelimb_cage() : GameObjectScript("go_bristlelimb_cage") { } bool OnGossipHello(Player* player, GameObject* go) override { go->SetGoState(GO_STATE_READY); if (player->GetQuestStatus(QUEST_THE_PROPHECY_OF_AKIDA) == QUEST_STATUS_INCOMPLETE) { if (Creature* capitive = go->FindNearestCreature(NPC_STILLPINE_CAPITIVE, 5.0f, true)) { go->ResetDoorOrButton(); ENSURE_AI(npc_stillpine_capitive::npc_stillpine_capitiveAI, capitive->AI())->StartMoving(player); return false; } } return true; } }; void AddSC_azuremyst_isle() { new npc_draenei_survivor(); new npc_engineer_spark_overgrind(); new npc_injured_draenei(); new npc_magwin(); new npc_death_ravager(); new go_ravager_cage(); new npc_stillpine_capitive(); new go_bristlelimb_cage(); }
gpl-2.0
DarkNinjaShadowDeLaMort/4Tunes
src/manager/artiste/ArtisteManager.java
416
package manager.artiste; import java.util.List; import javax.ejb.Local; import model.Artiste; @Local public interface ArtisteManager { public boolean artisteExist(String nom); public void addArtiste(String nom); public List <Artiste> getArtistes(); public List<Artiste> getArtistesByIdUser(int idUser); public Artiste getArtisteByName(String nom); public Artiste getArtisteById(int id); }
gpl-2.0
THINKGlobalSchool/labs
activate.php
591
<?php /** * Spot Labs Plugin Activation Script * * @package SpotLabs * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License version 2 * @author Jeff Tilson * @copyright THINK Global School 2010 - 2014 * @link http://www.thinkglobalschool.com/ * */ // Get the plugin entity $plugin = elgg_get_plugin_from_id('labs'); $defaults = array( // Labs menu item 'enable_labs_menu_item' => false, ); // Set default config values foreach ($defaults as $setting => $value) { if (!$plugin->getSetting($setting)) { $plugin->setSetting($setting, $value); } }
gpl-2.0
logicmoo/jrelisp-abcl-ws
src/org/armedbear/j/Buffer.java
75817
/* * Buffer.java * * Copyright (C) 1998-2007 Peter Graves * $Id: Buffer.java,v 1.56 2007/08/01 17:00:32 piso Exp $ * * 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. */ package org.armedbear.j; import java.awt.Cursor; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import java.util.zip.ZipEntry; import javax.swing.Icon; import javax.swing.SwingUtilities; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import javax.swing.undo.CompoundEdit; import javax.swing.undo.UndoableEdit; public class Buffer extends SystemBuffer { private static int untitledCount; protected boolean isUntitled; protected Formatter formatter; protected String title; private boolean needsParsing; boolean needsRenumbering; public final boolean needsRenumbering() { return needsRenumbering; } public final void needsRenumbering(boolean b) { needsRenumbering = b; } private int visibleLineCount; protected boolean supportsUndo = true; public final boolean supportsUndo() { return supportsUndo; } private int modCount; private int saveModCount; // Value of modCount when last saved. // Autosave. protected boolean autosaveEnabled; private File autosaveFile; private int autosaveModCount; // Value of modCount when last autosaved. private File cache; private String listing; public final String getListing() { return listing; } public final void setListing(String s) { this.listing = s; } private View lastView; private boolean backedUp = false; // Ignored for local buffers. private int fileType = FILETYPE_UNKNOWN; private Compression compression; public final Compression getCompression() { return compression; } public final void setCompression(Compression compression) { this.compression = compression; } protected PropertyList properties = new PropertyList(); private BackgroundProcess backgroundProcess; private Mutex mutex = new Mutex(); private final ReadWriteLock rwlock = new ReadWriteLock(); private boolean isNewFile; protected Buffer parentBuffer; public final Buffer getParentBuffer() { return parentBuffer; } public final void setParentBuffer(Buffer b) { this.parentBuffer = b; } private Position mark; public final Position getMark() { return mark; } public final void setMark(Position pos) { mark = pos; } public boolean isPrimary() { return true; } public boolean isSecondary() { return false; } public boolean isPaired() { return isSecondary() || getSecondary() != null; } public Buffer getPrimary() { return null; } public Buffer getSecondary() { return null; } public float getSplit() { return 0.5F; } public void promote() { } public final boolean isNewFile() { return isNewFile; } private final void setNewFile(boolean b) { isNewFile = b; } protected Buffer() { // Add new buffer to global buffer list. Editor.getBufferList().add(this); } // Called only by Editor.newBuffer(). public Buffer(int i /* ignored */) { this(); Debug.assertTrue(Editor.getBufferList().contains(this)); initializeUndo(); type = TYPE_NORMAL; isUntitled = true; ++untitledCount; String name = "Untitled-" + untitledCount; File directory = Editor.currentEditor().getCurrentDirectory(); if (directory == null || directory.isRemote()) directory = Directories.getUserHomeDirectory(); setFile(File.getInstance(directory, name)); autosaveEnabled = true; lineSeparator = System.getProperty("line.separator"); mode = PlainTextMode.getMode(); formatter = mode.getFormatter(this); setNewFile(true); try { lockWrite(); } catch (InterruptedException e) { Log.debug(e); return; // Shouldn't happen. } try { appendLine(""); renumber(); setLoaded(true); } finally { unlockWrite(); } } public Buffer(File file) { this(); Debug.assertTrue(Editor.getBufferList().contains(this)); initializeUndo(); setFile(file); type = TYPE_NORMAL; autosaveEnabled = true; } public static Buffer createBuffer(File file) { if (file instanceof FtpFile) { FtpSession session = FtpSession.getSession((FtpFile) file); if (session == null) return null; return new RemoteBuffer((FtpFile) file, session); } if (file instanceof HttpFile) { if (Editor.getModeList().modeAccepts(IMAGE_MODE, file.getName())) return new RemoteBuffer(file); if (Editor.preferences().getBooleanProperty(Property.ENABLE_WEB)) { int modeId = Editor.getModeList().getModeIdForFileName(file.getName()); if (modeId < 0 || modeId == HTML_MODE) return WebBuffer.createWebBuffer(file, null, null); } return new RemoteBuffer(file); } if (file instanceof SshFile) { SshFile sshFile = (SshFile) file; SshSession session = SshSession.getSession(sshFile); if (session == null) return null; if (!session.isLocked()) { Debug.bug(); return null; } session.checkLogin(); if (sshFile.getUserName() == null) { Debug.bug(); sshFile.setUserName(session.getUserName()); } if (!sshFile.getUserName().equals(session.getUserName())) { Debug.bug(); session.unlock(); return null; } session.unlock(); return new RemoteBuffer(file); } // Special case for unsent messages. File dir = file.getParentFile(); if (dir != null && dir.equals(Directories.getDraftsFolder())) { Mode sendMailMode = Editor.getModeList().getMode(SEND_MAIL_MODE); if (sendMailMode != null) return sendMailMode.createBuffer(file); } // Local file. return createBuffer(file, null, null); } protected static Buffer createBuffer(File file, File cache, String listing) { Compression compression = null; int fileType = Utilities.getFileType(cache != null ? cache : file); if (fileType == FILETYPE_GZIP) { // If we're looking at a remote file, gunzip the cached copy // of it; otherwise, gunzip the file itself into the cache. File uncompressed = cacheGZIP(cache != null ? cache : file); if (uncompressed != null) { cache = uncompressed; fileType = Utilities.getFileType(cache); compression = new Compression(COMPRESSION_GZIP); } else fileType = FILETYPE_BINARY; // Something went wrong. } if (fileType == FILETYPE_JPEG || Editor.getModeList().modeAccepts(IMAGE_MODE, file.getName())) { Buffer buffer = ImageBuffer.createImageBuffer(file, cache, listing); if (buffer != null) { buffer.setFileType(fileType); return buffer; } } // Normal case. Buffer buffer = new Buffer(file); Debug.assertTrue(Editor.getBufferList().contains(buffer)); buffer.setFileType(fileType); buffer.setCache(cache); buffer.setListing(listing); buffer.setCompression(compression); if (file.isLocal() && !file.isFile()) buffer.setNewFile(true); return buffer; } // For Session.createBuffers(). public static Buffer precreateBuffer(File file) { if (file == null) { Debug.bug(); return null; } if (file.isRemote()) { Debug.bug(); return null; } // Special case for unsent messages. File dir = file.getParentFile(); if (dir != null && dir.equals(Directories.getDraftsFolder())) { Mode sendMailMode = Editor.getModeList().getMode(SEND_MAIL_MODE); if (sendMailMode != null) return sendMailMode.createBuffer(file); } // Normal case. return new Buffer(file); } private boolean initialized; public synchronized boolean initialized() { return initialized; } public synchronized void setInitialized(boolean b) { initialized = b; } public synchronized void initialize() { Debug.assertTrue(!initialized); final File file = getFile(); if (fileType == FILETYPE_UNKNOWN) { fileType = Utilities.getFileType(cache != null ? cache : file); if (fileType == FILETYPE_GZIP) { // If we're looking at a remote file, gunzip the cached copy // of it; otherwise, gunzip the file itself into the cache. File uncompressed = cacheGZIP(cache != null ? cache : file); if (uncompressed != null) { cache = uncompressed; fileType = Utilities.getFileType(cache); compression = new Compression(COMPRESSION_GZIP); } else fileType = FILETYPE_BINARY; // Something went wrong. } } mode = getDefaultMode(); formatter = mode.getFormatter(this); if (fileType == FILETYPE_ZIP) { supportsUndo = false; type = TYPE_ARCHIVE; readOnly = true; } else if (fileType == FILETYPE_BINARY) { readOnly = true; } else if (fileType == FILETYPE_WORD) { readOnly = true; } else if (file != null) { FileHistoryEntry entry = FileHistory.getFileHistory().findEntry(file.netPath()); if (entry != null) { // Set encoding. final String encoding = entry.getEncoding(); if (encoding != null && Utilities.isSupportedEncoding(encoding)) file.setEncoding(encoding); // Set mode. mode = Editor.getModeList().getModeFromModeName(entry.getMode()); if (mode == null) mode = Editor.getModeList().getMode(PLAIN_TEXT_MODE); else if (mode.getId() == BINARY_MODE) readOnly = true; formatter = mode.getFormatter(this); // Properties from FileHistoryEntry override defaults set by // mode. properties.putAll(entry.getProperties()); } } if (file != null) { if (file.getProtocol() == File.PROTOCOL_HTTP || file.getProtocol() == File.PROTOCOL_HTTPS) readOnly = true; } initialized = true; } public Mode getDefaultMode() { final File file = getFile(); final ModeList modeList = Editor.getModeList(); switch (fileType) { case FILETYPE_XML: return modeList.getMode(XML_MODE); case FILETYPE_SHELLSCRIPT: { Mode m = grovelModeFromFile(file); if (m != null) return m; return modeList.getMode(SHELL_SCRIPT_MODE); } case FILETYPE_PERL: return modeList.getMode(PERL_MODE); case FILETYPE_PHP: return modeList.getMode(PHP_MODE); case FILETYPE_ZIP: return modeList.getMode(ARCHIVE_MODE); case FILETYPE_GZIP: case FILETYPE_BINARY: return modeList.getMode(BINARY_MODE); case FILETYPE_JPEG: return modeList.getMode(IMAGE_MODE); case FILETYPE_WORD: return modeList.getMode(WORD_MODE); case FILETYPE_TEXT: default: { Mode m = grovelModeFromFile(file); if (m == null) { if (compression != null && compression.getType() == COMPRESSION_ZIP) { String entryName = compression.getEntryName(); if (entryName != null) m = getModeForFileName(entryName); } else if (file != null) { m = getModeForFileName(file.getName()); } if (m != null && m.getId() == IMAGE_MODE) { if (fileType == FILETYPE_TEXT) m = modeList.getMode(PLAIN_TEXT_MODE); else m = modeList.getMode(BINARY_MODE); } else if (m == null) { if (file != null) { if (file.getProtocol() == File.PROTOCOL_HTTP || file.getProtocol() == File.PROTOCOL_HTTPS) m = modeList.getMode(HTML_MODE); } if (m == null) m = modeList.getMode(PLAIN_TEXT_MODE); } } return m; } } } private static final Mode grovelModeFromFile(File file) { if (file == null) return null; if (!file.isLocal()) return null; if (!file.isFile()) return null; Mode mode = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream())); String s = reader.readLine(); if (s != null) { mode = grovelModeFromString(s); if (mode == null && s.startsWith("#!")) { // Consider second line too. s = reader.readLine(); if (s != null) mode = grovelModeFromString(s); } } reader.close(); } catch (IOException e) { Log.error(e); } return mode; } private static final Mode grovelModeFromString(String s) { if (s != null) { int begin = s.indexOf("-*-"); if (begin >= 0) { s = s.substring(begin + 3); int end = s.indexOf("-*-"); if (end >= 0) { s = s.substring(0, end).trim().toLowerCase(); int index = s.indexOf("mode:"); String modeName; if (index < 0) { // "-*- Lisp -*-" modeName = s; } else { // "-*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 // -*-" s = s.substring(5).trim(); for (end = 0; end < s.length(); end++) { char c = s.charAt(end); if (c == ' ' || c == '\t' || c == ';') break; } modeName = s.substring(0, end); } return Editor.getModeList().getModeFromModeName(modeName); } } } return null; } // Locking. public final boolean isInUse() { return mutex.isInUse(); } public void acquire() throws InterruptedException { mutex.acquire(); } public synchronized void release() { mutex.release(); } public boolean attempt() throws InterruptedException { return mutex.attempt(); } public boolean attempt(long msecs) throws InterruptedException { return mutex.attempt(msecs); } public final boolean isLocked() { return isInUse(); } public synchronized boolean lock() { try { return attempt(); } catch (InterruptedException e) { return false; } } public synchronized void unlock() { release(); } public final void lockRead() throws InterruptedException { rwlock.lockRead(); } public final void unlockRead() { rwlock.unlockRead(); } public final void lockWrite() throws InterruptedException { rwlock.lockWrite(); } public final void unlockWrite() { rwlock.unlockWrite(); } public final boolean isWriteLocked() { return rwlock.isWriteLocked(); } public boolean isVisible() { for (EditorIterator it = new EditorIterator(); it.hasNext();) if (it.nextEditor().getBuffer() == this) return true; return false; } public void setWaitCursor() { for (EditorIterator it = new EditorIterator(); it.hasNext();) { Editor ed = it.nextEditor(); if (ed.getBuffer() == this) ed.setWaitCursor(); } } public void setDefaultCursor() { for (EditorIterator it = new EditorIterator(); it.hasNext();) { Editor ed = it.nextEditor(); if (ed.getBuffer() == this) ed.setDefaultCursor(); } } public final PropertyList getProperties() { return properties; } public final void setCache(File file) { cache = file; } public final File getCache() { return cache; } public final Formatter getFormatter() { return formatter; } public final void setFormatter(Formatter formatter) { this.formatter = formatter; } public boolean isReadOnly() { return readOnly || forceReadOnly; } private boolean busy; public synchronized final boolean isBusy() { return busy; } public synchronized final void setBusy(boolean b) { busy = b; } public final BackgroundProcess getBackgroundProcess() { return backgroundProcess; } public final void setBackgroundProcess(BackgroundProcess backgroundProcess) { this.backgroundProcess = backgroundProcess; } public File getCurrentDirectory() { return getFile() != null ? getFile().getParentFile() : Directories.getUserHomeDirectory(); } // Subclasses should override this method if appropriate! public File getCompletionDirectory() { final File file = getFile(); if (file != null) { if (file.isLocal() || file instanceof SshFile) return file.isDirectory() ? file : file.getParentFile(); } return Directories.getUserHomeDirectory(); } public View getInitialView() { View view = new View(); view.setDot(getInitialDotPos()); return view; } private int initialLineNumber; private int initialOffset; public Position getInitialDotPos() { Line line = getLine(initialLineNumber); if (line == null) { line = getFirstLine(); return line != null ? new Position(line, 0) : null; } return new Position(line, Math.min(initialOffset, line.length())); } public void setInitialDotPos(int lineNumber, int offset) { initialLineNumber = lineNumber; initialOffset = offset; } private long lastActivated; public final long getLastActivated() { return lastActivated; } public final void setLastActivated(long l) { lastActivated = l; } public final int getLineCount() { return lineCount; } public final int getModCount() { return modCount; } public final synchronized void setModCount(int count) { if (count != modCount) { modCount = count; srText = null; } } public final synchronized void incrementModCount() { ++modCount; srText = null; } public final void setModCountWhenLastSaved(int count) { autosaveModCount = count; } public final KeyMap getKeyMapForMode() { // Should never return null. return mode.getKeyMap(); } public final int getFileType() { return fileType; } private final void setFileType(int fileType) { this.fileType = fileType; } private static File cacheGZIP(File f) { try { File tempFile = Utilities.getTempFile(); if (tempFile != null) { InputStream in = new GZIPInputStream(f.getInputStream()); if (in != null) { OutputStream out = tempFile.getOutputStream(); byte[] buf = new byte[4096]; int bytesRead; while ((bytesRead = in.read(buf)) > 0) out.write(buf, 0, bytesRead); out.close(); in.close(); return tempFile; } } } catch (IOException e) { Log.error(e); } return null; } // Handles all the paperwork when we rename a buffer. public void changeFile(File f) { if (f == null) return; String newName = f.canonicalPath(); if (newName == null) return; File oldFile = getFile(); String oldName = oldFile != null ? oldFile.canonicalPath() : null; setFile(f); setCompression(null); type = TYPE_NORMAL; title = null; Mode oldMode = mode; if (oldMode == PlainTextMode.getMode()) { setModeFromFilename(newName); if (mode != oldMode) { // Mode has changed. needsParsing = true; // Make sure we parse the buffer before we display it. if (formatter != null) formatter.parseBuffer(); } } readOnly = false; isUntitled = false; if (oldName != null) Autosave.rename(oldName, newName); Editor.getBufferList().modified(); Sidebar.setUpdateFlagInAllFrames(SIDEBAR_BUFFER_LIST_CHANGED); for (EditorIterator it = new EditorIterator(); it.hasNext();) { Editor editor = it.nextEditor(); if (editor.getBuffer() == this) { editor.updateLocation(); editor.getDisplay().repaint(); } } } protected void setModeFromFilename(String filename) { mode = Editor.getModeList().getModeForFileName(filename); if (mode == null) mode = Editor.getModeList().getMode(PLAIN_TEXT_MODE); formatter = mode.getFormatter(this); } private static Mode getModeForFileName(String filename) { if (filename.endsWith(".gz")) filename = filename.substring(0, filename.length() - 3); // Strip path prefix (if any). // Look for '/' on both Windows and Unix (filename might be a ZipEntry // name). int index = filename.lastIndexOf('/'); if (index >= 0) filename = filename.substring(index + 1); // Look for '\' on Windows only. if (Platform.isPlatformWindows()) { index = filename.lastIndexOf('\\'); if (index >= 0) filename = filename.substring(index + 1); } return Editor.getModeList().getModeForFileName(filename); } public final void setMode(Mode mode) { this.mode = mode; formatter = mode.getFormatter(this); } public void changeMode(Mode newMode) { final int oldModeId = mode.getId(); if (oldModeId == DIRECTORY_MODE) return; final int newModeId = newMode.getId(); if (newModeId != oldModeId) { // Must reload buffer if changing into or out of binary mode. boolean reloading = newModeId == BINARY_MODE || oldModeId == BINARY_MODE; mode = newMode; formatter = mode.getFormatter(this); if (reloading) { reload(); if (newModeId == IMAGE_MODE) return; } if (newModeId == BINARY_MODE) { readOnly = true; } else { final File file = getFile(); if (file != null && !file.isRemote() && file.isFile()) readOnly = !file.canWrite(); } formatter.parseBuffer(); for (EditorIterator it = new EditorIterator(); it.hasNext();) { Editor ed = it.nextEditor(); if (ed.getBuffer() == this) { if (reloading) { ed.setDot(getFirstLine(), 0); ed.setMark(null); ed.setTopLine(getFirstLine()); ed.moveCaretToDotCol(); ed.updateLocation(); } ed.setUpdateFlag(REPAINT); ed.updateDisplay(); } } } } public final String getCommentStart() { return mode.getCommentStart(); } public final String getCommentEnd() { return mode.getCommentEnd(); } private long lastModified; public final long getLastModified() { return lastModified; } public final void setLastModified(long lastModified) { this.lastModified = lastModified; } protected void loadFile(File toBeLoaded) { try { int modeId = getModeId(); if (modeId == ARCHIVE_MODE || modeId == WORD_MODE || modeId == XML_MODE) mode.loadFile(this, toBeLoaded); else { final String encoding = toBeLoaded.getEncoding(); load(toBeLoaded.getInputStream(), encoding); if (encoding != null) saveProperties(); // Remember encoding for next time. } } catch (IOException e) { Log.error(e); } // Handle zero length files. if (getFirstLine() == null) { appendLine(""); lineSeparator = System.getProperty("line.separator"); } final File file = getFile(); if (file != null && file.getProtocol() != File.PROTOCOL_HTTP) lastModified = toBeLoaded.lastModified(); renumberOriginal(); } public int load() { if (!isLoaded()) { try { lockWrite(); } catch (InterruptedException e) { Log.error(e); return LOAD_FAILED; } try { final File file = getFile(); final File toBeLoaded = cache != null ? cache : file; if (toBeLoaded.isFile()) { Editor editor = Editor.currentEditor(); FastStringBuffer sb = new FastStringBuffer("Loading"); if (compression != null) { if (compression.getType() == COMPRESSION_ZIP) { String entryName = compression.getEntryName(); if (entryName != null) { sb.append(' '); sb.append(entryName); } } } else if (file != null) { sb.append(' '); sb.append(file.getName()); } sb.append("..."); editor.status(sb.toString()); Debug.assertTrue(mode != null); Debug.assertTrue(toBeLoaded != null); loadFile(toBeLoaded); // At this point, if we loaded from a cache, lastModified // will // be set based on the cache file, which is not what we want // in the case of a local file. if (toBeLoaded == cache && file != null && !file.isRemote()) lastModified = file.lastModified(); formatter.parseBuffer(); checkCVS(); sb.append("done"); editor.status(sb.toString()); } else { // File doesn't exist. if (getFirstLine() == null) { appendLine(""); lineSeparator = System.getProperty("line.separator"); } renumberOriginal(); setModeFromFilename(file.canonicalPath()); setLoaded(true); } } catch (OutOfMemoryError e) { _empty(); throw e; } finally { unlockWrite(); } } return LOAD_COMPLETED; } private void reloadSucceeded() { Debug.assertTrue(!rwlock.isWriteLocked()); Debug.assertTrue(SwingUtilities.isEventDispatchThread()); for (EditorIterator it = new EditorIterator(); it.hasNext();) { Editor ed = it.nextEditor(); if (ed.getBuffer() != this) continue; View view = ed.getView(this); if (view != null) { Line dotLine = getLine(view.getDotLineNumber()); if (dotLine == null) dotLine = getFirstLine(); if (dotLine != null) { ed.setDot(dotLine, 0); ed.moveCaretToDotCol(); } Line topLine = getLine(view.getTopLineNumber()); if (topLine == null) topLine = dotLine; ed.setTopLine(topLine); } else { ed.setDot(getFirstLine(), 0); ed.moveCaretToDotCol(); ed.setTopLine(getFirstLine()); } ed.setUpdateFlag(REPAINT); ed.updateDisplay(); } // The buffer is unmodified now, so we need to update its icon in the // buffer list(s). Sidebar.setUpdateFlagInAllFrames(SIDEBAR_REPAINT_BUFFER_LIST); } private void reloadFailed() { MessageDialog.showMessageDialog("Reload failed", "Error"); } public void reload() { final File file = getFile(); if (file == null) return; switch (file.getProtocol()) { case File.PROTOCOL_FTP: reloadFtp((FtpFile) file); return; case File.PROTOCOL_HTTP: case File.PROTOCOL_HTTPS: reloadHttp((HttpFile) file); return; case File.PROTOCOL_FILE: if (file.isFile()) { // Local file. if (getModeId() == ARCHIVE_MODE) { empty(); resetUndo(); mode.loadFile(this, file); } else reloadLocal(file); } reloadSucceeded(); return; default: Debug.assertTrue(false); break; } } // Asynchronous. private void reloadFtp(FtpFile file) { Log.debug("reloadFtp"); Debug.assertTrue(SwingUtilities.isEventDispatchThread()); FtpSession session = FtpSession.getSession(file); final FtpLoadProcess ftpLoadProcess = new FtpLoadProcess(this, file, session); Runnable successRunnable = new Runnable() { public void run() { File newCache = ftpLoadProcess.getCache(); if (newCache != null) { Log.debug("newCache != null"); if (cache != null && cache.isFile()) cache.delete(); cache = newCache; reloadLocal(cache); } else { // User cancelled. setLoaded(true); } setBusy(false); reloadSucceeded(); } }; ErrorRunnable errorRunnable = new ErrorRunnable("Reload failed") { public void run() { setBusy(false); reloadFailed(); } }; ftpLoadProcess.setProgressNotifier(new StatusBarProgressNotifier(this)); ftpLoadProcess.setSuccessRunnable(successRunnable); ftpLoadProcess.setErrorRunnable(errorRunnable); ftpLoadProcess.start(); } private void reloadHttp(HttpFile file) { Log.debug("reloadHttp"); Debug.assertTrue(SwingUtilities.isEventDispatchThread()); final HttpLoadProcess httpLoadProcess = new HttpLoadProcess(this, file); Runnable successRunnable = new Runnable() { public void run() { File newCache = httpLoadProcess.getCache(); if (newCache != null) { Log.debug("newCache != null"); if (cache != null && cache.isFile()) cache.delete(); cache = newCache; reloadLocal(cache); } else { // User cancelled. setLoaded(true); } setBusy(false); reloadSucceeded(); } }; ErrorRunnable errorRunnable = new ErrorRunnable("Reload failed") { public void run() { setBusy(false); reloadFailed(); } }; httpLoadProcess.setProgressNotifier(new StatusBarProgressNotifier(this)); httpLoadProcess.setSuccessRunnable(successRunnable); httpLoadProcess.setErrorRunnable(errorRunnable); setBusy(true); new Thread(httpLoadProcess).start(); } private void reloadLocal(File file) { try { lockWrite(); } catch (InterruptedException e) { Log.error(e); return; } try { empty(); loadFile(file); formatter.parseBuffer(); } finally { unlockWrite(); } unmodified(); deleteAutosaveFile(); resetUndo(); } public synchronized void kill() { BufferList bufferList = Editor.getBufferList(); if (!bufferList.contains(this)) { Debug.bug("buffer.kill() buffer not in list"); return; } Marker.invalidateMarkers(this); Buffer buf = bufferList.getPreviousPrimaryBuffer(this); if (buf != null && buf.isPaired()) { Buffer secondary = buf.getSecondary(); if (secondary != null) { if (secondary.getLastActivated() > buf.getLastActivated()) buf = secondary; } } if (buf == null) buf = new Directory(getCurrentDirectory()); // Copy editor list since switchToBuffer() may close an editor. ArrayList editors = new ArrayList(); for (EditorIterator it = new EditorIterator(); it.hasNext();) editors.add(it.next()); for (Iterator it = editors.iterator(); it.hasNext();) { Editor ed = (Editor) it.next(); // Skip editor if it has been closed. if (Editor.getEditorList().contains(ed)) { if (ed.getBuffer() == this) ed.switchToBuffer(buf); ed.removeView(this); } } deleteAutosaveFile(); bufferList.remove(this); dispose(); Sidebar.setUpdateFlagInAllFrames(SIDEBAR_BUFFER_LIST_CHANGED | SIDEBAR_MODIFIED_BUFFER_COUNT); } public synchronized void relink() { BufferList bufferList = Editor.getBufferList(); if (bufferList.contains(this)) { Debug.bug(); return; } bufferList.add(this); } private Thread startTaggerThread(int priority) { if (mode != null) { Tagger tagger = mode.getTagger(this); if (tagger != null) { Thread thread = new Thread(tagger); thread.setPriority(priority); thread.setDaemon(true); thread.setName("tagger " + getFile().getName()); thread.start(); return thread; } } return null; } public boolean isTaggable() { final File file = getFile(); if (file == null) return false; if (file.isRemote()) return false; return mode.isTaggable(); } // Runs tagger if tags == null. public List getTags(boolean update) { List tags = getTags(); if (tags != null) return tags; if (mode != null) { Tagger tagger = mode.getTagger(this); if (tagger != null) tagger.run(); } return getTags(); } public boolean saveToCache() { if (lineSeparator == null) lineSeparator = System.getProperty("line.separator"); final File tempFile = Utilities.getTempFile(); if (tempFile != null) { File file = getFile(); if (file != null) tempFile.setEncoding(file.getEncoding()); if (writeFile(tempFile)) { final File oldCache = cache; cache = tempFile; if (oldCache != null && oldCache.isFile()) oldCache.delete(); return true; } } return false; } private boolean maybeWriteBackupFromCache() { if (cache == null) { Log.error("maybeWriteBackupFromCache cache is null"); return false; } if (!cache.isFile()) { Log.error("maybeWriteBackupFromCache cache is not a file"); return false; } if (!cache.canRead()) { Log.error("maybeWriteBackupFromCache cache is not readable"); return false; } if (backedUp) return true; // We only want to do the backup once! File file = getFile(); if (file == null) { Debug.bug(); return false; } String name = file.getName(); if (compression != null && compression.getType() == COMPRESSION_GZIP) { if (name.endsWith(".gz")) name = name.substring(0, name.length() - 3); } return backedUp = Utilities.makeBackup(cache, name, false); } public boolean save() { Debug.assertTrue(SwingUtilities.isEventDispatchThread()); if (!isModified()) return true; addUndoBoundary(); boolean succeeded = false; final File file = getFile(); if (file != null) { if (file.isLocal()) succeeded = saveLocal(file); if (file instanceof FtpFile) succeeded = saveFtp(); if (file instanceof SshFile) succeeded = saveSsh((SshFile) file); } if (succeeded && Editor.isLispInitialized()) LispAPI.invokeAfterSaveHook(this); return succeeded; } private boolean saveLocal(final File file) { Debug.assertTrue(file.isLocal()); if (compression != null && compression.getType() == COMPRESSION_GZIP) return saveLocalCompressed(file); try { writeBuffer(); renumberOriginal(); saved(); lastModified = file.lastModified(); } catch (SaveException e) { final String where = "Save"; String message = e.getMessage(); // Tell user exactly what error occurred. if (message != null) MessageDialog.showMessageDialog(message, where); // Display summary message. message = "Unable to save " + file.canonicalPath(); MessageDialog.showMessageDialog(message, where); return false; } if (isTaggable()) Editor.getTagFileManager().addToQueue(file.getParentFile(), mode); startTaggerThread(Thread.MIN_PRIORITY); boolean repaint = false; final ModeList modeList = Editor.getModeList(); if (file.equals(Preferences.getPreferencesFile())) { // Reload preferences. Editor.loadPreferences(); if (Editor.preferences().getBooleanProperty(Property.AUTO_RELOAD_KEY_MAPS)) { // Reload keymaps. KeyMap.reloadKeyMaps(); } repaint = true; } else { if (Editor.preferences().getBooleanProperty(Property.AUTO_RELOAD_KEY_MAPS)) { // Reload mode-specific keymap(s) if modified. synchronized (modeList) { for (Iterator it = modeList.iterator(); it.hasNext();) { ModeListEntry entry = (ModeListEntry) it.next(); Mode mode = entry.getMode(false); if (mode != null) { if (file.equals(mode.getKeyMapFile())) mode.deleteKeyMap(); } } } // Global keymap. if (file.equals(KeyMap.getGlobalKeyMapFile())) KeyMap.deleteGlobalKeyMap(); } } // Reload theme if modified. String theme = Editor.preferences().getStringProperty(Property.THEME); if (theme != null) { if (Utilities.isFilenameAbsolute(theme)) { if (file.canonicalPath().equals(File.getInstance(theme).canonicalPath())) { Editor.loadPreferences(); repaint = true; } } else if (file.getName().equals(theme)) { Editor.loadPreferences(); repaint = true; } } // Reload aliases if modified. if (file.equals(Editor.getAliasesFile())) Editor.reloadAliases(); // Update listRegisters buffer (if any). File parent = file.getParentFile(); if (parent != null && parent.equals(Directories.getRegistersDirectory())) { Buffer buf = Registers.findListRegistersBuffer(); if (buf != null) buf.reload(); } checkCVS(); if (repaint) { // Force formatters to be re-initialized. for (BufferIterator it = new BufferIterator(); it.hasNext();) { Buffer buf = it.nextBuffer(); if (buf.getFormatter() != null) buf.getFormatter().reset(); } Display.initializeStaticValues(); for (int i = 0; i < Editor.getFrameCount(); i++) { Frame f = Editor.getFrame(i); if (f != null) { f.resetDisplay(); f.repaint(); } } Editor.restoreFocus(); } return true; } private boolean saveLocalCompressed(File file) { final String dialogTitle = "Save"; final Editor editor = Editor.currentEditor(); // Do this before saving changes to cache! if (!maybeWriteBackupFromCache()) { FastStringBuffer sb = new FastStringBuffer("Unable to write backup file for "); sb.append(file.getName()); sb.append(". Save anyway?"); if (!editor.confirm(dialogTitle, sb.toString())) return false; } if (!saveToCache()) { FastStringBuffer sb = new FastStringBuffer("Unable to write temporary file for "); sb.append(file.getName()); MessageDialog.showMessageDialog(sb.toString(), dialogTitle); return false; } if (!compress(cache, file)) return false; saved(); lastModified = file.lastModified(); return true; } private boolean compress(File source, File destination) { if (source == null) { Debug.bug(); return false; } if (destination == null) { Debug.bug(); return false; } if (!source.isFile()) { Debug.bug(); return false; } final File tempFile = Utilities.getTempFile(destination.getParentFile()); try { final int bufSize = 4096; BufferedInputStream in = new BufferedInputStream(source.getInputStream()); GZIPOutputStream out = new GZIPOutputStream(new BufferedOutputStream(tempFile.getOutputStream()), bufSize); byte[] buffer = new byte[bufSize]; while (true) { int bytesRead = in.read(buffer, 0, bufSize); if (bytesRead > 0) out.write(buffer, 0, bytesRead); else break; } in.close(); out.flush(); out.close(); return Utilities.deleteRename(tempFile, destination); } catch (IOException e) { Log.error(e); return false; } } private boolean saveFtp() { Debug.assertTrue(SwingUtilities.isEventDispatchThread()); Debug.assertTrue(getFile() instanceof FtpFile); final FtpFile file = (FtpFile) getFile(); final FtpSession session = FtpSession.getSession(file); if (session == null) return false; Debug.assertTrue(session.isLocked()); if (!lock()) { session.unlock(); MessageDialog.showMessageDialog("Buffer is busy", file.netPath()); return false; } Debug.assertTrue(isLocked()); final Editor editor = Editor.currentEditor(); editor.setWaitCursor(); // Do this before saving changes to cache! if (!maybeWriteBackupFromCache()) { editor.setDefaultCursor(); String message = "Unable to write backup file for " + file.getName() + ". Save anyway?"; if (!editor.confirm("Save", message)) { unlock(); session.unlock(); return false; } editor.setWaitCursor(); } if (!saveToCache()) { unlock(); session.unlock(); editor.setDefaultCursor(); String message = "Unable to write temporary file for " + file.getName(); MessageDialog.showMessageDialog(message, "Save"); return false; } final FtpSaveProcess saveProcess; if (compression != null && compression.getType() == COMPRESSION_GZIP) { final File tempFile = Utilities.getTempFile(); if (!compress(cache, tempFile)) { String message = "Unable to compress temporary file for " + file.getName(); MessageDialog.showMessageDialog(message, "Save"); return false; } saveProcess = new FtpSaveProcess(this, tempFile, file, session); } else saveProcess = new FtpSaveProcess(this, cache, file, session); saveProcess.setConfirmIfDestinationChanged(true); saveProcess.setTitle("Save"); final Runnable successRunnable = new Runnable() { public void run() { saved(); setListing(saveProcess.getListing()); for (EditorIterator it = new EditorIterator(); it.hasNext();) { Editor ed = it.nextEditor(); if (ed.getBuffer() == Buffer.this) ed.setDefaultCursor(); } Sidebar.repaintBufferListInAllFrames(); } }; saveProcess.setSuccessRunnable(successRunnable); Debug.assertTrue(isLocked()); saveProcess.start(); return true; } private boolean saveSsh(final SshFile file) { final String title = "Save"; final Editor editor = Editor.currentEditor(); boolean succeeded = false; String message = null; // Do this before saving changes to cache! if (!maybeWriteBackupFromCache()) { message = "Unable to write backup file for " + file.getName() + ". Save anyway?"; if (!editor.confirm(title, message)) return false; } if (!saveToCache()) { message = "Unable to write temporary file for " + file.getName(); MessageDialog.showMessageDialog(message, title); return false; } Ssh ssh = new Ssh(); if (compression != null && compression.getType() == COMPRESSION_GZIP) { final File tempFile = Utilities.getTempFile(); if (!compress(cache, tempFile)) { message = "Unable to compress temporary file for " + file.getName(); MessageDialog.showMessageDialog(message, "Save"); return false; } succeeded = ssh.copy(tempFile, file); } else succeeded = ssh.copy(cache, file); if (!succeeded) message = ssh.getErrorText(); if (succeeded) { saved(); } else { // Tell user exactly what error occurred. if (message != null) MessageDialog.showMessageDialog(message, title); // Display summary message. message = "Unable to save " + file.canonicalPath(); MessageDialog.showMessageDialog(message, title); } return succeeded; } public void saveAs(File destination) { File file = getFile(); if (file != null) destination.setEncoding(file.getEncoding()); if (destination.isLocal()) saveAsLocal(destination); else if (destination instanceof FtpFile) saveAsFtp((FtpFile) destination); else MessageDialog.showMessageDialog("Invalid destination", "Save As"); } private boolean saveAsLocal(File destination) { Debug.assertTrue(SwingUtilities.isEventDispatchThread()); if (destination == null) return false; if (destination.isDirectory()) { final String prompt = destination.canonicalPath().concat(" is a directory"); MessageDialog.showMessageDialog(prompt, "Save As"); return false; } setBusy(true); Editor.currentEditor().setWaitCursor(); boolean succeeded = false; String message = null; if (lineSeparator == null) lineSeparator = System.getProperty("line.separator"); final File tempFile = Utilities.getTempFile(destination.getParent()); if (tempFile == null) { message = "Unable to create temporary file for " + destination.canonicalPath(); } else { tempFile.setEncoding(destination.getEncoding()); if (writeFile(tempFile)) { Log.debug("buffer written to " + tempFile.canonicalPath()); if (Utilities.makeBackup(destination, false)) { destination.delete(); if (tempFile.renameTo(destination)) { succeeded = true; } else { Log.error( "unable to rename " + tempFile.canonicalPath() + " to " + destination.canonicalPath()); message = "Unable to rename temporary file"; } } else { Log.error("backup failed"); message = "Unable to write backup file for " + destination.canonicalPath(); } } else { Log.error("writeFile failed"); message = "Unable to create temporary file in " + tempFile.getParent(); } } setBusy(false); if (succeeded) { saved(); changeFile(destination); setLastModified(getFile().lastModified()); checkCVS(); final String encoding = destination.getEncoding(); if (encoding != null) saveProperties(); // Remember encoding for next time. if (isTaggable()) Editor.getTagFileManager().addToQueue(destination.getParentFile(), mode); Sidebar.setUpdateFlagInAllFrames(SIDEBAR_REPAINT_BUFFER_LIST); } else { // Tell user exactly what error occurred. if (message != null) MessageDialog.showMessageDialog(message, "Save As"); MessageDialog.showMessageDialog("Save failed", "Save As"); } return succeeded; } private void saveAsFtp(final FtpFile destination) { Debug.assertTrue(SwingUtilities.isEventDispatchThread()); FtpSession session = FtpSession.getSession(destination); if (session == null) return; Debug.assertTrue(session.isLocked()); if (!lock()) { session.unlock(); MessageDialog.showMessageDialog("Buffer is busy", getFile().netPath()); return; } final Editor editor = Editor.currentEditor(); editor.setWaitCursor(); if (!saveToCache()) { unlock(); session.unlock(); editor.setDefaultCursor(); String message = "Unable to write temporary file for " + destination.netPath(); MessageDialog.showMessageDialog(message, "Save As"); return; } final FtpSaveProcess saveProcess = new FtpSaveProcess(this, cache, destination, session); saveProcess.setConfirmOverwrite(true); saveProcess.setTitle("Save As"); final Runnable successRunnable = new Runnable() { public void run() { saved(); changeFile(destination); setListing(saveProcess.getListing()); Sidebar.setUpdateFlagInAllFrames(SIDEBAR_REPAINT_BUFFER_LIST); for (EditorIterator it = new EditorIterator(); it.hasNext();) { Editor ed = it.nextEditor(); if (ed.getBuffer() == Buffer.this) ed.setDefaultCursor(); } Sidebar.repaintBufferListInAllFrames(); } }; saveProcess.setSuccessRunnable(successRunnable); Debug.assertTrue(isLocked()); saveProcess.start(); } public void saveCopy(File destination) { if (destination.isLocal()) saveCopyLocal(destination); else if (destination instanceof FtpFile) saveCopyFtp((FtpFile) destination); else MessageDialog.showMessageDialog("Invalid destination", "Save Copy"); } private void saveCopyLocal(File destination) { boolean succeeded = false; String message = null; if (lineSeparator == null) lineSeparator = System.getProperty("line.separator"); File tempFile = Utilities.getTempFile(destination.getParent()); if (tempFile == null) { message = "Unable to create temporary file for " + destination.canonicalPath(); } else { tempFile.setEncoding(destination.getEncoding()); if (writeFile(tempFile)) { Log.debug("buffer written to " + tempFile.canonicalPath()); if (Utilities.makeBackup(destination, false)) { destination.delete(); if (tempFile.renameTo(destination)) { succeeded = true; } else { Log.error( "unable to rename " + tempFile.canonicalPath() + " to " + destination.canonicalPath()); message = "Unable to rename temporary file"; } } else { Log.error("backup failed"); message = "Unable to write backup file for " + destination.canonicalPath(); } } else { Log.error("writeFile failed"); message = "Unable to create temporary file in " + tempFile.getParent(); } } if (succeeded) { if (isTaggable()) Editor.getTagFileManager().addToQueue(destination.getParentFile(), mode); } else { // Tell user exactly what error occurred. if (message != null) MessageDialog.showMessageDialog(message, "Save Copy"); MessageDialog.showMessageDialog("Save failed", "Save Copy"); } } private void saveCopyFtp(FtpFile destination) { Debug.assertTrue(SwingUtilities.isEventDispatchThread()); FtpSession session = FtpSession.getSession(destination); if (session == null) return; Debug.assertTrue(session.isLocked()); if (!lock()) { session.unlock(); MessageDialog.showMessageDialog("Buffer is busy", getFile().netPath()); return; } final Editor editor = Editor.currentEditor(); editor.setWaitCursor(); if (!saveToCache()) { unlock(); session.unlock(); editor.setDefaultCursor(); String message = "Unable to write temporary file for " + destination.netPath(); MessageDialog.showMessageDialog(message, "Save Copy"); return; } final Runnable successRunnable = new Runnable() { public void run() { for (EditorIterator it = new EditorIterator(); it.hasNext();) { Editor ed = it.nextEditor(); if (ed.getBuffer() == Buffer.this) ed.setDefaultCursor(); } Sidebar.repaintBufferListInAllFrames(); } }; final FtpSaveProcess saveProcess = new FtpSaveProcess(this, cache, destination, session); saveProcess.setConfirmOverwrite(true); saveProcess.setTitle("Save Copy"); saveProcess.setSuccessRunnable(successRunnable); Debug.assertTrue(isLocked()); saveProcess.start(); } // Removes tabs and spaces only. public void removeTrailingWhitespace() { boolean bufferChanged = false; CompoundEdit compoundEdit = null; try { lockWrite(); } catch (InterruptedException e) { Log.error(e); return; } try { for (Line line = getFirstLine(); line != null; line = line.next()) { final String text = line.getText(); final int originalLength = text.length(); int length = originalLength; for (int i = originalLength - 1; i >= 0; i--) { char c = text.charAt(i); if (c == ' ' || c == '\t') --length; else break; } if (length != originalLength) { if (!bufferChanged) { // First change. compoundEdit = new CompoundEdit(); bufferChanged = true; } compoundEdit.addEdit(new UndoLineEdit(this, line)); line.setText(text.substring(0, length)); } } if (bufferChanged) modified(); } finally { unlockWrite(); } if (compoundEdit != null && undoManager != null) { compoundEdit.end(); undoManager.addEdit(compoundEdit); } if (bufferChanged) { for (EditorIterator it = new EditorIterator(); it.hasNext();) { Editor ed = it.nextEditor(); if (ed.getBuffer() == this) { if (ed.getDotOffset() > ed.getDotLine().length()) { ed.getDot().setOffset(ed.getDotLine().length()); if (getBooleanProperty(Property.RESTRICT_CARET)) { ed.moveCaretToDotCol(); ed.updateDotLine(); } } if (ed.getMark() != null) { if (ed.getMarkOffset() > ed.getMarkLine().length()) ed.getMark().setOffset(ed.getMarkLine().length()); } ed.repaintDisplay(); } } } } public synchronized void autosave() { if (autosaveEnabled && Autosave.isAutosaveEnabled()) if (modCount != autosaveModCount) new Thread(autosaveRunnable, "autosave").start(); } private final Runnable autosaveRunnable = new Runnable() { public void run() { try { lockRead(); } catch (InterruptedException e) { Log.error(e); return; } try { autosaveInternal(); } finally { unlockRead(); } } }; private void autosaveInternal() { if (autosaveFile == null) { final File autosaveDirectory = Autosave.getAutosaveDirectory(); if (autosaveDirectory == null) return; autosaveFile = Utilities.getTempFile(autosaveDirectory); if (autosaveFile == null) return; // Update autosave catalog file. Autosave.put(getFile().netPath(), autosaveFile.getName()); Autosave.flush(); } autosaveFile.setEncoding(getFile().getEncoding()); if (writeFile(autosaveFile)) autosaveModCount = modCount; else Log.error("autosave writeFile failed"); } public void deleteAutosaveFile() { if (autosaveFile != null) autosaveFile.delete(); } public void setFirstLine(Line line) { if (!rwlock.isWriteLocked()) { Log.error("----- setFirstLine() called without write lock -----"); Debug.dumpStack(); } super.setFirstLine(line); } public void modified() { if (!rwlock.isWriteLocked()) { Log.error("----- modified() called without write lock -----"); Debug.dumpStack(); } if (modCount > saveModCount) { // Already modified. incrementModCount(); } else { // First change. setModCount(saveModCount + 1); Sidebar.setUpdateFlagInAllFrames(SIDEBAR_MODIFIED_BUFFER_COUNT); Sidebar.repaintBufferListInAllFrames(); } invalidate(); } public void unmodified() { setModCount(0); saveModCount = 0; autosaveModCount = 0; Sidebar.setUpdateFlagInAllFrames(SIDEBAR_MODIFIED_BUFFER_COUNT); Sidebar.repaintBufferListInAllFrames(); } public void saved() { saveModCount = modCount; autosaveModCount = modCount; if (isNewFile()) { for (Line line = getFirstLine(); line != null; line = line.next()) { line.setOriginalText(null); line.setNew(false); } setNewFile(false); } else { for (Line line = getFirstLine(); line != null; line = line.next()) { if (line.isModified()) line.setSaved(true); } if (getBooleanProperty(Property.SHOW_CHANGE_MARKS)) repaint(); } backedUp = false; // Ignored for local buffers. Sidebar.setUpdateFlagInAllFrames(SIDEBAR_MODIFIED_BUFFER_COUNT); Sidebar.repaintBufferListInAllFrames(); deleteAutosaveFile(); } public void empty() { try { lockWrite(); } catch (InterruptedException e) { Log.debug(e); return; } try { _empty(); } finally { unlockWrite(); } setTags(null); // Invalidate any stored views that are referencing the old contents // of this buffer. if (lastView != null) lastView.invalidate(); for (EditorIterator it = new EditorIterator(); it.hasNext();) { Editor ed = it.nextEditor(); View view = ed.getView(this); if (view != null) view.invalidate(); if (ed.getBuffer() == this) { ed.setDot(null); ed.setMark(null); ed.setTopLine(null); } } } public void invalidate() { needsParsing = true; maxColsValid = false; setTags(null); setMark(null); } public final View getLastView() { if (lastView != null) return (View) lastView.clone(); else return null; } public final void setLastView(View view) { lastView = (View) view.clone(); } public void saveView(Editor editor) { final View view = saveViewInternal(editor); editor.setView(this, view); setLastView(view); } protected View saveViewInternal(Editor editor) { final Display display = editor.getDisplay(); View view = editor.getView(this); if (view == null) view = new View(); final Position dot = editor.getDot(); view.dot = dot == null ? null : new Position(dot); final Position mark = editor.getMark(); view.mark = mark == null ? null : new Position(mark); view.selection = editor.getSelection(); view.setColumnSelection(editor.isColumnSelection()); view.topLine = editor.getTopLine(); if (view.topLine != null) view.topLineNumber = view.topLine.lineNumber(); view.pixelsAboveTopLine = display.getPixelsAboveTopLine(); view.shift = display.shift; view.caretCol = display.caretCol; view.timestamp = System.currentTimeMillis(); if (view.dot == null) { view.lineNumber = 0; view.offs = 0; } else { view.lineNumber = view.dot.lineNumber(); view.offs = view.dot.getOffset(); } return view; } public boolean needsParsing() { return needsParsing; } public final void setNeedsParsing(boolean b) { needsParsing = b; } public boolean isModified() { return modCount != saveModCount; } public Line getLine(int lineNumber) { if (lineNumber < 0) return null; int n = 0; Line line = getFirstLine(); while (line != null && n != lineNumber) { line = line.next(); ++n; } return line; } /** * Returns position in buffer based on original line number. Never returns * null. * * @param lineNumber * the original line number to look for * @param offset * the offset within the line * @return the position. */ public Position findOriginal(int lineNumber, int offset) { if (offset < 0) offset = 0; Line line = getFirstLine(); while (line != null && line.originalLineNumber() != lineNumber) line = line.next(); if (line != null) return new Position(line, Math.min(offset, line.length())); if (line == null) { // We didn't find the exact line we were looking for. Find the // line with the next highest original line number. line = getFirstLine(); while (line != null && line.originalLineNumber() < lineNumber) line = line.next(); } if (line != null) return new Position(line, 0); return getEnd(); } // Convert position into absolute character offset from start of buffer. public int getAbsoluteOffset(Position pos) { Line targetLine = pos.getLine(); int offset = 0; Line line = getFirstLine(); while (line != null && line != targetLine) { offset += line.length() + 1; line = line.next(); } if (line == null) return -1; // Line not in buffer. else return offset + pos.getOffset(); } // Convert absolute character offset from start of buffer into position. public Position getPosition(int goal) { int offset = 0; Line line = getFirstLine(); while (line != null) { // Line separator always counts as 1. offset += line.length() + 1; if (offset >= goal) { if (offset == goal) line = line.next(); break; } line = line.next(); } if (line == null) return null; // We hit the end of the buffer without reaching our // goal. if (offset == goal) return new Position(line, 0); offset -= line.length() + 1; return new Position(line, goal - offset); } private UndoManager undoManager; protected void initializeUndo() { undoManager = new UndoManager(); } public void resetUndo() { if (supportsUndo) undoManager.discardAllEdits(); } public void resetRedo() { } public final UndoManager getUndoManager() { return undoManager; } public final void addEdit(UndoableEdit edit) { if (undoManager != null) undoManager.addEdit(edit); } public final void addUndoBoundary() { if (undoManager != null) undoManager.addEdit(UndoBoundary.getInstance()); } public final void appendUndoFold(Editor editor) { if (undoManager != null) undoManager.appendUndoFold(editor); } public boolean canUndo() { return (undoManager != null && undoManager.canUndo()); } public void undo() { if (undoManager != null) { if (needsRenumbering) renumber(); try { undoManager.undo(); } catch (CannotUndoException e) { Editor.currentEditor().status("Nothing to undo"); } } } public boolean canRedo() { return (undoManager != null && undoManager.canRedo()); } public void redo() { if (undoManager != null) { if (needsRenumbering) renumber(); try { undoManager.redo(); } catch (CannotRedoException e) { Editor.currentEditor().status("Nothing to redo"); } } } public CompoundEdit beginCompoundEdit() { if (supportsUndo) { CompoundEdit compoundEdit = new CompoundEdit(); undoManager.addEdit(compoundEdit); return compoundEdit; } else return null; } public void endCompoundEdit(CompoundEdit compoundEdit) { if (compoundEdit != null) compoundEdit.end(); } protected void setText(String text) { try { lockWrite(); } catch (InterruptedException e) { Log.debug(e); return; } try { empty(); if (text != null) { FastStringReader reader = new FastStringReader(text); String s; while ((s = reader.readLine()) != null) appendLine(s); } if (getFirstLine() == null) appendLine(""); renumber(); invalidate(); setLoaded(true); } finally { unlockWrite(); } } // Inserts s at pos, moves pos past s. public void insertString(Position pos, String s) { try { lockWrite(); } catch (InterruptedException e) { Log.error(e); return; } try { FastStringBuffer sb = new FastStringBuffer(); final int limit = s.length(); boolean skipLF = false; for (int i = 0; i < limit; i++) { char c = s.charAt(i); if (c == '\r') { if (sb.length() > 0) { insertChars(pos, sb.toString()); sb.setLength(0); } insertLineSeparator(pos); skipLF = true; } else if (c == '\n') { if (skipLF) { skipLF = false; } else { if (sb.length() > 0) { insertChars(pos, sb.toString()); sb.setLength(0); } insertLineSeparator(pos); } } else { skipLF = false; sb.append(c); } } if (sb.length() > 0) insertChars(pos, sb.toString()); } finally { unlockWrite(); } } // Inserts s at pos, moves pos past s. // String must not contain a line separator! public void insertChars(Position pos, String s) { final int length = s.length(); if (length > 0) { String text = pos.getLine().getText(); FastStringBuffer sb = new FastStringBuffer(text.length() + length); sb.append(text.substring(0, pos.getOffset())); sb.append(s); sb.append(text.substring(pos.getOffset())); pos.getLine().setText(sb.toString()); pos.skip(length); modified(); } } public void insertLineSeparator(Position pos) { final Line line = pos.getLine(); final int offset = pos.getOffset(); if (offset == 0) { final Line newLine = new TextLine(""); newLine.setNew(true); // Assume that the line flags should carry over to the new line. newLine.setFlags(line.flags()); final Line prevLine = line.previous(); newLine.setPrevious(prevLine); if (prevLine != null) { prevLine.setNext(newLine); } else { Debug.assertTrue(line == getFirstLine()); setFirstLine(newLine); } newLine.setNext(line); line.setPrevious(newLine); } else if (offset == line.length()) { final Line newLine = new TextLine(""); newLine.setNew(true); // Assume that the line flags should carry over to the new line. newLine.setFlags(line.flags()); final Line prevLine = line; final Line nextLine = line.next(); newLine.setPrevious(prevLine); if (prevLine != null) { prevLine.setNext(newLine); } else { Debug.assertTrue(line == getFirstLine()); setFirstLine(newLine); } newLine.setNext(nextLine); if (nextLine != null) nextLine.setPrevious(newLine); pos.moveTo(newLine, 0); } else { final String head = line.substring(0, offset); final String tail = line.substring(offset); line.setText(head); final Line nextLine = line.next(); final Line newLine = new TextLine(tail); newLine.setNew(true); // Assume that the line flags should carry over to the new line. newLine.setFlags(line.flags()); line.setNext(newLine); newLine.setPrevious(line); newLine.setNext(nextLine); if (nextLine != null) nextLine.setPrevious(newLine); pos.moveTo(newLine, 0); } needsRenumbering = true; modified(); repaint(); } // Repaint all windows displaying this buffer. public final void repaint() { for (EditorIterator it = new EditorIterator(); it.hasNext();) { Editor ed = it.nextEditor(); if (ed.getBuffer() == this) ed.repaintDisplay(); } } public String getTitle() { if (title != null) return title; final File file = getFile(); if (file != null) return file.netPath(); else return ""; } public final void setTitle(String s) { title = s; } public String getFileNameForDisplay() { final File file = getFile(); if (file != null) return file.isRemote() ? file.netPath() : file.getAbsolutePath(); return ""; } // For the buffer list. public String toString() { if (title != null) return title; final File file = getFile(); if (file == null) { // This case should be handled by toString() in the derived class. return null; } if (file instanceof HttpFile) return file.netPath(); if (file.isRemote()) { // SSH, FTP. FastStringBuffer sb = new FastStringBuffer(file.getName()); sb.append(" ["); sb.append(file.netPath()); sb.append(']'); return sb.toString(); } // Local file. if (file.isDirectory()) return file.canonicalPath(); return Editor.getBufferList().getUniqueName(this); } // For the buffer list. public Icon getIcon() { if (isModified()) return Utilities.getIconFromFile("modified.png"); else if (isReadOnly()) return Utilities.getIconFromFile("read_only.png"); else return Utilities.getIconFromFile("buffer.png"); } public final int getCol(Position pos) { return getCol(pos.getLine(), pos.getOffset()); } // Returns the absolute column for a given line and offset, based on the // tab width of the buffer. public final int getCol(Line line, int offset) { return getCol(line, offset, getTabWidth()); } public final static int getCol(Line line, int offset, int tabWidth) { final int limit = Math.min(offset, line.length()); int col = 0; for (int i = 0; i < limit; i++) { if (line.charAt(i) == '\t') col += tabWidth - col % tabWidth; else ++col; } return col; } // Return existing indentation of line (number of columns). public int getIndentation(Line line) { int indent = 0; final int tabWidth = getTabWidth(); final int limit = line.length(); for (int i = 0; i < limit; i++) { char c = line.charAt(i); if (c == '\t') indent += tabWidth - indent % tabWidth; else if (c == ' ') ++indent; else break; } return indent; } // No write locking, does not call modified(). public void setIndentation(Line line, int indent) { // Skip over existing indentation. final int length = line.length(); int i = 0; while (i < length && Character.isWhitespace(line.charAt(i))) ++i; if (i < length) { String remainder = line.substring(i); if (indent > 0) { // Put required indentation into stringbuffer. FastStringBuffer sb = getCorrectIndentationString(indent); sb.append(remainder); line.setText(sb.toString()); } else line.setText(remainder); } else line.setText(""); } public FastStringBuffer getCorrectIndentationString(int indent) { FastStringBuffer sb = new FastStringBuffer(256); if (getUseTabs()) { final int tabWidth = getTabWidth(); int col = 0; while (col + tabWidth <= indent) { sb.append('\t'); col += tabWidth; } while (col < indent) { sb.append(' '); ++col; } } else sb.append(Utilities.spaces(indent)); return sb; } private boolean folded; public final void renumber() { folded = false; lineCount = 0; visibleLineCount = 0; for (Line line = getFirstLine(); line != null; line = line.next()) { line.setLineNumber(lineCount++); if (line.isHidden()) folded = true; else ++visibleLineCount; } needsRenumbering = false; } protected void renumberOriginal() { folded = false; lineCount = 0; visibleLineCount = 0; for (Line line = getFirstLine(); line != null; line = line.next()) { line.setOriginalLineNumber(lineCount); line.setLineNumber(lineCount++); if (line.isHidden()) folded = true; else ++visibleLineCount; } needsRenumbering = false; } protected void enforceOutputLimit(Property property) { Debug.assertTrue(property != null); final int outputLimit = Editor.preferences().getIntegerProperty(property); if (outputLimit == 0 || lineCount <= outputLimit) return; try { lockWrite(); } catch (InterruptedException e) { Log.error(e); return; } try { Position begin = new Position(getFirstLine(), 0); Line line = getFirstLine(); for (int i = lineCount - outputLimit; i > 0; i--) { if (line.next() == null) break; line = line.next(); } Position end = new Position(line, 0); Region r = new Region(this, begin, end); r.deleteLines(); if (needsRenumbering) renumber(); resetUndo(); } finally { unlockWrite(); } } public void saveProperties() { if (type != TYPE_NORMAL) return; if (isUntitled) return; final File file = getFile(); if (file == null) return; final String netPath = file.netPath(); // Name must not contain any characters that can't appear in an XML // attribute value. In particular, an HTTP query might contain '&'. if (netPath.indexOf('<') >= 0 || netPath.indexOf('&') >= 0) return; FileHistoryEntry entry = new FileHistoryEntry(); entry.setName(netPath); entry.setEncoding(file.getEncoding()); entry.setMode(mode.toString()); entry.setWhen(System.currentTimeMillis()); entry.setProperties(properties); FileHistory fileHistory = FileHistory.getFileHistory(); fileHistory.store(entry); fileHistory.save(); } public void windowClosing() { } public void dispose() { if (cache != null && cache.isFile()) { // Only delete the cache file if no other buffer is using it. for (BufferIterator it = new BufferIterator(); it.hasNext();) { Buffer buf = it.nextBuffer(); if (buf != this && buf.getCache() == cache) return; } // Not in use. OK to delete. cache.delete(); } } protected void finalize() throws Throwable { try { lockWrite(); } catch (InterruptedException e) { Log.debug(e); return; } try { empty(); } finally { unlockWrite(); } super.finalize(); } public final boolean canBeRestored() { final File file = getFile(); if (file != null && file.isRemote()) return false; if (this instanceof RemoteBuffer) return false; switch (type) { case TYPE_NORMAL: case TYPE_ARCHIVE: case TYPE_DIRECTORY: return true; default: return false; } } public final boolean isUntitled() { return isUntitled; } private boolean isTransient; public boolean isTransient() { return isTransient; } public final void setTransient(boolean b) { unsplitOnClose = isTransient = b; } private boolean unsplitOnClose; public boolean unsplitOnClose() { return unsplitOnClose; } public final void setUnsplitOnClose(boolean b) { unsplitOnClose = b; } // Cache for getText(). private SoftReference srText; // Never returns null. public synchronized String getText() { if (srText != null) { final String text = (String) srText.get(); if (text != null) return text; } FastStringBuffer sb = new FastStringBuffer(16384); Line line = getFirstLine(); if (line != null) { String text = line.getText(); if (text != null) sb.append(text); line = line.next(); while (line != null) { text = line.getText(); if (text != null) { sb.append('\n'); sb.append(text); } line = line.next(); } } final String text = sb.toString(); srText = new SoftReference(text); return text; } public boolean isEmpty() { Line first = getFirstLine(); if (first == null) return true; if (first.next() != null) return false; return first.length() == 0; } public int getDisplayHeight() { return visibleLineCount * Display.getCharHeight(); } // Returns cumulative height to top of target line. public int getY(Line line) { Debug.assertTrue(!line.isHidden()); if (folded) { final int charHeight = Display.getCharHeight(); int y = 0; for (Line l = getFirstLine(); l != null; l = l.nextVisible()) { if (l == line) break; else y += charHeight; } return y; } else return line.lineNumber() * Display.getCharHeight(); } public int getDisplayWidth() { return Display.getGutterWidth(this) + (getMaximumColumns() + 1) * Display.getCharWidth(); } private int maxCols = 0; private boolean maxColsValid = false; public int getMaximumColumns() { if (maxCols == 0) { maxCols = calculateMaximumColumns(); maxColsValid = true; } return maxCols; } private int calculateMaximumColumns() { if (getModeId() == BINARY_MODE) return getFirstLine().length(); final int tabWidth = getTabWidth(); int max = 0; for (Line line = getFirstLine(); line != null; line = line.next()) { int cols; if ((cols = getCol(line, line.length(), tabWidth)) > max) max = cols; } return max; } // Returns true if there was a change. public boolean validateMaximumColumns() { if (maxColsValid) return false; final int oldMaxCols = maxCols; maxCols = calculateMaximumColumns(); maxColsValid = true; return maxCols != oldMaxCols; } public void setProperty(Property property, Object value) { properties.setProperty(property, value); } public void setProperty(Property property, boolean value) { properties.setProperty(property, value); } public void setProperty(Property property, int value) { properties.setProperty(property, value); } boolean setPropertyFromString(Property property, String value) { return properties.setPropertyFromString(property, value); } boolean removeProperty(Property property) { return properties.removeProperty(property); } public String getStringProperty(Property property) { Object value = properties.getProperty(property); if (value instanceof String) return (String) value; if (mode != null) return mode.getStringProperty(property); return (String) property.getDefaultValue(); } public int getIntegerProperty(Property property) { if (!property.isIntegerProperty()) Debug.bug(); Object value = properties.getProperty(property); if (value instanceof Integer) return ((Integer) value).intValue(); if (mode != null) return mode.getIntegerProperty(property); return ((Integer) property.getDefaultValue()).intValue(); } public boolean getBooleanProperty(Property property) { if (!property.isBooleanProperty()) Debug.bug(); Object value = properties.getProperty(property); if (value == Boolean.TRUE) return true; if (value == Boolean.FALSE) return false; if (mode != null) return mode.getBooleanProperty(property); return ((Boolean) property.getDefaultValue()).booleanValue(); } public final int getTabWidth() { return getIntegerProperty(Property.TAB_WIDTH); } public void setTabWidth(int tabWidth) { properties.setProperty(Property.TAB_WIDTH, tabWidth); } public final boolean getUseTabs() { return getBooleanProperty(Property.USE_TABS); } public final int getIndentSize() { return getIntegerProperty(Property.INDENT_SIZE); } public final void setIndentSize(int indentSize) { properties.setProperty(Property.INDENT_SIZE, indentSize); } private static final Cursor textCursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR); public Cursor getDefaultCursor() { return textCursor; } public Cursor getDefaultCursor(Position pos) { if (pos == null || pos.getLine() instanceof ImageLine) return Cursor.getDefaultCursor(); else return textCursor; } public String getStatusText(Editor editor) { Debug.assertTrue(editor.getBuffer() == this); Position dot = editor.getDotCopy(); if (dot == null) return null; final FastStringBuffer sb = new FastStringBuffer(); if (cvsEntry != null) { sb.append("CVS "); final String revision = cvsEntry.getRevision(); if (revision.equals("0")) { sb.append('A'); } else { sb.append(revision); final long checkout = cvsEntry.getCheckoutTime(); if (lastModified != checkout) { if (Math.abs(lastModified - checkout) >= 1000) sb.append(" M"); } } sb.append(" "); } if (Editor.preferences().getBooleanProperty(Property.STATUS_BAR_DISPLAY_LINE_SEPARATOR)) { if (lineSeparator != null) { if (lineSeparator.equals("\n")) sb.append("LF "); else if (lineSeparator.equals("\r\n")) sb.append("CR+LF "); else if (lineSeparator.equals("\r")) sb.append("CR "); } } sb.append("Line "); sb.append(String.valueOf(dot.lineNumber() + 1)); if (Editor.preferences().getBooleanProperty(Property.STATUS_BAR_DISPLAY_LINE_COUNT)) { sb.append(" of "); sb.append(String.valueOf(getLineCount())); } sb.append(" Col "); final Display display = editor.getDisplay(); sb.append(String.valueOf(display.getAbsoluteCaretCol() + 1)); if (getBooleanProperty(Property.WRAP)) sb.append(" Wrap"); if (Editor.isRecordingMacro()) sb.append(" [Recording macro...]"); return sb.toString(); } public Expansion getExpansion(Position dot) { return new Expansion(dot, mode); } public void restoreView(Editor editor) { final Display display = editor.getDisplay(); final View view = editor.getView(this); Debug.assertTrue(view != null); if (view != null) { if (view.getDot() == null) { Line line = getLine(view.getDotLineNumber()); if (line != null) { int offset = view.getDotOffset(); if (offset < 0) offset = 0; else if (offset > line.length()) offset = line.length(); view.setDot(new Position(line, offset)); } else { line = getFirstLine(); if (line != null) view.setDot(new Position(line, 0)); } } editor.setDot(view.getDot() == null ? null : new Position(view.getDot())); editor.setMark(view.getMark() == null ? null : new Position(view.getMark())); editor.setSelection(view.getSelection()); editor.setColumnSelection(view.isColumnSelection()); if (view.getTopLine() == null) { view.topLine = getFirstLine(); view.pixelsAboveTopLine = 0; } display.setTopLine(view.getTopLine()); display.setPixelsAboveTopLine(view.pixelsAboveTopLine); display.setShift(view.getShift()); display.setCaretCol(view.getCaretCol()); } } private CVSEntry cvsEntry; public final CVSEntry getCVSEntry() { return cvsEntry; } public final void checkCVS() { cvsEntry = CVSEntry.parseEntryForFile(getFile()); } public final boolean isKeyword(String s) { return mode.isKeyword(s); } }
gpl-2.0
iiab/iiab-factory
ansible/roles/player/files/cc_list.php
1245
<?php // This provides a list of closed caption .vtt fies to the viewer.php $video_base = '/library/www/html/info/videos'; if ( ! isset($_REQUEST['name'])){ echo('Please enter the video name as a "name=blah" parameter'); exit(1); } else { if ( isset($_REQUEST['suffix'])) $suffix = $_REQUEST['suffix'];else $suffix = 'mp4'; if (substr($suffix,0,1) == '.') $suffix = substr($suffix,1); //name may include a category in path preceeding video directory specifier $video_name = $_REQUEST['name']; $video_basename = basename($video_name); $video_dirname = dirname($video_name); if ($video_dirname != '.') $video_dirname = $video_dirname . '/';else $video_dirname = ""; $video_stem = pathinfo($video_name, PATHINFO_FILENAME); } $two_ch_lang = 0; if ( isset($_REQUEST['lang'])) $two_ch_lang = 1; chdir("$video_base/$video_dirname$video_basename"); $vtt_files = glob("*.vtt"); $outstr = '['; if ($two_ch_lang != 0){ foreach ($vtt_files as $f) { $outstr .= substr($f,-6,2) . ','; } } else { foreach ($vtt_files as $f){ $outstr .= $f . ','; } } $outstr = rtrim($outstr,',') . ']'; echo($outstr); ?>
gpl-2.0
Emilio66/WordPress
wp-admin/ms-admin.php
215
<?php /** * Multisite administration panel. * * @package WordPress * @subpackage Multisite * @since 3.0.0 */ require_once (dirname ( __FILE__ ) . '/admin.php'); wp_redirect ( network_admin_url () ); exit ();
gpl-2.0
olafzieger/test-fabrik
plugins/fabrik_element/mytristate/mytristate.js
351
var FbMytristate = new Class({ Extends: FbElement, initialize: function (element, options) { this.parent(element, options); this.plugin = 'Mytristate'; }, changeValue: function () { location.reload(true); }, select: function () { this.element.select(); }, focus: function () { this.element.focus(); } });
gpl-2.0
asaokamei/Cena.Eloquent
tests/database/migrations/create_comment_table.php
852
<?php use Illuminate\Database\Capsule\Manager as Capsule; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCommentTable extends Migration { protected $table = 'comment'; /** * Run the migrations. * * @return void */ public function up() { Capsule::schema()->create( $this->table, function ( $table ) { /** @var Blueprint $table */ $table->increments( 'comment_id' ); $table->integer( 'post_id' ); $table->integer( 'status' ); $table->string( 'comment', 1024 * 10 ); $table->timestamps(); } ); } /** * Reverse the migrations. * * @return void */ public function down() { Capsule::schema()->dropIfExists( $this->table ); } }
gpl-2.0
RenZ0/php-show-controller
psc/index.php
130
<html> <head> <title>PSC</title> </head> <body> <h1>Php-Show-Controller</h1> <a href="dmx/index.php">Enter</a> </body> </html>
gpl-2.0
carlosway89/testshop
admin/includes/modules/gm_gprint_edit.inc.php
22863
<?php /* -------------------------------------------------------------- gm_gprint_edit.inc.php 2015-10-03 Gambio GmbH http://www.gambio.de Copyright (c) 2015 Gambio GmbH Released under the GNU General Public License (Version 2) [http://www.gnu.org/licenses/gpl-2.0.html] -------------------------------------------------------------- */ $t_gm_languages = xtc_get_languages(); ?> <div class="message_stack_container"> <div class="alert alert-info"> <?php echo GM_GPRINT_ADVICES; ?> </div> </div> <br /> <table border="0" cellpadding="0" cellspacing="0" width="100%" class="exclude-page-nav"> <tr class="dataTableHeadingRow"> <td class="dataTableHeadingContent" style="border-right: 0px;" id="surfaces_group_name_title"></td> <td class="dataTableHeadingContent" style="border-right: 0px; text-align: right;"> <?php foreach($t_gm_languages AS $t_gm_language) { echo '&nbsp;&nbsp;<a href="' . $_SERVER['PHP_SELF'] . '?' . xtc_get_all_get_params(array('languages_id')) . 'languages_id=' . $t_gm_language['id'] . '"><img src="'.DIR_WS_LANGUAGES.$t_gm_language['directory'].'/admin/images/'.$t_gm_language['image'].'" border="0" alt="' . $t_gm_language['name'] . '" title="' . $t_gm_language['name'] . '" style="padding-top: 2px" /></a>'; } ?> </td> </tr> </table> <table class="edit-page" border="0" cellpadding="0" cellspacing="0" width="100%"> <tr class="dataTableRow"> <td> <div id="toolbar"> <div class="grid"> <table class="span6" border="0" cellpadding="0" cellspacing="0"> <tr> <td style="width: 100px"> <h3><?php echo GM_GPRINT_TEXT_SURFACE; ?></h3> </td> <td> <input class="btn pull-left" type="button" name="show_create_surface_flyover" id="show_create_surface_flyover" value="<?php echo BUTTON_CREATE; ?>" /> <input style="display: none;" class="btn pull-left" type="button" name="show_edit_surface_flyover" id="show_edit_surface_flyover" value="<?php echo BUTTON_EDIT; ?>" /> </td> </tr> </table> <table class="span6" border="0" cellpadding="0" cellspacing="0"> <tr> <td> <h3><?php echo GM_GPRINT_TEXT_ELEMENT; ?></h3> </td> <td> <input style="display: none;" class="btn pull-left" type="button" name="show_create_element_flyover" id="show_create_element_flyover" value="<?php echo BUTTON_CREATE; ?>" /> <input style="display: none;" class="btn pull-left" type="button" name="show_edit_element_flyover" id="show_edit_element_flyover" value="<?php echo BUTTON_EDIT; ?>" /> </td> </tr> </table> </div> <div class="gm_gprint_flyover gx-configuration-box hidden"> <div class="configuration-box-content gx-container" data-gx-widget="checkbox"> <form id="create_surface_div"> <div class="configuration-box-header"> <button id="hide_create_surface_flyover" class="close" type="button">×</button> <h2><?php echo GM_GPRINT_TEXT_NEW_SURFACE; ?></h2> </div> <div class="configuration-box-body"> <div class="configuration-box-form-content editable"> <table class="normalize-table" border="0" cellpadding="0" cellspacing="0"> <tr> <td> <span class="options-title"><?php echo GM_GPRINT_TEXT_SIZE; ?></span> <input type="text" class="input_number" id="surface_width" name="surface_width" value="350" />px <input type="text" class="input_number" id="surface_height" name="surface_height" value="200" />px (<?php echo GM_GPRINT_TEXT_WIDTH . ' x ' . GM_GPRINT_TEXT_HEIGHT; ?>) </td> </tr> <tr> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_NAME; ?> </span> <?php foreach($t_gm_languages AS $t_gm_language) { ?> <input type="text" class="surface_name icon-input" id="surface_language_<?php echo $t_gm_language['id']; ?>" name="surface_language_<?php echo $t_gm_language['id']; ?>" value="" style="background: white url('<?php echo DIR_WS_CATALOG . 'lang/' . $t_gm_language['directory']; ?>/admin/images/icon.gif') no-repeat scroll right 8px center;" /> <?php } ?> </td> </tr> </table> </div> </div> <div class="configuration-box-footer"> <div class="button-container"> <input class="btn btn-primary" type="button" name="create_surface" id="create_surface" value="<?php echo ucfirst(GM_GPRINT_BUTTON_CREATE); ?>" /> </div> </div> <img class="gm_gprint_wait" src="../gm/images/gprint/wait.gif" /> </form> <form id="create_element_div" name="create_element_form" action="" method="post" enctype="multipart/form-data"> <div class="configuration-box-header"> <button id="hide_create_surface_flyover" class="close" type="button">×</button> <h2><?php echo GM_GPRINT_TEXT_NEW_ELEMENT; ?></h2> </div> <div class="configuration-box-body"> <div class="configuration-box-form-content editable"> <table class="normalize-table" border="0" cellpadding="0" cellspacing="0"> <tr> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_TYPE; ?> </span> <select id="element_type" name="element_type" size="1"> <option name="text" value="text" selected="selected"><?php echo GM_GPRINT_DIV_TEXT; ?></option> <option name="text_input" value="text_input"><?php echo GM_GPRINT_INPUT_TEXT; ?></option> <option name="text_input" value="textarea"><?php echo GM_GPRINT_TEXTAREA; ?></option> <option name="text_input" value="file"><?php echo GM_GPRINT_INPUT_FILE; ?></option> <option name="text_input" value="dropdown"><?php echo GM_GPRINT_DROPDOWN; ?></option> <option name="text_input" value="image"><?php echo GM_GPRINT_IMAGE; ?></option> </select> </td> </tr> <tr class="create_element_size"> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_SIZE; ?> </span> <input type="text" class="input_number" id="element_width" name="element_width" value="330" />px <input type="text" class="input_number" id="element_height" name="element_height" value="100" />px (<?php echo GM_GPRINT_TEXT_WIDTH . ' x ' . GM_GPRINT_TEXT_HEIGHT; ?>) </td> </tr> <tr> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_TOP; ?> </span> <input type="text" class="input_number" id="element_position_y" name="element_position_y" value="10" />px </td> </tr> <tr> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_LEFT; ?> </span> <input type="text" class="input_number" id="element_position_x" name="element_position_x" value="10" />px </td> </tr> <tr> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_Z_INDEX; ?> </span> <input type="text" class="input_number" id="element_z_index" name="element_z_index" value="0" /> </td> </tr> <tr class="create_element_max_characters" style="display: none;"> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_MAX_CHARACTERS; ?> </span> <input type="text" class="input_number" id="element_max_characters" name="element_max_characters" value="0" /> <?php echo GM_GPRINT_TEXT_MAX_CHARACTERS_INFO; ?> </td> </tr> <tr class="create_element_show_name" style="display: none;"> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_SHOW_NAME; ?> </span> <input type="checkbox" id="element_show_name" name="element_show_name" value="1" /> </td> </tr> <tr class="create_element_name"> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_NAME; ?> </span> <div class="grid remove-margin"> <div class="span6"> <?php echo GM_GPRINT_TEXT_NAME; ?> </div> <div class="span6 create_element_value"> <?php echo GM_GPRINT_TEXT_VALUE; ?> <span class="add_field" style="cursor: pointer; font-weight: bold; line-height: 12px; font-size: 14px; display: none;">+</span> <span class="remove_field" style="cursor: pointer; font-weight: bold; line-height: 12px; font-size: 18px; display: none;">-</span> </div> </div> <?php reset($t_gm_languages); foreach($t_gm_languages AS $t_gm_language) { ?> <div class="grid"> <div class="span6"> <input type="text" id="element_name_<?php echo $t_gm_language['id']; ?>" name="element_name" class="element_name icon-input" value="" style="background: white url('<?php echo DIR_WS_CATALOG . 'lang/' . $t_gm_language['directory']; ?>/admin/images/icon.gif') no-repeat scroll right 8px center;"/> </div> <div class="span6 create_element_value create_element_value_fields" id="create_element_value_fields_<?php echo $t_gm_language['id']; ?>"> <textarea class="element_value icon-input" name="element_language_<?php echo $t_gm_language['id']; ?>" style="background: white url('<?php echo DIR_WS_CATALOG . 'lang/' . $t_gm_language['directory']; ?>/admin/images/icon.gif') no-repeat scroll right 8px center;"></textarea> </div> </div> <?php } ?> </td> </tr> <tr class="create_element_allowed_extensions" style="display: none;"> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_ALLOWED_EXTENSIONS; ?> </span> <input type="text" id="element_allowed_extensions" name="element_allowed_extensions" class="element_allowed_extensions" value="" /> <?php echo GM_GPRINT_TEXT_ALLOWED_EXTENSIONS_2; ?> </td> </tr> <tr class="create_element_minimum_filesize" style="display: none;"> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_MINIMUM_FILESIZE; ?> </span> <input type="text" id="element_minimum_filesize" name="element_minimum_filesize" class="input_number" value="0" /><?php echo GM_GPRINT_TEXT_MINIMUM_FILESIZE_2; ?> </td> </tr> <tr class="create_element_maximum_filesize" style="display: none;"> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_MAXIMUM_FILESIZE; ?> </span> <input type="text" id="element_maximum_filesize" name="element_maximum_filesize" class="input_number" value="0" /><?php echo GM_GPRINT_TEXT_MAXIMUM_FILESIZE_2; ?> </td> </tr> <tr class="create_element_image" style="display: none;"> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_IMAGE; ?> </span> <?php reset($t_gm_languages); foreach($t_gm_languages AS $t_gm_language){ ?> <span class="language-flag"><?php echo '<img src="'.DIR_WS_LANGUAGES.$t_gm_language['directory'].'/admin/images/'.$t_gm_language['image'].'" border="0" alt="' . $t_gm_language['name'] . '" title="' . $t_gm_language['name'] . '" />'; ?></span> <input type="file" id="element_image_<?php echo $t_gm_language['id']; ?>" name="element_image_<?php echo $t_gm_language['id']; ?>" class="input" value="" /><br/> <?php } ?> </td> </tr> </table> </div> </div> <div class="configuration-box-footer"> <div class="button-container"> <input class="btn btn-primary" type="button" name="create_element" id="create_element" value="<?php echo ucfirst(GM_GPRINT_BUTTON_ADD); ?>" /> </div> </div> <img class="gm_gprint_wait" src="../gm/images/gprint/wait.gif" /> </form> <form id="edit_surface_div"> <div class="configuration-box-header"> <button id="hide_create_surface_flyover" class="close" type="button">×</button> <h2><?php echo GM_GPRINT_TEXT_SURFACE; ?>: <span id="surface_name_title"></span></h2> </div> <div class="configuration-box-body"> <div class="configuration-box-form-content editable"> <table class="normalize-table" border="0" cellpadding="0" cellspacing="0"> <tr> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_SIZE; ?> </span> <input type="text" class="input_number" id="current_surface_width" name="current_surface_width" value="" />px <input type="text" class="input_number" id="current_surface_height" name="current_surface_height" value="" />px (<?php echo GM_GPRINT_TEXT_WIDTH . ' x ' . GM_GPRINT_TEXT_HEIGHT; ?>)</td> </tr> <tr> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_NAME; ?> </span> <?php reset($t_gm_languages); foreach($t_gm_languages AS $t_gm_language){ ?> <input type="text" class="current_surface_name icon-input" id="current_surface_language_<?php echo $t_gm_language['id']; ?>" name="current_surface_language_<?php echo $t_gm_language['id']; ?>" value="" style="background: white url('<?php echo DIR_WS_CATALOG . 'lang/' . $t_gm_language['directory']; ?>/admin/images/icon.gif') no-repeat scroll right 8px center;" /> <?php } ?> </td> </tr> </table> </div> </div> <div class="configuration-box-footer"> <div class="button-container"> <input class="btn btn-primary" type="button" name="update_current_surface" id="update_current_surface" value="<?php echo ucfirst(GM_GPRINT_BUTTON_UPDATE); ?>" /> <input class="btn" type="button" name="delete_current_surface" id="delete_current_surface" value="<?php echo ucfirst(GM_GPRINT_BUTTON_DELETE); ?>" /> </div> </div> <img class="gm_gprint_wait" src="../gm/images/gprint/wait.gif" /> </form> <form id="edit_element_div"> <div class="configuration-box-header"> <button id="hide_create_surface_flyover" class="close" type="button">×</button> <h2><?php echo GM_GPRINT_TEXT_ELEMENT; ?>: <span id="element_name_title"></span></h2> </div> <div class="configuration-box-body"> <div class="configuration-box-form-content editable"> <table class="normalize-table" border="0" cellpadding="0" cellspacing="0"> <tr class="edit_element_size"> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_SIZE; ?> </span> <input type="text" class="input_number" id="current_element_width" name="current_element_width" value="" />px <input type="text" class="input_number" id="current_element_height" name="current_element_height" value="" />px (<?php echo GM_GPRINT_TEXT_WIDTH . ' x ' . GM_GPRINT_TEXT_HEIGHT; ?>) </td> </tr> <tr> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_TOP; ?> </span> <input type="text" class="input_number" id="current_element_position_y" name="current_element_position_y" value="" />px </td> </tr> <tr> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_LEFT; ?> </span> <input type="text" class="input_number" id="current_element_position_x" name="current_element_position_x" value="" />px </td> </tr> <tr> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_Z_INDEX; ?> </span> <input type="text" class="input_number" id="current_element_z_index" name="current_element_z_index" value="" /> </td> </tr> <tr class="edit_element_max_characters" style="display: none;"> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_MAX_CHARACTERS; ?> </span> <input type="text" class="input_number" id="current_element_max_characters" name="current_element_max_characters" value="" /> <?php echo GM_GPRINT_TEXT_MAX_CHARACTERS_INFO; ?> </td> </tr> <tr class="edit_element_show_name" style="display: none;"> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_SHOW_NAME; ?> </span> <input type="checkbox" id="current_element_show_name" name="current_element_show_name" value="1" /> </td> </tr> <tr class="edit_element_name_value"> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_NAME; ?> </span> <div class="grid remove-margin"> <div class="span6"> <?php echo GM_GPRINT_TEXT_NAME; ?> </div> <div class="span6 edit_element_value"> <?php echo GM_GPRINT_TEXT_VALUE; ?> <span class="add_field" style="cursor: pointer; font-weight: bold; line-height: 12px; font-size: 14px; display: none;">+</span> <span class="remove_field" style="cursor: pointer; font-weight: bold; line-height: 12px; font-size: 18px; display: none;">-</span> </div> </div> <?php reset($t_gm_languages); foreach($t_gm_languages AS $t_gm_language) { ?> <div class="grid"> <div class="span6"> <input type="text" id="current_element_name_<?php echo $t_gm_language['id']; ?>" name="current_element_name" class="current_element_name icon-input" value="" style="background: white url('<?php echo DIR_WS_CATALOG . 'lang/' . $t_gm_language['directory']; ?>/admin/images/icon.gif') no-repeat scroll right 8px center;"/> </div> <div class="span6 edit_element_value_fields edit_element_value" id="edit_element_value_fields_<?php echo $t_gm_language['id']; ?>"> <textarea class="current_element_value icon-input" name="current_element_language_<?php echo $t_gm_language['id']; ?>" style="background: white url('<?php echo DIR_WS_CATALOG . 'lang/' . $t_gm_language['directory']; ?>/admin/images/icon.gif') no-repeat scroll right 8px center;"></textarea> </div> </div> <?php } ?> </td> </tr> <tr class="edit_element_allowed_extensions" style="display: none;"> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_ALLOWED_EXTENSIONS; ?> </span> <input type="text" id="current_element_allowed_extensions" name="current_element_allowed_extensions" class="current_element_allowed_extensions" value="" /> <?php echo GM_GPRINT_TEXT_ALLOWED_EXTENSIONS_2; ?> </td> </tr> <tr class="edit_element_minimum_filesize" style="display: none;"> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_MINIMUM_FILESIZE; ?> </span> <input type="text" id="current_element_minimum_filesize" name="current_element_minimum_filesize" class="input_number" value="" /><?php echo GM_GPRINT_TEXT_MINIMUM_FILESIZE_2; ?> </td> </tr> <tr class="edit_element_maximum_filesize" style="display: none;"> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_MAXIMUM_FILESIZE; ?> </span> <input type="text" id="current_element_maximum_filesize" name="current_element_maximum_filesize" class="input_number" value="" /><?php echo GM_GPRINT_TEXT_MAXIMUM_FILESIZE_2; ?> </td> </tr> <tr class="edit_element_image" style="display: none;"> <td> <span class="options-title"> <?php echo GM_GPRINT_TEXT_IMAGE; ?> </span> <?php reset($t_gm_languages); foreach($t_gm_languages AS $t_gm_language){ ?> <span class="language-flag"><?php echo '<img src="'.DIR_WS_LANGUAGES.$t_gm_language['directory'].'/admin/images/'.$t_gm_language['image'].'" border="0" alt="' . $t_gm_language['name'] . '" title="' . $t_gm_language['name'] . '" />'; ?></span> <input type="file" id="edit_element_image_<?php echo $t_gm_language['id']; ?>" name="edit_element_image_<?php echo $t_gm_language['id']; ?>" class="input" value="" /><br/> <?php } ?> </td> </tr> </table> </div> </div> <div class="configuration-box-footer"> <div class="button-container"> <input type="button" class="btn btn-primary" name="update_current_element" id="update_current_element" value="<?php echo ucfirst(GM_GPRINT_BUTTON_UPDATE); ?>" /> <input type="button" class="btn" name="delete_current_element" id="delete_current_element" value="<?php echo ucfirst(GM_GPRINT_BUTTON_DELETE); ?>" /> </div> </div> <img class="gm_gprint_wait" src="../gm/images/gprint/wait.gif" /> </form> </div> </div> <br /> <ul id="gm_gprint_tabs"></ul> <div id="gm_gprint_content"></div> <br /> <br /> <div class="simple-container"> <input class="btn pull-right" type="button" onclick="$('#gm_gprint_help').toggle();" value="<?php echo GM_GPRINT_BUTTON_HELP; ?>" /> <a href="gm_gprint.php" class="pull-right"><button class="btn" style="display: inline; float: left" type="button" ><i class="fa fa-reply"></i> <?php echo BUTTON_BACK; ?></button></a> </div> <table border="0" cellpadding="0" cellspacing="0" id="gm_gprint_help"> <tr> <td> <br /> <br /> <?php echo GM_GPRINT_DESCRIPTION; ?> </td> </tr> </table> </div> </td> </tr> </table>
gpl-2.0
sunmoyi/ACM
sunmoyi-ac/UVA/10603/7297041_AC_10ms_0kB.cpp
2081
#include<cstdio> #include<cstring> #include<algorithm> #include<queue> #define maxn 210 using namespace std; struct node{ int v[3], dist; bool operator < (const node& rhs)const { return dist > rhs.dist; } }; int mark[maxn][maxn], dist[maxn][maxn], cap[3], ans[maxn]; void update_ans(const node& a) { for(int i = 0; i < 3; i++) { int d = a.v[i]; if(ans[d] < 0 || a.dist < ans[d]) ans[d] = a.dist; } } void solve(int a, int b, int c, int d) { cap[0] = a, cap[1] = b, cap[2] = c; memset(ans, -1, sizeof(ans)); memset(mark, 0, sizeof(mark)); memset(dist, -1, sizeof(dist)); priority_queue<node>Q; node start; start.dist = 0, start.v[0] = 0, start.v[1] = 0, start.v[2] = c; Q.push(start); dist[0][0] = 0; while(!Q.empty()) { node u = Q.top(); Q.pop(); if(mark[u.v[0]][u.v[1]]) continue; mark[u.v[0]][u.v[1]] = 1; update_ans(u); if(ans[d] >= 0) break; for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { if(i != j) { if(u.v[i] == 0 || u.v[j] == cap[j]) continue; int amount = min(cap[j] - u.v[j], u.v[i]); node u2 = u; u2.dist = u.dist + amount; u2.v[i] -= amount; u2.v[j] += amount; int &D = dist[u2.v[0]][u2.v[1]]; if(D < 0 || u2.dist < D) { D = u2.dist; Q.push((u2)); } } } } } while(d >= 0) { if(ans[d] >= 0) { printf("%d %d\n", ans[d], d); return; } d--; } } int main (void) { int T, a, b, c, d; scanf("%d", &T); while(T--) { scanf("%d %d %d %d", &a, &b, &c, &d); solve(a, b, c, d); } return 0; }
gpl-2.0
squallyou/LScore
src/sjy/elwg/notation/musicBeans/UIKey.java
7864
package sjy.elwg.notation.musicBeans; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JPanel; import sjy.elwg.notation.NoteCanvas; /** * µ÷ºÅʵÌå * ×¢ÒâÔÚС½ÚÖÐËù´æ´¢µÄ×Ö·û´®Ð͵÷ºÅÀàÐͱäÁ¿£¬ÓëС½ÚµÄʵ¼Êµ÷ºÅʵÌåµÄµ÷ºÅÀàÐÍ¿ÉÄܲ»Ò»Ñù£¬µ÷ºÅʵÌåÈ¡¾öÓÚС½ÚÔÚÀÖÆ×ÖеÄλÖÃ. * @author sjy * */ public class UIKey extends JPanel{ /** * ÐòÁкŠ*/ private static final long serialVersionUID = -8113634949273674746L; /** * ·ÅÖõ÷ºÅʱÓëǰһ¸öUI¶ÔÏóµÄ¼ä¾à */ public static final int KEY_GAP = 3; /** * ×é³Éµ÷ºÅµÄµ¥¸ö·ûºÅµÄ¿í¶È */ public static final int SINGLEWIDTH = 8; /** * ÉýºÅ£¬½µºÅÒÔ¼°»Ö¸´ºÅµÄµ¥¸ö·ûºÅ */ public static final String FONT_SHARP = "\uE10E"; public static final String FONT_FLAT = "\uE114"; public static final String FONT_NATURAL = "\uE113"; /** * µ÷ºÅÖµ. ȡֵ·¶Î§´Ó-7µ½7.²»ÄÜΪ0.ÕýÊýΪÉýºÅ£¬¸ºÊýΪ½µºÅ. */ private int keyValue; /** * ÊÇ·ñÊǻָ´Õý³£µ÷ºÅ */ private boolean restoreNatural; /** * Æ×ºÅÀàÐÍ.ÒòΪµ÷ºÅʵÌåµÄÐÎ×´Óë¶ÔÓ¦µÄÆ×ºÅÓйØ. */ private String clefType; /** * ÊÇ·ñ±»Ñ¡ÖÐ */ private boolean selected; /** * ¹¹Ô캯Êý * @param keyValue * @param clefType */ public UIKey(int keyValue, String clefType){ super(); this.keyValue = keyValue; this.clefType = clefType; selected = false; adjustSize(); setOpaque(false); //setBackground(Color.red); } /** * µ÷Õû´óС */ public void adjustSize(){ if(keyValue == 1 || keyValue == -1){ setSize(NoteCanvas.LINE_GAP+2, NoteCanvas.LINE_GAP*3 + 5); }else if(keyValue == 2 || keyValue == -2){ setSize(2*SINGLEWIDTH+2, NoteCanvas.LINE_GAP*4 + 5); }else if(keyValue == 3 || keyValue == -3){ setSize(3*SINGLEWIDTH+2, NoteCanvas.LINE_GAP*5 + 5); }else if(keyValue == 4 || keyValue == -4){ setSize(4*SINGLEWIDTH+2, NoteCanvas.LINE_GAP*5 + 5); }else if(keyValue == 5 || keyValue == -5){ setSize(5*SINGLEWIDTH+2, NoteCanvas.LINE_GAP*6 + 5); }else if(keyValue == 6 || keyValue == -6){ setSize(6*SINGLEWIDTH+2, NoteCanvas.LINE_GAP*6 + 5); }else if(keyValue == 7 || keyValue == -7){ setSize(7*SINGLEWIDTH+2, NoteCanvas.LINE_GAP*6 + 5); } } /** * »ñµÃÊÇ·ñ»Ö¸´Õý³£µ÷ * @return */ public boolean isRestoreNatural() { return restoreNatural; } /** * ÉèÖûָ´Õý³£µ÷ * @param restoreNatural */ public void setRestoreNatural(boolean restoreNatural) { this.restoreNatural = restoreNatural; } /** * »ñµÃµ÷ºÅÖµ£¬ * @return */ public int getKeyValue() { return keyValue; } /** * ÉèÖõ÷ºÅÖµ * @param keyValue */ public void setKeyValue(int keyValue) { this.keyValue = keyValue; } /** * »ñµÃÆ×ºÅÀàÐÍ * @return */ public String getClefType() { return clefType; } /** * ÉèÖÃÆ×ºÅÀàÐÍ. * @param clefType */ public void setClefType(String clefType) { this.clefType = clefType; } /** * »ñµÃÊÇ·ñ±»Ñ¡Ôñ * @return */ public boolean isSelected() { return selected; } /** * ÉèÖñ»Ñ¡Ôñ * @param selected */ public void setSelected(boolean selected) { this.selected = selected; } public void paintComponent(Graphics gg){ super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; RenderingHints renderHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); renderHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); g.setRenderingHints(renderHints); // g.setFont(new Font("mscore", Font.PLAIN, 35)); g.setFont(NoteCanvas.MCORE_FONT.deriveFont(35f)); if(selected) g.setColor(Color.red); else g.setColor(Color.black); String fontToUse = null; if(keyValue > 0){ if(restoreNatural) fontToUse = FONT_NATURAL; else fontToUse = FONT_SHARP; }else if(keyValue < 0){ if(restoreNatural) fontToUse = FONT_NATURAL; else fontToUse = FONT_FLAT; } if(clefType.equalsIgnoreCase("g/2") || clefType.equalsIgnoreCase("f/4") || clefType.equalsIgnoreCase("c/3")){ if(keyValue == 1){ g.drawString(fontToUse, 1, 15); }else if(keyValue == 2){ g.drawString(fontToUse, 1, 15); g.drawString(fontToUse, SINGLEWIDTH, 30); }else if(keyValue == 3){ g.drawString(fontToUse, 1, 20); g.drawString(fontToUse, SINGLEWIDTH, 35); g.drawString(fontToUse, 2*SINGLEWIDTH, 15); }else if(keyValue == 4){ g.drawString(fontToUse, 1, 20); g.drawString(fontToUse, SINGLEWIDTH, 35); g.drawString(fontToUse, 2*SINGLEWIDTH, 15); g.drawString(fontToUse, 3*SINGLEWIDTH, 30); }else if(keyValue == 5){ g.drawString(fontToUse, 1, 20); g.drawString(fontToUse, SINGLEWIDTH, 35); g.drawString(fontToUse, 2*SINGLEWIDTH, 15); g.drawString(fontToUse, 3*SINGLEWIDTH, 30); g.drawString(fontToUse, 4*SINGLEWIDTH, 45); }else if(keyValue == 6){ g.drawString(fontToUse, 1, 20); g.drawString(fontToUse, SINGLEWIDTH, 35); g.drawString(fontToUse, 2*SINGLEWIDTH, 15); g.drawString(fontToUse, 3*SINGLEWIDTH, 30); g.drawString(fontToUse, 4*SINGLEWIDTH, 45); g.drawString(fontToUse, 5*SINGLEWIDTH, 25); }else if(keyValue == 7){ g.drawString(fontToUse, 1, 20); g.drawString(fontToUse, SINGLEWIDTH, 35); g.drawString(fontToUse, 2*SINGLEWIDTH, 15); g.drawString(fontToUse, 3*SINGLEWIDTH, 30); g.drawString(fontToUse, 4*SINGLEWIDTH, 45); g.drawString(fontToUse, 5*SINGLEWIDTH, 25); g.drawString(fontToUse, 6*SINGLEWIDTH, 40); } if(keyValue == -1){ g.drawString(fontToUse, 1, 25); }else if(keyValue == -2){ g.drawString(fontToUse, 1, 40); g.drawString(fontToUse, SINGLEWIDTH, 25); }else if(keyValue == -3){ g.drawString(fontToUse, 1, 40); g.drawString(fontToUse, SINGLEWIDTH, 25); g.drawString(fontToUse, 2*SINGLEWIDTH, 45); }else if(keyValue == -4){ g.drawString(fontToUse, 1, 40); g.drawString(fontToUse, SINGLEWIDTH, 25); g.drawString(fontToUse, 2*SINGLEWIDTH, 45); g.drawString(fontToUse, 3*SINGLEWIDTH, 30); }else if(keyValue == -5){ g.drawString(fontToUse, 1, 40); g.drawString(fontToUse, SINGLEWIDTH, 25); g.drawString(fontToUse, 2*SINGLEWIDTH, 45); g.drawString(fontToUse, 3*SINGLEWIDTH, 30); g.drawString(fontToUse, 4*SINGLEWIDTH, 50); }else if(keyValue == -6){ g.drawString(fontToUse, 1, 40); g.drawString(fontToUse, SINGLEWIDTH, 25); g.drawString(fontToUse, 2*SINGLEWIDTH, 45); g.drawString(fontToUse, 3*SINGLEWIDTH, 30); g.drawString(fontToUse, 4*SINGLEWIDTH, 50); g.drawString(fontToUse, 5*SINGLEWIDTH, 35); }else if(keyValue == -7){ g.drawString(fontToUse, 1, 40); g.drawString(fontToUse, SINGLEWIDTH, 25); g.drawString(fontToUse, 2*SINGLEWIDTH, 45); g.drawString(fontToUse, 3*SINGLEWIDTH, 30); g.drawString(fontToUse, 4*SINGLEWIDTH, 50); g.drawString(fontToUse, 5*SINGLEWIDTH, 35); g.drawString(fontToUse, 6*SINGLEWIDTH, 55); } } } /** * ¸ù¾Ýµ÷ºÅÓëÆ×ºÅÀàÐÍ£¬·µ»Ø·ÅÖõ÷ºÅʱµ÷ºÅµÄy×ø±êÓëµ÷ºÅËùÔÚС½Úy×ø±êµÄ²îÖµ,¼´µ÷ºÅÏà¶ÔС½ÚµÄy×ø±êÖµ * @return */ public int getPositionOffset(){ if(keyValue == 0){ System.err.println("µ÷ºÅʵÌåµÄkeyValueÖµ²»ÄÜΪ0"); return 0; } if(clefType.equalsIgnoreCase("g/2")){ if(keyValue == 1 || keyValue == 2){ return -15; }else if(keyValue > 0){ return -20; }else if(keyValue == -1){ return -5; }else if(keyValue < 0){ return -20; } }else if(clefType.equalsIgnoreCase("f/4")){ if(keyValue == 1 || keyValue == 2){ return -5; }else if(keyValue > 0){ return -10; }else if(keyValue == -1){ return 5; }else if(keyValue < 0){ return -10; } }else if(clefType.equalsIgnoreCase("c/3")){ if(keyValue == 1 || keyValue == 2){ return -10; }else if(keyValue > 0){ return -15; }else if(keyValue == -1){ return 0; }else if(keyValue < 0){ return -15; } } return 0; } }
gpl-2.0
nickdhondt/dungeons-and-dragons
http/http_add_inventory.php
3558
<?php //This page expects: //"basic_id", "action", "user_id" //This page will execute the following: //Change the required values in the database require_once "../includes/functions.php"; session_start(); $errors = array(); $post_data = array(); $data_acquired = "false"; //$_POST["data"] = array("inventory"=>"3", "action"=>"add", "user_id"=>"1"); if(empty($_POST["data"])){ //Set the flag to false $data_acquired = "false"; $errors[] = "Foute of geen data ontvangen"; } else { //Set flag to true $data_acquired = "true"; //Decode the post $post_data = json_decode($_POST["data"], true); //$post_data = $_POST["data"]; //Check if the post data contains all the needed values if((isset($post_data["inventory"])) && (!empty($post_data["action"])) && (isset($post_data["user_id"]))){ //Save the values $item_id = $post_data["inventory"]; $action = $post_data["action"]; $user_id = $post_data["user_id"]; //Check if the user has got sufficient rights to do this action. //Get the permission type. $user_logged_id = user_logged_in(); if($user_logged_id != false){ $fields = array("user_id", "permission_type"); $user_data = user_data($user_logged_id, $fields); //Check for admin if($user_data["permission_type"] === "1"){ //DO SOME MAGICAL SHIT //Write to the database switch($action){ case "add": $request_completed = add_to_user_inventory($user_id, $item_id); $request_msg = "Er is iets fout gegaan. Whoopsie"; break; case "substract": $request_completed = add_to_user_inventory($user_id, $item_id, true); $request_msg = "Er is iets fout gegaan. Whoopsie"; break; default: $request_completed = "false"; $request_msg = "The action was undefined. (add or substract expected) Check your message header."; break; } if($request_completed == "true"){ $data_acquired = "true"; } else { $data_acquired = "true"; $errors[] = "Error, de server meldt het volgende"; $errors[] = $request_msg; } } else { $data_acquired = "false"; $errors[] = "U heeft geen rechten om deze bewerking uit te voeren. Contacteer een administrator."; } } else { $data_acquired = "false"; $errors[] = "Het systeem kon niet achterhalen wie of wat u bent."; $errors[] = "Gelieve uw identiteitscrisis achter u te laten en linea recta naar de mannen van de IT te zoeken."; } } else { $data_acquired = "false"; $errors[] = "Niet alle data ontvangen. Een of meerdere verwachte elementen ontbreken"; } } // Prepare the return data if ($data_acquired === "true" && empty($errors)) { $return_message = array( "request_accepted" => $data_acquired, "data" => "true" ); } else { $return_message = array( "request_accepted" => $data_acquired, "errors" => $errors ); } // JSON encode our array $return_data = json_encode($return_message); // "Return" the json string to the client echo $return_data;
gpl-2.0
OpenDrift/opendrift
examples/example_compare_oilbudgets.py
2948
#!/usr/bin/env python """ Comparing oil budgets ================================== """ from datetime import datetime, timedelta import numpy as np import matplotlib.pyplot as plt from opendrift.models.openoil import OpenOil #%% # Comparing the weathering and properties # of different oils at different wind speeds oiltypes = ['GENERIC HEAVY CRUDE', 'GENERIC MEDIUM CRUDE', 'GENERIC LIGHT CRUDE', 'GENERIC DIESEL'] wind_speeds = [5, 10] hours = 24 b = {} viscosities = {} densities = {} water_fractions = {} for wind_speed in wind_speeds: for ot in oiltypes: o = OpenOil(loglevel=50) print('%s m/s - %s' % (wind_speed, ot)) o.set_config('environment:constant:x_wind', wind_speed) o.set_config('environment:constant:y_wind', 0) o.set_config('environment:constant:x_sea_water_velocity', 0) o.set_config('environment:constant:y_sea_water_velocity', 0) o.set_config('environment:constant:land_binary_mask', 0) o.set_config('general:use_auto_landmask', False) o.set_config('processes:dispersion', False) o.seed_elements(lon=0, lat=0, time=datetime.now(), number=1000, oil_type=ot) o.run(duration=timedelta(hours=hours), time_step=600) b[ot] = o.get_oil_budget() # Get viscosity and density kin_viscosity = o.history['viscosity'] dyn_viscosity = kin_viscosity * o.history['density'] viscosities[ot] = dyn_viscosity.mean(axis=0) densities[ot] = o.history['density'].mean(axis=0) water_fractions[ot] = o.history['water_fraction'].mean(axis=0) time, time_relative = o.get_time_array() time = np.array([t.total_seconds() / 3600. for t in time_relative]) figw,(axevap, axsurf, axsub) = plt.subplots(3,1) figp,(axdens, axvisc, axw) = plt.subplots(3,1) for ot in oiltypes: axevap.plot(time, 100*b[ot]['mass_evaporated']/b[ot]['mass_total'], label=ot) axsurf.plot(time, 100*b[ot]['mass_surface']/b[ot]['mass_total'], label=ot) axsub.plot(time, 100*b[ot]['mass_submerged']/b[ot]['mass_total'], label=ot) axdens.plot(time, densities[ot], label=ot) axvisc.plot(time, viscosities[ot], label=ot) axw.plot(time, water_fractions[ot], label=ot) for ax in (axevap, axsurf, axsub, axdens, axvisc, axw): if ax in (axevap, axsurf, axsub): ax.set_ylim([0, 100]) ax.set_xlim([0, hours]) axevap.set_title('Wind speed %s m/s' % wind_speed) axsurf.set_ylabel('Surface [%]') axevap.set_ylabel('Evaporated [%]') axsub.set_ylabel('Submerged [%]') axsub.legend() axsub.set_xlabel('Time [hours]') axdens.set_title('Wind speed %s m/s' % wind_speed) axvisc.set_ylabel('Viscosity [mPas]') axvisc.set_yscale('log') axdens.set_ylabel('Density [kg/m3]') axw.set_ylabel('Water fraction') axw.set_xlabel('Time [hours]') axw.legend() plt.tight_layout() plt.show()
gpl-2.0
pierres/archlinux-mediawiki
includes/jobqueue/jobs/ClearWatchlistNotificationsJob.php
3304
<?php /** * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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. * http://www.gnu.org/copyleft/gpl.html * * @file * @ingroup JobQueue */ use MediaWiki\MediaWikiServices; /** * Job for clearing all of the "last viewed" timestamps for a user's watchlist, or setting them all * to the same value. * * Job parameters include: * - userId: affected user ID [required] * - casTime: UNIX timestamp of the event that triggered this job [required] * - timestamp: value to set all of the "last viewed" timestamps to [optional, defaults to null] * * @ingroup JobQueue * @since 1.31 */ class ClearWatchlistNotificationsJob extends Job implements GenericParameterJob { function __construct( array $params ) { parent::__construct( 'clearWatchlistNotifications', $params ); static $required = [ 'userId', 'casTime' ]; $missing = implode( ', ', array_diff( $required, array_keys( $this->params ) ) ); if ( $missing != '' ) { throw new InvalidArgumentException( "Missing parameter(s) $missing" ); } $this->removeDuplicates = true; } public function run() { $services = MediaWikiServices::getInstance(); $lbFactory = $services->getDBLoadBalancerFactory(); $rowsPerQuery = $services->getMainConfig()->get( 'UpdateRowsPerQuery' ); $dbw = $lbFactory->getMainLB()->getConnectionRef( DB_MASTER ); $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ ); $timestamp = $this->params['timestamp'] ?? null; if ( $timestamp === null ) { $timestampCond = 'wl_notificationtimestamp IS NOT NULL'; } else { $timestamp = $dbw->timestamp( $timestamp ); $timestampCond = 'wl_notificationtimestamp != ' . $dbw->addQuotes( $timestamp ) . ' OR wl_notificationtimestamp IS NULL'; } // New notifications since the reset should not be cleared $casTimeCond = 'wl_notificationtimestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->params['casTime'] ) ) . ' OR wl_notificationtimestamp IS NULL'; $firstBatch = true; do { $idsToUpdate = $dbw->selectFieldValues( 'watchlist', 'wl_id', [ 'wl_user' => $this->params['userId'], $timestampCond, $casTimeCond, ], __METHOD__, [ 'LIMIT' => $rowsPerQuery ] ); if ( $idsToUpdate ) { $dbw->update( 'watchlist', [ 'wl_notificationtimestamp' => $timestamp ], [ 'wl_id' => $idsToUpdate, // For paranoia, enforce the CAS time condition here too $casTimeCond ], __METHOD__ ); if ( !$firstBatch ) { $lbFactory->commitAndWaitForReplication( __METHOD__, $ticket ); } $firstBatch = false; } } while ( $idsToUpdate ); return true; } }
gpl-2.0
Gambiit/pmb-on-docker
web_appli/pmb/opac_css/includes/expl.inc.php
343
<?php // +-------------------------------------------------+ // © 2002-2004 PMB Services / www.sigb.net [email protected] et contributeurs (voir www.sigb.net) // +-------------------------------------------------+ // $Id: expl.inc.php,v 1.15 2007-03-10 10:05:50 touraine37 Exp $ if (stristr($_SERVER['REQUEST_URI'], ".inc.php")) die("no access");
gpl-2.0
andriiryzhkov/tsatu-homelayout
includes/sidebar.php
1127
<?php /** * Register home widget areas */ function tsatu_homelayout_generate() { $widget_areas_names = array( __('One', 'tsatu-homelayout'), __('Two', 'tsatu-homelayout'), __('Three', 'tsatu-homelayout'), __('Four', 'tsatu-homelayout'), __('Five', 'tsatu-homelayout') ); if (get_option('tsatu_show_widget_areas')) { for ($wa = 1; $wa <= 5; $wa++) { $col_n = get_option('tsatu_columns_' . $wa) + 1; for ($cl = 1; $cl <= $col_n; $cl++) { register_sidebar(array( 'name' => sprintf(__('Front Page Area %1$s - %2$s/%3$s', 'tsatu-homelayout'), $widget_areas_names[$wa - 1], $cl, $col_n), 'id' => 'sidebar-home-' . $wa . '-' . $cl, 'before_widget' => '<section class="widget %1$s %2$s">', 'after_widget' => '</section>', 'before_title' => '<h3>', 'after_title' => '</h3>', )); } } } } add_action('widgets_init', 'tsatu_homelayout_generate');
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest06181.java
1814
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest06181") public class BenchmarkTest06181 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = request.getQueryString(); String bar; // Simple ? condition that assigns param to bar on false condition int i = 106; bar = (7*42) - i > 200 ? "This should never happen" : param; Object[] obj = { bar, "b"}; response.getWriter().printf("notfoo",obj); } }
gpl-2.0
7taghap/wpxtreme
wp-content/plugins/profilepress/includes/class-theme.php
5441
<?php /** * ProfilePress theme class * * @link http://wp3.in * @since 0.0.1 * @package ProfilePress */ // If this file is called directly, abort. if (!defined('WPINC')) { die; } class PP_Theme { public function __construct() { pp_register_user_page('profile', __('Profile', 'pp'), array($this, 'profile_page')); pp_register_user_page('about', __('About', 'pp'), array($this, 'pp_about')); pp_register_user_page('favorites', __('Favorites', 'pp'), array($this, 'page_favorites')); pp_register_user_page('posts', __('Posts', 'pp'), array($this, 'page_my_posts')); if(defined('AP_VERSION')){ pp_register_user_page('questions', __('Questions', 'pp'), array($this, 'page_questions')); pp_register_user_page('answers', __('Answers', 'pp'), array($this, 'page_answers')); } add_action('init', array($this, 'theme_function') ); add_filter('wp_title', array($this, 'wp_title'), 100, 2); add_filter('the_title', array($this, 'the_title'), 100, 2); add_filter('pp_blocks', array($this, 'users_qa')); add_filter('pp_blocks', array($this, 'user_posts')); add_filter('ap_post_actions_buttons', array($this, 'post_action_favorite_button')); } public function profile_page() { include (pp_get_theme_location('profile.php')); } public function pp_about() { include (pp_get_theme_location('about.php')); } public function page_my_posts() { include (pp_get_theme_location('posts.php')); } public function page_favorites() { include (pp_get_theme_location('favorites.php')); } public function theme_function() { add_shortcode('profilepress', array(PP_BasePage_Shortcode::get_instance(), 'pp_sc')); require_once pp_get_theme_location('functions.php'); } public function page_questions() { require_once pp_get_theme_location('questions.php'); } public function page_answers() { require_once pp_get_theme_location('answers.php'); } /** * @param string $title * @return void */ public function wp_title($title) { if (is_profilepress()) { $new_title = pp_page_title(); $new_title = str_replace('PROFILE_TITLE', $new_title, $title); $new_title = apply_filters('profile_title', $new_title); return $new_title; } return $title; } public function the_title($title, $id) { if ($id == pp_opt('base_page')) { return pp_page_title(); } return $title; } public function users_qa($user_id) { if(!defined('AP_VERSION')) return; $args = array('post_type' => array('question', 'answer'), 'author' => pp_get_current_user(), 'showposts' => 5, 'post_status' => 'publish'); $posts = new WP_Query($args); if ($posts->have_posts()) { ?> <h3 class="pp-list-head"> <?php _e('Questions & Answers', 'pp') ?> <span class="user-post-count">(<?php echo count_user_posts(pp_get_current_user(), 'question') + count_user_posts(pp_get_current_user(), 'answer') ?>)</span> </h3> <?php while ($posts->have_posts()): $posts->the_post(); include pp_get_theme_location('content-question.php'); endwhile; echo '<div class="show-all">' . __('Show all', 'pp') . ' <a href="' . pp_get_link_to('answers') . '">' . __('answers by', 'pp') . '</a> ' . pp_display_name(pp_get_current_user()) . ' &rarr; <span> | </span>' . __('Show all', 'pp') . ' <a href="' . pp_get_link_to('questions') . '">' . __('questions by', 'pp') . '</a> ' . pp_display_name(pp_get_current_user()) . ' &rarr;</div>'; } else { _e('No question and answer posted by this user.', 'pp'); } wp_reset_postdata(); } public function user_posts($user_id) { $args = array('post_type' => 'post', 'author' => pp_get_current_user(), 'showposts' => 5, 'post_status' => 'publish'); $posts = new WP_Query($args); if ($posts->have_posts()) { ?> <h3 class="pp-list-head"> <?php _e('Posts', 'pp') ?> <span class="user-post-count">(<?php echo count_user_posts(pp_get_current_user(), 'post') ?>)</span> </h3> <?php while ($posts->have_posts()): $posts->the_post(); include pp_get_theme_location('content-post.php'); endwhile; echo '<div class="show-all">' . __('Show all', 'pp') . ' <a href="' . pp_get_link_to('posts') . '">' . __('posts by', 'pp') . '</a> ' . pp_display_name(pp_get_current_user()) . ' &rarr;</div>'; } else { _e('No posts were written by this user.', 'pp'); } wp_reset_postdata(); } public function post_action_favorite_button($metas) { $metas['favorite'] = wp3_favorite_btn(get_the_ID()); return $metas; } }
gpl-2.0
kbeswick/evergreen
Open-ILS/web/js/dojo/openils/actor/nls/register.js
664
{ "DELETE_ADDRESS" : "Delete address ${0}?", "NEED_ADDRESS" : "An address is required during registration.", "DUPE_PATRON_NAME" : "Found ${0} patron(s) with the same name", "DUPE_PATRON_EMAIL" : "Found ${0} patron(s) with the same email address", "DUPE_PATRON_IDENT" : "Found ${0} patron(s) with the same identification", "DUPE_PATRON_PHONE" : "Found ${0} patron(s) with the same phone number", "DUPE_PATRON_ADDR" : "Found ${0} patron(s) with the same address", "REPLACED_ADDRESS" : "<div>Replaces address <b>${0}</b><br/> ${1} ${2}<br/> ${3}, ${4} ${5}</div>", "INVALID_FORM" : "Form is invalid. Please edit and try again." }
gpl-2.0
haidarafif0809/qwooxcqmkozzxce
data_tbs_penjualan_inap.php
7145
<?php include 'session_login.php'; /* Database connection start */ include 'sanitasi.php'; include 'db.php'; /* Database connection end */ $no_reg = stringdoang($_POST['no_reg']); $pilih_akses_tombol = $db->query("SELECT * FROM otoritas_penjualan_inap WHERE id_otoritas = '$_SESSION[otoritas_id]' "); $otoritas_tombol = mysqli_fetch_array($pilih_akses_tombol); // storing request (ie, get/post) global array to a variable $requestData= $_REQUEST; $columns = array( // datatable column index => database column name 0=>'kode_barang', 1=>'nama_barang', 2=>'jumlah_barang', 3=>'satuan', 4=>'harga', 5=>'subtotal', 6=>'potongan', 7=>'tax', 8=>'jam', 9=>'id', 9=>'dosis' ); // getting total number records without any search $sql =" SELECT tp.id,tp.kode_barang,tp.satuan,tp.nama_barang,tp.jumlah_barang,tp.harga,tp.subtotal,tp.potongan,tp.tax,tp.tanggal,tp.jam,tp.no_reg,tp.tipe_barang,tp.dosis,s.nama,r.nama_ruangan"; $sql.=" FROM tbs_penjualan tp LEFT JOIN satuan s ON tp.satuan = s.id LEFT JOIN ruangan r ON tp.ruangan = r.id"; $sql.=" WHERE tp.no_reg = '$no_reg' AND (tp.lab IS NULL OR tp.lab = '') AND (tp.no_faktur IS NULL OR tp.no_faktur = '') AND tp.tipe_barang = 'Bed'"; $query = mysqli_query($conn, $sql) or die("eror 1"); $totalData = mysqli_num_rows($query); $totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows. if( !empty($requestData['search']['value']) ) { // if there is a search parameter, $requestData['search']['value'] contains search parameter $sql =" SELECT tp.id,tp.kode_barang,tp.satuan,tp.nama_barang,tp.jumlah_barang,tp.harga,tp.subtotal,tp.potongan,tp.tax,tp.tanggal,tp.jam,tp.no_reg,tp.tipe_barang,tp.dosis,s.nama,r.nama_ruangan"; $sql.=" FROM tbs_penjualan tp LEFT JOIN satuan s ON tp.satuan = s.id LEFT JOIN ruangan r ON tp.ruangan = r.id"; $sql.=" WHERE tp.no_reg = '$no_reg' AND (tp.lab IS NULL OR tp.lab = '') AND (tp.no_faktur IS NULL OR tp.no_faktur = '') AND tp.tipe_barang = 'Bed'"; $sql.=" AND (tp.kode_barang LIKE '".$requestData['search']['value']."%'"; $sql.=" OR tp.nama_barang LIKE '".$requestData['search']['value']."%' "; $sql.=" OR s.nama LIKE '".$requestData['search']['value']."%' )"; } $query=mysqli_query($conn, $sql) or die("eror 2"); $totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result. $sql.=" ORDER BY tp.tanggal,tp.jam DESC LIMIT ".$requestData['start']." ,".$requestData['length']." "; /* $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc */ $query=mysqli_query($conn, $sql) or die("eror 3"); $data = array(); while( $row=mysqli_fetch_array($query) ) { // preparing an array $nestedData=array(); $nestedData[] = $row["kode_barang"]; $nestedData[] = $row["nama_barang"]; $nestedData[] = $row["nama_ruangan"]; $kdD = $db->query("SELECT f.nama_petugas, u.nama FROM tbs_fee_produk f LEFT JOIN user u ON f.nama_petugas = u.id WHERE f.kode_produk = '$row[kode_barang]' AND f.jam = '$row[jam]' "); $nama_fee = "<p style='font-size:15px;'>"; while($nur = mysqli_fetch_array($kdD)) { $nama_fee .= " ".$nur["nama"].","; } $nama_fee .= "</p>"; $nestedData[] = $nama_fee; if ($otoritas_tombol['edit_produk_inap'] > 0){ $nestedData[] = "<p style='font-size:15px' align='right' class='edit-jumlah' data-id='".$row['id']."' data-kode='".$row['kode_barang']."'><span id='text-jumlah-".$row['id']."'>". $row['jumlah_barang'] ."</span> <input type='hidden' id='input-jumlah-".$row['id']."' value='".$row['jumlah_barang']."' class='input_jumlah' data-id='".$row['id']."' autofocus='' data-kode='".$row['kode_barang']."' data-harga='".$row['harga']."' data-tipe='".$row['tipe_barang']."' data-satuan='".$row['satuan']."' data-nama-barang='".$row['nama_barang']."' onkeydown='return numbersonly(this, event);'> </p>"; } else{ $nestedData[] = "<p style='font-size:15px' align='right' class='gk_bisa_edit'>". rp($row['jumlah_barang']) ." </p>"; } $nestedData[] = $row["nama"]; $nestedData[] = "<p style='font-size:15px' class='edit-dosis' data-id='".$row['id']."'> <span id='text-dosis-".$row['id']."'>".$row["dosis"]."</span> <input type='hidden' id='input-dosis-".$row['id']."' value='".$row['dosis']."' class='input_dosis' data-id='".$row['id']."' autofocus='' data-kode='".$row['kode_barang']."' data-tipe='".$row['tipe_barang']."' data-nama-barang='".$row['nama_barang']."'> </p>"; $nestedData[] = "<p align='right'>".rp($row["harga"])."</p>"; $nestedData[] = "<p style='font-size:15px' align='right'><span id='text-subtotal-".$row['id']."'> ".rp($row["subtotal"])." </span> </p>"; $nestedData[] = "<p style='font-size:15px' align='right'><span id='text-potongan-".$row['id']."'> ".rp($row["potongan"])." </span> </p>"; $nestedData[] = "<p style='font-size:15px' align='right'><span id='text-tax-".$row['id']."'> ".rp($row["tax"])." </span> </p>"; if ($otoritas_tombol['edit_tanggal_inap'] > 0){ $nestedData[] = "<p style='font-size:15px' align='right' class='edit-tanggal' data-id='".$row['id']."' data-kode='".$row['kode_barang']."'> <span id='text-tanggal-".$row['id']."'> ".$row['tanggal']." ".$row['jam']." </span> <input type='hidden' id='input-tanggal-".$row['id']."' value='".$row['tanggal']."' class='input_tanggal' data-id='".$row['id']."' autofocus='' data-kode='".$row['kode_barang']."' data-jam='".$row['jam']."' > </p>"; } else { $nestedData[] = "<p style='font-size:15px' align='right' class='gk_bisa_edit_tanggal'> ".$row['tanggal']." ".$row['jam']." </p>"; } if ($otoritas_tombol['hapus_produk_inap'] > 0) { $nestedData[] = "<button class='btn btn-danger btn-sm btn-hapus-tbs' id='hapus-tbs-".$row['id']."' data-id='". $row['id'] ."' data-kode-barang='". $row['kode_barang'] ."' data-barang='". $row['nama_barang'] ."' data-subtotal='". $row['subtotal'] ."' data-tipe='".$row['tipe_barang']."'>Hapus</button>"; } else{ $nestedData[] = "<p style='font-size:15px; color:red'> Tidak Ada Otoritas</p>"; } $nestedData[] = $row["id"]; $data[] = $nestedData; } $json_data = array( "draw" => intval( $requestData['draw'] ), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw. "recordsTotal" => intval( $totalData ), // total number of records "recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData "data" => $data // total data array ); echo json_encode($json_data); // send data as json format ?>
gpl-2.0
crito/syrianarchive
database/translation.py
1554
from modeltranslation.translator import translator, TranslationOptions from database.models import * class DatabaseEntryTranslationOptions(TranslationOptions): fields = ('name', 'description', 'chain_of_custody_notes_public', 'international_instrument_notes', 'landmarks', 'weather_in_media', 'weapons_used', 'urls_and_news', 'acquired_from', ) class InternationalInstrumentTranslationOptions(TranslationOptions): fields = ('name',) class MediaContentTypeTranslationOptions(TranslationOptions): fields = ('name',) class SourceConnectionTranslationOptions(TranslationOptions): fields = ('name',) class LocationPlaceTranslationOptions(TranslationOptions): fields = ('name',) class DeviceTranslationOptions(TranslationOptions): fields = ('name',) class ViolationTypeTranslationOptions(TranslationOptions): fields = ('name',) class CollectionTranslationOptions(TranslationOptions): fields = ('name', 'description') translator.register(DatabaseEntry, DatabaseEntryTranslationOptions) translator.register(MediaContentType, MediaContentTypeTranslationOptions) translator.register(InternationalInstrument, InternationalInstrumentTranslationOptions) translator.register(SourceConnection, SourceConnectionTranslationOptions) translator.register(LocationPlace, LocationPlaceTranslationOptions) translator.register(Device, DeviceTranslationOptions) translator.register(ViolationType, ViolationTypeTranslationOptions) translator.register(Collection, CollectionTranslationOptions)
gpl-2.0
briot/geneapro
backend/geneaprove/views/stats.py
5608
""" Statistics """ import collections import datetime from django.db.models import Count, F import logging from .. import models from ..utils.date import DateRange from ..sql import PersonSet, Relationship from .to_json import JSONView logger = logging.getLogger('geneaprove.STATS') class StatsView(JSONView): """Display the statistics for a given person""" def get_json(self, params, id): # pylint: disable=redefined-builtin # pylint: disable=arguments-differ max_age = int(params.get('max_age', '0')) bar_width = int(params.get('bar_width', '5')) # ??? The stats includes persons "Unknown" that were created during a # gedcom import for the purpose of preserving families. Will be fixed # when we store children differently (for instance in a group) persons = PersonSet() persons.add_folks(person_id=int(id), relationship=Relationship.ANCESTORS) persons.add_folks(person_id=int(id), relationship=Relationship.DESCENDANTS) persons.fetch_p2e() # compute births and deaths logger.debug('count persons in tree') fathers = [p for p in persons.persons.values() if p.sex == 'M'] mothers = [p for p in persons.persons.values() if p.sex == 'F'] # Compute birth and death dates for all persons, taking into account # the max_age setting logger.debug('parse dates') current_year = datetime.datetime.now().year dates = {} for p in persons.persons.values(): b_year = DateRange(p.birthISODate).year() \ if p.birthISODate else None d_year = DateRange(p.deathISODate).year() \ if p.deathISODate else None if not d_year and max_age > 0: if b_year: d_year = min(b_year + max_age, current_year) else: # no birth nor death known pass dates[p.main_id] = [b_year, d_year] # Group persons by generations. Do not use a recursive approach, since # it will fail with large numbers of generations distance = persons.compute_generations(gen_0_ids=[int(id)]) generations = collections.defaultdict(list) for main_id, gen in distance.items(): generations[gen].append(main_id) # Compute timespans for generations logger.debug('compute timespans') ranges = [] for index in sorted(generations): births = None deaths = None gen_range = [index + 1, "?", "?", ""] # gen, min, max, legend for main_id in generations[index]: a = dates[main_id] if a[0] and (births is None or a[0] < births): births = a[0] gen_range[1] = a[0] if a[1] and (deaths is None or a[1] > deaths): deaths = a[1] gen_range[2] = a[1] if index >= 16: gen_range[3] = f"Gen. {index + 1:02d} ({len(generations[index])}) {gen_range[1]} - {gen_range[2]}" elif index >= 0 and index <= 16: gen_range[3] = f"Gen. {index + 1:02d} ({len(generations[index])} / {2 ** index}) {gen_range[1]} - {gen_range[2]}" else: # No need to count maximum number of persons, this becomes # too large, and irrelevant since there is implex gen_range[3] = f"Desc. {-index:02d} ({len(generations[index])}) {gen_range[1]} - {gen_range[2]}" # Postprocess the ranges: # generation n's earliest date has to be at least 15 years before # its children's earliest date (can't have children before # that) # generation n's latest date (death) has to be after the # children's generation earliest date (first birth) if len(ranges) > 0: if gen_range[1] == "?": gen_range[1] = ranges[-1][1] - 15 if gen_range[2] == "?" or gen_range[2] < ranges[-1][1]: gen_range[2] = ranges[-1][1] if gen_range[2] == '?': gen_range[2] = datetime.datetime.now().year ranges.append(gen_range) # Compute the age pyramid logger.debug('group by age') ages = [] # date_range, males, females, unknown for main_id in persons.persons: a = dates[main_id] if a[0] and a[1]: # age could be negative in some invalid files age = max(0, int((a[1] - a[0]) / bar_width)) for b in range(len(ages), age + 1): ages.append([b * bar_width, 0, 0, 0]) p = persons.get_from_id(main_id) if p.sex == "M": ages[age][1] += 1 elif p.sex == "F": ages[age][2] += 1 else: ages[age][3] += 1 total_in_db = models.Persona.objects \ .filter(id=F('main_id')).aggregate(count=Count('id')) decujus = persons.get_from_id(int(id)) return { "total_ancestors": len(persons.persons), "total_father": len(fathers), "total_mother": len(mothers), "total_persons": int(total_in_db['count']), "ranges": ranges, "ages": ages, "decujus": decujus.main_id, "decujus_name": decujus.display_name, }
gpl-2.0
lioncash/dolphin
Source/Core/DiscIO/NANDImporter.cpp
9221
// Copyright 2017 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include "DiscIO/NANDImporter.h" #include <algorithm> #include <array> #include <cinttypes> #include <cstring> #include <fmt/format.h> #include "Common/Crypto/AES.h" #include "Common/File.h" #include "Common/FileUtil.h" #include "Common/Logging/Log.h" #include "Common/MsgHandler.h" #include "Common/Swap.h" #include "Core/IOS/ES/Formats.h" namespace DiscIO { constexpr size_t NAND_SIZE = 0x20000000; constexpr size_t NAND_KEYS_SIZE = 0x400; NANDImporter::NANDImporter() = default; NANDImporter::~NANDImporter() = default; void NANDImporter::ImportNANDBin(const std::string& path_to_bin, std::function<void()> update_callback, std::function<std::string()> get_otp_dump_path) { m_update_callback = std::move(update_callback); if (!ReadNANDBin(path_to_bin, get_otp_dump_path)) return; const std::string nand_root = File::GetUserPath(D_WIIROOT_IDX); m_nand_root_length = nand_root.length(); if (nand_root.back() == '/') m_nand_root_length++; FindSuperblock(); ProcessEntry(0, nand_root); ExportKeys(nand_root); ExtractCertificates(nand_root); } bool NANDImporter::ReadNANDBin(const std::string& path_to_bin, std::function<std::string()> get_otp_dump_path) { constexpr size_t NAND_TOTAL_BLOCKS = 0x40000; constexpr size_t NAND_BLOCK_SIZE = 0x800; constexpr size_t NAND_ECC_BLOCK_SIZE = 0x40; constexpr size_t NAND_BIN_SIZE = (NAND_BLOCK_SIZE + NAND_ECC_BLOCK_SIZE) * NAND_TOTAL_BLOCKS; // 0x21000000 File::IOFile file(path_to_bin, "rb"); const u64 image_size = file.GetSize(); if (image_size != NAND_BIN_SIZE + NAND_KEYS_SIZE && image_size != NAND_BIN_SIZE) { PanicAlertT("This file does not look like a BootMii NAND backup."); return false; } m_nand.resize(NAND_SIZE); for (size_t i = 0; i < NAND_TOTAL_BLOCKS; i++) { // Instead of updating on every cycle, we only update every 1000 cycles for a balance between // not updating fast enough vs updating too fast if (i % 1000 == 0) m_update_callback(); file.ReadBytes(&m_nand[i * NAND_BLOCK_SIZE], NAND_BLOCK_SIZE); file.Seek(NAND_ECC_BLOCK_SIZE, SEEK_CUR); // We don't care about the ECC blocks } m_nand_keys.resize(NAND_KEYS_SIZE); // Read the OTP/SEEPROM dump. // If it is not included in the NAND image, get a path to the dump and read key data from it. if (image_size == NAND_BIN_SIZE) { const std::string otp_dump_path = get_otp_dump_path(); if (otp_dump_path.empty()) return false; File::IOFile keys_file{otp_dump_path, "rb"}; return keys_file.ReadBytes(m_nand_keys.data(), NAND_KEYS_SIZE); } // Otherwise, just read the key data from the NAND image. return file.ReadBytes(m_nand_keys.data(), NAND_KEYS_SIZE); } void NANDImporter::FindSuperblock() { constexpr size_t NAND_SUPERBLOCK_START = 0x1fc00000; constexpr size_t NAND_SUPERBLOCK_SIZE = 0x40000; size_t superblock = 0; u32 newest_version = 0; for (size_t pos = NAND_SUPERBLOCK_START; pos < NAND_SIZE; pos += NAND_SUPERBLOCK_SIZE) { if (!memcmp(m_nand.data() + pos, "SFFS", 4)) { u32 version = Common::swap32(&m_nand[pos + 4]); INFO_LOG(DISCIO, "Found superblock at 0x%zx with version 0x%x", pos, version); if (superblock == 0 || version > newest_version) { superblock = pos; newest_version = version; } } } m_nand_fat_offset = superblock + 0xC; m_nand_fst_offset = m_nand_fat_offset + 0x10000; INFO_LOG(DISCIO, "Using superblock version 0x%x at position 0x%zx. FAT/FST offset: 0x%zx/0x%zx", newest_version, superblock, m_nand_fat_offset, m_nand_fst_offset); } std::string NANDImporter::GetPath(const NANDFSTEntry& entry, const std::string& parent_path) { std::string name(entry.name, strnlen(entry.name, sizeof(NANDFSTEntry::name))); if (name.front() == '/' || parent_path.back() == '/') return parent_path + name; return parent_path + '/' + name; } std::string NANDImporter::FormatDebugString(const NANDFSTEntry& entry) { return fmt::format( "{:12.12} {:#04x} {:#04x} {:#06x} {:#06x} {:#010x} {:#06x} {:#06x} {:#06x} {:#010x}", entry.name, entry.mode, entry.attr, entry.sub, entry.sib, entry.size, entry.x1, entry.uid, entry.gid, entry.x3); } void NANDImporter::ProcessEntry(u16 entry_number, const std::string& parent_path) { NANDFSTEntry entry; memcpy(&entry, &m_nand[m_nand_fst_offset + sizeof(NANDFSTEntry) * Common::swap16(entry_number)], sizeof(NANDFSTEntry)); if (entry.sib != 0xffff) ProcessEntry(entry.sib, parent_path); if ((entry.mode & 3) == 1) ProcessFile(entry, parent_path); else if ((entry.mode & 3) == 2) ProcessDirectory(entry, parent_path); else ERROR_LOG(DISCIO, "Unknown mode: %s", FormatDebugString(entry).c_str()); } void NANDImporter::ProcessDirectory(const NANDFSTEntry& entry, const std::string& parent_path) { m_update_callback(); INFO_LOG(DISCIO, "Path: %s", FormatDebugString(entry).c_str()); const std::string path = GetPath(entry, parent_path); File::CreateDir(path); if (entry.sub != 0xffff) ProcessEntry(entry.sub, path); INFO_LOG(DISCIO, "Path: %s", parent_path.c_str() + m_nand_root_length); } void NANDImporter::ProcessFile(const NANDFSTEntry& entry, const std::string& parent_path) { constexpr size_t NAND_AES_KEY_OFFSET = 0x158; constexpr size_t NAND_FAT_BLOCK_SIZE = 0x4000; m_update_callback(); INFO_LOG(DISCIO, "File: %s", FormatDebugString(entry).c_str()); const std::string path = GetPath(entry, parent_path); File::IOFile file(path, "wb"); std::array<u8, 16> key{}; std::copy(&m_nand_keys[NAND_AES_KEY_OFFSET], &m_nand_keys[NAND_AES_KEY_OFFSET + key.size()], key.begin()); u16 sub = Common::swap16(entry.sub); u32 remaining_bytes = Common::swap32(entry.size); while (remaining_bytes > 0) { std::array<u8, 16> iv{}; std::vector<u8> block = Common::AES::Decrypt( key.data(), iv.data(), &m_nand[NAND_FAT_BLOCK_SIZE * sub], NAND_FAT_BLOCK_SIZE); u32 size = remaining_bytes < NAND_FAT_BLOCK_SIZE ? remaining_bytes : NAND_FAT_BLOCK_SIZE; file.WriteBytes(block.data(), size); remaining_bytes -= size; sub = Common::swap16(&m_nand[m_nand_fat_offset + 2 * sub]); } } bool NANDImporter::ExtractCertificates(const std::string& nand_root) { const std::string content_dir = nand_root + "/title/00000001/0000000d/content/"; File::IOFile tmd_file(content_dir + "title.tmd", "rb"); std::vector<u8> tmd_bytes(tmd_file.GetSize()); if (!tmd_file.ReadBytes(tmd_bytes.data(), tmd_bytes.size())) { ERROR_LOG(DISCIO, "ExtractCertificates: Could not read IOS13 TMD"); return false; } IOS::ES::TMDReader tmd(std::move(tmd_bytes)); IOS::ES::Content content_metadata; if (!tmd.GetContent(tmd.GetBootIndex(), &content_metadata)) { ERROR_LOG(DISCIO, "ExtractCertificates: Could not get content ID from TMD"); return false; } File::IOFile content_file(content_dir + fmt::format("{:08x}.app", content_metadata.id), "rb"); std::vector<u8> content_bytes(content_file.GetSize()); if (!content_file.ReadBytes(content_bytes.data(), content_bytes.size())) { ERROR_LOG(DISCIO, "ExtractCertificates: Could not read IOS13 contents"); return false; } struct PEMCertificate { std::string filename; std::array<u8, 4> search_bytes; }; std::array<PEMCertificate, 3> certificates = {{ {"/clientca.pem", {{0x30, 0x82, 0x03, 0xE9}}}, {"/clientcakey.pem", {{0x30, 0x82, 0x02, 0x5D}}}, {"/rootca.pem", {{0x30, 0x82, 0x03, 0x7D}}}, }}; for (const PEMCertificate& certificate : certificates) { const auto search_result = std::search(content_bytes.begin(), content_bytes.end(), certificate.search_bytes.begin(), certificate.search_bytes.end()); if (search_result == content_bytes.end()) { ERROR_LOG(DISCIO, "ExtractCertificates: Could not find offset for certficate '%s'", certificate.filename.c_str()); return false; } const std::string pem_file_path = nand_root + certificate.filename; const ptrdiff_t certificate_offset = std::distance(content_bytes.begin(), search_result); const u16 certificate_size = Common::swap16(&content_bytes[certificate_offset - 2]); INFO_LOG(DISCIO, "ExtractCertificates: '%s' offset: 0x%tx size: 0x%x", certificate.filename.c_str(), certificate_offset, certificate_size); File::IOFile pem_file(pem_file_path, "wb"); if (!pem_file.WriteBytes(&content_bytes[certificate_offset], certificate_size)) { ERROR_LOG(DISCIO, "ExtractCertificates: Unable to write to file %s", pem_file_path.c_str()); return false; } } return true; } void NANDImporter::ExportKeys(const std::string& nand_root) { const std::string file_path = nand_root + "/keys.bin"; File::IOFile file(file_path, "wb"); if (!file.WriteBytes(m_nand_keys.data(), NAND_KEYS_SIZE)) PanicAlertT("Unable to write to file %s", file_path.c_str()); } } // namespace DiscIO
gpl-2.0
MersadBase/MersadBase
AdvancedPlans/Penalty.cpp
3291
/* * Copyright 2002-2010, Mersad Team, Allameh Helli High School (NODET). * * 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. * * 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 Library General Public License for more details. * * This file is created by: Mehrdad Bakhtiari * * Released on Sunday 9 July 2010, 17 Tir 1389 by Mersad RoboCup Team. * For more information please read README file. */ #include <Penalty.h> #include <cmath> #include <Vector.h> #include <BasicKick.h> #include <Command.h> #include <FastIC.h> #include <Intercept.h> #include <Logger.h> #include <Rectangle.h> #include <vector> #include <Dribble.h> #include <BasicDash.h> #include <WorldModel.h> #include <Tackle.h> #include <BasicTackle.h> #include <Basics.h> #include <Degree.h> using namespace std; using namespace Degree; using namespace Basics; void Penalty::execute(Form& form) { const float dist_thr = 1.0, dir_thr = 15, dash_power = 90; Point homePos = getPos(worldModel->getBody().getUniNum()); LOG << "my homePos : " << homePos << endl; command = new EmptyCommand(); LOG << "ourKicker : " << worldModel->getOurPenaltyKicker() << endl; switch (worldModel->getPlayMode()) { case PM_PENALTY_SETUP: case PM_PENALTY_READY: { LOG << "its our turn" << endl; if (worldModel->getOurPenaltyKicker() == worldModel->getBody().getUniNum()) // decide for kicker doKicker(form); else // decide for other players command = PerfectGotoPoint(homePos, worldModel->getBody(), dist_thr, dash_power).getCommand(); } break; case PM_PENALTY_SETUP_OPP: case PM_PENALTY_READY_OPP: default: if (worldModel->getBody().isGoalie()) homePos = Point(-40, 0.f); if (worldModel->getBody().isGoalie() and worldModel->getVirtualPlayMode() == VPM_PENALTY_TAKEN_OPP) // decide for goalie obtainBall(form); else // decide for other players command = PerfectGotoPoint(homePos, worldModel->getBody(), dist_thr, dash_power).getCommand(); break; } } void Penalty::doKicker(Form& form) { if (worldModel->isBallKickable() and worldModel->getPlayMode() == PM_PENALTY_READY) { LOG << "ball is in kickable area" << endl; // **** it's your task to decide about kicker! } else { LOG << "return intercept" << endl; Intercept intercept = Intercept(worldModel); intercept.getValue(); intercept.execute(form); command = intercept.getCommand(); } } void Penalty::obtainBall(Form& form) { if (worldModel->isBallKickable()) { command = FastKickToPoint(Point(0.0, 0.0), worldModel->getBall(), worldModel->getBody()).getCommand(); } else { // A simple action is intercepting ball LOG << "return intercept" << endl; Intercept intercept = Intercept(worldModel); intercept.getValue(); intercept.execute(form); command = intercept.getCommand(); } } Point Penalty::getPos(unsigned num) { if (num == 1) return Point(-54, 25); Point pos; pos.x = -5 + (int)num - 1; pos.y = num % 2? 5 : -5; return pos; } Command* Penalty::getCommand() { return command; }
gpl-2.0
daniambrosio/numis
spec/views/sub_categories/new.html.erb_spec.rb
539
# require 'rails_helper' # RSpec.describe "sub_categories/new", type: :view do # before(:each) do # assign(:sub_category, SubCategory.new( # :name => "MyString", # :system => false # )) # end # it "renders new sub_category form" do # render # assert_select "form[action=?][method=?]", sub_categories_path, "post" do # assert_select "input#sub_category_name[name=?]", "sub_category[name]" # assert_select "input#sub_category_system[name=?]", "sub_category[system]" # end # end # end
gpl-2.0
acassis/langc
MDC.C
1293
#include<stdio.h> void main() { int m,n,k,j,i,col=20,r=0; char *ta; clrscr(); puts("Este Programa calcula o maximo divisor comum entre dois n§!"); printf("\nInforme um n§:"); scanf("%d",&m); printf("\nInforme outro n§:"); scanf("%d",&n); clrscr(); while(n!=0) { itoa(m,ta,10); i = strlen(ta); gotoxy(col,11); printf("%s",ta); gotoxy(col,13); printf("%d",m%n); if(m<r) { itoa(r,ta,10); i = strlen(ta); } for(j=0;j<i;j++) { gotoxy(col,10); printf("Ä"); gotoxy(col,12); printf("Ä"); col++; } gotoxy(col,9); printf("³"); gotoxy(col,10); printf("Å"); gotoxy(col,11); printf("³"); gotoxy(col,12); printf("Å"); gotoxy(col,13); printf("³"); col++; gotoxy(col,9); printf("%d",m/n); r = m/n; gotoxy(col,11); printf("%d",n); k = (m%n); m = n; n = k; } itoa(m,ta,10); i = strlen(ta); if(m<r) { itoa(r,ta,10); i = strlen(ta); } for(j=0;j<i;j++) { gotoxy(col,10); printf("Ä"); gotoxy(col,12); printf("Ä"); col++; } gotoxy(20,24); printf("O maximo divisor comum e : %d",m); getch(); }
gpl-2.0
rikanov/Rubik-Dev
global_variables.cpp
120
#include "globals.h" const char * NIL="NIL"; const char * L_TRUE="T"; const char * MACRO_SYNTAX="([^ ]+)\\(([^ ]+)\\)";
gpl-2.0
sanger/labwhere
app/models/location_finder.rb
2158
# frozen_string_literal: true require 'csv' class LocationFinder include ActiveModel::Model validate :check_number_of_columns attr_accessor :file def data # we could have an empty file we have a validation for that # this removes the need for any expensive logic. @data ||= ::CSV.parse(file || "") end def barcodes @barcodes ||= formatted_data end # this is only a single column file so we can flatten it. # remove any blanks and duplicates # no need to error it as it a report def formatted_data data.flatten.compact.collect { |barcode| barcode.try(:strip) } end def results @results ||= {} end def run return unless valid? find_locations end def csv @csv ||= create_csv end private def create_csv CSV.generate do |csv| csv << csv_headers results.each do |k, v| csv << create_csv_row(k, v) end end end def csv_headers %w[labware_barcode labware_exists location_barcode location_name location_parentage] end # produces a row for each record # 0 - labware barcode - original barcode passed from the file # 1 - labware_exists - Yes/No - depending on whether the labware does exist # 2 - location_barcode - barcode of the location where labware is stored - Empty if doesn't exist # 3 - location_name - name of location where labware is stored - Empty of doesn't exist # 4 - Location_parentage - where is the location? - Empty if does not exist def create_csv_row(labware_barcode, labware) [ labware_barcode, labware.exists, labware.location.barcode, labware.location.name, labware.location.parentage ] end def find_locations barcodes.each do |barcode| results[barcode] = Labware.includes(:location).find_by(barcode: barcode) || NullLabware.new end end def check_number_of_columns # again we could have some expensive logic but this will cover empty files and multiple columns return if data.try(:first).try(:length) == 1 errors.add(:base, 'There is something wrong with the file. There should only be 1 column with barcodes.') end end
gpl-2.0
deadlyhifi/woocomm-nested-layered-nav
src/WidgetNestedLayeredNav.php
4361
<?php class WidgetNestedLayeredNav extends WC_Widget_Layered_Nav { /** * Show list based layered nav. * @param array $terms * @param string $taxonomy * @param string $query_type * @return bool Will nav display? */ protected function layered_nav_list( $terms, $taxonomy, $query_type ) { $term_counts = $this->get_filtered_term_product_counts( wp_list_pluck( $terms, 'term_id' ), $taxonomy, $query_type ); $_chosen_attributes = WC_Query::get_layered_nav_chosen_attributes(); $found = false; $hierarchy = []; foreach ( $terms as $term ) { $current_values = isset( $_chosen_attributes[ $taxonomy ]['terms'] ) ? $_chosen_attributes[ $taxonomy ]['terms'] : array(); $option_is_set = in_array( $term->slug, $current_values ); $count = isset( $term_counts[ $term->term_id ] ) ? $term_counts[ $term->term_id ] : 0; // skip the term for the current archive if ($count === 0 || $this->get_current_term_id() === $term->term_id) { continue; } // Only show options with count > 0 if ( 0 < $count ) { $found = true; } elseif ( 'and' === $query_type && 0 < $count && ! $option_is_set ) { continue; } $filter_name = 'filter_' . sanitize_title( str_replace( 'pa_', '', $taxonomy ) ); $current_filter = isset( $_GET[ $filter_name ] ) ? explode( ',', wc_clean( $_GET[ $filter_name ] ) ) : array(); $current_filter = array_map( 'sanitize_title', $current_filter ); if ( ! in_array( $term->slug, $current_filter ) ) { $current_filter[] = $term->slug; } $link = $this->get_page_base_url( $taxonomy ); // Add current filters to URL. foreach ( $current_filter as $key => $value ) { // Exclude query arg for current term archive term if ( $value === $this->get_current_term_slug() ) { unset( $current_filter[ $key ] ); } // Exclude self so filter can be unset on click. if ( $option_is_set && $value === $term->slug ) { unset( $current_filter[ $key ] ); } } if ( ! empty( $current_filter ) ) { $link = add_query_arg( $filter_name, implode( ',', $current_filter ), $link ); // Add Query type Arg to URL if ( $query_type === 'or' && ! ( 1 === sizeof( $current_filter ) && $option_is_set ) ) { $link = add_query_arg( 'query_type_' . sanitize_title( str_replace( 'pa_', '', $taxonomy ) ), 'or', $link ); } } if ((int) $term->parent === 0) { $hierarchy[$term->term_id]['parent'] = $this->build_list_item($term, 'parent', $option_is_set, $count, $link); } else { $hierarchy[$term->parent]['children'][] = $this->build_list_item($term, 'child', $option_is_set, $count, $link); } } // List display echo '<ul>'; foreach ($hierarchy as $filter) { echo $filter['parent']; if (isset($filter['children']) && ! empty(array_filter($filter['children']))) { echo '<ul>'; foreach ($filter['children'] as $child) { echo $child . '</li>'; } echo '</ul>'; } echo '</li>'; // close list } echo '</ul>'; return $found; } protected function build_list_item($term, $relationhip, $option_is_set, $count, $link) { $listItem = '<li class="wc-layered-nav-term' . ' ' . $relationhip . ( $option_is_set ? ' chosen' : '' ) . '">'; $listItem .= ( $count > 0 || $option_is_set ) ? '<a href="' . esc_url( apply_filters( 'woocommerce_layered_nav_link', $link ) ) . '">' : '<span>'; $listItem .= esc_html( $term->name ); $listItem .= ( $count > 0 || $option_is_set ) ? '</a> ' : '</span> '; $listItem .= apply_filters( 'woocommerce_layered_nav_count', '<span class="count">(' . absint( $count ) . ')</span>', $count, $term ); return $listItem; } }
gpl-2.0
34benma/openjdk
jaxp/test/javax/xml/jaxp/unittest/stream/XMLStreamReaderTest/IsValidatingTest.java
6360
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package stream.XMLStreamReaderTest; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.XMLEvent; import org.testng.Assert; import org.testng.annotations.Test; /* * @bug 6440324 * @summary Test StAX can accept non-existent DTD if IS_VALIDATING if false. */ public class IsValidatingTest { /** * File with non-existent DTD. */ private static final String INPUT_FILE = "IsValidatingTest.xml"; /** * File with internal subset and non-existent DTD. */ private static final String INPUT_FILE_INTERNAL_SUBSET = "IsValidatingTestInternalSubset.xml"; /** * Test StAX with IS_VALIDATING = false and a non-existent DTD. * Test should pass. * * Try to parse an XML file that references a a non-existent DTD. * Desired behavior: * If IS_VALIDATING == false, then continue processing. * * Note that an attempt is made to read the DTD even if IS_VALIDATING == false. * This is not required for DTD validation, but for entity resolution. * The XML specification allows the optional reading of an external DTD * even for non-validating processors. * */ @Test public void testStAXIsValidatingFalse() { XMLStreamReader reader = null; Boolean isValidating = null; String propertyValues = null; boolean dtdEventOccured = false; XMLInputFactory xif = XMLInputFactory.newInstance(); xif.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE); try { reader = xif.createXMLStreamReader(this.getClass().getResource(INPUT_FILE).toExternalForm(), this.getClass().getResourceAsStream(INPUT_FILE)); isValidating = (Boolean) reader.getProperty(XMLInputFactory.IS_VALIDATING); propertyValues = "IS_VALIDATING=" + isValidating; while (reader.hasNext()) { int e = reader.next(); if (e == XMLEvent.DTD) { dtdEventOccured = true; System.out.println("testStAXIsValidatingFalse(): " + "reader.getText() with Event == DTD: " + reader.getText()); } } // expected success // should have see DTD Event if (!dtdEventOccured) { Assert.fail("Unexpected failure: did not see DTD event"); } } catch (Exception e) { // unexpected failure System.err.println("Exception with reader.getEventType(): " + reader.getEventType()); e.printStackTrace(); Assert.fail("Unexpected failure with " + propertyValues + ", " + e.toString()); } } /** * Test StAX with IS_VALIDATING = false, an internal subset and a * non-existent DTD. * * Test should pass. */ @Test public void testStAXIsValidatingFalseInternalSubset() { XMLStreamReader reader = null; Boolean isValidating = null; String propertyValues = null; boolean dtdEventOccured = false; boolean entityReferenceEventOccured = false; XMLInputFactory xif = XMLInputFactory.newInstance(); xif.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE); xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.FALSE); try { reader = xif.createXMLStreamReader(this.getClass().getResource(INPUT_FILE).toExternalForm(), this.getClass().getResourceAsStream(INPUT_FILE_INTERNAL_SUBSET)); isValidating = (Boolean) reader.getProperty(XMLInputFactory.IS_VALIDATING); propertyValues = "IS_VALIDATING=" + isValidating; while (reader.hasNext()) { int e = reader.next(); if (e == XMLEvent.DTD) { dtdEventOccured = true; System.out.println("testStAXIsValidatingFalseInternalSubset(): " + "reader.getText() with Event == DTD: " + reader.getText()); } else if (e == XMLEvent.ENTITY_REFERENCE) { // expected ENTITY_REFERENCE values? if (reader.getLocalName().equals("foo") && reader.getText().equals("bar")) { entityReferenceEventOccured = true; } System.out.println("testStAXIsValidatingFalseInternalSubset(): " + "reader.get(LocalName, Text)() with Event " + " == ENTITY_REFERENCE: " + reader.getLocalName() + " = " + reader.getText()); } } // expected success // should have see DTD Event if (!dtdEventOccured) { Assert.fail("Unexpected failure: did not see DTD event"); } // should have seen an ENITY_REFERENCE Event if (!entityReferenceEventOccured) { Assert.fail("Unexpected failure: did not see ENTITY_REFERENCE event"); } } catch (Exception e) { // unexpected failure System.err.println("Exception with reader.getEventType(): " + reader.getEventType()); e.printStackTrace(); Assert.fail("Unexpected failure with " + propertyValues + ", " + e.toString()); } } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/jaxws/drop_included/jaxws_src/src/com/sun/xml/internal/rngom/parse/compact/JavaCharStream.java
13989
/* * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ /* Generated By:JavaCC: Do not edit this line. JavaCharStream.java Version 3.0 */ package com.sun.xml.internal.rngom.parse.compact; /** * An implementation of interface CharStream, where the stream is assumed to * contain only ASCII characters (with java-like unicode escape processing). */ public class JavaCharStream { public static final boolean staticFlag = false; static final int hexval(char c) throws java.io.IOException { switch(c) { case '0' : return 0; case '1' : return 1; case '2' : return 2; case '3' : return 3; case '4' : return 4; case '5' : return 5; case '6' : return 6; case '7' : return 7; case '8' : return 8; case '9' : return 9; case 'a' : case 'A' : return 10; case 'b' : case 'B' : return 11; case 'c' : case 'C' : return 12; case 'd' : case 'D' : return 13; case 'e' : case 'E' : return 14; case 'f' : case 'F' : return 15; } throw new java.io.IOException(); // Should never come here } public int bufpos = -1; int bufsize; int available; int tokenBegin; protected int bufline[]; protected int bufcolumn[]; protected int column = 0; protected int line = 1; protected boolean prevCharIsCR = false; protected boolean prevCharIsLF = false; protected java.io.Reader inputStream; protected char[] nextCharBuf; protected char[] buffer; protected int maxNextCharInd = 0; protected int nextCharInd = -1; protected int inBuf = 0; protected void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int newbufline[] = new int[bufsize + 2048]; int newbufcolumn[] = new int[bufsize + 2048]; try { if (wrapAround) { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; bufpos += (bufsize - tokenBegin); } else { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; bufpos -= tokenBegin; } } catch (Throwable t) { throw new Error(t.getMessage()); } available = (bufsize += 2048); tokenBegin = 0; } protected void FillBuff() throws java.io.IOException { int i; if (maxNextCharInd == 4096) maxNextCharInd = nextCharInd = 0; try { if ((i = inputStream.read(nextCharBuf, maxNextCharInd, 4096 - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { if (bufpos != 0) { --bufpos; backup(0); } else { bufline[bufpos] = line; bufcolumn[bufpos] = column; } throw e; } } protected char ReadByte() throws java.io.IOException { if (++nextCharInd >= maxNextCharInd) FillBuff(); return nextCharBuf[nextCharInd]; } public char BeginToken() throws java.io.IOException { if (inBuf > 0) { --inBuf; if (++bufpos == bufsize) bufpos = 0; tokenBegin = bufpos; return buffer[bufpos]; } tokenBegin = 0; bufpos = -1; return readChar(); } protected void AdjustBuffSize() { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = 0; available = tokenBegin; } else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } protected void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r' : prevCharIsCR = true; break; case '\n' : prevCharIsLF = true; break; case '\t' : column--; column += (8 - (column & 07)); break; default : break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; } public char readChar() throws java.io.IOException { if (inBuf > 0) { --inBuf; if (++bufpos == bufsize) bufpos = 0; return buffer[bufpos]; } char c; if (++bufpos == available) AdjustBuffSize(); if ((buffer[bufpos] = c = ReadByte()) == '\\') { UpdateLineColumn(c); int backSlashCnt = 1; for (;;) // Read all the backslashes { if (++bufpos == available) AdjustBuffSize(); try { if ((buffer[bufpos] = c = ReadByte()) != '\\') { UpdateLineColumn(c); // found a non-backslash char. if ((c == 'u') && ((backSlashCnt & 1) == 1)) { if (--bufpos < 0) bufpos = bufsize - 1; break; } backup(backSlashCnt); return '\\'; } } catch(java.io.IOException e) { if (backSlashCnt > 1) backup(backSlashCnt); return '\\'; } UpdateLineColumn(c); backSlashCnt++; } // Here, we have seen an odd number of backslash's followed by a 'u' try { while ((c = ReadByte()) == 'u') ++column; buffer[bufpos] = c = (char)(hexval(c) << 12 | hexval(ReadByte()) << 8 | hexval(ReadByte()) << 4 | hexval(ReadByte())); column += 4; } catch(java.io.IOException e) { throw new Error("Invalid escape character at line " + line + " column " + column + "."); } if (backSlashCnt == 1) return c; else { backup(backSlashCnt - 1); return '\\'; } } else { UpdateLineColumn(c); return (c); } } /** * @deprecated * @see #getEndColumn */ public int getColumn() { return bufcolumn[bufpos]; } /** * @deprecated * @see #getEndLine */ public int getLine() { return bufline[bufpos]; } public int getEndColumn() { return bufcolumn[bufpos]; } public int getEndLine() { return bufline[bufpos]; } public int getBeginColumn() { return bufcolumn[tokenBegin]; } public int getBeginLine() { return bufline[tokenBegin]; } public void backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; } public JavaCharStream(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; nextCharBuf = new char[4096]; } public JavaCharStream(java.io.Reader dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } public JavaCharStream(java.io.Reader dstream) { this(dstream, 1, 1, 4096); } public void ReInit(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; if (buffer == null || buffersize != buffer.length) { available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; nextCharBuf = new char[4096]; } prevCharIsLF = prevCharIsCR = false; tokenBegin = inBuf = maxNextCharInd = 0; nextCharInd = bufpos = -1; } public void ReInit(java.io.Reader dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } public void ReInit(java.io.Reader dstream) { ReInit(dstream, 1, 1, 4096); } public JavaCharStream(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { this(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096); } public JavaCharStream(java.io.InputStream dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } public JavaCharStream(java.io.InputStream dstream) { this(dstream, 1, 1, 4096); } public void ReInit(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096); } public void ReInit(java.io.InputStream dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } public void ReInit(java.io.InputStream dstream) { ReInit(dstream, 1, 1, 4096); } public String GetImage() { if (bufpos >= tokenBegin) return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); else return new String(buffer, tokenBegin, bufsize - tokenBegin) + new String(buffer, 0, bufpos + 1); } public char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); else { System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; } public void Done() { nextCharBuf = null; buffer = null; bufline = null; bufcolumn = null; } /** * Method to adjust line and column numbers for the start of a token. */ public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; } }
gpl-2.0