code
stringlengths
4
1.01M
language
stringclasses
2 values
#ifndef UI_UNDOVIEW_H #define UI_UNDOVIEW_H #include <QtWidgets/QUndoView> namespace ui { class UndoView : public QUndoView { Q_OBJECT public: explicit UndoView(QWidget *parent = 0); signals: public slots: }; } // namespace ui #endif // UI_UNDOVIEW_H
Java
<?php global $post; if( tie_get_option( 'archives_socail' ) ):?> <div class="mini-share-post"> <ul> <li><a href="https://twitter.com/share" class="twitter-share-button" data-url="<?php the_permalink(); ?>" data-text="<?php the_title(); ?>" data-via="<?php echo tie_get_option( 'share_twitter_username' ) ?>" data-lang="en">tweet</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script></li> <li> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="fb-like" data-href="<?php the_permalink(); ?>" data-send="false" data-layout="button_count" data-width="90" data-show-faces="false"></div> </li> <li><div class="g-plusone" data-size="medium" data-href="<?php the_permalink(); ?>"></div> <script type='text/javascript'> (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> </li> <li><script type="text/javascript" src="http://assets.pinterest.com/js/pinit.js"></script><a href="http://pinterest.com/pin/create/button/?url=<?php the_permalink(); ?>&amp;media=<?php echo tie_thumb_src('', 660 ,330); ?>" class="pin-it-button" count-layout="horizontal"><img border="0" src="http://assets.pinterest.com/images/PinExt.png" title="Pin It" /></a></li> </ul> </div> <!-- .share-post --> <?php endif; ?>
Java
/* * Driver for the SGS-Thomson M48T35 Timekeeper RAM chip * * Real Time Clock interface for Linux * * TODO: Implement periodic interrupts. * * Copyright (C) 2000 Silicon Graphics, Inc. * Written by Ulf Carlsson (ulfc@engr.sgi.com) * * Based on code written by Paul Gortmaker. * * This driver allows use of the real time clock (built into * nearly all computers) from user space. It exports the /dev/rtc * interface supporting various ioctl() and also the /proc/rtc * pseudo-file for status information. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * */ #define RTC_VERSION "1.09b" #include <linux/bcd.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/smp_lock.h> #include <linux/types.h> #include <linux/miscdevice.h> #include <linux/ioport.h> #include <linux/fcntl.h> #include <linux/rtc.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/proc_fs.h> #include <asm/m48t35.h> #include <asm/sn/ioc3.h> #include <asm/io.h> #include <asm/uaccess.h> #include <asm/system.h> #include <asm/sn/klconfig.h> #include <asm/sn/sn0/ip27.h> #include <asm/sn/sn0/hub.h> #include <asm/sn/sn_private.h> static long rtc_ioctl(struct file *filp, unsigned int cmd, unsigned long arg); static int rtc_read_proc(char *page, char **start, off_t off, int count, int *eof, void *data); static void get_rtc_time(struct rtc_time *rtc_tm); /* * Bits in rtc_status. (6 bits of room for future expansion) */ #define RTC_IS_OPEN 0x01 /* means /dev/rtc is in use */ #define RTC_TIMER_ON 0x02 /* missed irq timer active */ static unsigned char rtc_status; /* bitmapped status byte. */ static unsigned long rtc_freq; /* Current periodic IRQ rate */ static struct m48t35_rtc *rtc; /* * If this driver ever becomes modularised, it will be really nice * to make the epoch retain its value across module reload... */ static unsigned long epoch = 1970; /* year corresponding to 0x00 */ static const unsigned char days_in_mo[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; static long rtc_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct rtc_time wtime; switch (cmd) { case RTC_RD_TIME: /* Read the time/date from RTC */ { get_rtc_time(&wtime); break; } case RTC_SET_TIME: /* Set the RTC */ { struct rtc_time rtc_tm; unsigned char mon, day, hrs, min, sec, leap_yr; unsigned int yrs; if (!capable(CAP_SYS_TIME)) return -EACCES; if (copy_from_user(&rtc_tm, (struct rtc_time*)arg, sizeof(struct rtc_time))) return -EFAULT; yrs = rtc_tm.tm_year + 1900; mon = rtc_tm.tm_mon + 1; /* tm_mon starts at zero */ day = rtc_tm.tm_mday; hrs = rtc_tm.tm_hour; min = rtc_tm.tm_min; sec = rtc_tm.tm_sec; if (yrs < 1970) return -EINVAL; leap_yr = ((!(yrs % 4) && (yrs % 100)) || !(yrs % 400)); if ((mon > 12) || (day == 0)) return -EINVAL; if (day > (days_in_mo[mon] + ((mon == 2) && leap_yr))) return -EINVAL; if ((hrs >= 24) || (min >= 60) || (sec >= 60)) return -EINVAL; if ((yrs -= epoch) > 255) /* They are unsigned */ return -EINVAL; if (yrs > 169) return -EINVAL; if (yrs >= 100) yrs -= 100; sec = bin2bcd(sec); min = bin2bcd(min); hrs = bin2bcd(hrs); day = bin2bcd(day); mon = bin2bcd(mon); yrs = bin2bcd(yrs); spin_lock_irq(&rtc_lock); rtc->control |= M48T35_RTC_SET; rtc->year = yrs; rtc->month = mon; rtc->date = day; rtc->hour = hrs; rtc->min = min; rtc->sec = sec; rtc->control &= ~M48T35_RTC_SET; spin_unlock_irq(&rtc_lock); return 0; } default: return -EINVAL; } return copy_to_user((void *)arg, &wtime, sizeof wtime) ? -EFAULT : 0; } /* * We enforce only one user at a time here with the open/close. * Also clear the previous interrupt data on an open, and clean * up things on a close. */ static int rtc_open(struct inode *inode, struct file *file) { lock_kernel(); spin_lock_irq(&rtc_lock); if (rtc_status & RTC_IS_OPEN) { spin_unlock_irq(&rtc_lock); unlock_kernel(); return -EBUSY; } rtc_status |= RTC_IS_OPEN; spin_unlock_irq(&rtc_lock); unlock_kernel(); return 0; } static int rtc_release(struct inode *inode, struct file *file) { /* * Turn off all interrupts once the device is no longer * in use, and clear the data. */ spin_lock_irq(&rtc_lock); rtc_status &= ~RTC_IS_OPEN; spin_unlock_irq(&rtc_lock); return 0; } /* * The various file operations we support. */ static const struct file_operations rtc_fops = { .owner = THIS_MODULE, .unlocked_ioctl = rtc_ioctl, .open = rtc_open, .release = rtc_release, }; static struct miscdevice rtc_dev= { RTC_MINOR, "rtc", &rtc_fops }; static int __init rtc_init(void) { rtc = (struct m48t35_rtc *) (KL_CONFIG_CH_CONS_INFO(master_nasid)->memory_base + IOC3_BYTEBUS_DEV0); printk(KERN_INFO "Real Time Clock Driver v%s\n", RTC_VERSION); if (misc_register(&rtc_dev)) { printk(KERN_ERR "rtc: cannot register misc device.\n"); return -ENODEV; } if (!create_proc_read_entry("driver/rtc", 0, NULL, rtc_read_proc, NULL)) { printk(KERN_ERR "rtc: cannot create /proc/rtc.\n"); misc_deregister(&rtc_dev); return -ENOENT; } rtc_freq = 1024; return 0; } static void __exit rtc_exit (void) { /* interrupts and timer disabled at this point by rtc_release */ remove_proc_entry ("rtc", NULL); misc_deregister(&rtc_dev); } module_init(rtc_init); module_exit(rtc_exit); /* * Info exported via "/proc/rtc". */ static int rtc_get_status(char *buf) { char *p; struct rtc_time tm; /* * Just emulate the standard /proc/rtc */ p = buf; get_rtc_time(&tm); /* * There is no way to tell if the luser has the RTC set for local * time or for Universal Standard Time (GMT). Probably local though. */ p += sprintf(p, "rtc_time\t: %02d:%02d:%02d\n" "rtc_date\t: %04d-%02d-%02d\n" "rtc_epoch\t: %04lu\n" "24hr\t\t: yes\n", tm.tm_hour, tm.tm_min, tm.tm_sec, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, epoch); return p - buf; } static int rtc_read_proc(char *page, char **start, off_t off, int count, int *eof, void *data) { int len = rtc_get_status(page); if (len <= off+count) *eof = 1; *start = page + off; len -= off; if (len>count) len = count; if (len<0) len = 0; return len; } static void get_rtc_time(struct rtc_time *rtc_tm) { /* * Do we need to wait for the last update to finish? */ /* * Only the values that we read from the RTC are set. We leave * tm_wday, tm_yday and tm_isdst untouched. Even though the * RTC has RTC_DAY_OF_WEEK, we ignore it, as it is only updated * by the RTC when initially set to a non-zero value. */ spin_lock_irq(&rtc_lock); rtc->control |= M48T35_RTC_READ; rtc_tm->tm_sec = rtc->sec; rtc_tm->tm_min = rtc->min; rtc_tm->tm_hour = rtc->hour; rtc_tm->tm_mday = rtc->date; rtc_tm->tm_mon = rtc->month; rtc_tm->tm_year = rtc->year; rtc->control &= ~M48T35_RTC_READ; spin_unlock_irq(&rtc_lock); rtc_tm->tm_sec = bcd2bin(rtc_tm->tm_sec); rtc_tm->tm_min = bcd2bin(rtc_tm->tm_min); rtc_tm->tm_hour = bcd2bin(rtc_tm->tm_hour); rtc_tm->tm_mday = bcd2bin(rtc_tm->tm_mday); rtc_tm->tm_mon = bcd2bin(rtc_tm->tm_mon); rtc_tm->tm_year = bcd2bin(rtc_tm->tm_year); /* * Account for differences between how the RTC uses the values * and how they are defined in a struct rtc_time; */ if ((rtc_tm->tm_year += (epoch - 1900)) <= 69) rtc_tm->tm_year += 100; rtc_tm->tm_mon--; }
Java
<!DOCTYPE html> <html> <head> <title>Asterisk Project : Asterisk Standard Channel Variables</title> <link rel="stylesheet" href="styles/site.css" type="text/css" /> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body class="theme-default aui-theme-default"> <div id="page"> <div id="main" class="aui-page-panel"> <div id="main-header"> <div id="breadcrumb-section"> <ol id="breadcrumbs"> <li class="first"> <span><a href="index.html">Asterisk Project</a></span> </li> <li> <span><a href="Configuration-and-Operation_4260139.html">Configuration and Operation</a></span> </li> <li> <span><a href="Channel-Variables_4620340.html">Channel Variables</a></span> </li> </ol> </div> <h1 id="title-heading" class="pagetitle"> <span id="title-text"> Asterisk Project : Asterisk Standard Channel Variables </span> </h1> </div> <div id="content" class="view"> <div class="page-metadata"> Added by mdavenport , edited by mjordan on Aug 11, 2012 </div> <div id="main-content" class="wiki-content group"> <p>There are a number of variables that are defined or read by Asterisk. Here is a listing of them. More information is available in each application's help text. All these variables are in UPPER CASE only.</p> <p>Variables marked with a * are builtin functions and can't be set, only read in the dialplan. Writes to such variables are silently ignored.</p> <h3 id="AsteriskStandardChannelVariables-VariablespresentinAsterisk1.8andforward%3A">Variables present in Asterisk 1.8 and forward:</h3> <ul> <li>${CDR(accountcode)} * - Account code (if specified)</li> <li>${BLINDTRANSFER} - The name of the channel on the other side of a blind transfer</li> <li>${BRIDGEPEER} - Bridged peer</li> <li>${BRIDGEPVTCALLID} - Bridged peer PVT call ID (SIP Call ID if a SIP call)</li> <li>${CALLERID(ani)} * - Caller ANI (PRI channels)</li> <li>${CALLERID(ani2)} * - ANI2 (Info digits) also called Originating line information or OLI</li> <li>${CALLERID(all)} * - Caller ID</li> <li>${CALLERID(dnid)} * - Dialed Number Identifier</li> <li>${CALLERID(name)} * - Caller ID Name only</li> <li>${CALLERID(num)} * - Caller ID Number only</li> <li>${CALLERID(rdnis)} * - Redirected Dial Number ID Service</li> <li>${CALLINGANI2} * - Caller ANI2 (PRI channels)</li> <li>${CALLINGPRES} * - Caller ID presentation for incoming calls (PRI channels)</li> <li>${CALLINGTNS} * - Transit Network Selector (PRI channels)</li> <li>${CALLINGTON} * - Caller Type of Number (PRI channels)</li> <li>${CHANNEL} * - Current channel name</li> <li>${CONTEXT} * - Current context</li> <li>${DATETIME} * - Current date time in the format: DDMMYYYY-HH:MM:SS (Deprecated; use ${STRFTIME(${EPOCH},,%d%m%Y-%H:%M:%S)})</li> <li>${DB_RESULT} - Result value of DB_EXISTS() dial plan function</li> <li>${EPOCH} * - Current unix style epoch</li> <li>${EXTEN} * - Current extension</li> <li>${ENV(VAR)} - Environmental variable VAR</li> <li>${GOTO_ON_BLINDXFR} - Transfer to the specified context/extension/priority after a blind transfer (use ^ characters in place of | to separate context/extension/priority when setting this variable from the dialplan)</li> <li>${HANGUPCAUSE} * - Asterisk cause of hangup (inbound/outbound)</li> <li>${HINT} * - Channel hints for this extension</li> <li>${HINTNAME} * - Suggested Caller*ID name for this extension</li> <li>${INVALID_EXTEN} - The invalid called extension (used in the &quot;i&quot; extension)</li> <li>${LANGUAGE} * - Current language (Deprecated; use ${LANGUAGE()})</li> <li>${LEN(VAR)} - String length of VAR (integer)</li> <li>${PRIORITY} * - Current priority in the dialplan</li> <li>${PRIREDIRECTREASON} - Reason for redirect on PRI, if a call was directed</li> <li>${TIMESTAMP} * - Current date time in the format: YYYYMMDD-HHMMSS (Deprecated; use ${STRFTIME(${EPOCH},,%Y%m%d-%H%M%S)})</li> <li>${TRANSFER_CONTEXT} - Context for transferred calls</li> <li>${FORWARD_CONTEXT} - Context for forwarded calls</li> <li>${DYNAMIC_PEERNAME} - The name of the channel on the other side when a dynamic feature is used.</li> <li>${DYNAMIC_FEATURENAME} The name of the last triggered dynamic feature.</li> <li>${UNIQUEID} * - Current call unique identifier</li> <li>${SYSTEMNAME} * - value of the systemname option of asterisk.conf</li> <li>${ENTITYID} * - Global Entity ID set automatically, or from asterisk.conf</li> </ul> <h3 id="AsteriskStandardChannelVariables-VariablespresentinAsterisk11andforward%3A">Variables present in Asterisk 11 and forward:</h3> <ul> <li>${AGIEXITONHANGUP} - set to <code>1</code> to force the behavior of a call to AGI to behave as it did in 1.4, where the AGI script would exit immediately on detecting a channel hangup</li> <li>${CALENDAR_SUCCESS} * - Status of the <a href="https://wiki.asterisk.org/wiki/display/AST/Asterisk+11+Function_CALENDAR_WRITE">CALENDAR_WRITE</a> function. Set to <code>1</code> if the function completed successfully; <code>0</code> otherwise.</li> <li>${SIP_RECVADDR} * - the address a SIP MESSAGE request was received from</li> <li>${VOICEMAIL_PLAYBACKSTATUS} * - Status of the <a href="https://wiki.asterisk.org/wiki/display/AST/Asterisk+11+Application_VoiceMailPlayMsg">VoiceMailPlayMsg</a> application. <code>SUCCESS</code> if the voicemail was played back successfully, {{FAILED} otherwise</li> </ul> </div> </div> </div> <div id="footer"> <section class="footer-body"> <p>Document generated by Confluence on Dec 20, 2013 14:18</p> </section> </div> </div> </body> </html>
Java
<?php class Miscinfo_b extends Lxaclass { static $__desc_realname = array("", "", "real_name"); static $__desc_paddress = array("", "", "personal_address"); static $__desc_padd_city = array("", "", "city"); static $__desc_padd_country = array( "", "", "Country", "Country of the Client"); static $__desc_ptelephone = array("", "", "telephone_no"); static $__desc_caddress = array("", "", "company_address"); static $__desc_cadd_country = array("", "", "country" ); static $__desc_cadd_city = array("", "", "city"); static $__desc_ctelephone = array("", "", "telephone"); static $__desc_cfax = array("", "", "fax"); static $__desc_text_comment = array("t", "", "comments"); } class sp_Miscinfo extends LxSpecialClass { static $__desc = array("","", "miscinfo"); static $__desc_nname = array("", "", "name"); static $__desc_miscinfo_b = array("", "", "personal_info_of_client"); static $__acdesc_update_miscinfo = array("","", "details"); function updateform($subaction, $param) { $vlist['nname']= array('M', $this->getSpecialname()); $vlist['miscinfo_b_s_realname']= ""; $vlist['miscinfo_b_s_paddress']= ""; $vlist['miscinfo_b_s_padd_city']= ""; $vlist['miscinfo_b_s_padd_country']= ""; $vlist['miscinfo_b_s_ptelephone']= ""; $vlist['miscinfo_b_s_caddress']= ""; $vlist['miscinfo_b_s_ctelephone']= ""; $vlist['miscinfo_b_s_cadd_city']= ""; $vlist['miscinfo_b_s_cadd_country']= ""; $vlist['miscinfo_b_s_cfax']= ""; return $vlist; } }
Java
<?php /** * @version SEBLOD 3.x Core * @package SEBLOD (App Builder & CCK) // SEBLOD nano (Form Builder) * @url https://www.seblod.com * @editor Octopoos - www.octopoos.com * @copyright Copyright (C) 2009 - 2018 SEBLOD. All Rights Reserved. * @license GNU General Public License version 2 or later; see _LICENSE.php **/ defined( '_JEXEC' ) or die; $after_html = '<span class="switch notice">'.JText::_( 'COM_CCK_FIELD_WILL_NOT_BE_LINKED' ).JText::_( 'COM_CCK_FIELD_WILL_BE_LINKED' ).'</span>'; $object = 'joomla_user_group'; echo JCckDev::renderForm( 'core_form', '', $config, array( 'label'=>'Content Type2', 'selectlabel'=>'None', 'options'=>'Linked to Content Type=optgroup', 'options2'=>'{"query":"","table":"#__cck_core_types","name":"title","where":"published=1 AND storage_location=\"'.$object.'\"","value":"name","orderby":"title","orderby_direction":"ASC","limit":"","language_detection":"joomla","language_codes":"EN,GB,US,FR","language_default":"EN"}', 'bool4'=>1, 'required'=>'', 'css'=>'storage-cck-more', 'attributes'=>'disabled="disabled"', 'storage_field'=>'storage_cck' ), array( 'after'=>$after_html ), 'w100' ); ?>
Java
/* * File: ShardExceptions.cpp * Author: dagothar * * Created on October 22, 2015, 8:00 PM */ #include "ShardExceptions.hpp" using namespace gripperz::shards;
Java
äòR<?php exit; ?>a:6:{s:10:"last_error";s:0:"";s:10:"last_query";s:104:"SELECT ID FROM jj_posts WHERE post_parent = 6 AND post_type = 'page' AND post_status = 'publish' LIMIT 1";s:11:"last_result";a:0:{}s:8:"col_info";a:1:{i:0;O:8:"stdClass":13:{s:4:"name";s:2:"ID";s:5:"table";s:8:"jj_posts";s:3:"def";s:0:"";s:10:"max_length";i:0;s:8:"not_null";i:1;s:11:"primary_key";i:1;s:12:"multiple_key";i:0;s:10:"unique_key";i:0;s:7:"numeric";i:1;s:4:"blob";i:0;s:4:"type";s:3:"int";s:8:"unsigned";i:1;s:8:"zerofill";i:0;}}s:8:"num_rows";i:0;s:10:"return_val";i:0;}
Java
/* sane - Scanner Access Now Easy. Copyright (C) 2002 Frank Zago (sane at zago dot net) This file is part of the SANE package. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, the authors of SANE give permission for additional uses of the libraries contained in this release of SANE. The exception is that, if you link a SANE library with other files to produce an executable, this does not by itself cause the resulting executable to be covered by the GNU General Public License. Your use of that executable is in no way restricted on account of linking the SANE library code into it. This exception does not, however, invalidate any other reasons why the executable file might be covered by the GNU General Public License. If you submit changes to SANE to the maintainers to be included in a subsequent release, you agree by submitting the changes that those changes may be distributed with this exception intact. If you write modifications of your own for SANE, it is your choice whether to permit this exception to apply to your modifications. If you do not wish that, delete this exception notice. */ /* $Id: leo.h,v 1.4 2005-07-07 11:55:42 fzago-guest Exp $ */ /* Commands supported by the scanner. */ #define SCSI_TEST_UNIT_READY 0x00 #define SCSI_INQUIRY 0x12 #define SCSI_SCAN 0x1b #define SCSI_SET_WINDOW 0x24 #define SCSI_READ_10 0x28 #define SCSI_SEND_10 0x2a #define SCSI_REQUEST_SENSE 0x03 #define SCSI_GET_DATA_BUFFER_STATUS 0x34 typedef struct { unsigned char data[16]; int len; } CDB; /* Set a specific bit depending on a boolean. * MKSCSI_BIT(TRUE, 3) will generate 0x08. */ #define MKSCSI_BIT(bit, pos) ((bit)? 1<<(pos): 0) /* Set a value in a range of bits. * MKSCSI_I2B(5, 3, 5) will generate 0x28 */ #define MKSCSI_I2B(bits, pos_b, pos_e) ((bits) << (pos_b) & ((1<<((pos_e)-(pos_b)+1))-1)) /* Store an integer in 2, 3 or 4 byte in an array. */ #define Ito16(val, buf) { \ ((unsigned char *)buf)[0] = ((val) >> 8) & 0xff; \ ((unsigned char *)buf)[1] = ((val) >> 0) & 0xff; \ } #define Ito24(val, buf) { \ ((unsigned char *)buf)[0] = ((val) >> 16) & 0xff; \ ((unsigned char *)buf)[1] = ((val) >> 8) & 0xff; \ ((unsigned char *)buf)[2] = ((val) >> 0) & 0xff; \ } #define Ito32(val, buf) { \ ((unsigned char *)buf)[0] = ((val) >> 24) & 0xff; \ ((unsigned char *)buf)[1] = ((val) >> 16) & 0xff; \ ((unsigned char *)buf)[2] = ((val) >> 8) & 0xff; \ ((unsigned char *)buf)[3] = ((val) >> 0) & 0xff; \ } #define MKSCSI_GET_DATA_BUFFER_STATUS(cdb, wait, buflen) \ cdb.data[0] = SCSI_GET_DATA_BUFFER_STATUS; \ cdb.data[1] = MKSCSI_BIT(wait, 0); \ cdb.data[2] = 0; \ cdb.data[3] = 0; \ cdb.data[4] = 0; \ cdb.data[5] = 0; \ cdb.data[6] = 0; \ cdb.data[7] = (((buflen) >> 8) & 0xff); \ cdb.data[8] = (((buflen) >> 0) & 0xff); \ cdb.data[9] = 0; \ cdb.len = 10; #define MKSCSI_INQUIRY(cdb, buflen) \ cdb.data[0] = SCSI_INQUIRY; \ cdb.data[1] = 0; \ cdb.data[2] = 0; \ cdb.data[3] = 0; \ cdb.data[4] = buflen; \ cdb.data[5] = 0; \ cdb.len = 6; #define MKSCSI_SCAN(cdb) \ cdb.data[0] = SCSI_SCAN; \ cdb.data[1] = 0; \ cdb.data[2] = 0; \ cdb.data[3] = 0; \ cdb.data[4] = 0; \ cdb.data[5] = 0; \ cdb.len = 6; #define MKSCSI_SEND_10(cdb, dtc, dtq, buflen) \ cdb.data[0] = SCSI_SEND_10; \ cdb.data[1] = 0; \ cdb.data[2] = (dtc); \ cdb.data[3] = 0; \ cdb.data[4] = (((dtq) >> 8) & 0xff); \ cdb.data[5] = (((dtq) >> 0) & 0xff); \ cdb.data[6] = (((buflen) >> 16) & 0xff); \ cdb.data[7] = (((buflen) >> 8) & 0xff); \ cdb.data[8] = (((buflen) >> 0) & 0xff); \ cdb.data[9] = 0; \ cdb.len = 10; #define MKSCSI_SET_WINDOW(cdb, buflen) \ cdb.data[0] = SCSI_SET_WINDOW; \ cdb.data[1] = 0; \ cdb.data[2] = 0; \ cdb.data[3] = 0; \ cdb.data[4] = 0; \ cdb.data[5] = 0; \ cdb.data[6] = (((buflen) >> 16) & 0xff); \ cdb.data[7] = (((buflen) >> 8) & 0xff); \ cdb.data[8] = (((buflen) >> 0) & 0xff); \ cdb.data[9] = 0; \ cdb.len = 10; #define MKSCSI_READ_10(cdb, dtc, dtq, buflen) \ cdb.data[0] = SCSI_READ_10; \ cdb.data[1] = 0; \ cdb.data[2] = (dtc); \ cdb.data[3] = 0; \ cdb.data[4] = (((dtq) >> 8) & 0xff); \ cdb.data[5] = (((dtq) >> 0) & 0xff); \ cdb.data[6] = (((buflen) >> 16) & 0xff); \ cdb.data[7] = (((buflen) >> 8) & 0xff); \ cdb.data[8] = (((buflen) >> 0) & 0xff); \ cdb.data[9] = 0; \ cdb.len = 10; #define MKSCSI_REQUEST_SENSE(cdb, buflen) \ cdb.data[0] = SCSI_REQUEST_SENSE; \ cdb.data[1] = 0; \ cdb.data[2] = 0; \ cdb.data[3] = 0; \ cdb.data[4] = (buflen); \ cdb.data[5] = 0; \ cdb.len = 6; #define MKSCSI_TEST_UNIT_READY(cdb) \ cdb.data[0] = SCSI_TEST_UNIT_READY; \ cdb.data[1] = 0; \ cdb.data[2] = 0; \ cdb.data[3] = 0; \ cdb.data[4] = 0; \ cdb.data[5] = 0; \ cdb.len = 6; /*--------------------------------------------------------------------------*/ static int getbitfield(unsigned char *pageaddr, int mask, int shift) { return ((*pageaddr >> shift) & mask); } /* defines for request sense return block */ #define get_RS_information_valid(b) getbitfield(b + 0x00, 1, 7) #define get_RS_error_code(b) getbitfield(b + 0x00, 0x7f, 0) #define get_RS_filemark(b) getbitfield(b + 0x02, 1, 7) #define get_RS_EOM(b) getbitfield(b + 0x02, 1, 6) #define get_RS_ILI(b) getbitfield(b + 0x02, 1, 5) #define get_RS_sense_key(b) getbitfield(b + 0x02, 0x0f, 0) #define get_RS_information(b) getnbyte(b+0x03, 4) #define get_RS_additional_length(b) b[0x07] #define get_RS_ASC(b) b[0x0c] #define get_RS_ASCQ(b) b[0x0d] #define get_RS_SKSV(b) getbitfield(b+0x0f,1,7) /*--------------------------------------------------------------------------*/ #define mmToIlu(mm) (((mm) * dev->x_resolution) / SANE_MM_PER_INCH) #define iluToMm(ilu) (((ilu) * SANE_MM_PER_INCH) / dev->x_resolution) /*--------------------------------------------------------------------------*/ #define GAMMA_LENGTH 0x100 /* number of value per color */ /*--------------------------------------------------------------------------*/ enum Leo_Option { /* Must come first */ OPT_NUM_OPTS = 0, OPT_MODE_GROUP, OPT_MODE, /* scanner modes */ OPT_RESOLUTION, /* X and Y resolution */ OPT_GEOMETRY_GROUP, OPT_TL_X, /* upper left X */ OPT_TL_Y, /* upper left Y */ OPT_BR_X, /* bottom right X */ OPT_BR_Y, /* bottom right Y */ OPT_ENHANCEMENT_GROUP, OPT_CUSTOM_GAMMA, /* Use the custom gamma tables */ OPT_GAMMA_VECTOR_R, /* Custom Red gamma table */ OPT_GAMMA_VECTOR_G, /* Custom Green Gamma table */ OPT_GAMMA_VECTOR_B, /* Custom Blue Gamma table */ OPT_GAMMA_VECTOR_GRAY, /* Custom Gray Gamma table */ OPT_HALFTONE_PATTERN, /* Halftone pattern */ OPT_PREVIEW, /* preview mode */ /* must come last: */ OPT_NUM_OPTIONS }; /*--------------------------------------------------------------------------*/ /* * Scanner supported by this backend. */ struct scanners_supported { int scsi_type; char scsi_vendor[9]; char scsi_product[17]; const char *real_vendor; const char *real_product; }; /*--------------------------------------------------------------------------*/ #define BLACK_WHITE_STR SANE_I18N("Black & White") #define GRAY_STR SANE_I18N("Grayscale") #define COLOR_STR SANE_I18N("Color") /*--------------------------------------------------------------------------*/ /* Define a scanner occurence. */ typedef struct Leo_Scanner { struct Leo_Scanner *next; SANE_Device sane; char *devicename; int sfd; /* device handle */ /* Infos from inquiry. */ char scsi_type; char scsi_vendor[9]; char scsi_product[17]; char scsi_version[5]; SANE_Range res_range; int x_resolution_max; /* maximum X dpi */ int y_resolution_max; /* maximum Y dpi */ /* SCSI handling */ size_t buffer_size; /* size of the buffer */ SANE_Byte *buffer; /* for SCSI transfer. */ /* Scanner infos. */ const struct scanners_supported *def; /* default options for that scanner */ /* Scanning handling. */ int scanning; /* TRUE if a scan is running. */ int x_resolution; /* X resolution in DPI */ int y_resolution; /* Y resolution in DPI */ int x_tl; /* X top left */ int y_tl; /* Y top left */ int x_br; /* X bottom right */ int y_br; /* Y bottom right */ int width; /* width of the scan area in mm */ int length; /* length of the scan area in mm */ int pass; /* current pass number */ enum { LEO_BW, LEO_HALFTONE, LEO_GRAYSCALE, LEO_COLOR } scan_mode; int depth; /* depth per color */ size_t bytes_left; /* number of bytes left to give to the backend */ size_t real_bytes_left; /* number of bytes left the scanner will return. */ SANE_Byte *image; /* keep the raw image here */ size_t image_size; /* allocated size of image */ size_t image_begin; /* first significant byte in image */ size_t image_end; /* first free byte in image */ SANE_Parameters params; /* Options */ SANE_Option_Descriptor opt[OPT_NUM_OPTIONS]; Option_Value val[OPT_NUM_OPTIONS]; /* Gamma table. 1 array per colour. */ SANE_Word gamma_R[GAMMA_LENGTH]; SANE_Word gamma_G[GAMMA_LENGTH]; SANE_Word gamma_B[GAMMA_LENGTH]; SANE_Word gamma_GRAY[GAMMA_LENGTH]; } Leo_Scanner; /*--------------------------------------------------------------------------*/ /* Debug levels. * Should be common to all backends. */ #define DBG_error0 0 #define DBG_error 1 #define DBG_sense 2 #define DBG_warning 3 #define DBG_inquiry 4 #define DBG_info 5 #define DBG_info2 6 #define DBG_proc 7 #define DBG_read 8 #define DBG_sane_init 10 #define DBG_sane_proc 11 #define DBG_sane_info 12 #define DBG_sane_option 13 /*--------------------------------------------------------------------------*/ /* 32 bits from an array to an integer (eg ntohl). */ #define B32TOI(buf) \ ((((unsigned char *)buf)[0] << 24) | \ (((unsigned char *)buf)[1] << 16) | \ (((unsigned char *)buf)[2] << 8) | \ (((unsigned char *)buf)[3] << 0)) #define B24TOI(buf) \ ((((unsigned char *)buf)[0] << 16) | \ (((unsigned char *)buf)[1] << 8) | \ (((unsigned char *)buf)[2] << 0)) #define B16TOI(buf) \ ((((unsigned char *)buf)[0] << 8) | \ (((unsigned char *)buf)[1] << 0)) /*--------------------------------------------------------------------------*/ /* Downloadable halftone patterns */ typedef unsigned char halftone_pattern_t[256]; static const halftone_pattern_t haltfone_pattern_diamond = { 0xF0, 0xE0, 0x60, 0x20, 0x00, 0x19, 0x61, 0xD8, 0xF0, 0xE0, 0x60, 0x20, 0x00, 0x19, 0x61, 0xD8, 0xC0, 0xA0, 0x88, 0x40, 0x38, 0x58, 0x80, 0xB8, 0xC0, 0xA0, 0x88, 0x40, 0x38, 0x58, 0x80, 0xB8, 0x30, 0x50, 0x98, 0xB0, 0xC8, 0xA8, 0x90, 0x48, 0x30, 0x50, 0x98, 0xB0, 0xC8, 0xA8, 0x90, 0x48, 0x08, 0x10, 0x70, 0xD0, 0xF8, 0xE8, 0x68, 0x28, 0x08, 0x10, 0x70, 0xD0, 0xF8, 0xE8, 0x68, 0x28, 0x00, 0x18, 0x78, 0xD8, 0xF0, 0xE0, 0x60, 0x20, 0x00, 0x18, 0x78, 0xD8, 0xF0, 0xE0, 0x60, 0x20, 0x38, 0x58, 0x80, 0xB8, 0xC0, 0xA0, 0x88, 0x40, 0x38, 0x58, 0x80, 0xB8, 0xC0, 0xA0, 0x88, 0x40, 0xC8, 0xA8, 0x90, 0x48, 0x30, 0x50, 0x9B, 0xB0, 0xC8, 0xA8, 0x90, 0x48, 0x30, 0x50, 0x9B, 0xB0, 0xF8, 0xE8, 0x68, 0x28, 0x08, 0x18, 0x70, 0xD0, 0xF8, 0xE8, 0x68, 0x28, 0x08, 0x18, 0x70, 0xD0, 0xF0, 0xE0, 0x60, 0x20, 0x00, 0x19, 0x61, 0xD8, 0xF0, 0xE0, 0x60, 0x20, 0x00, 0x19, 0x61, 0xD8, 0xC0, 0xA0, 0x88, 0x40, 0x38, 0x58, 0x80, 0xB8, 0xC0, 0xA0, 0x88, 0x40, 0x38, 0x58, 0x80, 0xB8, 0x30, 0x50, 0x98, 0xB0, 0xC8, 0xA8, 0x90, 0x48, 0x30, 0x50, 0x98, 0xB0, 0xC8, 0xA8, 0x90, 0x48, 0x08, 0x10, 0x70, 0xD0, 0xF8, 0xE8, 0x68, 0x28, 0x08, 0x10, 0x70, 0xD0, 0xF8, 0xE8, 0x68, 0x28, 0x00, 0x18, 0x78, 0xD8, 0xF0, 0xE0, 0x60, 0x20, 0x00, 0x18, 0x78, 0xD8, 0xF0, 0xE0, 0x60, 0x20, 0x38, 0x58, 0x80, 0xB8, 0xC0, 0xA0, 0x88, 0x40, 0x38, 0x58, 0x80, 0xB8, 0xC0, 0xA0, 0x88, 0x40, 0xC8, 0xA8, 0x90, 0x48, 0x30, 0x50, 0x9B, 0xB0, 0xC8, 0xA8, 0x90, 0x48, 0x30, 0x50, 0x9B, 0xB0, 0xF8, 0xE8, 0x68, 0x28, 0x08, 0x18, 0x70, 0xD0, 0xF8, 0xE8, 0x68, 0x28, 0x08, 0x18, 0x70, 0xD0 }; static const halftone_pattern_t haltfone_pattern_8x8_Coarse_Fatting = { 0x12, 0x3A, 0xD2, 0xEA, 0xE2, 0xB6, 0x52, 0x1A, 0x12, 0x3A, 0xD2, 0xEA, 0xE2, 0xB6, 0x52, 0x1A, 0x42, 0x6A, 0x9A, 0xCA, 0xC2, 0x92, 0x72, 0x4A, 0x42, 0x6A, 0x9A, 0xCA, 0xC2, 0x92, 0x72, 0x4A, 0xAE, 0x8E, 0x7E, 0x26, 0x2E, 0x66, 0x86, 0xA6, 0xAE, 0x8E, 0x7E, 0x26, 0x2E, 0x66, 0x86, 0xA6, 0xFA, 0xBA, 0x5E, 0x06, 0x0E, 0x36, 0xDE, 0xF6, 0xFA, 0xBA, 0x5E, 0x06, 0x0E, 0x36, 0xDE, 0xF6, 0xE6, 0xBE, 0x56, 0x1E, 0x16, 0x3E, 0xD6, 0xEE, 0xE6, 0xBE, 0x56, 0x1E, 0x16, 0x3E, 0xD6, 0xEE, 0xC6, 0x96, 0x76, 0x4E, 0x46, 0x6E, 0x9E, 0xCE, 0xC6, 0x96, 0x76, 0x4E, 0x46, 0x6E, 0x9E, 0xCE, 0x2A, 0x62, 0x82, 0xA2, 0xAA, 0x8A, 0x7A, 0x22, 0x2A, 0x62, 0x82, 0xA2, 0xAA, 0x8A, 0x7A, 0x22, 0x0A, 0x32, 0xDA, 0xF2, 0xFE, 0xB2, 0x5A, 0x02, 0x0A, 0x32, 0xDA, 0xF2, 0xFE, 0xB2, 0x5A, 0x02, 0x12, 0x3A, 0xD2, 0xEA, 0xE2, 0xB6, 0x52, 0x1A, 0x12, 0x3A, 0xD2, 0xEA, 0xE2, 0xB6, 0x52, 0x1A, 0x42, 0x6A, 0x9A, 0xCA, 0xC2, 0x92, 0x72, 0x4A, 0x42, 0x6A, 0x9A, 0xCA, 0xC2, 0x92, 0x72, 0x4A, 0xAE, 0x8E, 0x7E, 0x26, 0x2E, 0x66, 0x86, 0xA6, 0xAE, 0x8E, 0x7E, 0x26, 0x2E, 0x66, 0x86, 0xA6, 0xFA, 0xBA, 0x5E, 0x06, 0x0E, 0x36, 0xDE, 0xF6, 0xFA, 0xBA, 0x5E, 0x06, 0x0E, 0x36, 0xDE, 0xF6, 0xE6, 0xBE, 0x56, 0x1E, 0x16, 0x3E, 0xD6, 0xEE, 0xE6, 0xBE, 0x56, 0x1E, 0x16, 0x3E, 0xD6, 0xEE, 0xC6, 0x96, 0x76, 0x4E, 0x46, 0x6E, 0x9E, 0xCE, 0xC6, 0x96, 0x76, 0x4E, 0x46, 0x6E, 0x9E, 0xCE, 0x2A, 0x62, 0x82, 0xA2, 0xAA, 0x8A, 0x7A, 0x22, 0x2A, 0x62, 0x82, 0xA2, 0xAA, 0x8A, 0x7A, 0x22, 0x0A, 0x32, 0xDA, 0xF2, 0xFE, 0xB2, 0x5A, 0x02, 0x0A, 0x32, 0xDA, 0xF2, 0xFE, 0xB2, 0x5A, 0x02 }; static const halftone_pattern_t haltfone_pattern_8x8_Fine_Fatting = { 0x02, 0x22, 0x92, 0xB2, 0x0A, 0x2A, 0x9A, 0xBA, 0x02, 0x22, 0x92, 0xB2, 0x0A, 0x2A, 0x9A, 0xBA, 0x42, 0x62, 0xD2, 0xF2, 0x4A, 0x6A, 0xDA, 0xFA, 0x42, 0x62, 0xD2, 0xF2, 0x4A, 0x6A, 0xDA, 0xFA, 0x82, 0xA2, 0x12, 0x32, 0x8A, 0xAA, 0x1A, 0x3A, 0x82, 0xA2, 0x12, 0x32, 0x8A, 0xAA, 0x1A, 0x3A, 0xC2, 0xE2, 0x52, 0x72, 0xCA, 0xEA, 0x5A, 0x7A, 0xC2, 0xE2, 0x52, 0x72, 0xCA, 0xEA, 0x5A, 0x7A, 0x0E, 0x2E, 0x9E, 0xBE, 0x06, 0x26, 0x96, 0xB6, 0x0E, 0x2E, 0x9E, 0xBE, 0x06, 0x26, 0x96, 0xB6, 0x4C, 0x6E, 0xDE, 0xFE, 0x46, 0x66, 0xD6, 0xF6, 0x4C, 0x6E, 0xDE, 0xFE, 0x46, 0x66, 0xD6, 0xF6, 0x8E, 0xAE, 0x1E, 0x3E, 0x86, 0xA6, 0x16, 0x36, 0x8E, 0xAE, 0x1E, 0x3E, 0x86, 0xA6, 0x16, 0x36, 0xCE, 0xEE, 0x60, 0x7E, 0xC6, 0xE6, 0x56, 0x76, 0xCE, 0xEE, 0x60, 0x7E, 0xC6, 0xE6, 0x56, 0x76, 0x02, 0x22, 0x92, 0xB2, 0x0A, 0x2A, 0x9A, 0xBA, 0x02, 0x22, 0x92, 0xB2, 0x0A, 0x2A, 0x9A, 0xBA, 0x42, 0x62, 0xD2, 0xF2, 0x4A, 0x6A, 0xDA, 0xFA, 0x42, 0x62, 0xD2, 0xF2, 0x4A, 0x6A, 0xDA, 0xFA, 0x82, 0xA2, 0x12, 0x32, 0x8A, 0xAA, 0x1A, 0x3A, 0x82, 0xA2, 0x12, 0x32, 0x8A, 0xAA, 0x1A, 0x3A, 0xC2, 0xE2, 0x52, 0x72, 0xCA, 0xEA, 0x5A, 0x7A, 0xC2, 0xE2, 0x52, 0x72, 0xCA, 0xEA, 0x5A, 0x7A, 0x0E, 0x2E, 0x9E, 0xBE, 0x06, 0x26, 0x96, 0xB6, 0x0E, 0x2E, 0x9E, 0xBE, 0x06, 0x26, 0x96, 0xB6, 0x4C, 0x6E, 0xDE, 0xFE, 0x46, 0x66, 0xD6, 0xF6, 0x4C, 0x6E, 0xDE, 0xFE, 0x46, 0x66, 0xD6, 0xF6, 0x8E, 0xAE, 0x1E, 0x3E, 0x86, 0xA6, 0x16, 0x36, 0x8E, 0xAE, 0x1E, 0x3E, 0x86, 0xA6, 0x16, 0x36, 0xCE, 0xEE, 0x60, 0x7E, 0xC6, 0xE6, 0x56, 0x76, 0xCE, 0xEE, 0x60, 0x7E, 0xC6, 0xE6, 0x56, 0x76 }; static const halftone_pattern_t haltfone_pattern_8x8_Bayer = { 0xF2, 0x42, 0x82, 0xC2, 0xFA, 0x4A, 0x8A, 0xCA, 0xF2, 0x42, 0x82, 0xC2, 0xFA, 0x4A, 0x8A, 0xCA, 0xB2, 0x02, 0x12, 0x52, 0xBA, 0x0A, 0x1A, 0x5A, 0xB2, 0x02, 0x12, 0x52, 0xBA, 0x0A, 0x1A, 0x5A, 0x72, 0x32, 0x22, 0x92, 0x7A, 0x3A, 0x2A, 0x9A, 0x72, 0x32, 0x22, 0x92, 0x7A, 0x3A, 0x2A, 0x9A, 0xE2, 0xA2, 0x62, 0xD2, 0xEA, 0xAA, 0x6A, 0xDA, 0xE2, 0xA2, 0x62, 0xD2, 0xEA, 0xAA, 0x6A, 0xDA, 0xFE, 0x4E, 0x8E, 0xCE, 0xF6, 0x46, 0xD6, 0xC6, 0xFE, 0x4E, 0x8E, 0xCE, 0xF6, 0x46, 0xD6, 0xC6, 0xBE, 0x0E, 0x1E, 0x5E, 0xB6, 0x06, 0x16, 0x56, 0xBE, 0x0E, 0x1E, 0x5E, 0xB6, 0x06, 0x16, 0x56, 0x7E, 0x3E, 0x2E, 0x9E, 0x76, 0x36, 0x26, 0x96, 0x7E, 0x3E, 0x2E, 0x9E, 0x76, 0x36, 0x26, 0x96, 0xEE, 0xAE, 0x6E, 0xDE, 0xE6, 0xA6, 0x66, 0xD6, 0xEE, 0xAE, 0x6E, 0xDE, 0xE6, 0xA6, 0x66, 0xD6, 0xF2, 0x42, 0x82, 0xC2, 0xFA, 0x4A, 0x8A, 0xCA, 0xF2, 0x42, 0x82, 0xC2, 0xFA, 0x4A, 0x8A, 0xCA, 0xB2, 0x02, 0x12, 0x52, 0xBA, 0x0A, 0x1A, 0x5A, 0xB2, 0x02, 0x12, 0x52, 0xBA, 0x0A, 0x1A, 0x5A, 0x72, 0x32, 0x22, 0x92, 0x7A, 0x3A, 0x2A, 0x9A, 0x72, 0x32, 0x22, 0x92, 0x7A, 0x3A, 0x2A, 0x9A, 0xE2, 0xA2, 0x62, 0xD2, 0xEA, 0xAA, 0x6A, 0xDA, 0xE2, 0xA2, 0x62, 0xD2, 0xEA, 0xAA, 0x6A, 0xDA, 0xFE, 0x4E, 0x8E, 0xCE, 0xF6, 0x46, 0xD6, 0xC6, 0xFE, 0x4E, 0x8E, 0xCE, 0xF6, 0x46, 0xD6, 0xC6, 0xBE, 0x0E, 0x1E, 0x5E, 0xB6, 0x06, 0x16, 0x56, 0xBE, 0x0E, 0x1E, 0x5E, 0xB6, 0x06, 0x16, 0x56, 0x7E, 0x3E, 0x2E, 0x9E, 0x76, 0x36, 0x26, 0x96, 0x7E, 0x3E, 0x2E, 0x9E, 0x76, 0x36, 0x26, 0x96, 0xEE, 0xAE, 0x6E, 0xDE, 0xE6, 0xA6, 0x66, 0xD6, 0xEE, 0xAE, 0x6E, 0xDE, 0xE6, 0xA6, 0x66, 0xD6 }; static const halftone_pattern_t haltfone_pattern_8x8_Vertical_Line = { 0x02, 0x42, 0x82, 0xC4, 0x0A, 0x4C, 0x8A, 0xCA, 0x02, 0x42, 0x82, 0xC4, 0x0A, 0x4C, 0x8A, 0xCA, 0x12, 0x52, 0x92, 0xD2, 0x1A, 0x5A, 0x9A, 0xDA, 0x12, 0x52, 0x92, 0xD2, 0x1A, 0x5A, 0x9A, 0xDA, 0x22, 0x62, 0xA2, 0xE2, 0x2A, 0x6A, 0xAA, 0xEA, 0x22, 0x62, 0xA2, 0xE2, 0x2A, 0x6A, 0xAA, 0xEA, 0x32, 0x72, 0xB2, 0xF2, 0x3A, 0x7A, 0xBA, 0xFA, 0x32, 0x72, 0xB2, 0xF2, 0x3A, 0x7A, 0xBA, 0xFA, 0x0E, 0x4E, 0x8E, 0xCE, 0x06, 0x46, 0x86, 0xC6, 0x0E, 0x4E, 0x8E, 0xCE, 0x06, 0x46, 0x86, 0xC6, 0x1E, 0x5E, 0x9E, 0xDE, 0x16, 0x56, 0x96, 0xD6, 0x1E, 0x5E, 0x9E, 0xDE, 0x16, 0x56, 0x96, 0xD6, 0x2E, 0x6E, 0xAE, 0xEE, 0x26, 0x66, 0xA6, 0xE6, 0x2E, 0x6E, 0xAE, 0xEE, 0x26, 0x66, 0xA6, 0xE6, 0x3E, 0x7E, 0xBE, 0xFE, 0x36, 0x76, 0xB6, 0xF6, 0x3E, 0x7E, 0xBE, 0xFE, 0x36, 0x76, 0xB6, 0xF6, 0x02, 0x42, 0x82, 0xC4, 0x0A, 0x4C, 0x8A, 0xCA, 0x02, 0x42, 0x82, 0xC4, 0x0A, 0x4C, 0x8A, 0xCA, 0x12, 0x52, 0x92, 0xD2, 0x1A, 0x5A, 0x9A, 0xDA, 0x12, 0x52, 0x92, 0xD2, 0x1A, 0x5A, 0x9A, 0xDA, 0x22, 0x62, 0xA2, 0xE2, 0x2A, 0x6A, 0xAA, 0xEA, 0x22, 0x62, 0xA2, 0xE2, 0x2A, 0x6A, 0xAA, 0xEA, 0x32, 0x72, 0xB2, 0xF2, 0x3A, 0x7A, 0xBA, 0xFA, 0x32, 0x72, 0xB2, 0xF2, 0x3A, 0x7A, 0xBA, 0xFA, 0x0E, 0x4E, 0x8E, 0xCE, 0x06, 0x46, 0x86, 0xC6, 0x0E, 0x4E, 0x8E, 0xCE, 0x06, 0x46, 0x86, 0xC6, 0x1E, 0x5E, 0x9E, 0xDE, 0x16, 0x56, 0x96, 0xD6, 0x1E, 0x5E, 0x9E, 0xDE, 0x16, 0x56, 0x96, 0xD6, 0x2E, 0x6E, 0xAE, 0xEE, 0x26, 0x66, 0xA6, 0xE6, 0x2E, 0x6E, 0xAE, 0xEE, 0x26, 0x66, 0xA6, 0xE6, 0x3E, 0x7E, 0xBE, 0xFE, 0x36, 0x76, 0xB6, 0xF6, 0x3E, 0x7E, 0xBE, 0xFE, 0x36, 0x76, 0xB6, 0xF6 };
Java
/* * AlwaysLowestAdaptationLogic.cpp ***************************************************************************** * Copyright (C) 2014 - VideoLAN authors * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "AlwaysLowestAdaptationLogic.hpp" #include "Representationselectors.hpp" using namespace adaptative::logic; using namespace adaptative::playlist; AlwaysLowestAdaptationLogic::AlwaysLowestAdaptationLogic(): AbstractAdaptationLogic() { } BaseRepresentation *AlwaysLowestAdaptationLogic::getCurrentRepresentation(BaseAdaptationSet *adaptSet) const { RepresentationSelector selector; return selector.select(adaptSet, 0); }
Java
package com.oa.bean; public class FeedBackInfo { private Long id; private String feedbackinfo; private String userid; private String date; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFeedbackinfo() { return feedbackinfo; } public void setFeedbackinfo(String feedbackinfo) { this.feedbackinfo = feedbackinfo; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } }
Java
<?php include('../../../operaciones.php'); conectar(); apruebadeintrusos(); if($_SESSION['cargo_user']!="Bodeguero"){ header('Location: ../../../login.php'); } ?> <html lang="en"> <head> <title>PNKS Inventario - Estadística de Productos</title> <!-- BEGIN META --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="keywords" content="your,keywords"> <meta name="description" content="Short explanation about this website"> <!-- END META --> <!-- BEGIN STYLESHEETS --> <link href='http://fonts.googleapis.com/css?family=Roboto:300italic,400italic,300,400,500,700,900' rel='stylesheet' type='text/css'/> <link type="text/css" rel="stylesheet" href="../../../css/bootstrap.css" /> <link type="text/css" rel="stylesheet" href="../../../css/materialadmin.css" /> <link type="text/css" rel="stylesheet" href="../../../css/font-awesome.min.css" /> <link type="text/css" rel="stylesheet" href="../../../css/material-design-iconic-font.min.css" /> <link type="text/css" rel="stylesheet" href="../../../css/libs/DataTables/jquery.dataTables.css" /> <link type="text/css" rel="stylesheet" href="../../../css/libs/DataTables/extensions/dataTables.colVis.css" /> <link type="text/css" rel="stylesheet" href="../../../css/libs/DataTables/extensions/dataTables.tableTools.css" /> <!-- END STYLESHEETS --> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script type="text/javascript" src="js/libs/utils/html5shiv.js?1403934957"></script> <script type="text/javascript" src="js/libs/utils/respond.min.js?1403934956"></script> <![endif]--> </head> <body class="menubar-hoverable header-fixed menubar-first menubar-visible menubar-pin"> <!-- BEGIN HEADER--> <header id="header" > <div class="headerbar"> <!-- Brand and toggle get grouped for better mobile display --> <div class="headerbar-left"> <ul class="header-nav header-nav-options"> <li class="header-nav-brand" > <div class="brand-holder"> <a href=""> <span class="text-lg text-bold text-primary">PNKS LTDA</span> </a> </div> </li> <li> <a class="btn btn-icon-toggle menubar-toggle" data-toggle="menubar" href="javascript:void(0);"> <i class="fa fa-bars"></i> </a> </li> </ul> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="headerbar-right"> <ul class="header-nav header-nav-profile"> <li class="dropdown"> <a href="javascript:void(0);" class="dropdown-toggle ink-reaction" data-toggle="dropdown"> <?php if(file_exists('../../../img/usuarios/'.$_SESSION['foto_user'])){ ?> <img src="../../../img/usuarios/<?php echo $_SESSION['foto_user']; ?>" alt="" /> <?php } else { ?> <img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNzEiIGhlaWdodD0iMTgwIj48cmVjdCB3aWR0aD0iMTcxIiBoZWlnaHQ9IjE4MCIgZmlsbD0iI2VlZSI+PC9yZWN0Pjx0ZXh0IHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9Ijg1LjUiIHk9IjkwIiBzdHlsZT0iZmlsbDojYWFhO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjEycHg7Zm9udC1mYW1pbHk6QXJpYWwsSGVsdmV0aWNhLHNhbnMtc2VyaWY7ZG9taW5hbnQtYmFzZWxpbmU6Y2VudHJhbCI+MTcxeDE4MDwvdGV4dD48L3N2Zz4="/> <?php } ?> <span class="profile-info"> <?php echo $_SESSION['usuario_session']; ?> <small><?php echo $_SESSION['cargo_user']; ?></small> </span> </a> <ul class="dropdown-menu animation-dock"> <li class="dropdown-header">Opciones de Cuenta</li> <li><a href="../../opcion/cambiarclave.php">Cambiar Clave</a></li> <li><a href="../../opcion/cambiarficha.php">Cambiar Datos Personales</a></li> <li><a href="../../opcion/cambiarfoto.php">Cambiar Foto de Perfil</a></li> <li class="divider"></li> <li><a href="../../../login.php" onClick=""><i class="fa fa-fw fa-power-off text-danger"></i> Salir</a></li> </ul><!--end .dropdown-menu --> </li><!--end .dropdown --> </ul><!--end .header-nav-profile --> </div><!--end #header-navbar-collapse --> </div> </header> <!-- END HEADER--> <!-- BEGIN BASE--> <div id="base"> <!-- BEGIN OFFCANVAS LEFT --> <div class="offcanvas"> </div><!--end .offcanvas--> <!-- END OFFCANVAS LEFT --> <!-- BEGIN CONTENT--> <div id="content"> <section> <div class="section-body"> <div class="row"> </div><!--end .row --> </div><!--end .section-body --> </section> </div><!--end #content--> <!-- END CONTENT --> <div id="menubar" class="menubar-first"> <div class="menubar-fixed-panel"> <div> <a class="btn btn-icon-toggle btn-default menubar-toggle" data-toggle="menubar" href="javascript:void(0);"> <i class="fa fa-bars"></i> </a> </div> <div class="expanded"> <a href=""> <span class="text-lg text-bold text-primary ">PNKS&nbsp;LTDA</span> </a> </div> </div> <div class="menubar-scroll-panel"> <!-- BEGIN MAIN MENU --> <ul id="main-menu" class="gui-controls"> <!-- BEGIN DASHBOARD --> <li> <a href="../index.php"> <div class="gui-icon"><i class="md md-home"></i></div> <span class="title">Inicio</span> </a> </li> <li> <a href="../producto.php"> <div class="gui-icon"><i class="md md-web"></i></div> <span class="title">Ficha Producto</span> </a> </li><!--end /menu-li --> <!-- END DASHBOARD --> <!-- BEGIN EMAIL --> <li> <a href="../etiqueta.php"> <div class="gui-icon"><i class="md md-chat"></i></div> <span class="title">Emisión de Etiqueta</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <li> <a href="../bodega.php"> <div class="gui-icon"><i class="glyphicon glyphicon-list-alt"></i></div> <span class="title">Administración de Bodega</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <li> <a href="../reserva.php"> <div class="gui-icon"><i class="md md-view-list"></i></div> <span class="title">Control de Reservas</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <a href="../inventario.php"> <div class="gui-icon"><i class="fa fa-table"></i></div> <span class="title">Inventario</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <a href="../stock.php"> <div class="gui-icon"><i class="md md-assignment-turned-in"></i></div> <span class="title">Control de Stock</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <a href="../precio.php"> <div class="gui-icon"><i class="md md-assignment"></i></div> <span class="title">Lista de Precio</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li> <a href="../cliente.php"> <div class="gui-icon"><i class="md md-description"></i></div> <span class="title">Ficha Cliente</span> </a> </li><!--end /menu-li --> <!-- END EMAIL --> <!-- BEGIN EMAIL --> <li class="gui-folder"> <a> <div class="gui-icon"><i class="md md-assessment"></i></div> <span class="title">Informes</span> </a> <!--start submenu --> <ul> <li><a href="stockbodega.php"><span class="title">Stock por Bodega</span></a></li> <li><a href="guia.php"><span class="title">Entrada y Salida</span></a></li> <li><a href="stock.php"><span class="title">Control de Stock</span></a></li> <li><a href="consumo.php"><span class="title">Consumo Interno</span></a></li> <li><a href="consignacion.php"><span class="title">Consignaciones</span></a></li> <li><a href="estadistica.php" class="active"><span class="title">Estadística de Producto</span></a></li> <li><a href="serie.php"><span class="title">Control de Serie</span></a></li> <li><a href="vencimiento.php" ><span class="title">Vencimiento de Producto</span></a></li> <li><a href="rotacion.php"><span class="title">Rotación de Inventario</span></a></li> <li><a href="toma.php"><span class="title">Toma de Inventario</span></a></li> </ul><!--end /submenu --> </li><!--end /menu-li --> <!-- END EMAIL --> </ul><!--end .main-menu --> <!-- END MAIN MENU --> <div class="menubar-foot-panel"> <small class="no-linebreak hidden-folded"> <span class="opacity-75">&copy; 2015</span> <strong>GH Soluciones Informáticas</strong> </small> </div> </div><!--end .menubar-scroll-panel--> </div><!--end #menubar--> <!-- END MENUBAR --> </div><!--end #base--> <!-- END BASE --> <!-- BEGIN JAVASCRIPT --> <script src="../../../js/libs/jquery/jquery-1.11.2.min.js"></script> <script src="../../../js/libs/jquery/jquery-migrate-1.2.1.min.js"></script> <script src="../../../js/libs/bootstrap/bootstrap.min.js"></script> <script src="../../../js/libs/spin.js/spin.min.js"></script> <script src="../../../js/libs/autosize/jquery.autosize.min.js"></script> <script src="../../../js/libs/DataTables/jquery.dataTables.min.js"></script> <script src="../../../js/libs/DataTables/extensions/ColVis/js/dataTables.colVis.min.js"></script> <script src="../../../js/libs/DataTables/extensions/TableTools/js/dataTables.tableTools.min.js"></script> <script src="../../../js/libs/nanoscroller/jquery.nanoscroller.min.js"></script> <script src="../../../js/core/source/App.js"></script> <script src="../../../js/core/source/AppNavigation.js"></script> <script src="../../../js/core/source/AppOffcanvas.js"></script> <script src="../../../js/core/source/AppCard.js"></script> <script src="../../../js/core/source/AppForm.js"></script> <script src="../../../js/core/source/AppVendor.js"></script> <!-- END JAVASCRIPT --> </body> </html>
Java
<?php /** * Vanillicon plugin. * * @author Todd Burry <todd@vanillaforums.com> * @copyright 2009-2017 Vanilla Forums Inc. * @license http://www.opensource.org/licenses/gpl-2.0.php GNU GPL v2 * @package vanillicon */ /** * Class VanilliconPlugin */ class VanilliconPlugin extends Gdn_Plugin { /** * Set up the plugin. */ public function setup() { $this->structure(); } /** * Perform any necessary database or configuration updates. */ public function structure() { touchConfig('Plugins.Vanillicon.Type', 'v2'); } /** * Set the vanillicon on the user' profile. * * @param ProfileController $sender * @param array $args */ public function profileController_afterAddSideMenu_handler($sender, $args) { if (!$sender->User->Photo) { $sender->User->Photo = userPhotoDefaultUrl($sender->User, ['Size' => 200]); } } /** * The settings page for vanillicon. * * @param Gdn_Controller $sender */ public function settingsController_vanillicon_create($sender) { $sender->permission('Garden.Settings.Manage'); $cf = new ConfigurationModule($sender); $items = [ 'v1' => 'Vanillicon 1', 'v2' => 'Vanillicon 2' ]; $cf->initialize([ 'Plugins.Vanillicon.Type' => [ 'LabelCode' => 'Vanillicon Set', 'Control' => 'radiolist', 'Description' => 'Which vanillicon set do you want to use?', 'Items' => $items, 'Options' => ['display' => 'after'], 'Default' => 'v1' ] ]); $sender->setData('Title', sprintf(t('%s Settings'), 'Vanillicon')); $cf->renderAll(); } /** * Overrides allowing admins to set the default avatar, since it has no effect when Vanillicon is on. * Adds messages to the top of avatar settings page and to the help panel asset. * * @param SettingsController $sender */ public function settingsController_avatarSettings_handler($sender) { // We check if Gravatar is enabled before adding any messages as Gravatar overrides Vanillicon. if (!Gdn::addonManager()->isEnabled('gravatar', \Vanilla\Addon::TYPE_ADDON)) { $message = t('You\'re using Vanillicon avatars as your default avatars.'); $message .= ' '.t('To set a custom default avatar, disable the Vanillicon plugin.'); $messages = $sender->data('messages', []); $messages = array_merge($messages, [$message]); $sender->setData('messages', $messages); $sender->setData('canSetDefaultAvatar', false); $help = t('Your users\' default avatars are Vanillicon avatars.'); helpAsset(t('How are my users\' default avatars set?'), $help); } } } if (!function_exists('userPhotoDefaultUrl')) { /** * Calculate the user's default photo url. * * @param array|object $user The user to examine. * @param array $options An array of options. * - Size: The size of the photo. * @return string Returns the vanillicon url for the user. */ function userPhotoDefaultUrl($user, $options = []) { static $iconSize = null, $type = null; if ($iconSize === null) { $thumbSize = c('Garden.Thumbnail.Size'); $iconSize = $thumbSize <= 50 ? 50 : 100; } if ($type === null) { $type = c('Plugins.Vanillicon.Type'); } $size = val('Size', $options, $iconSize); $email = val('Email', $user); if (!$email) { $email = val('UserID', $user, 100); } $hash = md5($email); $px = substr($hash, 0, 1); switch ($type) { case 'v2': $photoUrl = "//w$px.vanillicon.com/v2/{$hash}.svg"; break; default: $photoUrl = "//w$px.vanillicon.com/{$hash}_{$size}.png"; break; } return $photoUrl; } }
Java
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest17998") public class BenchmarkTest17998 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = ""; java.util.Enumeration<String> names = request.getParameterNames(); if (names.hasMoreElements()) { param = names.nextElement(); // just grab first element } String bar = doSomething(param); java.io.FileOutputStream fos = new java.io.FileOutputStream(new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir + bar),false); } // end doPost private static String doSomething(String param) throws ServletException, IOException { String bar = "safe!"; java.util.HashMap<String,Object> map37923 = new java.util.HashMap<String,Object>(); map37923.put("keyA-37923", "a_Value"); // put some stuff in the collection map37923.put("keyB-37923", param.toString()); // put it in a collection map37923.put("keyC", "another_Value"); // put some stuff in the collection bar = (String)map37923.get("keyB-37923"); // get it back out bar = (String)map37923.get("keyA-37923"); // get safe value back out return bar; } }
Java
package Classes::Sentry4; our @ISA = qw(Classes::Device); sub init { my $self = shift; if ($self->mode =~ /device::hardware::health/) { $self->analyze_and_check_environmental_subsystem('Classes::Sentry4::Components::EnvironmentalSubsystem'); } elsif ($self->mode =~ /device::power::health/) { $self->analyze_and_check_environmental_subsystem('Classes::Sentry4::Components::PowerSubsystem'); } else { $self->no_such_mode(); } if (! $self->check_messages()) { $self->add_ok('hardware working fine'); } }
Java
using System.Windows.Controls; namespace HomeControl { /// <summary> /// Interaction logic for UserControl1.xaml /// </summary> public partial class HomeCtrl : UserControl { public HomeCtrl() { InitializeComponent(); // doug's change... } } }
Java
package adamros.mods.transducers.item; import java.util.List; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import adamros.mods.transducers.Transducers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; public class ItemElectricEngine extends ItemBlock { public ItemElectricEngine(int par1) { super(par1); setHasSubtypes(true); setMaxDamage(0); setUnlocalizedName("itemElectricEngine"); setCreativeTab(Transducers.tabTransducers); } @Override public int getMetadata(int meta) { return meta; } @Override public String getUnlocalizedName(ItemStack is) { String suffix; switch (is.getItemDamage()) { case 0: suffix = "lv"; break; case 1: suffix = "mv"; break; case 2: suffix = "hv"; break; case 3: suffix = "ev"; break; default: suffix = "lv"; break; } return getUnlocalizedName() + "." + suffix; } @Override @SideOnly(Side.CLIENT) public void addInformation(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, List par3List, boolean par4) { super.addInformation(par1ItemStack, par2EntityPlayer, par3List, par4); String type; switch (par1ItemStack.getItemDamage()) { case 0: type = "lv"; break; case 1: type = "mv"; break; case 2: type = "hv"; break; case 3: type = "ev"; break; default: type = "lv"; break; } par3List.add(StatCollector.translateToLocal("tip.electricEngine." + type).trim()); } }
Java
cmd_sound/soc/s6000/built-in.o := rm -f sound/soc/s6000/built-in.o; ../prebuilt/linux-x86/toolchain/arm-eabi-4.4.0/bin/arm-eabi-ar rcs sound/soc/s6000/built-in.o
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>Sunible</title> <link rel="shortcut icon" href="images/favicon.ico"/> <!-- CSS --> <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/> <link rel="stylesheet" type="text/css" href="css/flat-ui.css"/> <link rel="stylesheet" type="text/css" href="css/general.css"/> <link rel="stylesheet" type="text/css" href="css/fonts.css"/> <link rel="stylesheet" type="text/css" href="css/forms.css"/> <link rel="stylesheet" type="text/css" href="css/layout.css"/> <link rel="stylesheet" type="text/css" href="css/pages.css"/> <!-- IE code --> <script type="text/javascript">var ie;</script> <!-- HTML5 shim, for IE6-8 support of HTML5 elements. All other JS at the end of file. --> <!--[if IE 8]> <link rel="stylesheet" type="text/css" href="css/ie8.css"/> <script type="text/javascript">ie = 8;</script> <![endif]--> <!--[if IE 9]> <link rel="stylesheet" type="text/css" href="css/ie8.css"/> <script type="text/javascript">ie = 9;</script> <![endif]--> <!--[if lt IE 9]> <script type="text/javascript" src="js/html5shiv.js"></script> <![endif]--> <link href="css/socialproof.css" rel="stylesheet" type="text/css"> </head> <body> <div class="pages"> <header class="page_header homepage dashboard social_proof registration message"> <!-- header has those classes to be toggled with those pages. With that approach, no need to duplicate the header on each page we have it--> <div class="questions"> <span class="question why_solar" data-toggle="tooltip" data-placement="bottom" title="Solar is the cleanest. most abundant source of energy on earth. Also, a solar-powered home can save on electricity from day one.">Why solar?</span><span class="question why_sunible" data-toggle="tooltip" data-placement="bottom" title="Like with flights, hotels, insurance or mobile services, there are lots of solar providers out there. We will help you compare, select and contact them. Choice is good!">Why Sunible?</span> </div> <a href="/" class="logo sunible"><img src="images/_project/logo_sunible.png"/></a> </header> <!-- HOMEPAGE --> <div class="page homepage show_header" id="page-homepage" data-page="homepage"> <section class="ad teaser container"> <a href="#" class="teaser" id="homepage_teaser_heading"> <span class="save">Save</span> <span class="money_with">Money with</span> <span class="solar">Solar</span> </a> <form class="zip search providers container" id="homepage-search_providers_by_zip-container"> <span class="field_container"> <input type="text" class="field zip" id="homepage-field-zip_code" name="zipcode" placeholder="Zip Code" pattern="\d{5}(?:[-\s]\d{4})?" value="93210"/> <span class="validation message"></span> </span> <button type="button" class="btn search providers zip" id="homepage-search_providers_by_zip-button">Go</button> </form> </section> </div> <!-- /HOMEPAGE --> <!-- SOCIAL PROOF --> <div class="page social_proof" id="page-social_proof" data-page="social_proof"> <h1>Fantastic, your area is very Sunible!</h1> <div class="block"> <p> You have selected<br/> <span class="counter selected providers number" id="dashboard-block-number_of_providers_selected">0</span> <br/> providers </p> <p class="max_length message">30 providers max</p> </div> <table align="center" width="80%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="25%" align="center"><table width="65px" height="65px" border="0" cellspacing="0" cellpadding="0" style="background-image:url(images/yellowdot.png);"> <tr> <td width="65px" align="center"><span class="socialproofaligncenterbig">23</span></td> </tr> </table> <p class="socialProofAlignCenter">homes have gone solar in your area</p></td> <td width="25%" align="center"><table width="65px" height="65px" border="0" cellspacing="0" cellpadding="0" style="background-image:url(images/yellowdot.png);"> <tr> <td width="65" align="center"><span class="socialproofaligncenterbig">18</span></td> </tr> </table> <p class="socialProofAlignCenter">of them started saving from day one</p></td> <td width="25%" align="center"><table width="65px" height="65px" border="0" cellspacing="0" cellpadding="0" style="background-image:url(images/yellowdot.png);"> <tr> <td width="65" align="center"><span class="socialproofaligncenterbig">14</span></td> </tr> </table> <p class="socialProofAlignCenter">experienced solar providers in your area</p></td> <td width="25%"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td> <div id="map" style="width: 250px; height: 250px"></div> <script src="js/leaflet.js"></script> <script> var map = L.map('map').setView([51.505, -0.09], 13); L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', { maxZoom: 18, attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>' }).addTo(map); L.marker([51.5, -0.09]).addTo(map) .bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup(); L.circle([51.508, -0.11], 500, { color: 'red', fillColor: '#f03', fillOpacity: 0.5 }).addTo(map).bindPopup("I am a circle."); L.polygon([ [51.509, -0.08], [51.503, -0.06], [51.51, -0.047] ]).addTo(map).bindPopup("I am a polygon."); var popup = L.popup(); function onMapClick(e) { popup .setLatLng(e.latlng) .setContent("You clicked the map at " + e.latlng.toString()) .openOn(map); } map.on('click', onMapClick); </script> </td> </tr> </table> <p class="socialProofAlignCenter">Number of solar homes in zip codes around you</p></td> </tr> </table> <button type="button" class="btn view providers" id="social_proof-view_providers">View providers</button> </div> <!-- /SOCIAL PROOF --> <!-- DASHBOARD --> <div class="page dashboard" id="page-dashboard" data-page="dashboard"> <!-- <aside class="logo"> <a href="/" class="logo sunible"><img src="images/_project/logo_sunible.png"/></a> </aside> --> <section class="providers number_of_selected"> <div class="block"> <p> You have selected<br/> <span class="counter selected providers number" id="dashboard-block-number_of_providers_selected">0</span> <br/> providers </p> <p class="max_length message">30 providers max</p> </div> <button type="button" class="btn register" id="dashboard-open_registration_page">Let's get Sunible</button> </section> <section class="providers container"> <header> <p> <span class="text">Showing</span> <span class="counter found providers number" id="dashboard-header-number_of_providers_found">25</span><!-- HARDCODE --> <span class="text">providers. Click to sort by Provider, $/Watt, Homes Installed or Rating</span> </p> </header> <div class="table container"> <table class="providers list grid" id="dashboard-grid-providers-list"> <thead> <tr> <th class="checkboxes"> <span class="text">Select</span> </th> <th class="name"> <span class="question_mark light" data-toggle="tooltip" data-placement="bottom" title="Some tooltip for 'Homes Installed' column.">?</span><br/> <span class="text">Solar Providers</span> </th> <th class="cost"> <span class="question_mark light" data-toggle="tooltip" data-placement="bottom" title="Some tooltip for 'Homes Installed' column.">?</span><br/> <span class="text">$/Watt</span> </th> <th class="number_of_homes_installed"> <span class="question_mark light" data-toggle="tooltip" data-placement="bottom" title="Some tooltip for 'Homes Installed' column.">?</span> <br/> <span class="text">Homes Installed</span> </th> <th class="rating"> <span class="question_mark light" data-toggle="tooltip" data-placement="bottom" title="Some tooltip for 'Homes Installed' column.">?</span><br/> <span class="text">Rating</span> </th> </tr> </thead> <tbody> <tr id="provider-10" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-10-checkbox"> <input type="checkbox" value="" id="provider-10-checkbox"/> </label> </td> <td class="name">Arise Solar<img src="images/_project/providers_logos/logo_AriseSolar.png"/></td> <td class="cost">100</td> <td class="number_of_homes_installed">12</td> <td class="rating"><span class="rating_stars has-4_5">*********</span></td> </tr> <tr id="provider-09" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-09-checkbox"> <input type="checkbox" value="" id="provider-09-checkbox"/> </label> </td> <td class="name">Real Goods Solar<img src="images/_project/providers_logos/logo_RealGoodsSolar.png"/></td> <td class="cost">96</td> <td class="number_of_homes_installed">123</td> <td class="rating"><span class="rating_stars has-2">****</span></td> </tr> <tr id="provider-08" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-08-checkbox"> <input type="checkbox" value="" id="provider-08-checkbox"/> </label> </td> <td class="name">Solar City<img src="images/_project/providers_logos/logo_SolarCity.png"/></td> <td class="cost">96</td> <td class="number_of_homes_installed">123</td> <td class="rating"><span class="rating_stars has-5">**********</span></td> </tr> <tr id="provider-07" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-07-checkbox"> <input type="checkbox" value="" id="provider-07-checkbox"/> </label> </td> <td class="name">Sungevity<img src="images/_project/providers_logos/logo_Sungevity.png"/></td> <td class="cost">96</td> <td class="number_of_homes_installed">123</td> <td class="rating"><span class="rating_stars has-1">**</span></td> </tr> <tr id="provider-06" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-06-checkbox"> <input type="checkbox" value="" id="provider-06-checkbox"/> </label> </td> <td class="name">Verengo Solar<img src="images/_project/providers_logos/logo_VerengoSolar.png"/></td> <td class="cost">96</td> <td class="number_of_homes_installed">123</td> <td class="rating"><span class="rating_stars has-5">**********</span></td> </tr> <tr id="provider-05" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-05-checkbox"> <input type="checkbox" value="" id="provider-05-checkbox"/> </label> </td> <td class="name">Arise Solar<img src="images/_project/providers_logos/logo_AriseSolar.png"/></td> <td class="cost">100</td> <td class="number_of_homes_installed">12</td> <td class="rating"><span class="rating_stars has-3">******</span></td> </tr> <tr id="provider-04" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-04-checkbox"> <input type="checkbox" value="" id="provider-04-checkbox"/> </label> </td> <td class="name">Real Goods Solar<img src="images/_project/providers_logos/logo_RealGoodsSolar.png"/></td> <td class="cost">96</td> <td class="number_of_homes_installed">123</td> <td class="rating"><span class="rating_stars has-4">********</span></td> </tr> <tr id="provider-03" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-03-checkbox"> <input type="checkbox" value="" id="provider-03-checkbox"/> </label> </td> <td class="name">Solar City<img src="images/_project/providers_logos/logo_SolarCity.png"/></td> <td class="cost">96</td> <td class="number_of_homes_installed">123</td> <td class="rating"><span class="rating_stars has-2_5">*****</span></td> </tr> <tr id="provider-02" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-02-checkbox"> <input type="checkbox" value="" id="provider-02-checkbox"/> </label> </td> <td class="name">Sungevity<img src="images/_project/providers_logos/logo_Sungevity.png"/></td> <td class="cost">96</td> <td class="number_of_homes_installed">123</td> <td class="rating"><span class="rating_stars has-2">****</span></td> </tr> <tr id="provider-01" class="provider row"> <td class="checkboxes"> <label class="checkbox" for="provider-01-checkbox"> <input type="checkbox" value="" id="provider-01-checkbox"/> </label> </td> <td class="name">Verengo Solar<img src="images/_project/providers_logos/logo_VerengoSolar.png"/></td> <td class="cost">96</td> <td class="number_of_homes_installed">123</td> <td class="rating"><span class="rating_stars has-3">******</span></td> </tr> </tbody> </table> </div> </section> </div> <!-- /DASHBOARD --> <!-- REGISTRATION --> <div class="page registration" id="page-registration" data-page="registration"> <h1> Registration <small>(Why do we collect this information <span class="question_mark dark" data-toggle="tooltip" data-placement="bottom" title="We collect this information to provide you better service">?</span>)</small> </h1> <form id="page-registration-form-register" class="registration_form" name="registration_form"> <p> My name is <!-- first name --> <span class="field_container"> <input type="text" class="field first_name" name="first_name" placeholder="First Name" required /> <span class="validation message"></span> </span> <!-- last name --> <span class="field_container"> <input type="text" class="field last_name" name="last_name" placeholder="Last Name" required/> <span class="validation message"></span> </span>, but you can call me <!-- nickname --> <span class="field_container"> <input type="text" class="field nickname" name="nickname" placeholder="Nickname" /> <span class="validation message"></span> </span>. <br/> I live at <!-- street address --> <span class="field_container"> <input type="text" class="field street_address" name="street_address" placeholder="Street Address" required/> <span class="validation message"></span> </span>, and can be reached on</span> <!-- phone number --> <span class="field_container"> <input type="tel" class="field phone_number" name="phone_number" placeholder="Phone Number (xxx)xxx-xxxx" pattern="^\(\d{3}\)\d{3}-\d{4}$" required/> <span class="validation message"></span> </span> <br/> or <!-- email --> <span class="field_container"> <input type="email" class="field email" name="email" placeholder="Email" pattern='(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))' required/> <span class="validation message"></span> </span>. I <!-- property type --> <span class="field_container"> <select class="field property_type" name="property_type" id="registration-select-appartment-property-type"> <option>rent</option> <option>own</option> </select> <span class="validation message"></span> </span> my place and pay about <!-- cost per month --> <span class="field_container"> <input type="text" class="field cost_per_month" name="cost_per_month" placeholder="$/month" min="0" required/> <span class="validation message"></span> </span> <br/> for electricity to the <!-- people nature --> <span class="field_container"> <select class="field people_nature" name="people_nature" id="registration-select-people-nature-type"> <option>good</option> <option>bad</option> <option>crazy</option> </select> <span class="validation message"></span> </span> people at <!-- electricity provider name --> <span class="field_container"> <select class="field electricity_provider_name" name="electricity_provider_name" id="registration-select-electricity-company-provider"> <option>Pacific Gas &amp; Electric (PG&amp;E)</option> <option>Southern California Edison</option> </select> <span class="validation message"></span> </span> I have a <!-- roof type --> <span class="field_container"> <select class="field roof_type" name="roof_type" id="registration-select-roof-type"> <option>tiled</option> <option>wood shake</option> <option>composite</option> <option>flat</option> <option>“no idea what”</option> </select> <span class="validation message"></span> </span> roof. </p> <button type="button" class="btn send_registration" id="registration-submit_registration_info">Go</button> </form> </div> <!-- /REGISTRATION --> <!-- THANK YOU --> <div class="page message" id="page-message" data-page="message"> <!-- This page is dynamic. Use it for messages like "Thank you", "Sorry", "Error", etc --> <p class="loading message">loading...</p> </div> <!-- /THANK YOU --> <!-- FOOTER --> <footer class="page_footer homepage social_proof dashboard registration message"> <!-- footer has those classes to be toggled with those pages. With that approach, no need to duplicate the footer on each page we have it--> <nav class="bottom navigation"> <a href="#">Blog</a> <a href="#">FAQ</a> <a href="#">Jobs</a> <a href="#">Contact</a> <a href="#">Terms</a> </nav> <span class="copyright">&copy; Sunible Inc. 2013</span> </footer> </div> <!-- JS --> <script type="text/javascript" src="js/jquery/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="js/jquery/jquery.placeholder.js"></script> <script type="text/javascript" src="js/jquery/jquery.validate.min.js"></script> <script type="text/javascript" src="js/jquery/additional-methods.min.js"></script> <script type="text/javascript" src="js/jquery/jquery.dropkick-1.0.0.js"></script> <script type="text/javascript" src="js/jquery/jquery.dataTables.min.js"></script> <script type="text/javascript" src="js/bootstrap/bootstrap-tooltip.js"></script> <script type="text/javascript" src="js/custom_checkbox_and_radio.js"></script> <script type="text/javascript" src="js/global_methods.js"></script> <script type="text/javascript" src="js/server_calls.js"></script> <script type="text/javascript" src="js/validation.js"></script> <script type="text/javascript" src="js/pages.js"></script> <script type="text/javascript" src="js/dashboard.js"></script> <script type="text/javascript" src="js/application_init.js"></script> </body> </html>
Java
<?php /** * @file * Opigno Learning Record Store stats - Course content - Course contexts statistics template file * * @param array $course_contexts_statistics */ ?> <div class="lrs-stats-widget" id="lrs-stats-widget-course-content-course-contexts-statistics"> <h2><?php print t('Course context statistics'); ?></h2> <?php print theme('opigno_lrs_stats_course_content_widget_course_contexts_statistics_list', compact('course_contexts_statistics')); ?> </div>
Java
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef GLK_DETECTION_H #define GLK_DETECTION_H #include "engines/advancedDetector.h" #include "engines/game.h" #define MAX_SAVES 99 /** * ScummVM Meta Engine interface */ class GlkMetaEngine : public MetaEngine { private: Common::String findFileByGameId(const Common::String &gameId) const; public: GlkMetaEngine() : MetaEngine() {} virtual const char *getName() const { return "ScummGlk"; } virtual const char *getOriginalCopyright() const { return "Infocom games (C) Infocom\nScott Adams games (C) Scott Adams"; } virtual bool hasFeature(MetaEngineFeature f) const override; virtual Common::Error createInstance(OSystem *syst, Engine **engine) const override; virtual SaveStateList listSaves(const char *target) const; virtual int getMaximumSaveSlot() const; virtual void removeSaveState(const char *target, int slot) const; SaveStateDescriptor querySaveMetaInfos(const char *target, int slot) const; /** * Returns a list of games supported by this engine. */ virtual PlainGameList getSupportedGames() const override; /** * Runs the engine's game detector on the given list of files, and returns a * (possibly empty) list of games supported by the engine which it was able * to detect amongst the given files. */ virtual DetectedGames detectGames(const Common::FSList &fslist) const override; /** * Query the engine for a PlainGameDescriptor for the specified gameid, if any. */ virtual PlainGameDescriptor findGame(const char *gameId) const override; /** * Calls each sub-engine in turn to ensure no game Id accidentally shares the same Id */ void detectClashes() const; }; namespace Glk { /** * Holds the name of a recognised game */ struct GameDescriptor { const char *_gameId; const char *_description; uint _options; GameDescriptor(const char *gameId, const char *description, uint options) : _gameId(gameId), _description(description), _options(options) {} GameDescriptor(const PlainGameDescriptor &gd) : _gameId(gd.gameId), _description(gd.description), _options(0) {} static PlainGameDescriptor empty() { return GameDescriptor(nullptr, nullptr, 0); } operator PlainGameDescriptor() const { PlainGameDescriptor pd; pd.gameId = _gameId; pd.description = _description; return pd; } }; } // End of namespace Glk #endif
Java
showWord(["v. ","vin jòn.<br>"])
Java
## ## Copyright 2007, Red Hat, Inc ## see AUTHORS ## ## This software may be freely redistributed under the terms of the GNU ## general public license. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ## import inspect from func import logger from func.config import read_config, BaseConfig from func.commonconfig import FuncdConfig from func.minion.func_arg import * #the arg getter stuff class FuncModule(object): # the version is meant to version = "0.0.0" api_version = "0.0.0" description = "No Description provided" class Config(BaseConfig): pass def __init__(self): config_file = '/etc/func/minion.conf' self.config = read_config(config_file, FuncdConfig) self.__init_log() self.__base_methods = { # __'s so we don't clobber useful names "module_version" : self.__module_version, "module_api_version" : self.__module_api_version, "module_description" : self.__module_description, "list_methods" : self.__list_methods, "get_method_args" : self.__get_method_args, } self.__init_options() def __init_log(self): log = logger.Logger() self.logger = log.logger def __init_options(self): options_file = '/etc/func/modules/'+self.__class__.__name__+'.conf' self.options = read_config(options_file, self.Config) return def register_rpc(self, handlers, module_name): # add the internal methods, note that this means they # can get clobbbered by subclass versions for meth in self.__base_methods: handlers["%s.%s" % (module_name, meth)] = self.__base_methods[meth] # register our module's handlers for name, handler in self.__list_handlers().items(): handlers["%s.%s" % (module_name, name)] = handler def __list_handlers(self): """ Return a dict of { handler_name, method, ... }. All methods that do not being with an underscore will be exposed. We also make sure to not expose our register_rpc method. """ handlers = {} for attr in dir(self): if self.__is_public_valid_method(attr): handlers[attr] = getattr(self, attr) return handlers def __list_methods(self): return self.__list_handlers().keys() + self.__base_methods.keys() def __module_version(self): return self.version def __module_api_version(self): return self.api_version def __module_description(self): return self.description def __is_public_valid_method(self,attr): if inspect.ismethod(getattr(self, attr)) and attr[0] != '_' and\ attr != 'register_rpc' and attr!='register_method_args': return True return False def __get_method_args(self): """ Gets arguments with their formats according to ArgCompatibility class' rules. @return : dict with args or Raise Exception if something wrong happens """ tmp_arg_dict = self.register_method_args() #if it is not implemeted then return empty stuff if not tmp_arg_dict: return {} #see if user tried to register an not implemented method :) for method in tmp_arg_dict.iterkeys(): if not hasattr(self,method): raise NonExistingMethodRegistered("%s is not in %s "%(method,self.__class__.__name__)) #create argument validation instance self.arg_comp = ArgCompatibility(tmp_arg_dict) #see if all registered arguments are there for method in tmp_arg_dict.iterkeys(): self.arg_comp.is_all_arguments_registered(self,method,tmp_arg_dict[method]['args']) #see if the options that were used are OK.. self.arg_comp.validate_all() return tmp_arg_dict def register_method_args(self): """ That is the method where users should override in their modules according to be able to send their method arguments to the Overlord. If they dont have it nothing breaks just that one in the base class is called @return : empty {} """ # to know they didnt implement it return {}
Java
package lambda; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class Esempio extends JFrame { public Esempio() { init(); } private void init() { BorderLayout b=new BorderLayout(); this.setLayout(b); JButton button=new JButton("Ok"); this.add(button,BorderLayout.SOUTH); this.setSize(400, 300); this.setVisible(true); ActionListener l=new Azione(); button.addActionListener(( e) -> System.out.println("ciao")); } public static void main(String[] args) { Esempio e=new Esempio(); } }
Java
/* DC++ Widget Toolkit Copyright (c) 2007-2013, Jacek Sieka All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the DWT nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <dwt/widgets/ProgressBar.h> namespace dwt { const TCHAR ProgressBar::windowClass[] = PROGRESS_CLASS; ProgressBar::Seed::Seed() : BaseType::Seed(WS_CHILD | PBS_SMOOTH) { } }
Java
<?php require "tableinitiateclass.php"; require "../queryinitiateclass.php"; $tbl = new AddTable; ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Table index</title> </head> <style> table { width:100%; } </style> <body> <?php // just the headers $arrayheaders = array("head1","head2","head3"); // just the rows $arrayrows = array(array("row1-1","row1-2","row1-3"), array("row2-1","row2-2","row2-3"), array("row3-1","row3-2","row3-3"), array("row4-1","row4-2","row4-3"), array("row5-1","row5-2","row5-3")); $query = new AddSql("root","","map_directory_uphrm","localhost"); $arraycolumns = $query->getallColumn("rooms_uphrm"); $arrayfields = $query->getallascolQuery("rooms_uphrm"); // display table styling still unfinished echo $tbl->settblQuery(sizeof($arrayfields),sizeof($arraycolumns),$arraycolumns,$arrayfields); // display search for row and column numbers echo $tbl->gettableData(2,1); // set search query $tbl->searchRows("-3"); // display search query echo $tbl->getsearchResults(); // reset table $tbl->resetAll(); // get query string $getquery = 'current'; // next page $nextpage = $tbl->checkSet($getquery) + 1; // back page $backpage = $tbl->checkSet($getquery) - 1; // display table with restriction of 2 echo $tbl->settblrestrictQuery(sizeof($arrayfields),sizeof($arraycolumns), $arraycolumns,$arrayfields,5, $tbl->checkSet($getquery)); // display back button $totaldist = sizeof($arrayfields) / 5; echo $tbl->toBack($backpage,$getquery); // display next button echo $tbl->toNext($nextpage,$getquery); ?> <button onclick = "ajaxNav()" > Next </button> <button onclick = "ajaxNavb()" > Back </button> <div id = "tableDiv" > </div> <?php echo $tbl->popupDelete(); ?> <script> var count = 1; function ajaxNav() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("tableDiv").innerHTML=xmlhttp.responseText; } } if(count<<?php echo $totaldist; ?>); count++; xmlhttp.open("GET","ajaxnav.php?<?php echo $getquery; ?>="+ count,true); xmlhttp.send(); } function ajaxNavb() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("tableDiv").innerHTML=xmlhttp.responseText; } } if(count>0); count--; xmlhttp.open("GET","ajaxnav.php?<?php echo $getquery; ?>="+ count,true); xmlhttp.send(); } </script> </body> </html>
Java
/* You may freely copy, distribute, modify and use this class as long as the original author attribution remains intact. See message below. Copyright (C) 1998-2006 Christian Pesch. All Rights Reserved. */ package slash.carcosts; import slash.gui.model.AbstractModel; /** * An CurrencyModel holds a Currency and provides get and set * methods for it. * * @author Christian Pesch */ public class CurrencyModel extends AbstractModel { /** * Construct a new CurrencyModel. */ public CurrencyModel() { this(Currency.getCurrency("DM")); } /** * Construct a new CurrencyModel. */ public CurrencyModel(Currency value) { setValue(value); } /** * Get the Currency value that is holded by the model. */ public Currency getValue() { return value; } /** * Set the Currency value to hold. */ public void setValue(Currency newValue) { if (value != newValue) { this.value = newValue; fireStateChanged(); } } public String toString() { return "CurrencyModel(" + value + ")"; } private Currency value; }
Java
/* c) The receipt screen */ .point-of-sale .pos-receipt-container { font-size: 10pt; } .point-of-sale .pos-sale-ticket { text-align: left; /* width: 76mm; */ width: 255px; /* background-color: white; */ margin: 0mm,0mm,0mm,0mm; /* padding: 1px; */ /* padding-bottom:1px; */ display: inline-block; font-family: "Tahoma","Inconsolata","Lucida Console", "monospace"; /* font-family: "Inconsolata"; */ /* border-radius: 2px; */ /* box-shadow: 0px 1px 0px white, 0px 3px 0px #C1B9D6, 0px 8px 16px rgba(0, 0, 0, 0.3);*/ } .point-of-sale .pos-sale-ticket .emph{ font-size: 12pt; margin:5px; font-weight: bolder; } .point-of-sale .pos-sale-ticket .ticket{ font-size: 16pt; font-weight: bolder; } .point-of-sale .pos-sale-ticket .titulo{ font-size: 16pt; font-weight: bolder; text-align: center; } .point-of-sale .pos-sale-ticket table { width: 100%; border: 0; table-layout: fixed; border-spacing: 1px 1px; border-collapse: collapse; } .point-of-sale .pos-sale-ticket p { font-size: 9pt; margin: 0px !important; padding: 0 !important; padding-bottom:0px !important; } .point-of-sale .pos-sale-ticket table td { font-size: 9pt; border: 0; margin: 0px !important; word-wrap: break-word; } @media print { .point-of-sale #topheader, .point-of-sale #leftpane { display: none !important; } .point-of-sale #content { top: 0px !important; } .point-of-sale #rightpane { left: 0px !important; background-color: white; } #receipt-screen header { display: none !important; } #receipt-screen { text-align: left; } .pos-actionbar { display: none !important; } .pos-sale-ticket { margin: 0px !important; } .debug-widget{ display: none !important; } .point-of-sale *{ text-shadow: none !important; box-shadow: none !important; background: transparent !important; } .point-of-sale .pos-sale-ticket{ margin-left: 0px !important; margin-right: 0px !important; border: none !important; } }
Java
/** * Ядро булевой логики */ /** * @author Алексей Кляузер <drum@pisem.net> * Ядро булевой логики */ package org.deneblingvo.booleans.core;
Java
#ifndef __LINUX_USB_H #define __LINUX_USB_H #include <linux/mod_devicetable.h> #include <linux/usb/ch9.h> #define USB_MAJOR 180 #define USB_DEVICE_MAJOR 189 #ifdef __KERNEL__ #include <linux/errno.h> /* for -ENODEV */ #include <linux/delay.h> /* for mdelay() */ #include <linux/interrupt.h> /* for in_interrupt() */ #include <linux/list.h> /* for struct list_head */ #include <linux/kref.h> /* for struct kref */ #include <linux/device.h> /* for struct device */ #include <linux/fs.h> /* for struct file_operations */ #include <linux/completion.h> /* for struct completion */ #include <linux/sched.h> /* for current && schedule_timeout */ #include <linux/mutex.h> /* for struct mutex */ #include <linux/pm_runtime.h> /* for runtime PM */ struct usb_device; struct usb_driver; struct wusb_dev; /*-------------------------------------------------------------------------*/ /* * Host-side wrappers for standard USB descriptors ... these are parsed * from the data provided by devices. Parsing turns them from a flat * sequence of descriptors into a hierarchy: * * - devices have one (usually) or more configs; * - configs have one (often) or more interfaces; * - interfaces have one (usually) or more settings; * - each interface setting has zero or (usually) more endpoints. * - a SuperSpeed endpoint has a companion descriptor * * And there might be other descriptors mixed in with those. * * Devices may also have class-specific or vendor-specific descriptors. */ struct ep_device; /** * struct usb_host_endpoint - host-side endpoint descriptor and queue * @desc: descriptor for this endpoint, wMaxPacketSize in native byteorder * @ss_ep_comp: SuperSpeed companion descriptor for this endpoint * @urb_list: urbs queued to this endpoint; maintained by usbcore * @hcpriv: for use by HCD; typically holds hardware dma queue head (QH) * with one or more transfer descriptors (TDs) per urb * @ep_dev: ep_device for sysfs info * @extra: descriptors following this endpoint in the configuration * @extralen: how many bytes of "extra" are valid * @enabled: URBs may be submitted to this endpoint * * USB requests are always queued to a given endpoint, identified by a * descriptor within an active interface in a given USB configuration. */ struct usb_host_endpoint { struct usb_endpoint_descriptor desc; struct usb_ss_ep_comp_descriptor ss_ep_comp; struct list_head urb_list; void *hcpriv; struct ep_device *ep_dev; /* For sysfs info */ unsigned char *extra; /* Extra descriptors */ int extralen; int enabled; }; /* host-side wrapper for one interface setting's parsed descriptors */ struct usb_host_interface { struct usb_interface_descriptor desc; /* array of desc.bNumEndpoint endpoints associated with this * interface setting. these will be in no particular order. */ struct usb_host_endpoint *endpoint; char *string; /* iInterface string, if present */ unsigned char *extra; /* Extra descriptors */ int extralen; }; enum usb_interface_condition { USB_INTERFACE_UNBOUND = 0, USB_INTERFACE_BINDING, USB_INTERFACE_BOUND, USB_INTERFACE_UNBINDING, }; /** * struct usb_interface - what usb device drivers talk to * @altsetting: array of interface structures, one for each alternate * setting that may be selected. Each one includes a set of * endpoint configurations. They will be in no particular order. * @cur_altsetting: the current altsetting. * @num_altsetting: number of altsettings defined. * @intf_assoc: interface association descriptor * @minor: the minor number assigned to this interface, if this * interface is bound to a driver that uses the USB major number. * If this interface does not use the USB major, this field should * be unused. The driver should set this value in the probe() * function of the driver, after it has been assigned a minor * number from the USB core by calling usb_register_dev(). * @condition: binding state of the interface: not bound, binding * (in probe()), bound to a driver, or unbinding (in disconnect()) * @sysfs_files_created: sysfs attributes exist * @ep_devs_created: endpoint child pseudo-devices exist * @unregistering: flag set when the interface is being unregistered * @needs_remote_wakeup: flag set when the driver requires remote-wakeup * capability during autosuspend. * @needs_altsetting0: flag set when a set-interface request for altsetting 0 * has been deferred. * @needs_binding: flag set when the driver should be re-probed or unbound * following a reset or suspend operation it doesn't support. * @dev: driver model's view of this device * @usb_dev: if an interface is bound to the USB major, this will point * to the sysfs representation for that device. * @pm_usage_cnt: PM usage counter for this interface * @reset_ws: Used for scheduling resets from atomic context. * @reset_running: set to 1 if the interface is currently running a * queued reset so that usb_cancel_queued_reset() doesn't try to * remove from the workqueue when running inside the worker * thread. See __usb_queue_reset_device(). * @resetting_device: USB core reset the device, so use alt setting 0 as * current; needs bandwidth alloc after reset. * * USB device drivers attach to interfaces on a physical device. Each * interface encapsulates a single high level function, such as feeding * an audio stream to a speaker or reporting a change in a volume control. * Many USB devices only have one interface. The protocol used to talk to * an interface's endpoints can be defined in a usb "class" specification, * or by a product's vendor. The (default) control endpoint is part of * every interface, but is never listed among the interface's descriptors. * * The driver that is bound to the interface can use standard driver model * calls such as dev_get_drvdata() on the dev member of this structure. * * Each interface may have alternate settings. The initial configuration * of a device sets altsetting 0, but the device driver can change * that setting using usb_set_interface(). Alternate settings are often * used to control the use of periodic endpoints, such as by having * different endpoints use different amounts of reserved USB bandwidth. * All standards-conformant USB devices that use isochronous endpoints * will use them in non-default settings. * * The USB specification says that alternate setting numbers must run from * 0 to one less than the total number of alternate settings. But some * devices manage to mess this up, and the structures aren't necessarily * stored in numerical order anyhow. Use usb_altnum_to_altsetting() to * look up an alternate setting in the altsetting array based on its number. */ struct usb_interface { /* array of alternate settings for this interface, * stored in no particular order */ struct usb_host_interface *altsetting; struct usb_host_interface *cur_altsetting; /* the currently * active alternate setting */ unsigned num_altsetting; /* number of alternate settings */ /* If there is an interface association descriptor then it will list * the associated interfaces */ struct usb_interface_assoc_descriptor *intf_assoc; int minor; /* minor number this interface is * bound to */ enum usb_interface_condition condition; /* state of binding */ unsigned sysfs_files_created:1; /* the sysfs attributes exist */ unsigned ep_devs_created:1; /* endpoint "devices" exist */ unsigned unregistering:1; /* unregistration is in progress */ unsigned needs_remote_wakeup:1; /* driver requires remote wakeup */ unsigned needs_altsetting0:1; /* switch to altsetting 0 is pending */ unsigned needs_binding:1; /* needs delayed unbind/rebind */ unsigned reset_running:1; unsigned resetting_device:1; /* true: bandwidth alloc after reset */ struct device dev; /* interface specific device info */ struct device *usb_dev; atomic_t pm_usage_cnt; /* usage counter for autosuspend */ struct work_struct reset_ws; /* for resets in atomic context */ }; #define to_usb_interface(d) container_of(d, struct usb_interface, dev) static inline void *usb_get_intfdata(struct usb_interface *intf) { return dev_get_drvdata(&intf->dev); } static inline void usb_set_intfdata(struct usb_interface *intf, void *data) { dev_set_drvdata(&intf->dev, data); } struct usb_interface *usb_get_intf(struct usb_interface *intf); void usb_put_intf(struct usb_interface *intf); /* this maximum is arbitrary */ #define USB_MAXINTERFACES 32 #define USB_MAXIADS (USB_MAXINTERFACES/2) /** * struct usb_interface_cache - long-term representation of a device interface * @num_altsetting: number of altsettings defined. * @ref: reference counter. * @altsetting: variable-length array of interface structures, one for * each alternate setting that may be selected. Each one includes a * set of endpoint configurations. They will be in no particular order. * * These structures persist for the lifetime of a usb_device, unlike * struct usb_interface (which persists only as long as its configuration * is installed). The altsetting arrays can be accessed through these * structures at any time, permitting comparison of configurations and * providing support for the /proc/bus/usb/devices pseudo-file. */ struct usb_interface_cache { unsigned num_altsetting; /* number of alternate settings */ struct kref ref; /* reference counter */ /* variable-length array of alternate settings for this interface, * stored in no particular order */ struct usb_host_interface altsetting[0]; }; #define ref_to_usb_interface_cache(r) \ container_of(r, struct usb_interface_cache, ref) #define altsetting_to_usb_interface_cache(a) \ container_of(a, struct usb_interface_cache, altsetting[0]) /** * struct usb_host_config - representation of a device's configuration * @desc: the device's configuration descriptor. * @string: pointer to the cached version of the iConfiguration string, if * present for this configuration. * @intf_assoc: list of any interface association descriptors in this config * @interface: array of pointers to usb_interface structures, one for each * interface in the configuration. The number of interfaces is stored * in desc.bNumInterfaces. These pointers are valid only while the * the configuration is active. * @intf_cache: array of pointers to usb_interface_cache structures, one * for each interface in the configuration. These structures exist * for the entire life of the device. * @extra: pointer to buffer containing all extra descriptors associated * with this configuration (those preceding the first interface * descriptor). * @extralen: length of the extra descriptors buffer. * * USB devices may have multiple configurations, but only one can be active * at any time. Each encapsulates a different operational environment; * for example, a dual-speed device would have separate configurations for * full-speed and high-speed operation. The number of configurations * available is stored in the device descriptor as bNumConfigurations. * * A configuration can contain multiple interfaces. Each corresponds to * a different function of the USB device, and all are available whenever * the configuration is active. The USB standard says that interfaces * are supposed to be numbered from 0 to desc.bNumInterfaces-1, but a lot * of devices get this wrong. In addition, the interface array is not * guaranteed to be sorted in numerical order. Use usb_ifnum_to_if() to * look up an interface entry based on its number. * * Device drivers should not attempt to activate configurations. The choice * of which configuration to install is a policy decision based on such * considerations as available power, functionality provided, and the user's * desires (expressed through userspace tools). However, drivers can call * usb_reset_configuration() to reinitialize the current configuration and * all its interfaces. */ struct usb_host_config { struct usb_config_descriptor desc; char *string; /* iConfiguration string, if present */ /* List of any Interface Association Descriptors in this * configuration. */ struct usb_interface_assoc_descriptor *intf_assoc[USB_MAXIADS]; /* the interfaces associated with this configuration, * stored in no particular order */ struct usb_interface *interface[USB_MAXINTERFACES]; /* Interface information available even when this is not the * active configuration */ struct usb_interface_cache *intf_cache[USB_MAXINTERFACES]; unsigned char *extra; /* Extra descriptors */ int extralen; }; int __usb_get_extra_descriptor(char *buffer, unsigned size, unsigned char type, void **ptr); #define usb_get_extra_descriptor(ifpoint, type, ptr) \ __usb_get_extra_descriptor((ifpoint)->extra, \ (ifpoint)->extralen, \ type, (void **)ptr) /* ----------------------------------------------------------------------- */ /* USB device number allocation bitmap */ struct usb_devmap { unsigned long devicemap[128 / (8*sizeof(unsigned long))]; }; /* * Allocated per bus (tree of devices) we have: */ struct usb_bus { struct device *controller; /* host/master side hardware */ int busnum; /* Bus number (in order of reg) */ const char *bus_name; /* stable id (PCI slot_name etc) */ u8 uses_dma; /* Does the host controller use DMA? */ u8 uses_pio_for_control; /* * Does the host controller use PIO * for control transfers? */ u8 otg_port; /* 0, or number of OTG/HNP port */ unsigned is_b_host:1; /* true during some HNP roleswitches */ unsigned b_hnp_enable:1; /* OTG: did A-Host enable HNP? */ unsigned sg_tablesize; /* 0 or largest number of sg list entries */ int devnum_next; /* Next open device number in * round-robin allocation */ struct usb_devmap devmap; /* device address allocation map */ struct usb_device *root_hub; /* Root hub */ struct usb_bus *hs_companion; /* Companion EHCI bus, if any */ struct list_head bus_list; /* list of busses */ int bandwidth_allocated; /* on this bus: how much of the time * reserved for periodic (intr/iso) * requests is used, on average? * Units: microseconds/frame. * Limits: Full/low speed reserve 90%, * while high speed reserves 80%. */ int bandwidth_int_reqs; /* number of Interrupt requests */ int bandwidth_isoc_reqs; /* number of Isoc. requests */ #ifdef CONFIG_USB_DEVICEFS struct dentry *usbfs_dentry; /* usbfs dentry entry for the bus */ #endif #if defined(CONFIG_USB_MON) || defined(CONFIG_USB_MON_MODULE) struct mon_bus *mon_bus; /* non-null when associated */ int monitored; /* non-zero when monitored */ #endif }; /* ----------------------------------------------------------------------- */ /* This is arbitrary. * From USB 2.0 spec Table 11-13, offset 7, a hub can * have up to 255 ports. The most yet reported is 10. * * Current Wireless USB host hardware (Intel i1480 for example) allows * up to 22 devices to connect. Upcoming hardware might raise that * limit. Because the arrays need to add a bit for hub status data, we * do 31, so plus one evens out to four bytes. */ #define USB_MAXCHILDREN (31) struct usb_tt; /** * struct usb_device - kernel's representation of a USB device * @devnum: device number; address on a USB bus * @devpath: device ID string for use in messages (e.g., /port/...) * @route: tree topology hex string for use with xHCI * @state: device state: configured, not attached, etc. * @speed: device speed: high/full/low (or error) * @tt: Transaction Translator info; used with low/full speed dev, highspeed hub * @ttport: device port on that tt hub * @toggle: one bit for each endpoint, with ([0] = IN, [1] = OUT) endpoints * @parent: our hub, unless we're the root * @bus: bus we're part of * @ep0: endpoint 0 data (default control pipe) * @dev: generic device interface * @descriptor: USB device descriptor * @config: all of the device's configs * @actconfig: the active configuration * @ep_in: array of IN endpoints * @ep_out: array of OUT endpoints * @rawdescriptors: raw descriptors for each config * @bus_mA: Current available from the bus * @portnum: parent port number (origin 1) * @level: number of USB hub ancestors * @can_submit: URBs may be submitted * @persist_enabled: USB_PERSIST enabled for this device * @have_langid: whether string_langid is valid * @authorized: policy has said we can use it; * (user space) policy determines if we authorize this device to be * used or not. By default, wired USB devices are authorized. * WUSB devices are not, until we authorize them from user space. * FIXME -- complete doc * @authenticated: Crypto authentication passed * @wusb: device is Wireless USB * @string_langid: language ID for strings * @product: iProduct string, if present (static) * @manufacturer: iManufacturer string, if present (static) * @serial: iSerialNumber string, if present (static) * @filelist: usbfs files that are open to this device * @usb_classdev: USB class device that was created for usbfs device * access from userspace * @usbfs_dentry: usbfs dentry entry for the device * @maxchild: number of ports if hub * @children: child devices - USB devices that are attached to this hub * @quirks: quirks of the whole device * @urbnum: number of URBs submitted for the whole device * @active_duration: total time device is not suspended * @connect_time: time device was first connected * @do_remote_wakeup: remote wakeup should be enabled * @reset_resume: needs reset instead of resume * @wusb_dev: if this is a Wireless USB device, link to the WUSB * specific data for the device. * @slot_id: Slot ID assigned by xHCI * * Notes: * Usbcore drivers should not set usbdev->state directly. Instead use * usb_set_device_state(). */ struct usb_device { int devnum; char devpath[16]; u32 route; enum usb_device_state state; enum usb_device_speed speed; struct usb_tt *tt; int ttport; unsigned int toggle[2]; struct usb_device *parent; struct usb_bus *bus; struct usb_host_endpoint ep0; struct device dev; struct usb_device_descriptor descriptor; struct usb_host_config *config; struct usb_host_config *actconfig; struct usb_host_endpoint *ep_in[16]; struct usb_host_endpoint *ep_out[16]; char **rawdescriptors; unsigned short bus_mA; u8 portnum; u8 level; unsigned can_submit:1; unsigned persist_enabled:1; unsigned have_langid:1; unsigned authorized:1; unsigned authenticated:1; unsigned wusb:1; int string_langid; /* static strings from the device */ char *product; char *manufacturer; char *serial; struct list_head filelist; #ifdef CONFIG_USB_DEVICE_CLASS struct device *usb_classdev; #endif #ifdef CONFIG_USB_DEVICEFS struct dentry *usbfs_dentry; #endif int maxchild; struct usb_device *children[USB_MAXCHILDREN]; u32 quirks; atomic_t urbnum; unsigned long active_duration; #ifdef CONFIG_PM unsigned long connect_time; unsigned do_remote_wakeup:1; unsigned reset_resume:1; #endif struct wusb_dev *wusb_dev; int slot_id; }; #define to_usb_device(d) container_of(d, struct usb_device, dev) static inline struct usb_device *interface_to_usbdev(struct usb_interface *intf) { return to_usb_device(intf->dev.parent); } extern struct usb_device *usb_get_dev(struct usb_device *dev); extern void usb_put_dev(struct usb_device *dev); /* USB device locking */ #define usb_lock_device(udev) device_lock(&(udev)->dev) #define usb_unlock_device(udev) device_unlock(&(udev)->dev) #define usb_trylock_device(udev) device_trylock(&(udev)->dev) extern int usb_lock_device_for_reset(struct usb_device *udev, const struct usb_interface *iface); /* USB port reset for device reinitialization */ extern int usb_reset_device(struct usb_device *dev); extern void usb_queue_reset_device(struct usb_interface *dev); /* USB autosuspend and autoresume */ #ifdef CONFIG_USB_SUSPEND extern void usb_enable_autosuspend(struct usb_device *udev); extern void usb_disable_autosuspend(struct usb_device *udev); extern int usb_autopm_get_interface(struct usb_interface *intf); extern void usb_autopm_put_interface(struct usb_interface *intf); extern int usb_autopm_get_interface_async(struct usb_interface *intf); extern void usb_autopm_put_interface_async(struct usb_interface *intf); extern void usb_autopm_get_interface_no_resume(struct usb_interface *intf); extern void usb_autopm_put_interface_no_suspend(struct usb_interface *intf); static inline void usb_mark_last_busy(struct usb_device *udev) { pm_runtime_mark_last_busy(&udev->dev); } #else static inline int usb_enable_autosuspend(struct usb_device *udev) { return 0; } static inline int usb_disable_autosuspend(struct usb_device *udev) { return 0; } static inline int usb_autopm_get_interface(struct usb_interface *intf) { return 0; } static inline int usb_autopm_get_interface_async(struct usb_interface *intf) { return 0; } static inline void usb_autopm_put_interface(struct usb_interface *intf) { } static inline void usb_autopm_put_interface_async(struct usb_interface *intf) { } static inline void usb_autopm_get_interface_no_resume( struct usb_interface *intf) { } static inline void usb_autopm_put_interface_no_suspend( struct usb_interface *intf) { } static inline void usb_mark_last_busy(struct usb_device *udev) { } #endif /*-------------------------------------------------------------------------*/ /* for drivers using iso endpoints */ extern int usb_get_current_frame_number(struct usb_device *usb_dev); /* Sets up a group of bulk endpoints to support multiple stream IDs. */ extern int usb_alloc_streams(struct usb_interface *interface, struct usb_host_endpoint **eps, unsigned int num_eps, unsigned int num_streams, gfp_t mem_flags); /* Reverts a group of bulk endpoints back to not using stream IDs. */ extern void usb_free_streams(struct usb_interface *interface, struct usb_host_endpoint **eps, unsigned int num_eps, gfp_t mem_flags); /* used these for multi-interface device registration */ extern int usb_driver_claim_interface(struct usb_driver *driver, struct usb_interface *iface, void *priv); /** * usb_interface_claimed - returns true iff an interface is claimed * @iface: the interface being checked * * Returns true (nonzero) iff the interface is claimed, else false (zero). * Callers must own the driver model's usb bus readlock. So driver * probe() entries don't need extra locking, but other call contexts * may need to explicitly claim that lock. * */ static inline int usb_interface_claimed(struct usb_interface *iface) { return (iface->dev.driver != NULL); } extern void usb_driver_release_interface(struct usb_driver *driver, struct usb_interface *iface); const struct usb_device_id *usb_match_id(struct usb_interface *interface, const struct usb_device_id *id); extern int usb_match_one_id(struct usb_interface *interface, const struct usb_device_id *id); extern struct usb_interface *usb_find_interface(struct usb_driver *drv, int minor); extern struct usb_interface *usb_ifnum_to_if(const struct usb_device *dev, unsigned ifnum); extern struct usb_host_interface *usb_altnum_to_altsetting( const struct usb_interface *intf, unsigned int altnum); extern struct usb_host_interface *usb_find_alt_setting( struct usb_host_config *config, unsigned int iface_num, unsigned int alt_num); /** * usb_make_path - returns stable device path in the usb tree * @dev: the device whose path is being constructed * @buf: where to put the string * @size: how big is "buf"? * * Returns length of the string (> 0) or negative if size was too small. * * This identifier is intended to be "stable", reflecting physical paths in * hardware such as physical bus addresses for host controllers or ports on * USB hubs. That makes it stay the same until systems are physically * reconfigured, by re-cabling a tree of USB devices or by moving USB host * controllers. Adding and removing devices, including virtual root hubs * in host controller driver modules, does not change these path identifiers; * neither does rebooting or re-enumerating. These are more useful identifiers * than changeable ("unstable") ones like bus numbers or device addresses. * * With a partial exception for devices connected to USB 2.0 root hubs, these * identifiers are also predictable. So long as the device tree isn't changed, * plugging any USB device into a given hub port always gives it the same path. * Because of the use of "companion" controllers, devices connected to ports on * USB 2.0 root hubs (EHCI host controllers) will get one path ID if they are * high speed, and a different one if they are full or low speed. */ static inline int usb_make_path(struct usb_device *dev, char *buf, size_t size) { int actual; actual = snprintf(buf, size, "usb-%s-%s", dev->bus->bus_name, dev->devpath); return (actual >= (int)size) ? -1 : actual; } /*-------------------------------------------------------------------------*/ #define USB_DEVICE_ID_MATCH_DEVICE \ (USB_DEVICE_ID_MATCH_VENDOR | USB_DEVICE_ID_MATCH_PRODUCT) #define USB_DEVICE_ID_MATCH_DEV_RANGE \ (USB_DEVICE_ID_MATCH_DEV_LO | USB_DEVICE_ID_MATCH_DEV_HI) #define USB_DEVICE_ID_MATCH_DEVICE_AND_VERSION \ (USB_DEVICE_ID_MATCH_DEVICE | USB_DEVICE_ID_MATCH_DEV_RANGE) #define USB_DEVICE_ID_MATCH_DEV_INFO \ (USB_DEVICE_ID_MATCH_DEV_CLASS | \ USB_DEVICE_ID_MATCH_DEV_SUBCLASS | \ USB_DEVICE_ID_MATCH_DEV_PROTOCOL) #define USB_DEVICE_ID_MATCH_INT_INFO \ (USB_DEVICE_ID_MATCH_INT_CLASS | \ USB_DEVICE_ID_MATCH_INT_SUBCLASS | \ USB_DEVICE_ID_MATCH_INT_PROTOCOL) /** * USB_DEVICE - macro used to describe a specific usb device * @vend: the 16 bit USB Vendor ID * @prod: the 16 bit USB Product ID * * This macro is used to create a struct usb_device_id that matches a * specific device. */ #define USB_DEVICE(vend, prod) \ .match_flags = USB_DEVICE_ID_MATCH_DEVICE, \ .idVendor = (vend), \ .idProduct = (prod) /** * USB_DEVICE_VER - describe a specific usb device with a version range * @vend: the 16 bit USB Vendor ID * @prod: the 16 bit USB Product ID * @lo: the bcdDevice_lo value * @hi: the bcdDevice_hi value * * This macro is used to create a struct usb_device_id that matches a * specific device, with a version range. */ #define USB_DEVICE_VER(vend, prod, lo, hi) \ .match_flags = USB_DEVICE_ID_MATCH_DEVICE_AND_VERSION, \ .idVendor = (vend), \ .idProduct = (prod), \ .bcdDevice_lo = (lo), \ .bcdDevice_hi = (hi) /** * USB_DEVICE_INTERFACE_PROTOCOL - describe a usb device with a specific interface protocol * @vend: the 16 bit USB Vendor ID * @prod: the 16 bit USB Product ID * @pr: bInterfaceProtocol value * * This macro is used to create a struct usb_device_id that matches a * specific interface protocol of devices. */ #define USB_DEVICE_INTERFACE_PROTOCOL(vend, prod, pr) \ .match_flags = USB_DEVICE_ID_MATCH_DEVICE | \ USB_DEVICE_ID_MATCH_INT_PROTOCOL, \ .idVendor = (vend), \ .idProduct = (prod), \ .bInterfaceProtocol = (pr) /** * USB_DEVICE_INFO - macro used to describe a class of usb devices * @cl: bDeviceClass value * @sc: bDeviceSubClass value * @pr: bDeviceProtocol value * * This macro is used to create a struct usb_device_id that matches a * specific class of devices. */ #define USB_DEVICE_INFO(cl, sc, pr) \ .match_flags = USB_DEVICE_ID_MATCH_DEV_INFO, \ .bDeviceClass = (cl), \ .bDeviceSubClass = (sc), \ .bDeviceProtocol = (pr) /** * USB_INTERFACE_INFO - macro used to describe a class of usb interfaces * @cl: bInterfaceClass value * @sc: bInterfaceSubClass value * @pr: bInterfaceProtocol value * * This macro is used to create a struct usb_device_id that matches a * specific class of interfaces. */ #define USB_INTERFACE_INFO(cl, sc, pr) \ .match_flags = USB_DEVICE_ID_MATCH_INT_INFO, \ .bInterfaceClass = (cl), \ .bInterfaceSubClass = (sc), \ .bInterfaceProtocol = (pr) /** * USB_DEVICE_AND_INTERFACE_INFO - describe a specific usb device with a class of usb interfaces * @vend: the 16 bit USB Vendor ID * @prod: the 16 bit USB Product ID * @cl: bInterfaceClass value * @sc: bInterfaceSubClass value * @pr: bInterfaceProtocol value * * This macro is used to create a struct usb_device_id that matches a * specific device with a specific class of interfaces. * * This is especially useful when explicitly matching devices that have * vendor specific bDeviceClass values, but standards-compliant interfaces. */ #define USB_DEVICE_AND_INTERFACE_INFO(vend, prod, cl, sc, pr) \ .match_flags = USB_DEVICE_ID_MATCH_INT_INFO \ | USB_DEVICE_ID_MATCH_DEVICE, \ .idVendor = (vend), \ .idProduct = (prod), \ .bInterfaceClass = (cl), \ .bInterfaceSubClass = (sc), \ .bInterfaceProtocol = (pr) /* ----------------------------------------------------------------------- */ /* Stuff for dynamic usb ids */ struct usb_dynids { spinlock_t lock; struct list_head list; }; struct usb_dynid { struct list_head node; struct usb_device_id id; }; extern ssize_t usb_store_new_id(struct usb_dynids *dynids, struct device_driver *driver, const char *buf, size_t count); /** * struct usbdrv_wrap - wrapper for driver-model structure * @driver: The driver-model core driver structure. * @for_devices: Non-zero for device drivers, 0 for interface drivers. */ struct usbdrv_wrap { struct device_driver driver; int for_devices; }; /** * struct usb_driver - identifies USB interface driver to usbcore * @name: The driver name should be unique among USB drivers, * and should normally be the same as the module name. * @probe: Called to see if the driver is willing to manage a particular * interface on a device. If it is, probe returns zero and uses * usb_set_intfdata() to associate driver-specific data with the * interface. It may also use usb_set_interface() to specify the * appropriate altsetting. If unwilling to manage the interface, * return -ENODEV, if genuine IO errors occurred, an appropriate * negative errno value. * @disconnect: Called when the interface is no longer accessible, usually * because its device has been (or is being) disconnected or the * driver module is being unloaded. * @unlocked_ioctl: Used for drivers that want to talk to userspace through * the "usbfs" filesystem. This lets devices provide ways to * expose information to user space regardless of where they * do (or don't) show up otherwise in the filesystem. * @suspend: Called when the device is going to be suspended by the system. * @resume: Called when the device is being resumed by the system. * @reset_resume: Called when the suspended device has been reset instead * of being resumed. * @pre_reset: Called by usb_reset_device() when the device is about to be * reset. This routine must not return until the driver has no active * URBs for the device, and no more URBs may be submitted until the * post_reset method is called. * @post_reset: Called by usb_reset_device() after the device * has been reset * @id_table: USB drivers use ID table to support hotplugging. * Export this with MODULE_DEVICE_TABLE(usb,...). This must be set * or your driver's probe function will never get called. * @dynids: used internally to hold the list of dynamically added device * ids for this driver. * @drvwrap: Driver-model core structure wrapper. * @no_dynamic_id: if set to 1, the USB core will not allow dynamic ids to be * added to this driver by preventing the sysfs file from being created. * @supports_autosuspend: if set to 0, the USB core will not allow autosuspend * for interfaces bound to this driver. * @soft_unbind: if set to 1, the USB core will not kill URBs and disable * endpoints before calling the driver's disconnect method. * * USB interface drivers must provide a name, probe() and disconnect() * methods, and an id_table. Other driver fields are optional. * * The id_table is used in hotplugging. It holds a set of descriptors, * and specialized data may be associated with each entry. That table * is used by both user and kernel mode hotplugging support. * * The probe() and disconnect() methods are called in a context where * they can sleep, but they should avoid abusing the privilege. Most * work to connect to a device should be done when the device is opened, * and undone at the last close. The disconnect code needs to address * concurrency issues with respect to open() and close() methods, as * well as forcing all pending I/O requests to complete (by unlinking * them as necessary, and blocking until the unlinks complete). */ struct usb_driver { const char *name; int (*probe) (struct usb_interface *intf, const struct usb_device_id *id); void (*disconnect) (struct usb_interface *intf); int (*unlocked_ioctl) (struct usb_interface *intf, unsigned int code, void *buf); int (*suspend) (struct usb_interface *intf, pm_message_t message); int (*resume) (struct usb_interface *intf); int (*reset_resume)(struct usb_interface *intf); int (*pre_reset)(struct usb_interface *intf); int (*post_reset)(struct usb_interface *intf); const struct usb_device_id *id_table; struct usb_dynids dynids; struct usbdrv_wrap drvwrap; unsigned int no_dynamic_id:1; unsigned int supports_autosuspend:1; unsigned int soft_unbind:1; }; #define to_usb_driver(d) container_of(d, struct usb_driver, drvwrap.driver) /** * struct usb_device_driver - identifies USB device driver to usbcore * @name: The driver name should be unique among USB drivers, * and should normally be the same as the module name. * @probe: Called to see if the driver is willing to manage a particular * device. If it is, probe returns zero and uses dev_set_drvdata() * to associate driver-specific data with the device. If unwilling * to manage the device, return a negative errno value. * @disconnect: Called when the device is no longer accessible, usually * because it has been (or is being) disconnected or the driver's * module is being unloaded. * @suspend: Called when the device is going to be suspended by the system. * @resume: Called when the device is being resumed by the system. * @drvwrap: Driver-model core structure wrapper. * @supports_autosuspend: if set to 0, the USB core will not allow autosuspend * for devices bound to this driver. * * USB drivers must provide all the fields listed above except drvwrap. */ struct usb_device_driver { const char *name; int (*probe) (struct usb_device *udev); void (*disconnect) (struct usb_device *udev); int (*suspend) (struct usb_device *udev, pm_message_t message); int (*resume) (struct usb_device *udev, pm_message_t message); struct usbdrv_wrap drvwrap; unsigned int supports_autosuspend:1; }; #define to_usb_device_driver(d) container_of(d, struct usb_device_driver, \ drvwrap.driver) extern struct bus_type usb_bus_type; /** * struct usb_class_driver - identifies a USB driver that wants to use the USB major number * @name: the usb class device name for this driver. Will show up in sysfs. * @devnode: Callback to provide a naming hint for a possible * device node to create. * @fops: pointer to the struct file_operations of this driver. * @minor_base: the start of the minor range for this driver. * * This structure is used for the usb_register_dev() and * usb_unregister_dev() functions, to consolidate a number of the * parameters used for them. */ struct usb_class_driver { char *name; char *(*devnode)(struct device *dev, umode_t *mode); const struct file_operations *fops; int minor_base; }; /* * use these in module_init()/module_exit() * and don't forget MODULE_DEVICE_TABLE(usb, ...) */ extern int usb_register_driver(struct usb_driver *, struct module *, const char *); /* use a define to avoid include chaining to get THIS_MODULE & friends */ #define usb_register(driver) \ usb_register_driver(driver, THIS_MODULE, KBUILD_MODNAME) extern void usb_deregister(struct usb_driver *); extern int usb_register_device_driver(struct usb_device_driver *, struct module *); extern void usb_deregister_device_driver(struct usb_device_driver *); extern int usb_register_dev(struct usb_interface *intf, struct usb_class_driver *class_driver); extern void usb_deregister_dev(struct usb_interface *intf, struct usb_class_driver *class_driver); extern int usb_disabled(void); /* ----------------------------------------------------------------------- */ /* * URB support, for asynchronous request completions */ /* * urb->transfer_flags: * * Note: URB_DIR_IN/OUT is automatically set in usb_submit_urb(). */ #define URB_SHORT_NOT_OK 0x0001 /* report short reads as errors */ #define URB_ISO_ASAP 0x0002 /* iso-only, urb->start_frame * ignored */ #define URB_NO_TRANSFER_DMA_MAP 0x0004 /* urb->transfer_dma valid on submit */ #define URB_NO_FSBR 0x0020 /* UHCI-specific */ #define URB_ZERO_PACKET 0x0040 /* Finish bulk OUT with short packet */ #define URB_NO_INTERRUPT 0x0080 /* HINT: no non-error interrupt * needed */ #define URB_FREE_BUFFER 0x0100 /* Free transfer buffer with the URB */ /* The following flags are used internally by usbcore and HCDs */ #define URB_DIR_IN 0x0200 /* Transfer from device to host */ #define URB_DIR_OUT 0 #define URB_DIR_MASK URB_DIR_IN #define URB_DMA_MAP_SINGLE 0x00010000 /* Non-scatter-gather mapping */ #define URB_DMA_MAP_PAGE 0x00020000 /* HCD-unsupported S-G */ #define URB_DMA_MAP_SG 0x00040000 /* HCD-supported S-G */ #define URB_MAP_LOCAL 0x00080000 /* HCD-local-memory mapping */ #define URB_SETUP_MAP_SINGLE 0x00100000 /* Setup packet DMA mapped */ #define URB_SETUP_MAP_LOCAL 0x00200000 /* HCD-local setup packet */ #define URB_DMA_SG_COMBINED 0x00400000 /* S-G entries were combined */ #define URB_ALIGNED_TEMP_BUFFER 0x00800000 /* Temp buffer was alloc'd */ struct usb_iso_packet_descriptor { unsigned int offset; unsigned int length; /* expected length */ unsigned int actual_length; int status; }; struct urb; struct usb_anchor { struct list_head urb_list; wait_queue_head_t wait; spinlock_t lock; unsigned int poisoned:1; }; static inline void init_usb_anchor(struct usb_anchor *anchor) { INIT_LIST_HEAD(&anchor->urb_list); init_waitqueue_head(&anchor->wait); spin_lock_init(&anchor->lock); } typedef void (*usb_complete_t)(struct urb *); /** * struct urb - USB Request Block * @urb_list: For use by current owner of the URB. * @anchor_list: membership in the list of an anchor * @anchor: to anchor URBs to a common mooring * @ep: Points to the endpoint's data structure. Will eventually * replace @pipe. * @pipe: Holds endpoint number, direction, type, and more. * Create these values with the eight macros available; * usb_{snd,rcv}TYPEpipe(dev,endpoint), where the TYPE is "ctrl" * (control), "bulk", "int" (interrupt), or "iso" (isochronous). * For example usb_sndbulkpipe() or usb_rcvintpipe(). Endpoint * numbers range from zero to fifteen. Note that "in" endpoint two * is a different endpoint (and pipe) from "out" endpoint two. * The current configuration controls the existence, type, and * maximum packet size of any given endpoint. * @stream_id: the endpoint's stream ID for bulk streams * @dev: Identifies the USB device to perform the request. * @status: This is read in non-iso completion functions to get the * status of the particular request. ISO requests only use it * to tell whether the URB was unlinked; detailed status for * each frame is in the fields of the iso_frame-desc. * @transfer_flags: A variety of flags may be used to affect how URB * submission, unlinking, or operation are handled. Different * kinds of URB can use different flags. * @transfer_buffer: This identifies the buffer to (or from) which the I/O * request will be performed unless URB_NO_TRANSFER_DMA_MAP is set * (however, do not leave garbage in transfer_buffer even then). * This buffer must be suitable for DMA; allocate it with * kmalloc() or equivalent. For transfers to "in" endpoints, contents * of this buffer will be modified. This buffer is used for the data * stage of control transfers. * @transfer_dma: When transfer_flags includes URB_NO_TRANSFER_DMA_MAP, * the device driver is saying that it provided this DMA address, * which the host controller driver should use in preference to the * transfer_buffer. * @sg: scatter gather buffer list * @num_sgs: number of entries in the sg list * @transfer_buffer_length: How big is transfer_buffer. The transfer may * be broken up into chunks according to the current maximum packet * size for the endpoint, which is a function of the configuration * and is encoded in the pipe. When the length is zero, neither * transfer_buffer nor transfer_dma is used. * @actual_length: This is read in non-iso completion functions, and * it tells how many bytes (out of transfer_buffer_length) were * transferred. It will normally be the same as requested, unless * either an error was reported or a short read was performed. * The URB_SHORT_NOT_OK transfer flag may be used to make such * short reads be reported as errors. * @setup_packet: Only used for control transfers, this points to eight bytes * of setup data. Control transfers always start by sending this data * to the device. Then transfer_buffer is read or written, if needed. * @setup_dma: DMA pointer for the setup packet. The caller must not use * this field; setup_packet must point to a valid buffer. * @start_frame: Returns the initial frame for isochronous transfers. * @number_of_packets: Lists the number of ISO transfer buffers. * @interval: Specifies the polling interval for interrupt or isochronous * transfers. The units are frames (milliseconds) for full and low * speed devices, and microframes (1/8 millisecond) for highspeed * and SuperSpeed devices. * @error_count: Returns the number of ISO transfers that reported errors. * @context: For use in completion functions. This normally points to * request-specific driver context. * @complete: Completion handler. This URB is passed as the parameter to the * completion function. The completion function may then do what * it likes with the URB, including resubmitting or freeing it. * @iso_frame_desc: Used to provide arrays of ISO transfer buffers and to * collect the transfer status for each buffer. * * This structure identifies USB transfer requests. URBs must be allocated by * calling usb_alloc_urb() and freed with a call to usb_free_urb(). * Initialization may be done using various usb_fill_*_urb() functions. URBs * are submitted using usb_submit_urb(), and pending requests may be canceled * using usb_unlink_urb() or usb_kill_urb(). * * Data Transfer Buffers: * * Normally drivers provide I/O buffers allocated with kmalloc() or otherwise * taken from the general page pool. That is provided by transfer_buffer * (control requests also use setup_packet), and host controller drivers * perform a dma mapping (and unmapping) for each buffer transferred. Those * mapping operations can be expensive on some platforms (perhaps using a dma * bounce buffer or talking to an IOMMU), * although they're cheap on commodity x86 and ppc hardware. * * Alternatively, drivers may pass the URB_NO_TRANSFER_DMA_MAP transfer flag, * which tells the host controller driver that no such mapping is needed for * the transfer_buffer since * the device driver is DMA-aware. For example, a device driver might * allocate a DMA buffer with usb_alloc_coherent() or call usb_buffer_map(). * When this transfer flag is provided, host controller drivers will * attempt to use the dma address found in the transfer_dma * field rather than determining a dma address themselves. * * Note that transfer_buffer must still be set if the controller * does not support DMA (as indicated by bus.uses_dma) and when talking * to root hub. If you have to trasfer between highmem zone and the device * on such controller, create a bounce buffer or bail out with an error. * If transfer_buffer cannot be set (is in highmem) and the controller is DMA * capable, assign NULL to it, so that usbmon knows not to use the value. * The setup_packet must always be set, so it cannot be located in highmem. * * Initialization: * * All URBs submitted must initialize the dev, pipe, transfer_flags (may be * zero), and complete fields. All URBs must also initialize * transfer_buffer and transfer_buffer_length. They may provide the * URB_SHORT_NOT_OK transfer flag, indicating that short reads are * to be treated as errors; that flag is invalid for write requests. * * Bulk URBs may * use the URB_ZERO_PACKET transfer flag, indicating that bulk OUT transfers * should always terminate with a short packet, even if it means adding an * extra zero length packet. * * Control URBs must provide a valid pointer in the setup_packet field. * Unlike the transfer_buffer, the setup_packet may not be mapped for DMA * beforehand. * * Interrupt URBs must provide an interval, saying how often (in milliseconds * or, for highspeed devices, 125 microsecond units) * to poll for transfers. After the URB has been submitted, the interval * field reflects how the transfer was actually scheduled. * The polling interval may be more frequent than requested. * For example, some controllers have a maximum interval of 32 milliseconds, * while others support intervals of up to 1024 milliseconds. * Isochronous URBs also have transfer intervals. (Note that for isochronous * endpoints, as well as high speed interrupt endpoints, the encoding of * the transfer interval in the endpoint descriptor is logarithmic. * Device drivers must convert that value to linear units themselves.) * * Isochronous URBs normally use the URB_ISO_ASAP transfer flag, telling * the host controller to schedule the transfer as soon as bandwidth * utilization allows, and then set start_frame to reflect the actual frame * selected during submission. Otherwise drivers must specify the start_frame * and handle the case where the transfer can't begin then. However, drivers * won't know how bandwidth is currently allocated, and while they can * find the current frame using usb_get_current_frame_number () they can't * know the range for that frame number. (Ranges for frame counter values * are HC-specific, and can go from 256 to 65536 frames from "now".) * * Isochronous URBs have a different data transfer model, in part because * the quality of service is only "best effort". Callers provide specially * allocated URBs, with number_of_packets worth of iso_frame_desc structures * at the end. Each such packet is an individual ISO transfer. Isochronous * URBs are normally queued, submitted by drivers to arrange that * transfers are at least double buffered, and then explicitly resubmitted * in completion handlers, so * that data (such as audio or video) streams at as constant a rate as the * host controller scheduler can support. * * Completion Callbacks: * * The completion callback is made in_interrupt(), and one of the first * things that a completion handler should do is check the status field. * The status field is provided for all URBs. It is used to report * unlinked URBs, and status for all non-ISO transfers. It should not * be examined before the URB is returned to the completion handler. * * The context field is normally used to link URBs back to the relevant * driver or request state. * * When the completion callback is invoked for non-isochronous URBs, the * actual_length field tells how many bytes were transferred. This field * is updated even when the URB terminated with an error or was unlinked. * * ISO transfer status is reported in the status and actual_length fields * of the iso_frame_desc array, and the number of errors is reported in * error_count. Completion callbacks for ISO transfers will normally * (re)submit URBs to ensure a constant transfer rate. * * Note that even fields marked "public" should not be touched by the driver * when the urb is owned by the hcd, that is, since the call to * usb_submit_urb() till the entry into the completion routine. */ struct urb { /* private: usb core and host controller only fields in the urb */ struct kref kref; /* reference count of the URB */ void *hcpriv; /* private data for host controller */ atomic_t use_count; /* concurrent submissions counter */ atomic_t reject; /* submissions will fail */ int unlinked; /* unlink error code */ /* public: documented fields in the urb that can be used by drivers */ struct list_head urb_list; /* list head for use by the urb's * current owner */ struct list_head anchor_list; /* the URB may be anchored */ struct usb_anchor *anchor; struct usb_device *dev; /* (in) pointer to associated device */ struct usb_host_endpoint *ep; /* (internal) pointer to endpoint */ unsigned int pipe; /* (in) pipe information */ unsigned int stream_id; /* (in) stream ID */ int status; /* (return) non-ISO status */ unsigned int transfer_flags; /* (in) URB_SHORT_NOT_OK | ...*/ void *transfer_buffer; /* (in) associated data buffer */ dma_addr_t transfer_dma; /* (in) dma addr for transfer_buffer */ struct scatterlist *sg; /* (in) scatter gather buffer list */ int num_mapped_sgs; /* (internal) mapped sg entries */ int num_sgs; /* (in) number of entries in the sg list */ u32 transfer_buffer_length; /* (in) data buffer length */ u32 actual_length; /* (return) actual transfer length */ unsigned char *setup_packet; /* (in) setup packet (control only) */ dma_addr_t setup_dma; /* (in) dma addr for setup_packet */ int start_frame; /* (modify) start frame (ISO) */ int number_of_packets; /* (in) number of ISO packets */ int interval; /* (modify) transfer interval * (INT/ISO) */ int error_count; /* (return) number of ISO errors */ void *context; /* (in) context for completion */ usb_complete_t complete; /* (in) completion routine */ struct usb_iso_packet_descriptor iso_frame_desc[0]; /* (in) ISO ONLY */ }; /* ----------------------------------------------------------------------- */ /** * usb_fill_control_urb - initializes a control urb * @urb: pointer to the urb to initialize. * @dev: pointer to the struct usb_device for this urb. * @pipe: the endpoint pipe * @setup_packet: pointer to the setup_packet buffer * @transfer_buffer: pointer to the transfer buffer * @buffer_length: length of the transfer buffer * @complete_fn: pointer to the usb_complete_t function * @context: what to set the urb context to. * * Initializes a control urb with the proper information needed to submit * it to a device. */ static inline void usb_fill_control_urb(struct urb *urb, struct usb_device *dev, unsigned int pipe, unsigned char *setup_packet, void *transfer_buffer, int buffer_length, usb_complete_t complete_fn, void *context) { urb->dev = dev; urb->pipe = pipe; urb->setup_packet = setup_packet; urb->transfer_buffer = transfer_buffer; urb->transfer_buffer_length = buffer_length; urb->complete = complete_fn; urb->context = context; } /** * usb_fill_bulk_urb - macro to help initialize a bulk urb * @urb: pointer to the urb to initialize. * @dev: pointer to the struct usb_device for this urb. * @pipe: the endpoint pipe * @transfer_buffer: pointer to the transfer buffer * @buffer_length: length of the transfer buffer * @complete_fn: pointer to the usb_complete_t function * @context: what to set the urb context to. * * Initializes a bulk urb with the proper information needed to submit it * to a device. */ static inline void usb_fill_bulk_urb(struct urb *urb, struct usb_device *dev, unsigned int pipe, void *transfer_buffer, int buffer_length, usb_complete_t complete_fn, void *context) { urb->dev = dev; urb->pipe = pipe; urb->transfer_buffer = transfer_buffer; urb->transfer_buffer_length = buffer_length; urb->complete = complete_fn; urb->context = context; } /** * usb_fill_int_urb - macro to help initialize a interrupt urb * @urb: pointer to the urb to initialize. * @dev: pointer to the struct usb_device for this urb. * @pipe: the endpoint pipe * @transfer_buffer: pointer to the transfer buffer * @buffer_length: length of the transfer buffer * @complete_fn: pointer to the usb_complete_t function * @context: what to set the urb context to. * @interval: what to set the urb interval to, encoded like * the endpoint descriptor's bInterval value. * * Initializes a interrupt urb with the proper information needed to submit * it to a device. * * Note that High Speed and SuperSpeed interrupt endpoints use a logarithmic * encoding of the endpoint interval, and express polling intervals in * microframes (eight per millisecond) rather than in frames (one per * millisecond). * * Wireless USB also uses the logarithmic encoding, but specifies it in units of * 128us instead of 125us. For Wireless USB devices, the interval is passed * through to the host controller, rather than being translated into microframe * units. */ static inline void usb_fill_int_urb(struct urb *urb, struct usb_device *dev, unsigned int pipe, void *transfer_buffer, int buffer_length, usb_complete_t complete_fn, void *context, int interval) { urb->dev = dev; urb->pipe = pipe; urb->transfer_buffer = transfer_buffer; urb->transfer_buffer_length = buffer_length; urb->complete = complete_fn; urb->context = context; if (dev->speed == USB_SPEED_HIGH || dev->speed == USB_SPEED_SUPER) urb->interval = 1 << (interval - 1); else urb->interval = interval; urb->start_frame = -1; } extern void usb_init_urb(struct urb *urb); extern struct urb *usb_alloc_urb(int iso_packets, gfp_t mem_flags); extern void usb_free_urb(struct urb *urb); #define usb_put_urb usb_free_urb extern struct urb *usb_get_urb(struct urb *urb); extern int usb_submit_urb(struct urb *urb, gfp_t mem_flags); extern int usb_unlink_urb(struct urb *urb); extern void usb_kill_urb(struct urb *urb); extern void usb_poison_urb(struct urb *urb); extern void usb_unpoison_urb(struct urb *urb); extern void usb_kill_anchored_urbs(struct usb_anchor *anchor); extern void usb_poison_anchored_urbs(struct usb_anchor *anchor); extern void usb_unpoison_anchored_urbs(struct usb_anchor *anchor); extern void usb_unlink_anchored_urbs(struct usb_anchor *anchor); extern void usb_anchor_urb(struct urb *urb, struct usb_anchor *anchor); extern void usb_unanchor_urb(struct urb *urb); extern int usb_wait_anchor_empty_timeout(struct usb_anchor *anchor, unsigned int timeout); extern struct urb *usb_get_from_anchor(struct usb_anchor *anchor); extern void usb_scuttle_anchored_urbs(struct usb_anchor *anchor); extern int usb_anchor_empty(struct usb_anchor *anchor); /** * usb_urb_dir_in - check if an URB describes an IN transfer * @urb: URB to be checked * * Returns 1 if @urb describes an IN transfer (device-to-host), * otherwise 0. */ static inline int usb_urb_dir_in(struct urb *urb) { return (urb->transfer_flags & URB_DIR_MASK) == URB_DIR_IN; } /** * usb_urb_dir_out - check if an URB describes an OUT transfer * @urb: URB to be checked * * Returns 1 if @urb describes an OUT transfer (host-to-device), * otherwise 0. */ static inline int usb_urb_dir_out(struct urb *urb) { return (urb->transfer_flags & URB_DIR_MASK) == URB_DIR_OUT; } void *usb_alloc_coherent(struct usb_device *dev, size_t size, gfp_t mem_flags, dma_addr_t *dma); void usb_free_coherent(struct usb_device *dev, size_t size, void *addr, dma_addr_t dma); #if 0 struct urb *usb_buffer_map(struct urb *urb); void usb_buffer_dmasync(struct urb *urb); void usb_buffer_unmap(struct urb *urb); #endif struct scatterlist; int usb_buffer_map_sg(const struct usb_device *dev, int is_in, struct scatterlist *sg, int nents); #if 0 void usb_buffer_dmasync_sg(const struct usb_device *dev, int is_in, struct scatterlist *sg, int n_hw_ents); #endif void usb_buffer_unmap_sg(const struct usb_device *dev, int is_in, struct scatterlist *sg, int n_hw_ents); /*-------------------------------------------------------------------* * SYNCHRONOUS CALL SUPPORT * *-------------------------------------------------------------------*/ extern int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype, __u16 value, __u16 index, void *data, __u16 size, int timeout); extern int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe, void *data, int len, int *actual_length, int timeout); extern int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe, void *data, int len, int *actual_length, int timeout); /* wrappers around usb_control_msg() for the most common standard requests */ extern int usb_get_descriptor(struct usb_device *dev, unsigned char desctype, unsigned char descindex, void *buf, int size); extern int usb_get_status(struct usb_device *dev, int type, int target, void *data); extern int usb_string(struct usb_device *dev, int index, char *buf, size_t size); /* wrappers that also update important state inside usbcore */ extern int usb_clear_halt(struct usb_device *dev, int pipe); extern int usb_reset_configuration(struct usb_device *dev); extern int usb_set_interface(struct usb_device *dev, int ifnum, int alternate); extern void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr); /* this request isn't really synchronous, but it belongs with the others */ extern int usb_driver_set_configuration(struct usb_device *udev, int config); /* * timeouts, in milliseconds, used for sending/receiving control messages * they typically complete within a few frames (msec) after they're issued * USB identifies 5 second timeouts, maybe more in a few cases, and a few * slow devices (like some MGE Ellipse UPSes) actually push that limit. */ #define USB_CTRL_GET_TIMEOUT 5000 #define USB_CTRL_SET_TIMEOUT 5000 /** * struct usb_sg_request - support for scatter/gather I/O * @status: zero indicates success, else negative errno * @bytes: counts bytes transferred. * * These requests are initialized using usb_sg_init(), and then are used * as request handles passed to usb_sg_wait() or usb_sg_cancel(). Most * members of the request object aren't for driver access. * * The status and bytecount values are valid only after usb_sg_wait() * returns. If the status is zero, then the bytecount matches the total * from the request. * * After an error completion, drivers may need to clear a halt condition * on the endpoint. */ struct usb_sg_request { int status; size_t bytes; /* private: * members below are private to usbcore, * and are not provided for driver access! */ spinlock_t lock; struct usb_device *dev; int pipe; int entries; struct urb **urbs; int count; struct completion complete; }; int usb_sg_init( struct usb_sg_request *io, struct usb_device *dev, unsigned pipe, unsigned period, struct scatterlist *sg, int nents, size_t length, gfp_t mem_flags ); void usb_sg_cancel(struct usb_sg_request *io); void usb_sg_wait(struct usb_sg_request *io); /* ----------------------------------------------------------------------- */ /* * For various legacy reasons, Linux has a small cookie that's paired with * a struct usb_device to identify an endpoint queue. Queue characteristics * are defined by the endpoint's descriptor. This cookie is called a "pipe", * an unsigned int encoded as: * * - direction: bit 7 (0 = Host-to-Device [Out], * 1 = Device-to-Host [In] ... * like endpoint bEndpointAddress) * - device address: bits 8-14 ... bit positions known to uhci-hcd * - endpoint: bits 15-18 ... bit positions known to uhci-hcd * - pipe type: bits 30-31 (00 = isochronous, 01 = interrupt, * 10 = control, 11 = bulk) * * Given the device address and endpoint descriptor, pipes are redundant. */ /* NOTE: these are not the standard USB_ENDPOINT_XFER_* values!! */ /* (yet ... they're the values used by usbfs) */ #define PIPE_ISOCHRONOUS 0 #define PIPE_INTERRUPT 1 #define PIPE_CONTROL 2 #define PIPE_BULK 3 #define usb_pipein(pipe) ((pipe) & USB_DIR_IN) #define usb_pipeout(pipe) (!usb_pipein(pipe)) #define usb_pipedevice(pipe) (((pipe) >> 8) & 0x7f) #define usb_pipeendpoint(pipe) (((pipe) >> 15) & 0xf) #define usb_pipetype(pipe) (((pipe) >> 30) & 3) #define usb_pipeisoc(pipe) (usb_pipetype((pipe)) == PIPE_ISOCHRONOUS) #define usb_pipeint(pipe) (usb_pipetype((pipe)) == PIPE_INTERRUPT) #define usb_pipecontrol(pipe) (usb_pipetype((pipe)) == PIPE_CONTROL) #define usb_pipebulk(pipe) (usb_pipetype((pipe)) == PIPE_BULK) static inline unsigned int __create_pipe(struct usb_device *dev, unsigned int endpoint) { return (dev->devnum << 8) | (endpoint << 15); } /* Create various pipes... */ #define usb_sndctrlpipe(dev, endpoint) \ ((PIPE_CONTROL << 30) | __create_pipe(dev, endpoint)) #define usb_rcvctrlpipe(dev, endpoint) \ ((PIPE_CONTROL << 30) | __create_pipe(dev, endpoint) | USB_DIR_IN) #define usb_sndisocpipe(dev, endpoint) \ ((PIPE_ISOCHRONOUS << 30) | __create_pipe(dev, endpoint)) #define usb_rcvisocpipe(dev, endpoint) \ ((PIPE_ISOCHRONOUS << 30) | __create_pipe(dev, endpoint) | USB_DIR_IN) #define usb_sndbulkpipe(dev, endpoint) \ ((PIPE_BULK << 30) | __create_pipe(dev, endpoint)) #define usb_rcvbulkpipe(dev, endpoint) \ ((PIPE_BULK << 30) | __create_pipe(dev, endpoint) | USB_DIR_IN) #define usb_sndintpipe(dev, endpoint) \ ((PIPE_INTERRUPT << 30) | __create_pipe(dev, endpoint)) #define usb_rcvintpipe(dev, endpoint) \ ((PIPE_INTERRUPT << 30) | __create_pipe(dev, endpoint) | USB_DIR_IN) static inline struct usb_host_endpoint * usb_pipe_endpoint(struct usb_device *dev, unsigned int pipe) { struct usb_host_endpoint **eps; eps = usb_pipein(pipe) ? dev->ep_in : dev->ep_out; return eps[usb_pipeendpoint(pipe)]; } /*-------------------------------------------------------------------------*/ static inline __u16 usb_maxpacket(struct usb_device *udev, int pipe, int is_out) { struct usb_host_endpoint *ep; unsigned epnum = usb_pipeendpoint(pipe); if (is_out) { WARN_ON(usb_pipein(pipe)); ep = udev->ep_out[epnum]; } else { WARN_ON(usb_pipeout(pipe)); ep = udev->ep_in[epnum]; } if (!ep) return 0; /* NOTE: only 0x07ff bits are for packet size... */ return le16_to_cpu(ep->desc.wMaxPacketSize); } /* ----------------------------------------------------------------------- */ /* Events from the usb core */ #define USB_DEVICE_ADD 0x0001 #define USB_DEVICE_REMOVE 0x0002 #define USB_BUS_ADD 0x0003 #define USB_BUS_REMOVE 0x0004 extern void usb_register_notify(struct notifier_block *nb); extern void usb_unregister_notify(struct notifier_block *nb); #ifdef DEBUG #define dbg(format, arg...) \ printk(KERN_DEBUG "%s: " format "\n", __FILE__, ##arg) #else #define dbg(format, arg...) \ do { \ if (0) \ printk(KERN_DEBUG "%s: " format "\n", __FILE__, ##arg); \ } while (0) #endif #define err(format, arg...) \ printk(KERN_ERR KBUILD_MODNAME ": " format "\n", ##arg) /* debugfs stuff */ extern struct dentry *usb_debug_root; #endif /* __KERNEL__ */ #endif
Java
/** @copyright Copyright (c) 2008 - 2010, AuthenTec Oy. All rights reserved. wince_wan_interface.h This file contains the type definitions and function declarations for Windows CE WAN Interfaces (i.e. dial-up interfaces). */ #ifndef SSH_WINCE_WAN_INTERFACE_H #define SSH_WINCE_WAN_INTERFACE_H #ifdef __cplusplus extern "C" { #endif #ifdef _WIN32_WCE /*-------------------------------------------------------------------------- DEFINITIONS --------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------- ENUMERATIONS --------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------- TYPE DEFINITIONS --------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------- EXPORTED FUNCTIONS --------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------- Frees buffer returned by ssh_wan_alloc_buffer_send(). Can be called from a WanSendComplete handler. --------------------------------------------------------------------------*/ void ssh_wan_free_buffer_send(PNDIS_WAN_PACKET wan_pkt); /*-------------------------------------------------------------------------- Inspects a PPP-encapsulated packet received from a WAN protocol. If it is an IPv4 or IPv6 packet, removes the PPP header from the packet, leaving a bare IPv4 or IPv6 packet, stores the protocol (IPv4 or IPv6) in *protocol and returns TRUE. Otherwise leaves the packet untouched and returns FALSE. --------------------------------------------------------------------------*/ Boolean ssh_wan_intercept_from_protocol(SshNdisIMAdapter adapter, PNDIS_WAN_PACKET packet, SshInterceptorProtocol *protocol); /*-------------------------------------------------------------------------- Processes a PPP-encapsulated non-IP packet received from a WAN protocol. The packet will be either dropped, rejected or passed directly to the corresponding WAN adapter. The status stored in *status should be returned to NDIS by the caller. --------------------------------------------------------------------------*/ void ssh_wan_process_from_protocol(SshNdisIMAdapter adapter, PNDIS_WAN_PACKET packet, PNDIS_STATUS status); /*-------------------------------------------------------------------------- Inspects a PPP-encapsulated packet received from a WAN adapter. If it is an IPv4 or IPv6 packet, removes the PPP header from the packet, leaving a bare IPv4 or IPv6 packet, stores the protocol (IPv4 or IPv6) in *protocol and returns TRUE. Otherwise leaves the packet untouched and returns FALSE. --------------------------------------------------------------------------*/ Boolean ssh_wan_intercept_from_adapter(SshNdisIMAdapter adapter, PUCHAR *packet, ULONG *packet_size, SshInterceptorProtocol *protocol); /*-------------------------------------------------------------------------- Processes a PPP-encapsulated non-IP packet received from a WAN adapter. The packet will be either dropped, rejected or passed directly to the corresponding WAN protocol. The status stored in *status should be returned to NDIS by the caller. --------------------------------------------------------------------------*/ void ssh_wan_process_from_adapter(SshNdisIMAdapter adapter, PUCHAR packet, ULONG packet_size, PNDIS_STATUS status); /*-------------------------------------------------------------------------- PPP-encapsulates an IPv4 or IPv6 packet and sends it to WAN adapter. If successful, returns TRUE, otherwise returns FALSE. --------------------------------------------------------------------------*/ Boolean ssh_wan_send_to_adapter(SshNdisIMAdapter adapter, SshNdisPacket packet, SshInterceptorProtocol protocol); /*-------------------------------------------------------------------------- PPP-encapsulates an IPv4 or IPv6 packet and indicates it to WAN protocol. If successful, returns TRUE, otherwise returns FALSE. --------------------------------------------------------------------------*/ Boolean ssh_wan_send_to_protocol(SshNdisIMAdapter adapter, SshNdisPacket packet, SshInterceptorProtocol protocol); #endif /* _WIN32_WCE */ #ifdef __cplusplus } #endif #endif /* SSH_WINCE_WAN_INTERCFACE */
Java
package de.superioz.moo.network.client; import de.superioz.moo.network.server.NetworkServer; import lombok.Getter; import de.superioz.moo.api.collection.UnmodifiableList; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * The hub for storing the client connections * * @see MooClient */ public final class ClientManager { /** * It is only necessary to only have one ClientHub instance so this is the static access for this * class after it has been initialised by the network server */ @Getter private static ClientManager instance; /** * The connected {@link MooClient}'s by the type of them */ private ConcurrentMap<ClientType, Map<InetSocketAddress, MooClient>> clientsByType = new ConcurrentHashMap<>(); /** * The ram usage of every daemon (as socketaddress) as percent */ @Getter private Map<InetSocketAddress, Integer> daemonRamUsage = new HashMap<>(); /** * The netty server the clients are connected to */ private NetworkServer netServer; public ClientManager(NetworkServer netServer) { instance = this; this.netServer = netServer; for(ClientType clientType : ClientType.values()) { clientsByType.put(clientType, new HashMap<>()); } } /** * Updates the ramUsage of a daemon * * @param address The address of the daemon/server * @param ramUsage The ramUsage in per cent */ public void updateRamUsage(InetSocketAddress address, int ramUsage) { Map<InetSocketAddress, MooClient> daemonClients = clientsByType.get(ClientType.DAEMON); if(!daemonClients.containsKey(address)) return; daemonRamUsage.put(address, ramUsage); } /** * Gets the best available daemon where the ram usage is the lowest * * @return The client */ public MooClient getBestDaemon() { Map<InetSocketAddress, MooClient> daemonClients = clientsByType.get(ClientType.DAEMON); if(daemonClients.isEmpty()) return null; int lowesRamUsage = -1; MooClient lowestRamUsageClient = null; for(InetSocketAddress address : daemonClients.keySet()) { if(!daemonRamUsage.containsKey(address)) continue; MooClient client = daemonClients.get(address); int ramUsage = daemonRamUsage.get(address); if((lowesRamUsage == -1 || lowesRamUsage > ramUsage) && !((lowesRamUsage = ramUsage) >= (Integer) netServer.getConfig().get("slots-ram-usage"))) { lowestRamUsageClient = client; } } return lowestRamUsageClient; } /** * Adds a client to the hub * * @param cl The client * @return The size of the map */ public int add(MooClient cl) { Map<InetSocketAddress, MooClient> map = clientsByType.get(cl.getType()); map.put(cl.getAddress(), cl); if(cl.getType() == ClientType.DAEMON) { daemonRamUsage.put(cl.getAddress(), 0); } return map.size(); } /** * Removes a client from the hub * * @param address The address (the key) * @return This */ public ClientManager remove(InetSocketAddress address) { for(Map<InetSocketAddress, MooClient> m : clientsByType.values()) { m.entrySet().removeIf(entry -> entry.getKey().equals(address)); } return this; } public ClientManager remove(MooClient cl) { return remove(cl.getAddress()); } /** * Gets a client from address * * @param address The address * @return The client */ public MooClient get(InetSocketAddress address) { MooClient client = null; for(Map.Entry<ClientType, Map<InetSocketAddress, MooClient>> entry : clientsByType.entrySet()) { if(entry.getValue().containsKey(address)) { client = entry.getValue().get(address); } } return client; } public boolean contains(InetSocketAddress address) { return get(address) != null; } /** * Get clients (from type) * * @param type The type * @return The list of clients (unmodifiable) */ public UnmodifiableList<MooClient> getClients(ClientType type) { Map<InetSocketAddress, MooClient> map = clientsByType.get(type); return new UnmodifiableList<>(map.values()); } /** * Get all clients inside one list * * @return The list of clients */ public List<MooClient> getAll() { List<MooClient> clients = new ArrayList<>(); for(ClientType clientType : ClientType.values()) { clients.addAll(getClients(clientType)); } return clients; } public UnmodifiableList<MooClient> getMinecraftClients() { List<MooClient> clients = new ArrayList<>(); clients.addAll(getClients(ClientType.PROXY)); clients.addAll(getClients(ClientType.SERVER)); return new UnmodifiableList<>(clients); } public UnmodifiableList<MooClient> getServerClients() { return getClients(ClientType.SERVER); } public UnmodifiableList<MooClient> getProxyClients() { return getClients(ClientType.PROXY); } public UnmodifiableList<MooClient> getCustomClients() { return getClients(ClientType.CUSTOM); } public UnmodifiableList<MooClient> getDaemonClients() { return getClients(ClientType.DAEMON); } }
Java
#include <stdio.h> #include <stdlib.h> #include <unistd.h> int f1(int limite); int f2(int limite) { int i; for (i = 1; i < limite; i ++) f1(i); } int f1(int limite) { int i; for (i = 1; i < limite; i ++) f2(i); } int main(void) { f1(25); }
Java
package models.planners import java.awt.Color import java.awt.image.BufferedImage import utils._ import models.{Yarn, Needle} import models.units.Stitches object Helper { /** First/last needle for the knitting with the given width when center alignment. */ def center(width: Stitches): (Needle, Needle) = { (Needle.middle - (width / 2).approx, Needle.middle + (width / 2).approx) } /** Convert two color image into a yarn pattern. */ def monochromeToPattern(img: BufferedImage, yarnWhite: Yarn, yarnBlack: Yarn): Matrix[Yarn] = { val rgbs = IndexedSeq.tabulate(img.getHeight, img.getWidth)((y, x) => new Color(img.getRGB(x, y))) val colors = rgbs.flatten.toSet.toSeq require(colors.size <= 2, s"not monochrome: ${colors.toList}") val white = if (colors.size > 1 && colors(0).getRGB > colors(1).getRGB) colors(1) else colors(0) rgbs.matrixMap(c => if (c == white) yarnWhite else yarnBlack) } /** Convert the image into a pattern, yarns are take from colors. */ def imageToPattern(img: BufferedImage): Matrix[Yarn] = { val rgbs = IndexedSeq.tabulate(img.getHeight, img.getWidth)((y, x) => new Color(img.getRGB(x, y))) val yarns = colorsToYarns(rgbs.flatten.toSet) val pattern = rgbs.matrixMap(yarns).reverseBoth pattern } def colorsToYarns(colors: Set[Color]) = { colors.zipWithIndex.map { case (c@Color.white, i) => c -> Yarn(s"White", new Color(0xf4f4f4)) case (c@Color.black, i) => c -> Yarn(s"Black", c) case (c@Color.yellow, i) => c -> Yarn(s"Yellow", c) case (c@Color.red, i) => c -> Yarn(s"Red", c) case (c@Color.green, i) => c -> Yarn(s"Green", c) case (c@Color.blue, i) => c -> Yarn(s"Blue", c) case (color, i) => color -> Yarn(s"Yarn $i", color) }.toMap } }
Java
/* dnsmasq is Copyright (c) 2000-2015 Simon Kelley This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 dated June, 1991, or (at your option) version 3 dated 29 June, 2007. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "dnsmasq.h" #ifdef HAVE_LOOP static ssize_t loop_make_probe(u32 uid); void loop_send_probes() { struct server *serv; if (!option_bool(OPT_LOOP_DETECT)) return; /* Loop through all upstream servers not for particular domains, and send a query to that server which is identifiable, via the uid. If we see that query back again, then the server is looping, and we should not use it. */ for (serv = daemon->servers; serv; serv = serv->next) if (!(serv->flags & (SERV_LITERAL_ADDRESS | SERV_NO_ADDR | SERV_USE_RESOLV | SERV_NO_REBIND | SERV_HAS_DOMAIN | SERV_FOR_NODOTS | SERV_LOOP))) { ssize_t len = loop_make_probe(serv->uid); int fd; struct randfd *rfd = NULL; if (serv->sfd) fd = serv->sfd->fd; else { if (!(rfd = allocate_rfd(serv->addr.sa.sa_family))) continue; fd = rfd->fd; } while (retry_send(sendto(fd, daemon->packet, len, 0, &serv->addr.sa, sa_len(&serv->addr)))); free_rfd(rfd); } } static ssize_t loop_make_probe(u32 uid) { struct dns_header *header = (struct dns_header *)daemon->packet; unsigned char *p = (unsigned char *)(header+1); /* packet buffer overwritten */ daemon->srv_save = NULL; header->id = rand16(); header->ancount = header->nscount = header->arcount = htons(0); header->qdcount = htons(1); header->hb3 = HB3_RD; header->hb4 = 0; SET_OPCODE(header, QUERY); *p++ = 8; sprintf((char *)p, "%.8x", uid); p += 8; *p++ = strlen(LOOP_TEST_DOMAIN); strcpy((char *)p, LOOP_TEST_DOMAIN); /* Add terminating zero */ p += strlen(LOOP_TEST_DOMAIN) + 1; PUTSHORT(LOOP_TEST_TYPE, p); PUTSHORT(C_IN, p); return p - (unsigned char *)header; } int detect_loop(char *query, int type) { int i; u32 uid; struct server *serv; if (!option_bool(OPT_LOOP_DETECT)) return 0; if (type != LOOP_TEST_TYPE || strlen(LOOP_TEST_DOMAIN) + 9 != strlen(query) || strstr(query, LOOP_TEST_DOMAIN) != query + 9) return 0; for (i = 0; i < 8; i++) if (!isxdigit(query[i])) return 0; uid = strtol(query, NULL, 16); for (serv = daemon->servers; serv; serv = serv->next) if (!(serv->flags & (SERV_LITERAL_ADDRESS | SERV_NO_ADDR | SERV_USE_RESOLV | SERV_NO_REBIND | SERV_HAS_DOMAIN | SERV_FOR_NODOTS | SERV_LOOP)) && uid == serv->uid) { serv->flags |= SERV_LOOP; check_servers(); /* log new state */ return 1; } return 0; } #endif
Java
import math as mth import numpy as np #---------------------- # J Matthews, 21/02 # This is a file containing useful constants for python coding # # Units in CGS unless stated # #---------------------- #H=6.62606957E-27 HEV=4.13620e-15 #C=29979245800.0 #BOLTZMANN=1.3806488E-16 VERY_BIG=1e50 H=6.6262e-27 HC=1.98587e-16 HEV=4.13620e-15 # Planck's constant in eV HRYD=3.04005e-16 # NSH 1204 Planck's constant in Rydberg C =2.997925e10 G=6.670e-8 BOLTZMANN =1.38062e-16 WIEN= 5.879e10 # NSH 1208 Wien Disp Const in frequency units H_OVER_K=4.799437e-11 STEFAN_BOLTZMANN =5.6696e-5 THOMPSON=0.66524e-24 PI = 3.1415927 MELEC = 9.10956e-28 E= 4.8035e-10 # Electric charge in esu MPROT = 1.672661e-24 MSOL = 1.989e33 PC= 3.08e18 YR = 3.1556925e7 PI_E2_OVER_MC=0.02655103 # Classical cross-section PI_E2_OVER_M =7.96e8 ALPHA= 7.297351e-3 # Fine structure constant BOHR= 0.529175e-8 # Bohr radius CR= 3.288051e15 #Rydberg frequency for H != Ryd freq for infinite mass ANGSTROM = 1.e-8 #Definition of an Angstrom in units of this code, e.g. cm EV2ERGS =1.602192e-12 RADIAN= 57.29578 RYD2ERGS =2.1798741e-11 PARSEC=3.086E18
Java
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; namespace WeifenLuo.WinFormsUI.Docking { #region DockPanelSkin classes /// <summary> /// The skin to use when displaying the DockPanel. /// The skin allows custom gradient color schemes to be used when drawing the /// DockStrips and Tabs. /// </summary> [TypeConverter(typeof(DockPanelSkinConverter))] public class DockPanelSkin { private AutoHideStripSkin m_autoHideStripSkin; private DockPaneStripSkin m_dockPaneStripSkin; public DockPanelSkin() { m_autoHideStripSkin = new AutoHideStripSkin(); m_dockPaneStripSkin = new DockPaneStripSkin(); } /// <summary> /// The skin used to display the auto hide strips and tabs. /// </summary> public AutoHideStripSkin AutoHideStripSkin { get { return m_autoHideStripSkin; } set { m_autoHideStripSkin = value; } } /// <summary> /// The skin used to display the Document and ToolWindow style DockStrips and Tabs. /// </summary> public DockPaneStripSkin DockPaneStripSkin { get { return m_dockPaneStripSkin; } set { m_dockPaneStripSkin = value; } } } /// <summary> /// The skin used to display the auto hide strip and tabs. /// </summary> [TypeConverter(typeof(AutoHideStripConverter))] public class AutoHideStripSkin { private DockPanelGradient m_dockStripGradient; private TabGradient m_TabGradient; public AutoHideStripSkin() { m_dockStripGradient = new DockPanelGradient(); m_dockStripGradient.StartColor = SystemColors.ControlLight; m_dockStripGradient.EndColor = SystemColors.ControlLight; m_TabGradient = new TabGradient(); m_TabGradient.TextColor = SystemColors.ControlDarkDark; } /// <summary> /// The gradient color skin for the DockStrips. /// </summary> public DockPanelGradient DockStripGradient { get { return m_dockStripGradient; } set { m_dockStripGradient = value; } } /// <summary> /// The gradient color skin for the Tabs. /// </summary> public TabGradient TabGradient { get { return m_TabGradient; } set { m_TabGradient = value; } } } /// <summary> /// The skin used to display the document and tool strips and tabs. /// </summary> [TypeConverter(typeof(DockPaneStripConverter))] public class DockPaneStripSkin { private DockPaneStripGradient m_DocumentGradient; private DockPaneStripToolWindowGradient m_ToolWindowGradient; public DockPaneStripSkin() { m_DocumentGradient = new DockPaneStripGradient(); m_DocumentGradient.DockStripGradient.StartColor = SystemColors.Control; m_DocumentGradient.DockStripGradient.EndColor = SystemColors.Control; m_DocumentGradient.ActiveTabGradient.StartColor = SystemColors.ControlLightLight; m_DocumentGradient.ActiveTabGradient.EndColor = SystemColors.ControlLightLight; m_DocumentGradient.InactiveTabGradient.StartColor = SystemColors.ControlLight; m_DocumentGradient.InactiveTabGradient.EndColor = SystemColors.ControlLight; m_ToolWindowGradient = new DockPaneStripToolWindowGradient(); m_ToolWindowGradient.DockStripGradient.StartColor = SystemColors.ControlLight; m_ToolWindowGradient.DockStripGradient.EndColor = SystemColors.ControlLight; m_ToolWindowGradient.ActiveTabGradient.StartColor = SystemColors.Control; m_ToolWindowGradient.ActiveTabGradient.EndColor = SystemColors.Control; m_ToolWindowGradient.InactiveTabGradient.StartColor = Color.Transparent; m_ToolWindowGradient.InactiveTabGradient.EndColor = Color.Transparent; m_ToolWindowGradient.InactiveTabGradient.TextColor = SystemColors.ControlDarkDark; m_ToolWindowGradient.ActiveCaptionGradient.StartColor = SystemColors.GradientActiveCaption; m_ToolWindowGradient.ActiveCaptionGradient.EndColor = SystemColors.ActiveCaption; m_ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; m_ToolWindowGradient.ActiveCaptionGradient.TextColor = SystemColors.ActiveCaptionText; m_ToolWindowGradient.InactiveCaptionGradient.StartColor = SystemColors.GradientInactiveCaption; m_ToolWindowGradient.InactiveCaptionGradient.EndColor = SystemColors.GradientInactiveCaption; m_ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; m_ToolWindowGradient.InactiveCaptionGradient.TextColor = SystemColors.ControlText; } /// <summary> /// The skin used to display the Document style DockPane strip and tab. /// </summary> public DockPaneStripGradient DocumentGradient { get { return m_DocumentGradient; } set { m_DocumentGradient = value; } } /// <summary> /// The skin used to display the ToolWindow style DockPane strip and tab. /// </summary> public DockPaneStripToolWindowGradient ToolWindowGradient { get { return m_ToolWindowGradient; } set { m_ToolWindowGradient = value; } } } /// <summary> /// The skin used to display the DockPane ToolWindow strip and tab. /// </summary> [TypeConverter(typeof(DockPaneStripGradientConverter))] public class DockPaneStripToolWindowGradient : DockPaneStripGradient { private TabGradient m_activeCaptionGradient; private TabGradient m_inactiveCaptionGradient; public DockPaneStripToolWindowGradient() { m_activeCaptionGradient = new TabGradient(); m_inactiveCaptionGradient = new TabGradient(); } /// <summary> /// The skin used to display the active ToolWindow caption. /// </summary> public TabGradient ActiveCaptionGradient { get { return m_activeCaptionGradient; } set { m_activeCaptionGradient = value; } } /// <summary> /// The skin used to display the inactive ToolWindow caption. /// </summary> public TabGradient InactiveCaptionGradient { get { return m_inactiveCaptionGradient; } set { m_inactiveCaptionGradient = value; } } } /// <summary> /// The skin used to display the DockPane strip and tab. /// </summary> [TypeConverter(typeof(DockPaneStripGradientConverter))] public class DockPaneStripGradient { private DockPanelGradient m_dockStripGradient; private TabGradient m_activeTabGradient; private TabGradient m_inactiveTabGradient; public DockPaneStripGradient() { m_dockStripGradient = new DockPanelGradient(); m_activeTabGradient = new TabGradient(); m_inactiveTabGradient = new TabGradient(); } /// <summary> /// The gradient color skin for the DockStrip. /// </summary> public DockPanelGradient DockStripGradient { get { return m_dockStripGradient; } set { m_dockStripGradient = value; } } /// <summary> /// The skin used to display the active DockPane tabs. /// </summary> public TabGradient ActiveTabGradient { get { return m_activeTabGradient; } set { m_activeTabGradient = value; } } /// <summary> /// The skin used to display the inactive DockPane tabs. /// </summary> public TabGradient InactiveTabGradient { get { return m_inactiveTabGradient; } set { m_inactiveTabGradient = value; } } } /// <summary> /// The skin used to display the dock pane tab /// </summary> [TypeConverter(typeof(DockPaneTabGradientConverter))] public class TabGradient : DockPanelGradient { private Color m_textColor; public TabGradient() { m_textColor = SystemColors.ControlText; } /// <summary> /// The text color. /// </summary> [DefaultValue(typeof(SystemColors), "ControlText")] public Color TextColor { get { return m_textColor; } set { m_textColor = value; } } } /// <summary> /// The gradient color skin. /// </summary> [TypeConverter(typeof(DockPanelGradientConverter))] public class DockPanelGradient { private Color m_startColor; private Color m_endColor; private LinearGradientMode m_linearGradientMode; public DockPanelGradient() { m_startColor = SystemColors.Control; m_endColor = SystemColors.Control; m_linearGradientMode = LinearGradientMode.Horizontal; } /// <summary> /// The beginning gradient color. /// </summary> [DefaultValue(typeof(SystemColors), "Control")] public Color StartColor { get { return m_startColor; } set { m_startColor = value; } } /// <summary> /// The ending gradient color. /// </summary> [DefaultValue(typeof(SystemColors), "Control")] public Color EndColor { get { return m_endColor; } set { m_endColor = value; } } /// <summary> /// The gradient mode to display the colors. /// </summary> [DefaultValue(LinearGradientMode.Horizontal)] public LinearGradientMode LinearGradientMode { get { return m_linearGradientMode; } set { m_linearGradientMode = value; } } } #endregion DockPanelSkin classes #region Converters public class DockPanelSkinConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(DockPanelSkin)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is DockPanelSkin) { return "DockPanelSkin"; } return base.ConvertTo(context, culture, value, destinationType); } } public class DockPanelGradientConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(DockPanelGradient)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is DockPanelGradient) { return "DockPanelGradient"; } return base.ConvertTo(context, culture, value, destinationType); } } public class AutoHideStripConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(AutoHideStripSkin)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is AutoHideStripSkin) { return "AutoHideStripSkin"; } return base.ConvertTo(context, culture, value, destinationType); } } public class DockPaneStripConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(DockPaneStripSkin)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is DockPaneStripSkin) { return "DockPaneStripSkin"; } return base.ConvertTo(context, culture, value, destinationType); } } public class DockPaneStripGradientConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(DockPaneStripGradient)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is DockPaneStripGradient) { return "DockPaneStripGradient"; } return base.ConvertTo(context, culture, value, destinationType); } } public class DockPaneTabGradientConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(TabGradient)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String) && value is TabGradient) { return "DockPaneTabGradient"; } return base.ConvertTo(context, culture, value, destinationType); } } #endregion Converters }
Java
/* * General control styling */ .control-table .table-container { border: 1px solid #e0e0e0; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; overflow: hidden; margin-bottom: 15px; } .control-table .table-container:last-child { margin-bottom: 0; } .control-table.active .table-container { border-color: #808c8d; } .control-table table { width: 100%; border-collapse: collapse; table-layout: fixed; } .control-table table td, .control-table table th { padding: 0; font-size: 13px; color: #555555; } .control-table table [data-view-container] { padding: 5px 10px; width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-height: 28px; } .control-table table.headers:after { content: ' '; display: block; position: absolute; left: 1px; right: 1px; margin-top: -1px; border-bottom: 1px solid #e0e0e0; } .control-table table.headers th { padding: 7px 10px; font-size: 13px; text-transform: uppercase; font-weight: 600; color: #333333; background: white; border-right: 1px solid #ecf0f1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .control-table table.headers th [data-view-container] { padding-bottom: 6px; } .control-table table.headers th:last-child { border-right: none; } .control-table.active table.headers:after { border-bottom-color: #808c8d; } .control-table table.data td { border: 1px solid #ecf0f1; } .control-table table.data td .content-container { position: relative; padding: 1px; } .control-table table.data td.active { border-color: #5fb6f5 !important; } .control-table table.data td.active .content-container { padding: 0; border: 1px solid #5fb6f5; } .control-table table.data td.active .content-container:before, .control-table table.data td.active .content-container:after { content: ' '; background: #5fb6f5; position: absolute; left: -2px; top: -2px; } .control-table table.data td.active .content-container:before { width: 1px; bottom: -2px; } .control-table table.data td.active .content-container:after { right: -2px; height: 1px; } .control-table table.data tr { background-color: white; } .control-table table.data tr.error { background-color: #fbecec!important; } .control-table table.data tr.error td.active.error { border-color: #ec0000!important; } .control-table table.data tr.error td.active.error .content-container { border-color: #ec0000!important; } .control-table table.data tr.error td.active.error .content-container:before, .control-table table.data tr.error td.active.error .content-container:after { background-color: #ec0000!important; } .control-table table.data tr:nth-child(2n) { background-color: #fbfbfb; } .control-table table.data tr:first-child td { border-top: none; } .control-table table.data tr:last-child td { border-bottom: none; } .control-table table.data td:first-child { border-left: none; } .control-table table.data td:last-child { border-right: none; } .control-table .control-scrollbar > div { border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; overflow: hidden; } .control-table .control-scrollbar table.data tr:last-child td { border-bottom: 1px solid #ecf0f1; } .control-table .toolbar { background: white; border-bottom: 1px solid #e0e0e0; } .control-table .toolbar a.btn { color: #323e50; padding: 10px; opacity: 0.5; filter: alpha(opacity=50); } .control-table .toolbar a.btn:hover { opacity: 1; filter: alpha(opacity=100); } .control-table .toolbar a.table-icon:before { display: inline-block; content: ' '; width: 16px; height: 16px; margin-right: 8px; position: relative; top: 3px; background: transparent url(../images/table-icons.gif) no-repeat; background-position: 0 0; background-size: 32px auto; } .control-table .toolbar a.table-icon.add-table-row-above:before { background-position: 0 -56px; } .control-table .toolbar a.table-icon.delete-table-row:before { background-position: 0 -113px; } .control-table.active .toolbar { border-bottom-color: #808c8d; } .control-table .pagination ul { padding: 0; margin-bottom: 15px; } .control-table .pagination ul li { list-style: none; padding: 4px 6px; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; display: inline-block; margin-right: 5px; font-size: 12px; background: #ecf0f1; line-height: 100%; } .control-table .pagination ul li a { text-decoration: none; color: #95a5a6; } .control-table .pagination ul li.active { background: #5fb6f5; } .control-table .pagination ul li.active a { color: #ffffff; } @media only screen and (-moz-min-device-pixel-ratio: 1.5), only screen and (-o-min-device-pixel-ratio: 3/2), only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min-devicepixel-ratio: 1.5), only screen and (min-resolution: 1.5dppx) { .control-table .toolbar a:before { background-position: 0px -9px; background-size: 16px auto; } .control-table .toolbar a.add-table-row-above:before { background-position: 0 -39px; } .control-table .toolbar a.delete-table-row:before { background-position: 0 -66px; } } /* * String editor */ .control-table td[data-column-type=string] input[type=text] { width: 100%; height: 100%; display: block; outline: none; border: none; padding: 5px 10px; } /* * Checkbox editor */ .control-table td[data-column-type=checkbox] div[data-checkbox-element] { width: 16px; height: 16px; border-radius: 2px; background-color: #FFFFFF; border: 1px solid #999999; margin: 5px 5px 5px 10px; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .control-table td[data-column-type=checkbox] div[data-checkbox-element]:hover { border-color: #808080; color: #4d4d4d; } .control-table td[data-column-type=checkbox] div[data-checkbox-element].checked { border-width: 2px; } .control-table td[data-column-type=checkbox] div[data-checkbox-element].checked:before { font-family: FontAwesome; font-weight: normal; font-style: normal; text-decoration: inherit; -webkit-font-smoothing: antialiased; *margin-right: .3em; content: "\f00c"; font-size: 10px; position: relative; left: 1px; top: -4px; } .control-table td[data-column-type=checkbox] div[data-checkbox-element]:focus { border-color: #5fb6f5; outline: none; } /* * Dropdown editor */ .control-table td[data-column-type=dropdown] { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .control-table td[data-column-type=dropdown] [data-view-container] { padding-right: 20px; position: relative; cursor: pointer; } .control-table td[data-column-type=dropdown] [data-view-container]:after { font-family: FontAwesome; font-weight: normal; font-style: normal; text-decoration: inherit; -webkit-font-smoothing: antialiased; *margin-right: .3em; content: "\f107"; font-size: 13px; line-height: 100%; color: #95a5a6; position: absolute; top: 8px; right: 10px; } .control-table td[data-column-type=dropdown] [data-view-container]:hover:after { color: #0181b9; } .control-table td[data-column-type=dropdown] [data-dropdown-open=true] { background: white; } .control-table td[data-column-type=dropdown] [data-dropdown-open=true] [data-view-container]:after { font-family: FontAwesome; font-weight: normal; font-style: normal; text-decoration: inherit; -webkit-font-smoothing: antialiased; *margin-right: .3em; content: "\f106"; } .control-table td[data-column-type=dropdown] .content-container { outline: none; } /* Frameless control styles start */ .widget-field.frameless .control-table .table-container { border-top: none; border-left: none; border-right: none; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .widget-field.frameless .control-table .toolbar { background: transparent; } /* Frameless control styles end */ html.cssanimations .control-table td[data-column-type=dropdown] [data-view-container].loading:after { background-image: url('../../../../../../modules/system/assets/ui/images/loader-transparent.svg'); background-size: 15px 15px; background-position: 50% 50%; position: absolute; width: 15px; height: 15px; top: 6px; right: 5px; content: ' '; -webkit-animation: spin 1s linear infinite; animation: spin 1s linear infinite; } .table-control-dropdown-list { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; position: absolute; background: white; border: 1px solid #808c8d; border-top: none; padding-top: 1px; overflow: hidden; z-index: 1000; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; } .table-control-dropdown-list ul { border-top: 1px solid #ecf0f1; padding: 0; margin: 0; max-height: 200px; overflow: auto; } .table-control-dropdown-list li { list-style: none; font-size: 13px; color: #555555; padding: 5px 10px; cursor: pointer; outline: none; } .table-control-dropdown-list li:hover, .table-control-dropdown-list li:focus, .table-control-dropdown-list li.selected { background: #5fb6f5; color: white; }
Java
def format_path( str ): while( str.find( '//' ) != -1 ): str = str.replace( '//', '/' ) return str
Java
/* page layout styles */ *{ margin:0; padding:0; } body { background-color:#eee; color:#fff; font:14px/1.3 Arial,sans-serif; } header { background-color:#212121; box-shadow: 0 -1px 2px #111111; display:block; height:70px; position:relative; width:100%; z-index:100; } header h2{ font-size:22px; font-weight:normal; left:50%; margin-left:-400px; padding:22px 0; position:absolute; width:540px; } header a.stuts,a.stuts:visited{ border:none; text-decoration:none; color:#fcfcfc; font-size:14px; left:50%; line-height:31px; margin:23px 0 0 110px; position:absolute; top:0; } header .stuts span { font-size:22px; font-weight:bold; margin-left:5px; } .container { color: #000; margin: 20px auto; overflow: hidden; position: relative; width: 600px; height: 400px; } .controls { border: 1px dashed gray; color: #000; margin: 20px auto; padding: 25px; position: relative; width: 550px; } .controls p { margin-bottom: 10px; } .controls input { margin-left: 10px; }
Java
#!/usr/bin/env bash # Usage example: # PLot the chirp signal and its frequency domain presentation: # (while true; do echo line; sleep 0.01; done)| \ # awk 'BEGIN{PI=atan2(0,-1);t=0;f0=1;f1=32;T=256;k=(f1-f0)/T;}{print sin(2*PI*(t*f0+k/2*t*t));t+=0.1;fflush()}'| \ # tee >(bin/dsp/fft.sh 64 "w1;0.5;0.5"|bin/dsp/fftabs.sh 64| \ # bin/gp/gnuplotblock.sh '-0.5:31.5;0:0.5' 'Chirp signal spectrum;1')| \ # bin/gp/gnuplotwindow.sh 128 "-1:1" "Chirp signal;2" N=${1:-64} # number of samples, default 64 wd=${2:-w0} # window function description, w0-rectangular window (default), w1-hanning window col=${3:-1} # input stream column to calculate fft for awk -v N="$N" -v col="$col" -v win_desc="$wd" ' function compl_add(a, b, ara,arb) { split(a, ara);split(b, arb); return ara[1]+arb[1]" "ara[2]+arb[2]; } function compl_sub(a, b, ara,arb) { split(a, ara);split(b, arb); return ara[1]-arb[1]" "ara[2]-arb[2]; } function compl_mul(a, b, ara,arb) { split(a, ara);split(b, arb); return ara[1]*arb[1]-ara[2]*arb[2]" "ara[1]*arb[2]+ara[2]*arb[1]; } function init_hanning_window(N,a,b, i) { for(i=0;i<N;++i) { w[i] = a - b*cos(2*PI*i/(N-1)); } } function init_window(N,win_desc, i,wa,a,b,win_type) { split(win_desc, wa, ";"); switch(wa[1]) { case "w1": # hanning window win_type = 1; if (2 in wa) a = wa[2]; else a = 0.5; if (3 in wa) b = wa[3]; else b = 0.5; init_hanning_window(N,a,b); break; case "w0": default: win_type = 0; break; } return win_type; } function apply_window(N, i) { for(i=0;i<N;++i) { c[i]*=w[i]; } } function calc_pow2(N, pow) { pow = 0; while(N = rshift(N,1)) { ++pow; }; return pow; } function bit_reverse(n,pow, i,r) { r = 0; pow-=1; for(i=pow;i>=0;--i) { r = or(r,lshift(and(rshift(n,i),1), pow-i)); } return r; } function binary_inversion(N,pow, tmp,i,j) { # pow = calc_pow2(N); for(i=0;i<N;++i) { j = bit_reverse(i,pow); if (i<j) { tmp = c[i]; c[i] = c[j]; c[j] = tmp; } } } function fft(start,end,e, N,N2,k,t,et) { N = end - start; if (N<2) return; N2 = N/2; et = e; for (k=0;k<N2;++k) { t = c[start+k]; c[start+k] = compl_add(t,c[start+k+N2]); c[start+k+N2] = compl_sub(t,c[start+k+N2]); if (k>0) { c[start+k+N2] = compl_mul(et,c[start+k+N2]); et = compl_mul(et,e); } } et = compl_mul(e,e); fft(start, start+N2, et); fft(start+N2, end, et); } function print_fft(N, N2,i) { N2 = N/2; for(i=1;i<=N2;++i) { print c[i]; } } BEGIN { if (and(N,N-1)!=0) { print "Error: Signal width shall be power of two!" > "/dev/stderr"; exit(1); } start=0;end=0; for(i=0;i<N;++i) a[i]=0; PI = atan2(0,-1); expN = cos(2*PI/N) " " (-sin(2*PI/N)); N2 = N/2; pow = calc_pow2(N); # win_type = 0; # rectangular window by default # win_type = 1; # hanning window win_type = init_window(N, win_desc); } { if (match($0,/^.+$/)) { a[end] = $col; ++end; if (end>start+N) { delete a[start]; start++; } for (i=start;i<N+start;++i) { (i<end)?c[i-start] = a[i]:c[i-start] = 0; } if (win_type!=0) { apply_window(N); } fft(0,N,expN); binary_inversion(N,pow); # N = 2^pow; print_fft(N); printf("\n"); fflush(); } } ' -
Java
document.addEventListener("DOMContentLoaded", function (event) { 'use strict'; var paragraph, url, proxy; paragraph = document.querySelectorAll('p.error_text'); chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) { url = tabs[0].url; if (url.indexOf('chrome://') == 0) { paragraph[0].innerHTML = 'Sorry, you can\'t activate Browse Google Cache on a page with a "chrome://" URL.'; } else if (url.indexOf('https://chrome.google.com/webstore') == 0) { paragraph[0].innerHTML = 'Sorry, you can\'t activate Browse Google Cache on the Chrome Web Store.'; } else { chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) { chrome.runtime.sendMessage({ action : 'extensionButtonClicked', 'tab': tabs[0] }); window.close(); }); } }); });
Java
using Deployer.Services.Config; using Deployer.Services.Config.Interfaces; using Moq; using NUnit.Framework; using System.Collections; namespace Deployer.Tests.Config { [TestFixture] public class ConfigBuildParamTests { private Mock<IJsonPersistence> _jsonPersist; private Mock<ISlugCreator> _slugCreator; private RealConfigurationService _sut; [SetUp] public void BeforeEachTest() { _jsonPersist = new Mock<IJsonPersistence>(); _slugCreator = new Mock<ISlugCreator>(); _sut = new RealConfigurationService(@"\root\", _jsonPersist.Object, _slugCreator.Object); } [Test] public void Empty_build_params() { _jsonPersist.Setup(x => x.Read(@"\root\config\slug-1.json")).Returns(new Hashtable()); var hash = _sut.GetBuildParams("slug-1"); Assert.IsNotNull(hash); Assert.AreEqual(0, hash.Count); _jsonPersist.Verify(x => x.Read(It.IsAny<string>()), Times.Once); _jsonPersist.Verify(x => x.Read(@"\root\config\slug-1.json"), Times.Once); } [Test] public void Read_params() { var mockHash = new Hashtable { {"key1", "value1"}, {"key2", "value2"} }; _jsonPersist.Setup(x => x.Read(@"\root\config\slug-1.json")).Returns(mockHash); var actualHash = _sut.GetBuildParams("slug-1"); Assert.IsNotNull(actualHash); Assert.AreEqual(2, actualHash.Count); Assert.AreEqual("value1", actualHash["key1"]); Assert.AreEqual("value2", actualHash["key2"]); _jsonPersist.Verify(x => x.Read(It.IsAny<string>()), Times.Once); _jsonPersist.Verify(x => x.Read(@"\root\config\slug-1.json"), Times.Once); } [Test] public void Write_params() { var mockHash = new Hashtable { {"key1", "value1"}, {"key2", "value2"} }; _jsonPersist.Setup(x => x.Write(@"\root\config\slug-1.json", It.IsAny<Hashtable>())) .Callback((string path, Hashtable hash) => { Assert.AreEqual(2, hash.Count); Assert.AreEqual("value1", hash["key1"]); Assert.AreEqual("value2", hash["key2"]); }); _sut.SaveBuildParams("slug-1", mockHash); _jsonPersist.Verify(x => x.Write(@"\root\config\slug-1.json", It.IsAny<Hashtable>()), Times.Once); } } }
Java
package ch.hgdev.toposuite.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Useful static method for manipulating String. * * @author HGdev */ public class StringUtils { public static final String UTF8_BOM = "\uFEFF"; /** * This method assumes that the String contains a number. * * @param str A String. * @return The String incremented by 1. * @throws IllegalArgumentException Thrown if the input String does not end with a suitable * number. */ public static String incrementAsNumber(String str) throws IllegalArgumentException { if (str == null) { throw new IllegalArgumentException("The input String must not be null!"); } Pattern p = Pattern.compile("([0-9]+)$"); Matcher m = p.matcher(str); if (!m.find()) { throw new IllegalArgumentException( "Invalid input argument! The input String must end with a valid number"); } String number = m.group(1); String prefix = str.substring(0, str.length() - number.length()); return prefix + String.valueOf(Integer.valueOf(number) + 1); } }
Java
package org.currconv.services.impl; import java.util.List; import org.currconv.dao.UserDao; import org.currconv.entities.user.User; import org.currconv.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service("userService") @Transactional public class UserServiceImpl implements UserService { @Autowired private UserDao dao; public void saveUser(User user) { dao.saveUser(user); } public List<User> findAllUsers(){ return dao.findAllUsers(); } public User findByUserName(String name){ return dao.findByUserName(name); } }
Java
package com.debugtoday.htmldecoder.output; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.regex.Matcher; import org.slf4j.Logger; import com.debugtoday.htmldecoder.decoder.GeneralDecoder; import com.debugtoday.htmldecoder.exception.GeneralException; import com.debugtoday.htmldecoder.log.CommonLog; import com.debugtoday.htmldecoder.output.object.FileOutputArg; import com.debugtoday.htmldecoder.output.object.PaginationOutputArg; import com.debugtoday.htmldecoder.output.object.TagFileOutputArg; import com.debugtoday.htmldecoder.output.object.TagOutputArg; import com.debugtoday.htmldecoder.output.object.TagWrapper; import com.debugtoday.htmldecoder.output.object.TemplateFullTextWrapper; /** * base class for output relative to file output, i.g. article/article page/tag page/category page * @author zydecx * */ public class AbstractFileOutput implements Output { private static final Logger logger = CommonLog.getLogger(); @Override public String export(Object object) throws GeneralException { // TODO Auto-generated method stub return DONE; } /** * @param file * @param template * @param arg * @throws GeneralException */ public void writeToFile(File file, TemplateFullTextWrapper template, FileOutputArg arg) throws GeneralException { File parentFile = file.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { throw new GeneralException("fail to create file[" + file.getAbsolutePath() + "]", e); } } try ( PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); ) { String formattedHead = ""; if (arg.getPageTitle() != null) { formattedHead += "<title>" + arg.getPageTitle() + "</title>"; } if (arg.getHead() != null) { formattedHead += "\n" + arg.getHead(); } String templateFullText = template.getFullText() .replace(GeneralDecoder.formatPlaceholderRegex("head"), formattedHead); if (arg.getBodyTitle() != null) { templateFullText = templateFullText .replace(GeneralDecoder.formatPlaceholderRegex("body_title"), arg.getBodyTitle()); } if (arg.getBody() != null) { templateFullText = templateFullText .replace(GeneralDecoder.formatPlaceholderRegex("body"), arg.getBody()); } if (arg.getPagination() != null) { templateFullText = templateFullText .replace(GeneralDecoder.formatPlaceholderRegex("pagination"), arg.getPagination()); } pw.write(templateFullText); } catch (FileNotFoundException | UnsupportedEncodingException e) { throw new GeneralException("fail to write to file[" + file.getAbsolutePath() + "]", e); } } /** * used for tag page/category page output * @param templateFullTextWrapper * @param arg * @throws GeneralException */ public void exportTagPage(TemplateFullTextWrapper templateFullTextWrapper, TagFileOutputArg arg) throws GeneralException { List<TagWrapper> itemList = arg.getTagList(); int itemSize = itemList.size(); int pagination = arg.getPagination(); int pageSize = (int) Math.ceil(itemSize * 1.0 / pagination); Output tagOutput = arg.getTagOutput(); Output paginationOutput = arg.getPaginationOutput(); for (int i = 1; i <= pageSize; i++) { List<TagWrapper> subList = itemList.subList((i - 1) * pagination, Math.min(itemSize, i * pagination)); StringBuilder sb = new StringBuilder(); for (TagWrapper item : subList) { String itemName = item.getName(); TagOutputArg tagArg = new TagOutputArg(itemName, arg.getRootUrl() + "/" + item.getName(), item.getArticleList().size()); sb.append(tagOutput.export(tagArg)); } File file = new File(formatPageFilePath(arg.getRootFile().getAbsolutePath(), i)); FileOutputArg fileOutputArg = new FileOutputArg(); fileOutputArg.setBodyTitle(arg.getBodyTitle()); fileOutputArg.setBody(sb.toString()); fileOutputArg.setPageTitle(arg.getBodyTitle()); fileOutputArg.setPagination(paginationOutput.export(new PaginationOutputArg(arg.getRootUrl(), pageSize, i))); writeToFile(file, templateFullTextWrapper, fileOutputArg); } } protected String formatPageUrl(String rootUrl, int index) { return PaginationOutput.formatPaginationUrl(rootUrl, index); } protected String formatPageFilePath(String rootPath, int index) { return PaginationOutput.formatPaginationFilePath(rootPath, index); } }
Java
void dflu_pack_fin(DFluPack *p) { UC(dmap_fin(NFRAGS, /**/ &p->map)); UC(comm_bags_fin(PINNED, NONE, /**/ &p->hpp, &p->dpp)); if (p->opt.ids) UC(comm_bags_fin(PINNED, NONE, /**/ &p->hii, &p->dii)); if (p->opt.colors) UC(comm_bags_fin(PINNED, NONE, /**/ &p->hcc, &p->dcc)); EFREE(p); } void dflu_comm_fin(DFluComm *c) { UC(comm_fin(c->pp)); if (c->opt.ids) UC(comm_fin(c->ii)); if (c->opt.colors) UC(comm_fin(c->cc)); EFREE(c); } void dflu_unpack_fin(DFluUnpack *u) { UC(comm_bags_fin(HST_ONLY, NONE, &u->hpp, NULL)); if (u->opt.ids) UC(comm_bags_fin(HST_ONLY, NONE, &u->hii, NULL)); if (u->opt.colors) UC(comm_bags_fin(HST_ONLY, NONE, &u->hcc, NULL)); CC(d::Free(u->ppre)); if (u->opt.ids) CC(d::Free(u->iire)); if (u->opt.colors) CC(d::Free(u->ccre)); EFREE(u); }
Java
/* MobileRobots Advanced Robotics Interface for Applications (ARIA) Copyright (C) 2004, 2005 ActivMedia Robotics LLC Copyright (C) 2006, 2007, 2008, 2009 MobileRobots Inc. Copyright (C) 2010, 2011 Adept Technology, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA If you wish to redistribute ARIA under different terms, contact Adept MobileRobots for information about a commercial version of ARIA at robots@mobilerobots.com or Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; 800-639-9481 */ #include "Aria.h" #include "ArExport.h" #include "ArServerModeRatioDrive.h" #include "ArServerHandlerCommands.h" AREXPORT ArServerModeRatioDrive::ArServerModeRatioDrive( ArServerBase *server, ArRobot *robot, bool takeControlOnJoystick, bool useComputerJoystick, bool useRobotJoystick, bool useServerCommands, const char *name, bool robotJoystickOverridesLocks) : ArServerMode(robot, server, name), myRatioDriveGroup(robot), myJoyUserTaskCB(this, &ArServerModeRatioDrive::joyUserTask), myServerSetSafeDriveCB(this, &ArServerModeRatioDrive::serverSetSafeDrive), myServerGetSafeDriveCB(this, &ArServerModeRatioDrive::serverGetSafeDrive), myServerRatioDriveCB(this, &ArServerModeRatioDrive::serverRatioDrive), myRatioFireCB(this, &ArServerModeRatioDrive::ratioFireCallback), myServerSafeDrivingEnableCB(this, &ArServerModeRatioDrive::serverSafeDrivingEnable), myServerSafeDrivingDisableCB(this, &ArServerModeRatioDrive::serverSafeDrivingDisable) { myHandlerCommands = NULL; myDriveSafely = true; myTakeControlOnJoystick = takeControlOnJoystick; myUseComputerJoystick = useComputerJoystick; myUseRobotJoystick = useRobotJoystick; myUseServerCommands = useServerCommands; myUseLocationDependentDevices = true; myRobotJoystickOverridesLock = robotJoystickOverridesLocks; myTimeout = 2; myGotServerCommand = true; myLastTimedOut = false; // SEEKUR mySentRecenter = false; // add the actions, put the ratio input on top, then have the // limiters since the ratio doesn't touch decel except lightly // whereas the limiter will touch it strongly myRatioAction = new ArActionRatioInput; myRatioDriveGroup.addAction(myRatioAction, 50); myLimiterForward = new ArActionDeceleratingLimiter( "DeceleratingLimiterForward", ArActionDeceleratingLimiter::FORWARDS); myRatioDriveGroup.addAction(myLimiterForward, 40); myLimiterBackward = new ArActionDeceleratingLimiter( "DeceleratingLimiterBackward", ArActionDeceleratingLimiter::BACKWARDS); myRatioDriveGroup.addAction(myLimiterBackward, 39); myLimiterLateralLeft = NULL; myLimiterLateralRight = NULL; if (myRobot->hasLatVel()) { myLimiterLateralLeft = new ArActionDeceleratingLimiter( "DeceleratingLimiterLateralLeft", ArActionDeceleratingLimiter::LATERAL_LEFT); myRatioDriveGroup.addAction(myLimiterLateralLeft, 38); myLimiterLateralRight = new ArActionDeceleratingLimiter( "DeceleratingLimiterLateralRight", ArActionDeceleratingLimiter::LATERAL_RIGHT); myRatioDriveGroup.addAction(myLimiterLateralRight, 37); } myMovementParameters = new ArActionMovementParameters("TeleopMovementParameters", false); myRatioDriveGroup.addAction(myMovementParameters, 1); myRatioFireCB.setName("ArServerModeRatioDrive"); myRatioAction->addFireCallback(30, &myRatioFireCB); myLastRobotSafeDrive = true; if (myServer != NULL && myUseServerCommands) { addModeData("ratioDrive", "drives the robot as with a joystick", &myServerRatioDriveCB, "double: transRatio; double: rotRatio; double: throttleRatio ", "none", "Movement", "RETURN_NONE"); myServer->addData("setSafeDrive", "sets whether we drive the robot safely or not", &myServerSetSafeDriveCB, "byte: 1 == drive safely, 0 == drive unsafely", "none", "UnsafeMovement", "RETURN_NONE"); myServer->addData("getSafeDrive", "gets whether we drive the robot safely or not", &myServerGetSafeDriveCB, "none", "byte: 1 == driving safely, 0 == driving unsafely", "Movement", "RETURN_SINGLE"); } if (myUseComputerJoystick) { myJoydrive = new ArRatioInputJoydrive(robot, myRatioAction); if ((myJoyHandler = Aria::getJoyHandler()) == NULL) { myJoyHandler = new ArJoyHandler; myJoyHandler->init(); Aria::setJoyHandler(myJoyHandler); } } if (myUseRobotJoystick) { myRobotJoydrive = new ArRatioInputRobotJoydrive(robot, myRatioAction); if ((myRobotJoyHandler = Aria::getRobotJoyHandler()) == NULL) { myRobotJoyHandler = new ArRobotJoyHandler(robot); Aria::setRobotJoyHandler(myRobotJoyHandler); } } if (myUseRobotJoystick || myUseComputerJoystick) { std::string taskName = name; taskName += "::joyUserTask"; myRobot->addUserTask(taskName.c_str(), 75, &myJoyUserTaskCB); } myPrinting = false; } AREXPORT ArServerModeRatioDrive::~ArServerModeRatioDrive() { } AREXPORT void ArServerModeRatioDrive::addToConfig(ArConfig *config, const char *section) { config->addParam( ArConfigArg( "Timeout", &myTimeout, "If there are no commands for this period of time, then the robot will stop. 0 Disables. This is a double so you can do like .1 seconds if you want.", 0), section, ArPriority::ADVANCED); myRatioAction->addToConfig(config, section); myLimiterForward->addToConfig(config, section, "Forward"); myLimiterBackward->addToConfig(config, section, "Backward"); if (myLimiterLateralLeft != NULL) myLimiterLateralLeft->addToConfig(config, section, "Lateral"); if (myLimiterLateralRight != NULL) myLimiterLateralRight->addToConfig(config, section, "Lateral"); myMovementParameters->addToConfig(config, section, "Teleop"); } AREXPORT void ArServerModeRatioDrive::activate(void) { //if (!baseActivate()) { // return; //} ratioDrive(0, 0, 100, true); } AREXPORT void ArServerModeRatioDrive::deactivate(void) { myRatioDriveGroup.deactivate(); baseDeactivate(); } AREXPORT void ArServerModeRatioDrive::setSafeDriving(bool safe, bool internal) { if (!internal) myRobot->lock(); // if this is a change then print it if (safe != myDriveSafely) { if (safe) { ArLog::log(ArLog::Normal, "%s: Driving safely again", myName.c_str()); } else { ArLog::log(ArLog::Normal, "%s: Driving UNSAFELY", myName.c_str()); } myNewDriveSafely = true; } myDriveSafely = safe; // ratioDrive is only called if this mode is already active if (isActive()) ratioDrive(myRatioAction->getTransRatio(), myRatioAction->getRotRatio(), myRatioAction->getThrottleRatio()); if (!internal) myRobot->unlock(); } AREXPORT bool ArServerModeRatioDrive::getSafeDriving(void) { return myDriveSafely; } AREXPORT void ArServerModeRatioDrive::serverSafeDrivingEnable(void) { setSafeDriving(true); } AREXPORT void ArServerModeRatioDrive::serverSafeDrivingDisable(void) { setSafeDriving(false); } AREXPORT void ArServerModeRatioDrive::addControlCommands(ArServerHandlerCommands *handlerCommands) { if (!myUseServerCommands) { ArLog::log(ArLog::Normal, "ArServerModeRatioDrive::addControlCommands: Tried to add control commands to a ratio drive not using the server"); return; } myHandlerCommands = handlerCommands; myHandlerCommands->addCommand( "safeRatioDrivingEnable", "Enables safe driving with ratioDrive, which will attempt to prevent collisions (default)", &myServerSafeDrivingEnableCB, "UnsafeMovement"); myHandlerCommands->addCommand( "safeRatioDrivingDisable", "Disables safe driving with ratioDrive, this is UNSAFE and will let you drive your robot into things or down stairs, use at your own risk", &myServerSafeDrivingDisableCB, "UnsafeMovement"); } /** * @param isActivating a bool set to true only if this method is called from the activate() * method, otherwise false * @param transRatio Amount of forward velocity to request * @param rotRatio Amount of rotational velocity to request * @param throttleRatio Amount of speed to request * @param latRatio amount of lateral velocity to request (if robot supports it) **/ AREXPORT void ArServerModeRatioDrive::ratioDrive( double transRatio, double rotRatio, double throttleRatio, bool isActivating, double latRatio) { bool wasActive; wasActive = isActive(); myTransRatio = transRatio; myRotRatio = rotRatio; myThrottleRatio = throttleRatio; myLatRatio = latRatio; // KMC: Changed the following test to include isActivating. // if (!wasActive && !baseActivate()) // return; // The baseActivate() method should only be called in the context of the activate() // method. if (isActivating && !wasActive) { if (!baseActivate()) { return; } } // end if activating and wasn't previously active // This is to handle the case where ratioDrive is called outside the // activate() method, and the activation was not successful. if (!isActive()) { return; } if (!wasActive || myNewDriveSafely) { myRobot->clearDirectMotion(); if (myDriveSafely) { myRatioDriveGroup.activateExclusive(); myMode = "Drive"; ArLog::log(ArLog::Normal, "%s: Driving safely", myName.c_str()); } else { myRobot->deactivateActions(); myRatioAction->activate(); myMode = "UNSAFE Drive"; ArLog::log(ArLog::Normal, "%s: Driving unsafely", myName.c_str()); } if (myDriveSafely) mySafeDrivingCallbacks.invoke(); else myUnsafeDrivingCallbacks.invoke(); } myNewDriveSafely = false; // MPL why is this here twice? myTransRatio = transRatio; myRotRatio = rotRatio; myThrottleRatio = throttleRatio; myLatRatio = latRatio; setActivityTimeToNow(); // SEEKUR mySentRecenter = false; if (myPrinting) printf("cmd %.0f %.0f %.0f %.0f\n", transRatio, rotRatio, throttleRatio, latRatio); if (myTransRatio < -0.1) myDrivingBackwardsCallbacks.invoke(); //myRatioAction.setRatios(transRatio, rotRatio, throttleRatio); } AREXPORT void ArServerModeRatioDrive::serverRatioDrive(ArServerClient *client, ArNetPacket *packet) { double transRatio = packet->bufToDouble(); double rotRatio = packet->bufToDouble(); double throttleRatio = packet->bufToDouble(); double lateralRatio = packet->bufToDouble(); myGotServerCommand = true; if (!myDriveSafely && !client->hasGroupAccess("UnsafeMovement")) serverSafeDrivingEnable(); myRobot->lock(); // Activate if necessary. Note that this is done before the ratioDrive // call because we want the new ratio values to be applied after the // default ones. if (!isActive()) { activate(); } /* ArLog::log(ArLog::Normal, "RatioDrive trans %.0f rot %.0f lat %.0f ratio %.0f", transRatio, rotRatio, lateralRatio, throttleRatio); */ ratioDrive(transRatio, rotRatio, throttleRatio, false, lateralRatio); myRobot->unlock(); } AREXPORT void ArServerModeRatioDrive::serverSetSafeDrive( ArServerClient *client, ArNetPacket *packet) { if (packet->bufToUByte() == 0) setSafeDriving(false); else setSafeDriving(true); } AREXPORT void ArServerModeRatioDrive::serverGetSafeDrive( ArServerClient *client, ArNetPacket *packet) { ArNetPacket sendPacket; if (getSafeDriving()) sendPacket.uByteToBuf(1); else sendPacket.uByteToBuf(0); client->sendPacketTcp(&sendPacket); } AREXPORT void ArServerModeRatioDrive::joyUserTask(void) { // if we're not active but we should be if (myTakeControlOnJoystick && !isActive() && ((myUseComputerJoystick && myJoyHandler->haveJoystick() && myJoyHandler->getButton(1)) || (myUseRobotJoystick && myRobotJoyHandler->gotData() && myRobotJoyHandler->getButton1()))) { if (ArServerMode::getActiveMode() != NULL) ArLog::log(ArLog::Normal, "%s: Activating instead of %s because of local joystick", ArServerMode::getActiveMode()->getName(), myName.c_str()); else ArLog::log(ArLog::Normal, "%s: Activating because of local joystick", myName.c_str()); // if we're locked and are overriding that lock for the robot // joystick and it was the robot joystick that caused it to happen if (myUseRobotJoystick && myRobotJoyHandler->gotData() && myRobotJoyHandler->getButton1() && myRobotJoystickOverridesLock && ArServerMode::ourActiveModeLocked) { ArLog::log(ArLog::Terse, "Robot joystick is overriding locked mode %s", ourActiveMode->getName()); ourActiveMode->forceUnlock(); myRobot->enableMotors(); } activate(); } bool unsafeRobotDrive; if (myUseRobotJoystick && myRobotJoyHandler->gotData() && ((unsafeRobotDrive = (bool)(myRobot->getFaultFlags() & ArUtil::BIT15)) != !myLastRobotSafeDrive)) { myLastRobotSafeDrive = !unsafeRobotDrive; setSafeDriving(myLastRobotSafeDrive, true); } } AREXPORT void ArServerModeRatioDrive::userTask(void) { // Sets the robot so that we always think we're trying to move in // this mode myRobot->forceTryingToMove(); // if the joystick is pushed then set that we're active, server // commands'll go into ratioDrive and set it there too if ((myUseComputerJoystick && myJoyHandler->haveJoystick() && myJoyHandler->getButton(1)) || (myUseRobotJoystick && myRobotJoyHandler->gotData() && myRobotJoyHandler->getButton1()) || (myUseServerCommands && myGotServerCommand)) { setActivityTimeToNow(); } myGotServerCommand = false; bool timedOut = false; // if we're moving, and there is a timeout, and the activity time is // greater than the timeout, then stop the robot if ((fabs(myRobot->getVel()) > 0 || fabs(myRobot->getRotVel()) > 0 || fabs(myRobot->getLatVel()) > 0) && myTimeout > .0000001 && getActivityTime().mSecSince()/1000.0 >= myTimeout) { if (!myLastTimedOut) { ArLog::log(ArLog::Normal, "Stopping the robot since teleop timed out"); myRobot->stop(); myRobot->clearDirectMotion(); ratioDrive(0, 0, 0, 0); } timedOut = true; } myLastTimedOut = timedOut; // SEEKUR (needed for prototype versions) /* if (myRobot->hasLatVel() && !mySentRecenter && getActivityTime().secSince() >= 10) { mySentRecenter = true; myRobot->com(120); } */ if (!myStatusSetThisCycle) { if (myRobot->isLeftMotorStalled() || myRobot->isRightMotorStalled()) myStatus = "Stalled"; // this works because if the motors stalled above caught it, if // not and more values it means a stall else if (myRobot->getStallValue()) myStatus = "Bumped"; else if (ArMath::fabs(myRobot->getVel()) < 2 && ArMath::fabs(myRobot->getRotVel()) < 2 && (!myRobot->hasLatVel() || ArMath::fabs(myRobot->getLatVel()) < 2)) myStatus = "Stopped"; else myStatus = "Driving"; } myStatusSetThisCycle = false; } // end method userTask AREXPORT void ArServerModeRatioDrive::ratioFireCallback(void) { if (myPrinting) ArLog::log(ArLog::Normal, "ArServerModeRatioDrive: TransRatio=%.0f RotRatio=%.0f ThrottleRatio=%.0f LatRatio=%.0f", myTransRatio, myRotRatio, myThrottleRatio, myLatRatio); myRatioAction->setRatios(myTransRatio, myRotRatio, myThrottleRatio, myLatRatio); } AREXPORT void ArServerModeRatioDrive::setUseLocationDependentDevices( bool useLocationDependentDevices, bool internal) { if (!internal) myRobot->lock(); // if this is a change then print it if (useLocationDependentDevices != myUseLocationDependentDevices) { if (useLocationDependentDevices) { ArLog::log(ArLog::Normal, "%s: Using location dependent range devices", myName.c_str()); } else { ArLog::log(ArLog::Normal, "%s: Not using location dependent range devices", myName.c_str()); } myUseLocationDependentDevices = useLocationDependentDevices; myLimiterForward->setUseLocationDependentDevices( myUseLocationDependentDevices); myLimiterBackward->setUseLocationDependentDevices( myUseLocationDependentDevices); if (myLimiterLateralLeft != NULL) myLimiterLateralLeft->setUseLocationDependentDevices( myUseLocationDependentDevices); if (myLimiterLateralRight != NULL) myLimiterLateralRight->setUseLocationDependentDevices( myUseLocationDependentDevices); } if (!internal) myRobot->unlock(); } AREXPORT bool ArServerModeRatioDrive::getUseLocationDependentDevices(void) { return myUseLocationDependentDevices; }
Java
package com.networkprofiles.widget; /** Service to refresh the widget **/ import android.app.Service; import android.appwidget.AppWidgetManager; import android.content.Intent; import android.graphics.Color; import android.os.IBinder; import android.provider.Settings; import android.widget.RemoteViews; import com.networkprofiles.R; import com.networkprofiles.utils.MyNetControll; public class NPWidgetService extends Service { private Boolean mobile; private Boolean cell; private Boolean gps; private Boolean display; private Boolean sound; private int [] widgetIds; private RemoteViews rv; private AppWidgetManager wm; private MyNetControll myController; public void onCreate() { wm = AppWidgetManager.getInstance(NPWidgetService.this);//this.getApplicationContext() myController = new MyNetControll(NPWidgetService.this); myController.myStart(); //rv = new RemoteViews(getPackageName(), R.layout.npwidgetwifi); } public int onStartCommand(Intent intent, int flags, int startId) { // /** Check the state of the network devices and set the text for the text fields **/ // //set the TextView for 3G data // if(telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED || telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTING) { // rv.setTextViewText(R.id.textMobile, "3G data is ON"); // } // if(telephonyManager.getDataState() == TelephonyManager.DATA_DISCONNECTED) { // rv.setTextViewText(R.id.textMobile, "3G data is OFF"); // } // //set the TextView for WiFi // if(wifim.getWifiState() == WifiManager.WIFI_STATE_ENABLED || wifim.getWifiState() == WifiManager.WIFI_STATE_ENABLING) { // rv.setTextViewText(R.id.textWifi, "Wifi is ON"); // } // if(wifim.getWifiState() == WifiManager.WIFI_STATE_DISABLED || wifim.getWifiState() == WifiManager.WIFI_STATE_DISABLING) { // rv.setTextViewText(R.id.textWifi, "Wifi is OFF"); // } // //set the TextView for Bluetooth // if(myBluetooth.getState() == BluetoothAdapter.STATE_ON || myBluetooth.getState() == BluetoothAdapter.STATE_TURNING_ON) { // rv.setTextViewText(R.id.textBluetooth, "Bluetooth is ON"); // } // if(myBluetooth.getState() == BluetoothAdapter.STATE_OFF || myBluetooth.getState() == BluetoothAdapter.STATE_TURNING_OFF) { // rv.setTextViewText(R.id.textBluetooth, "Bluetooth is Off"); // } // //set the TextView for Cell voice // if(Settings.System.getInt(NPWidgetService.this.getContentResolver(), // Settings.System.AIRPLANE_MODE_ON, 0) == 0) { // rv.setTextViewText(R.id.textCell, "Cell is ON"); // } else { // rv.setTextViewText(R.id.textCell, "Cell is OFF"); // } // //set the TextView for GPS // locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); // if(locationProviders.contains("gps")) { // rv.setTextViewText(R.id.textGps, "GPS is ON"); // } else { // rv.setTextViewText(R.id.textGps, "GPS is OFF"); // } /** Check which textView was clicked and switch the state of the corresponding device **/ widgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS); mobile = intent.getBooleanExtra("mobile", false); cell = intent.getBooleanExtra("cell", false); gps = intent.getBooleanExtra("gps", false); display = intent.getBooleanExtra("display", false); sound = intent.getBooleanExtra("sound", false); if(widgetIds.length > 0) { if(mobile) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetmobiledata); rv.setTextColor(R.id.textWidgetMobileData, Color.GREEN); updateWidgets(); rv.setTextColor(R.id.textWidgetMobileData, Color.WHITE); myController.mobileOnOff(); } if(cell) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetcell); rv.setTextColor(R.id.textWidgetCell, Color.GREEN); if(Settings.System.getInt(NPWidgetService.this.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 0) { myController.cellOff(); } else { myController.cellOn(); } if(Settings.System.getInt(NPWidgetService.this.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 0) { rv.setTextViewText(R.id.textWidgetCell, "Cell ON"); } else { rv.setTextViewText(R.id.textWidgetCell, "Cell OFF"); } updateWidgets(); rv.setTextColor(R.id.textWidgetCell, Color.WHITE); } if(gps) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetgps); rv.setTextColor(R.id.textWidgetGps, Color.GREEN); updateWidgets(); rv.setTextColor(R.id.textWidgetGps, Color.WHITE); myController.gpsOnOff(); } if(display) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetdisplay); rv.setTextColor(R.id.textWidgetDisplay, Color.GREEN); updateWidgets(); rv.setTextColor(R.id.textWidgetDisplay, Color.WHITE); myController.displayOnOff(); } if(sound) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetsound); rv.setTextColor(R.id.textViewWidgetSound, Color.GREEN); updateWidgets(); rv.setTextColor(R.id.textViewWidgetSound, Color.WHITE); myController.soundSettings(); } } updateWidgets(); stopSelf(); return 1; } public void onStart(Intent intent, int startId) { } public IBinder onBind(Intent arg0) { return null; } private void updateWidgets() { for(int id : widgetIds) { wm.updateAppWidget(id, rv); } } }//close class NPWidgetService
Java
#!/usr/bin/env python3 # Copyright (c) 2008-9 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 2 of the License, or # version 3 of the License, or (at your option) any later version. It is # provided for educational purposes and is distributed in the hope that # it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See # the GNU General Public License for more details. """Provides the Item example classes. """ class Item(object): def __init__(self, artist, title, year=None): self.__artist = artist self.__title = title self.__year = year def artist(self): return self.__artist def setArtist(self, artist): self.__artist = artist def title(self): return self.__title def setTitle(self, title): self.__title = title def year(self): return self.__year def setYear(self, year): self.__year = year def __str__(self): year = "" if self.__year is not None: year = " in {0}".format(self.__year) return "{0} by {1}{2}".format(self.__title, self.__artist, year) class Painting(Item): def __init__(self, artist, title, year=None): super(Painting, self).__init__(artist, title, year) class Sculpture(Item): def __init__(self, artist, title, year=None, material=None): super(Sculpture, self).__init__(artist, title, year) self.__material = material def material(self): return self.__material def setMaterial(self, material): self.__material = material def __str__(self): materialString = "" if self.__material is not None: materialString = " ({0})".format(self.__material) return "{0}{1}".format(super(Sculpture, self).__str__(), materialString) class Dimension(object): def __init__(self, width, height, depth=None): self.__width = width self.__height = height self.__depth = depth def width(self): return self.__width def setWidth(self, width): self.__width = width def height(self): return self.__height def setHeight(self, height): self.__height = height def depth(self): return self.__depth def setDepth(self, depth): self.__depth = depth def area(self): raise NotImplemented def volume(self): raise NotImplemented if __name__ == "__main__": items = [] items.append(Painting("Cecil Collins", "The Poet", 1941)) items.append(Painting("Cecil Collins", "The Sleeping Fool", 1943)) items.append(Painting("Edvard Munch", "The Scream", 1893)) items.append(Painting("Edvard Munch", "The Sick Child", 1896)) items.append(Painting("Edvard Munch", "The Dance of Life", 1900)) items.append(Sculpture("Auguste Rodin", "Eternal Springtime", 1917, "plaster")) items.append(Sculpture("Auguste Rodin", "Naked Balzac", 1917, "plaster")) items.append(Sculpture("Auguste Rodin", "The Secret", 1925, "bronze")) uniquematerials = set() for item in items: print(item) if hasattr(item, "material"): uniquematerials.add(item.material()) print("Sculptures use {0} unique materials".format( len(uniquematerials)))
Java
<?php /** * The template for displaying all posts having layout like: sidebar/content/sidebar. * * @package Sage Theme */ ?> <?php get_sidebar('second'); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'single' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || get_comments_number() ) : comments_template(); endif; ?> <?php endwhile; // end of the loop. ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); ?>
Java
/* GNU ddrescue - Data recovery tool Copyright (C) 2004-2019 Antonio Diaz Diaz. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define _FILE_OFFSET_BITS 64 #include <algorithm> #include <cctype> #include <cerrno> #include <climits> #include <cstdio> #include <cstdlib> #include <ctime> #include <string> #include <vector> #include <stdint.h> #include <termios.h> #include <unistd.h> #include "block.h" #include "mapbook.h" namespace { void input_pos_error( const long long pos, const long long insize ) { char buf[128]; snprintf( buf, sizeof buf, "Can't start reading at pos %s.\n" " Input file is only %s bytes long.", format_num3( pos ), format_num3( insize ) ); show_error( buf ); } } // end namespace bool Mapbook::save_mapfile( const char * const name ) { std::remove( name ); FILE * const f = std::fopen( name, "w" ); if( f && write_mapfile( f, true, true ) && std::fclose( f ) == 0 ) { char buf[80]; snprintf( buf, sizeof buf, "Mapfile saved in '%s'\n", name ); final_msg( buf ); return true; } return false; } bool Mapbook::emergency_save() { static bool first_time = true; static std::string home_name; const std::string dead_name( "ddrescue.map" ); if( filename() != dead_name && save_mapfile( dead_name.c_str() ) ) return true; if( first_time ) { first_time = false; const char * const p = std::getenv( "HOME" ); if( p ) { home_name = p; home_name += '/'; home_name += dead_name; } } if( home_name.size() && filename() != home_name && save_mapfile( home_name.c_str() ) ) return true; show_error( "Emergency save failed." ); return false; } Mapbook::Mapbook( const long long offset, const long long insize, Domain & dom, const Mb_options & mb_opts, const char * const mapname, const int cluster, const int hardbs, const bool complete_only, const bool rescue ) : Mapfile( mapname ), Mb_options( mb_opts ), offset_( offset ), mapfile_insize_( 0 ), domain_( dom ), hardbs_( hardbs ), softbs_( cluster * hardbs_ ), iobuf_size_( softbs_ + hardbs_ ), // +hardbs for direct unaligned reads final_errno_( 0 ), um_t1( 0 ), um_t1s( 0 ), um_prev_mf_sync( false ), mapfile_exists_( false ) { long alignment = sysconf( _SC_PAGESIZE ); if( alignment < hardbs_ || alignment % hardbs_ ) alignment = hardbs_; if( alignment < 2 ) alignment = 0; iobuf_ = iobuf_base = new uint8_t[ alignment + iobuf_size_ + hardbs_ ]; if( alignment > 1 ) // align iobuf for direct disc access { const int disp = alignment - ( reinterpret_cast<unsigned long long> (iobuf_) % alignment ); if( disp > 0 && disp < alignment ) iobuf_ += disp; } if( insize > 0 ) { if( domain_.pos() >= insize ) { input_pos_error( domain_.pos(), insize ); std::exit( 1 ); } domain_.crop_by_file_size( insize ); } if( filename() ) { mapfile_exists_ = read_mapfile( 0, false ); if( mapfile_exists_ ) mapfile_insize_ = extent().end(); } if( !complete_only ) extend_sblock_vector( insize ); else domain_.crop( extent() ); // limit domain to blocks read from mapfile compact_sblock_vector(); if( rescue ) join_subsectors( hardbs_ ); split_by_domain_borders( domain_ ); if( sblocks() == 0 ) domain_.clear(); } // Writes periodically the mapfile to disc. // Returns false only if update is attempted and fails. // bool Mapbook::update_mapfile( const int odes, const bool force ) { if( !filename() ) return true; const int interval = ( mapfile_save_interval >= 0 ) ? mapfile_save_interval : 30 + std::min( 270L, sblocks() / 38 ); // auto, 30s to 5m const long t2 = std::time( 0 ); if( um_t1 == 0 || um_t1 > t2 ) um_t1 = um_t1s = t2; // initialize if( !force && t2 - um_t1 < interval ) return true; const bool mf_sync = ( force || t2 - um_t1s >= mapfile_sync_interval ); if( odes >= 0 ) fsync( odes ); if( um_prev_mf_sync ) { std::string mapname_bak( filename() ); mapname_bak += ".bak"; std::remove( mapname_bak.c_str() ); // break possible hard link std::rename( filename(), mapname_bak.c_str() ); } um_prev_mf_sync = mf_sync; while( true ) { errno = 0; if( write_mapfile( 0, true, mf_sync ) ) // update times here to exclude writing time from intervals { um_t1 = std::time( 0 ); if( mf_sync ) um_t1s = um_t1; return true; } if( verbosity < 0 ) return false; const int saved_errno = errno; std::fputc( '\n', stderr ); char buf[80]; snprintf( buf, sizeof buf, "Error writing mapfile '%s'", filename() ); show_error( buf, saved_errno ); std::fputs( "Fix the problem and press ENTER to retry,\n" " or E+ENTER for an emergency save and exit,\n" " or Q+ENTER to abort.\n", stderr ); std::fflush( stderr ); while( true ) { tcflush( STDIN_FILENO, TCIFLUSH ); const int c = std::tolower( std::fgetc( stdin ) ); int tmp = c; while( tmp != '\n' && tmp != EOF ) tmp = std::fgetc( stdin ); if( c == '\r' || c == '\n' || c == 'e' || c == 'q' ) { if( c == 'q' || ( c == 'e' && emergency_save() ) ) { if( !force ) std::fputs( "\n\n\n\n", stdout ); return false; } break; } } } }
Java
/* Copyright (c) 2008 The Board of Trustees of The Leland Stanford * Junior University * * We are making the OpenFlow specification and associated documentation * (Software) available for public use and benefit with the expectation * that others will use, modify and enhance the Software and contribute * those enhancements back to the community. However, since we would * like to make the Software available for broadest use, with as few * restrictions as possible permission is hereby granted, free of * charge, to any person obtaining a copy of this Software to deal in * the Software under the copyrights without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * The name and trademarks of copyright holder(s) may NOT be used in * advertising or publicity pertaining to the Software or any * derivatives without specific, written prior permission. */ #include "../include/config.h" #include "csum.hh" CLICK_DECLS /* Returns the IP checksum of the 'n' bytes in 'data'. */ uint16_t csum(const void *data, size_t n) { return csum_finish(csum_continue(0, data, n)); } /* Adds the 16 bits in 'new' to the partial IP checksum 'partial' and returns * the updated checksum. (To start a new checksum, pass 0 for 'partial'. To * obtain the finished checksum, pass the return value to csum_finish().) */ uint32_t csum_add16(uint32_t partial, uint16_t New) { return partial + New; } /* Adds the 32 bits in 'new' to the partial IP checksum 'partial' and returns * the updated checksum. (To start a new checksum, pass 0 for 'partial'. To * obtain the finished checksum, pass the return value to csum_finish().) */ uint32_t csum_add32(uint32_t partial, uint32_t New) { return partial + (New >> 16) + (New & 0xffff); } /* Adds the 'n' bytes in 'data' to the partial IP checksum 'partial' and * returns the updated checksum. (To start a new checksum, pass 0 for * 'partial'. To obtain the finished checksum, pass the return value to * csum_finish().) */ uint32_t csum_continue(uint32_t partial, const void *data_, size_t n) { const uint16_t *data = (const uint16_t*)data_; for (; n > 1; n -= 2) { partial = csum_add16(partial, *data++); } if (n) { partial += *(uint8_t *) data; } return partial; } /* Returns the IP checksum corresponding to 'partial', which is a value updated * by some combination of csum_add16(), csum_add32(), and csum_continue(). */ uint16_t csum_finish(uint32_t partial) { return ~((partial & 0xffff) + (partial >> 16)); } /* Returns the new checksum for a packet in which the checksum field previously * contained 'old_csum' and in which a field that contained 'old_u16' was * changed to contain 'new_u16'. */ uint16_t recalc_csum16(uint16_t old_csum, uint16_t old_u16, uint16_t new_u16) { /* Ones-complement arithmetic is endian-independent, so this code does not * use htons() or ntohs(). * * See RFC 1624 for formula and explanation. */ uint16_t hc_complement = ~old_csum; uint16_t m_complement = ~old_u16; uint16_t m_prime = new_u16; uint32_t sum = hc_complement + m_complement + m_prime; uint16_t hc_prime_complement = sum + (sum >> 16); return ~hc_prime_complement; } /* Returns the new checksum for a packet in which the checksum field previously * contained 'old_csum' and in which a field that contained 'old_u32' was * changed to contain 'new_u32'. */ uint16_t recalc_csum32(uint16_t old_csum, uint32_t old_u32, uint32_t new_u32) { return recalc_csum16(recalc_csum16(old_csum, old_u32, new_u32), old_u32 >> 16, new_u32 >> 16); } CLICK_ENDDECLS ELEMENT_PROVIDES(Of_Csum)
Java
#!/usr/bin/env python # -*- coding:utf-8 -*- """ @author: Will """ from django import forms from app01 import models class ImportFrom(forms.Form): HOST_TYPE=((1,"001"),(2,"002")) #替換爲文件 host_type = forms.IntegerField( widget=forms.Select(choices=HOST_TYPE) ) hostname = forms.CharField() def __init__(self,*args,**kwargs): super(ImportFrom,self).__init__(*args,**kwargs) HOST_TYPE=((1,"001"),(2,"002")) #替換爲文件 self.fields['host_type'].widget.choices = models.userInfo.objects.all().values_list("id","name") models.userInfo.objects.get() models.userInfo.objects.filter()
Java
package net.minecartrapidtransit.path.launcher; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class FileStoreUtils { private String version; public FileStoreUtils(String versionFile) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(new File(getDataFilePath(versionFile)))); version = br.readLine(); br.close(); } public String getVersionedFile(String filename, String type){ return String.format("%s-%s.%s", filename, version, type); } public boolean fileNeedsUpdating(String filename, String type) { return(new File(getVersionedFile(filename, type)).exists()); } public String getVersionedDataFilePath(String filename, String type){ return getDataFilePath(getVersionedFile(filename, type)); } public static String getDataFolderPath(){ String os = System.getProperty("os.name").toLowerCase(); boolean windows = os.contains("windows"); boolean mac = os.contains("macosx"); if(windows){ return System.getenv("APPDATA") + "\\MRTPath2"; }else{ String home = System.getProperty("user.home"); if(mac){ return home + "/Library/Application Support/MRTPath2"; }else{ // Linux return home + "/.mrtpath2"; } } } public static String getDataFilePath(String file){ return getDataFolderPath() + File.separator + file.replace('/', File.separatorChar); } }
Java
/****************************************************************************** * Icinga 2 * * Copyright (C) 2012-2016 Icinga Development Team (https://www.icinga.org/) * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software Foundation * * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * ******************************************************************************/ #include "livestatus/endpointstable.hpp" #include "icinga/host.hpp" #include "icinga/service.hpp" #include "icinga/icingaapplication.hpp" #include "remote/endpoint.hpp" #include "remote/zone.hpp" #include "base/configtype.hpp" #include "base/objectlock.hpp" #include "base/convert.hpp" #include "base/utility.hpp" #include <boost/algorithm/string/classification.hpp> #include <boost/tuple/tuple.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/algorithm/string/split.hpp> using namespace icinga; EndpointsTable::EndpointsTable(void) { AddColumns(this); } void EndpointsTable::AddColumns(Table *table, const String& prefix, const Column::ObjectAccessor& objectAccessor) { table->AddColumn(prefix + "name", Column(&EndpointsTable::NameAccessor, objectAccessor)); table->AddColumn(prefix + "identity", Column(&EndpointsTable::IdentityAccessor, objectAccessor)); table->AddColumn(prefix + "node", Column(&EndpointsTable::NodeAccessor, objectAccessor)); table->AddColumn(prefix + "is_connected", Column(&EndpointsTable::IsConnectedAccessor, objectAccessor)); table->AddColumn(prefix + "zone", Column(&EndpointsTable::ZoneAccessor, objectAccessor)); } String EndpointsTable::GetName(void) const { return "endpoints"; } String EndpointsTable::GetPrefix(void) const { return "endpoint"; } void EndpointsTable::FetchRows(const AddRowFunction& addRowFn) { for (const Endpoint::Ptr& endpoint : ConfigType::GetObjectsByType<Endpoint>()) { if (!addRowFn(endpoint, LivestatusGroupByNone, Empty)) return; } } Value EndpointsTable::NameAccessor(const Value& row) { Endpoint::Ptr endpoint = static_cast<Endpoint::Ptr>(row); if (!endpoint) return Empty; return endpoint->GetName(); } Value EndpointsTable::IdentityAccessor(const Value& row) { Endpoint::Ptr endpoint = static_cast<Endpoint::Ptr>(row); if (!endpoint) return Empty; return endpoint->GetName(); } Value EndpointsTable::NodeAccessor(const Value& row) { Endpoint::Ptr endpoint = static_cast<Endpoint::Ptr>(row); if (!endpoint) return Empty; return IcingaApplication::GetInstance()->GetNodeName(); } Value EndpointsTable::IsConnectedAccessor(const Value& row) { Endpoint::Ptr endpoint = static_cast<Endpoint::Ptr>(row); if (!endpoint) return Empty; unsigned int is_connected = endpoint->GetConnected() ? 1 : 0; /* if identity is equal to node, fake is_connected */ if (endpoint->GetName() == IcingaApplication::GetInstance()->GetNodeName()) is_connected = 1; return is_connected; } Value EndpointsTable::ZoneAccessor(const Value& row) { Endpoint::Ptr endpoint = static_cast<Endpoint::Ptr>(row); if (!endpoint) return Empty; Zone::Ptr zone = endpoint->GetZone(); if (!zone) return Empty; return zone->GetName(); }
Java
<?php /** * @file * Banana class. */ namespace Drupal\oop_example_12\BusinessLogic\Fruit; /** * Banana class. */ class Banana extends Fruit { /** * Returns color of the object. */ public function getColor() { return t('yellow'); } }
Java
/* * Copyright (c) 2011 Picochip Ltd., Jamie Iles * * This file contains the hardware definitions of the picoXcell SoC devices. * * 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. */ #ifndef __ASM_ARCH_HARDWARE_H #define __ASM_ARCH_HARDWARE_H #include <mach/picoxcell_soc.h> #endif
Java
<?php /** * The template for displaying the footer. * * @package WordPress */ ?> </div> </div> <!-- Begin footer --> <div id="footer"> <?php $pp_footer_display_sidebar = get_option('pp_footer_display_sidebar'); if(!empty($pp_footer_display_sidebar)) { $pp_footer_style = get_option('pp_footer_style'); $footer_class = ''; switch($pp_footer_style) { case 1: $footer_class = 'one'; break; case 2: $footer_class = 'two'; break; case 3: $footer_class = 'three'; break; case 4: $footer_class = 'four'; break; default: $footer_class = 'four'; break; } ?> <ul class="sidebar_widget <?php echo $footer_class; ?>"> <?php dynamic_sidebar('Footer Sidebar'); ?> </ul> <br class="clear"/> <?php } ?> </div> <!-- End footer --> <div> <div> <div id="copyright" <?php if(empty($pp_footer_display_sidebar)) { echo 'style="border-top:0"'; } ?>> <div class="copyright_wrapper"> <div class="one_fourth"> <?php /** * Get footer left text */ $pp_footer_text = get_option('pp_footer_text'); if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) { $pp_footer_text = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($pp_footer_text); } if(empty($pp_footer_text)) { $pp_footer_text = 'Copyright © 2012 Nemesis Theme. Powered by <a href="http://wordpress.org/">Wordpress</a>.<br/>Wordpress theme by <a href="http://themeforest.net/user/peerapong/portfolio" target="_blank">Peerapong</a>'; } echo nl2br(stripslashes(html_entity_decode($pp_footer_text))); ?> </div> <div class="one_fourth"> <?php /** * Get footer left text */ $pp_footer_second_text = get_option('pp_footer_second_text'); if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) { $pp_footer_second_text = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($pp_footer_second_text); } if(empty($pp_footer_second_text)) { $pp_footer_second_text = ' '; } echo nl2br(stripslashes(html_entity_decode($pp_footer_second_text))); ?> </div> <div class="one_fourth"> <?php /** * Get footer left text */ $pp_footer_third_text = get_option('pp_footer_third_text'); if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) { $pp_footer_third_text = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($pp_footer_third_text); } if(empty($pp_footer_third_text)) { $pp_footer_third_text = ' '; } echo nl2br(stripslashes(html_entity_decode($pp_footer_third_text))); ?> </div> <div class="one_fourth last"> <?php /** * Get footer right text */ $pp_footer_right_text = get_option('pp_footer_right_text'); if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) { $pp_footer_right_text = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($pp_footer_right_text); } if(empty($pp_footer_right_text)) { $pp_footer_right_text = 'All images are copyrighted to their respective owners.'; } echo nl2br(stripslashes(html_entity_decode($pp_footer_right_text))); ?> </div> <br class="clear"/> </div> </div> </div> </div> <?php /** * Setup Google Analyric Code **/ include (TEMPLATEPATH . "/google-analytic.php"); ?> <?php /* Always have wp_footer() just before the closing </body> * tag of your theme, or you will break many plugins, which * generally use this hook to reference JavaScript files. */ wp_footer(); ?> <?php $pp_blog_share = get_option('pp_blog_share'); if(!empty($pp_blog_share)) { ?> <script type="text/javascript" src="//assets.pinterest.com/js/pinit.js"></script> <?php } ?> </body> </html>
Java
#include "logging.hpp" #include <fstream> #include <boost/log/sinks/text_file_backend.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/sinks.hpp> namespace p2l { namespace common { //===================================================================== void _init_logging() { boost::log::add_common_attributes(); boost::log::core::get()->set_filter ( boost::log::trivial::severity >= boost::log::trivial::trace ); typedef boost::log::sinks::synchronous_sink< boost::log::sinks::text_ostream_backend > text_sink; // the file sink for hte default logger boost::shared_ptr< text_sink > default_sink = boost::make_shared< text_sink >(); default_sink->locked_backend()->add_stream ( boost::make_shared< std::ofstream >( "default_log.log" ) ); boost::log::core::get()->add_sink( default_sink ); // the file sink for hte stat logger boost::shared_ptr< text_sink > stat_sink = boost::make_shared< text_sink >(); stat_sink->locked_backend()->add_stream ( boost::make_shared< std::ofstream >( "stat_log.log" ) ); boost::log::core::get()->add_sink( stat_sink ); } //===================================================================== //===================================================================== //===================================================================== //===================================================================== //===================================================================== //===================================================================== //===================================================================== //===================================================================== //===================================================================== //===================================================================== //===================================================================== } }
Java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.dialect.unique; import org.hibernate.boot.Metadata; import org.hibernate.dialect.Dialect; import org.hibernate.mapping.UniqueKey; /** * Informix requires the constraint name to come last on the alter table. * * @author Brett Meyer */ public class InformixUniqueDelegate extends DefaultUniqueDelegate { public InformixUniqueDelegate( Dialect dialect ) { super( dialect ); } // legacy model ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @Override public String getAlterTableToAddUniqueKeyCommand(UniqueKey uniqueKey, Metadata metadata) { // Do this here, rather than allowing UniqueKey/Constraint to do it. // We need full, simplified control over whether or not it happens. final String tableName = metadata.getDatabase().getJdbcEnvironment().getQualifiedObjectNameFormatter().format( uniqueKey.getTable().getQualifiedTableName(), metadata.getDatabase().getJdbcEnvironment().getDialect() ); final String constraintName = dialect.quote( uniqueKey.getName() ); return dialect.getAlterTableString( tableName ) + " add constraint " + uniqueConstraintSql( uniqueKey ) + " constraint " + constraintName; } }
Java
/* * Copyright 2002-2005, Instant802 Networks, Inc. * Copyright 2005-2006, Devicescape Software, Inc. * Copyright 2007 Johannes Berg <johannes@sipsolutions.net> * Copyright 2008 Luis R. Rodriguez <lrodriguz@atheros.com> * * 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. */ /** * DOC: Wireless regulatory infrastructure * * The usual implementation is for a driver to read a device EEPROM to * determine which regulatory domain it should be operating under, then * looking up the allowable channels in a driver-local table and finally * registering those channels in the wiphy structure. * * Another set of compliance enforcement is for drivers to use their * own compliance limits which can be stored on the EEPROM. The host * driver or firmware may ensure these are used. * * In addition to all this we provide an extra layer of regulatory * conformance. For drivers which do not have any regulatory * information CRDA provides the complete regulatory solution. * For others it provides a community effort on further restrictions * to enhance compliance. * * Note: When number of rules --> infinity we will not be able to * index on alpha2 any more, instead we'll probably have to * rely on some SHA1 checksum of the regdomain for example. * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/slab.h> #include <linux/list.h> #include <linux/random.h> #include <linux/ctype.h> #include <linux/nl80211.h> #include <linux/platform_device.h> #include <net/cfg80211.h> #include "core.h" #include "reg.h" #include "regdb.h" #include "nl80211.h" #ifdef CONFIG_CFG80211_REG_DEBUG #define REG_DBG_PRINT(format, args...) \ do { \ printk(KERN_DEBUG pr_fmt(format), ##args); \ } while (0) #else #define REG_DBG_PRINT(args...) #endif /* Receipt of information from last regulatory request */ static struct regulatory_request *last_request; /* To trigger userspace events */ static struct platform_device *reg_pdev; static struct device_type reg_device_type = { .uevent = reg_device_uevent, }; /* * Central wireless core regulatory domains, we only need two, * the current one and a world regulatory domain in case we have no * information to give us an alpha2 */ const struct ieee80211_regdomain *cfg80211_regdomain; /* * Protects static reg.c components: * - cfg80211_world_regdom * - cfg80211_regdom * - last_request */ static DEFINE_MUTEX(reg_mutex); static inline void assert_reg_lock(void) { lockdep_assert_held(&reg_mutex); } /* Used to queue up regulatory hints */ static LIST_HEAD(reg_requests_list); static spinlock_t reg_requests_lock; /* Used to queue up beacon hints for review */ static LIST_HEAD(reg_pending_beacons); static spinlock_t reg_pending_beacons_lock; /* Used to keep track of processed beacon hints */ static LIST_HEAD(reg_beacon_list); struct reg_beacon { struct list_head list; struct ieee80211_channel chan; }; static void reg_todo(struct work_struct *work); static DECLARE_WORK(reg_work, reg_todo); static void reg_timeout_work(struct work_struct *work); static DECLARE_DELAYED_WORK(reg_timeout, reg_timeout_work); /* We keep a static world regulatory domain in case of the absence of CRDA */ static const struct ieee80211_regdomain world_regdom = { .n_reg_rules = 5, .alpha2 = "00", .reg_rules = { /* IEEE 802.11b/g, channels 1..11 */ REG_RULE(2412-10, 2462+10, 40, 6, 20, 0), /* IEEE 802.11b/g, channels 12..13. No HT40 * channel fits here. */ REG_RULE(2467-10, 2472+10, 20, 6, 20, NL80211_RRF_PASSIVE_SCAN | NL80211_RRF_NO_IBSS), /* IEEE 802.11 channel 14 - Only JP enables * this and for 802.11b only */ REG_RULE(2484-10, 2484+10, 20, 6, 20, NL80211_RRF_PASSIVE_SCAN | NL80211_RRF_NO_IBSS | NL80211_RRF_NO_OFDM), /* IEEE 802.11a, channel 36..48 */ REG_RULE(5180-10, 5240+10, 40, 6, 20, NL80211_RRF_PASSIVE_SCAN | NL80211_RRF_NO_IBSS), /* NB: 5260 MHz - 5700 MHz requies DFS */ /* IEEE 802.11a, channel 149..165 */ REG_RULE(5745-10, 5825+10, 40, 6, 20, NL80211_RRF_PASSIVE_SCAN | NL80211_RRF_NO_IBSS), } }; static const struct ieee80211_regdomain *cfg80211_world_regdom = &world_regdom; static char *ieee80211_regdom = "00"; static char user_alpha2[2]; module_param(ieee80211_regdom, charp, 0444); MODULE_PARM_DESC(ieee80211_regdom, "IEEE 802.11 regulatory domain code"); static void reset_regdomains(void) { /* avoid freeing static information or freeing something twice */ if (cfg80211_regdomain == cfg80211_world_regdom) cfg80211_regdomain = NULL; if (cfg80211_world_regdom == &world_regdom) cfg80211_world_regdom = NULL; if (cfg80211_regdomain == &world_regdom) cfg80211_regdomain = NULL; kfree(cfg80211_regdomain); kfree(cfg80211_world_regdom); cfg80211_world_regdom = &world_regdom; cfg80211_regdomain = NULL; } /* * Dynamic world regulatory domain requested by the wireless * core upon initialization */ static void update_world_regdomain(const struct ieee80211_regdomain *rd) { BUG_ON(!last_request); reset_regdomains(); cfg80211_world_regdom = rd; cfg80211_regdomain = rd; } bool is_world_regdom(const char *alpha2) { if (!alpha2) return false; if (alpha2[0] == '0' && alpha2[1] == '0') return true; return false; } static bool is_alpha2_set(const char *alpha2) { if (!alpha2) return false; if (alpha2[0] != 0 && alpha2[1] != 0) return true; return false; } static bool is_unknown_alpha2(const char *alpha2) { if (!alpha2) return false; /* * Special case where regulatory domain was built by driver * but a specific alpha2 cannot be determined */ if (alpha2[0] == '9' && alpha2[1] == '9') return true; return false; } static bool is_intersected_alpha2(const char *alpha2) { if (!alpha2) return false; /* * Special case where regulatory domain is the * result of an intersection between two regulatory domain * structures */ if (alpha2[0] == '9' && alpha2[1] == '8') return true; return false; } static bool is_an_alpha2(const char *alpha2) { if (!alpha2) return false; if (isalpha(alpha2[0]) && isalpha(alpha2[1])) return true; return false; } static bool alpha2_equal(const char *alpha2_x, const char *alpha2_y) { if (!alpha2_x || !alpha2_y) return false; if (alpha2_x[0] == alpha2_y[0] && alpha2_x[1] == alpha2_y[1]) return true; return false; } static bool regdom_changes(const char *alpha2) { assert_cfg80211_lock(); if (!cfg80211_regdomain) return true; if (alpha2_equal(cfg80211_regdomain->alpha2, alpha2)) return false; return true; } /* * The NL80211_REGDOM_SET_BY_USER regdom alpha2 is cached, this lets * you know if a valid regulatory hint with NL80211_REGDOM_SET_BY_USER * has ever been issued. */ static bool is_user_regdom_saved(void) { if (user_alpha2[0] == '9' && user_alpha2[1] == '7') return false; /* This would indicate a mistake on the design */ if (WARN((!is_world_regdom(user_alpha2) && !is_an_alpha2(user_alpha2)), "Unexpected user alpha2: %c%c\n", user_alpha2[0], user_alpha2[1])) return false; return true; } static int reg_copy_regd(const struct ieee80211_regdomain **dst_regd, const struct ieee80211_regdomain *src_regd) { struct ieee80211_regdomain *regd; int size_of_regd = 0; unsigned int i; size_of_regd = sizeof(struct ieee80211_regdomain) + ((src_regd->n_reg_rules + 1) * sizeof(struct ieee80211_reg_rule)); regd = kzalloc(size_of_regd, GFP_KERNEL); if (!regd) return -ENOMEM; memcpy(regd, src_regd, sizeof(struct ieee80211_regdomain)); for (i = 0; i < src_regd->n_reg_rules; i++) memcpy(&regd->reg_rules[i], &src_regd->reg_rules[i], sizeof(struct ieee80211_reg_rule)); *dst_regd = regd; return 0; } #ifdef CONFIG_CFG80211_INTERNAL_REGDB struct reg_regdb_search_request { char alpha2[2]; struct list_head list; }; static LIST_HEAD(reg_regdb_search_list); static DEFINE_MUTEX(reg_regdb_search_mutex); static void reg_regdb_search(struct work_struct *work) { struct reg_regdb_search_request *request; const struct ieee80211_regdomain *curdom, *regdom; int i, r; mutex_lock(&reg_regdb_search_mutex); while (!list_empty(&reg_regdb_search_list)) { request = list_first_entry(&reg_regdb_search_list, struct reg_regdb_search_request, list); list_del(&request->list); for (i=0; i<reg_regdb_size; i++) { curdom = reg_regdb[i]; if (!memcmp(request->alpha2, curdom->alpha2, 2)) { r = reg_copy_regd(&regdom, curdom); if (r) break; mutex_lock(&cfg80211_mutex); set_regdom(regdom); mutex_unlock(&cfg80211_mutex); break; } } kfree(request); } mutex_unlock(&reg_regdb_search_mutex); } static DECLARE_WORK(reg_regdb_work, reg_regdb_search); static void reg_regdb_query(const char *alpha2) { struct reg_regdb_search_request *request; if (!alpha2) return; request = kzalloc(sizeof(struct reg_regdb_search_request), GFP_KERNEL); if (!request) return; memcpy(request->alpha2, alpha2, 2); mutex_lock(&reg_regdb_search_mutex); list_add_tail(&request->list, &reg_regdb_search_list); mutex_unlock(&reg_regdb_search_mutex); schedule_work(&reg_regdb_work); } #else static inline void reg_regdb_query(const char *alpha2) {} #endif /* CONFIG_CFG80211_INTERNAL_REGDB */ /* * This lets us keep regulatory code which is updated on a regulatory * basis in userspace. Country information is filled in by * reg_device_uevent */ static int call_crda(const char *alpha2) { if (!is_world_regdom((char *) alpha2)) pr_info("Calling CRDA for country: %c%c\n", alpha2[0], alpha2[1]); else pr_info("Calling CRDA to update world regulatory domain\n"); /* query internal regulatory database (if it exists) */ reg_regdb_query(alpha2); return kobject_uevent(&reg_pdev->dev.kobj, KOBJ_CHANGE); } /* Used by nl80211 before kmalloc'ing our regulatory domain */ bool reg_is_valid_request(const char *alpha2) { assert_cfg80211_lock(); if (!last_request) return false; return alpha2_equal(last_request->alpha2, alpha2); } /* Sanity check on a regulatory rule */ static bool is_valid_reg_rule(const struct ieee80211_reg_rule *rule) { const struct ieee80211_freq_range *freq_range = &rule->freq_range; u32 freq_diff; if (freq_range->start_freq_khz <= 0 || freq_range->end_freq_khz <= 0) return false; if (freq_range->start_freq_khz > freq_range->end_freq_khz) return false; freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz; if (freq_range->end_freq_khz <= freq_range->start_freq_khz || freq_range->max_bandwidth_khz > freq_diff) return false; return true; } static bool is_valid_rd(const struct ieee80211_regdomain *rd) { const struct ieee80211_reg_rule *reg_rule = NULL; unsigned int i; if (!rd->n_reg_rules) return false; if (WARN_ON(rd->n_reg_rules > NL80211_MAX_SUPP_REG_RULES)) return false; for (i = 0; i < rd->n_reg_rules; i++) { reg_rule = &rd->reg_rules[i]; if (!is_valid_reg_rule(reg_rule)) return false; } return true; } static bool reg_does_bw_fit(const struct ieee80211_freq_range *freq_range, u32 center_freq_khz, u32 bw_khz) { u32 start_freq_khz, end_freq_khz; start_freq_khz = center_freq_khz - (bw_khz/2); end_freq_khz = center_freq_khz + (bw_khz/2); if (start_freq_khz >= freq_range->start_freq_khz && end_freq_khz <= freq_range->end_freq_khz) return true; return false; } /** * freq_in_rule_band - tells us if a frequency is in a frequency band * @freq_range: frequency rule we want to query * @freq_khz: frequency we are inquiring about * * This lets us know if a specific frequency rule is or is not relevant to * a specific frequency's band. Bands are device specific and artificial * definitions (the "2.4 GHz band" and the "5 GHz band"), however it is * safe for now to assume that a frequency rule should not be part of a * frequency's band if the start freq or end freq are off by more than 2 GHz. * This resolution can be lowered and should be considered as we add * regulatory rule support for other "bands". **/ static bool freq_in_rule_band(const struct ieee80211_freq_range *freq_range, u32 freq_khz) { #define ONE_GHZ_IN_KHZ 1000000 if (abs(freq_khz - freq_range->start_freq_khz) <= (2 * ONE_GHZ_IN_KHZ)) return true; if (abs(freq_khz - freq_range->end_freq_khz) <= (2 * ONE_GHZ_IN_KHZ)) return true; return false; #undef ONE_GHZ_IN_KHZ } /* * Helper for regdom_intersect(), this does the real * mathematical intersection fun */ static int reg_rules_intersect( const struct ieee80211_reg_rule *rule1, const struct ieee80211_reg_rule *rule2, struct ieee80211_reg_rule *intersected_rule) { const struct ieee80211_freq_range *freq_range1, *freq_range2; struct ieee80211_freq_range *freq_range; const struct ieee80211_power_rule *power_rule1, *power_rule2; struct ieee80211_power_rule *power_rule; u32 freq_diff; freq_range1 = &rule1->freq_range; freq_range2 = &rule2->freq_range; freq_range = &intersected_rule->freq_range; power_rule1 = &rule1->power_rule; power_rule2 = &rule2->power_rule; power_rule = &intersected_rule->power_rule; freq_range->start_freq_khz = max(freq_range1->start_freq_khz, freq_range2->start_freq_khz); freq_range->end_freq_khz = min(freq_range1->end_freq_khz, freq_range2->end_freq_khz); freq_range->max_bandwidth_khz = min(freq_range1->max_bandwidth_khz, freq_range2->max_bandwidth_khz); freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz; if (freq_range->max_bandwidth_khz > freq_diff) freq_range->max_bandwidth_khz = freq_diff; power_rule->max_eirp = min(power_rule1->max_eirp, power_rule2->max_eirp); power_rule->max_antenna_gain = min(power_rule1->max_antenna_gain, power_rule2->max_antenna_gain); intersected_rule->flags = (rule1->flags | rule2->flags); if (!is_valid_reg_rule(intersected_rule)) return -EINVAL; return 0; } /** * regdom_intersect - do the intersection between two regulatory domains * @rd1: first regulatory domain * @rd2: second regulatory domain * * Use this function to get the intersection between two regulatory domains. * Once completed we will mark the alpha2 for the rd as intersected, "98", * as no one single alpha2 can represent this regulatory domain. * * Returns a pointer to the regulatory domain structure which will hold the * resulting intersection of rules between rd1 and rd2. We will * kzalloc() this structure for you. */ static struct ieee80211_regdomain *regdom_intersect( const struct ieee80211_regdomain *rd1, const struct ieee80211_regdomain *rd2) { int r, size_of_regd; unsigned int x, y; unsigned int num_rules = 0, rule_idx = 0; const struct ieee80211_reg_rule *rule1, *rule2; struct ieee80211_reg_rule *intersected_rule; struct ieee80211_regdomain *rd; /* This is just a dummy holder to help us count */ struct ieee80211_reg_rule irule; /* Uses the stack temporarily for counter arithmetic */ intersected_rule = &irule; memset(intersected_rule, 0, sizeof(struct ieee80211_reg_rule)); if (!rd1 || !rd2) return NULL; /* * First we get a count of the rules we'll need, then we actually * build them. This is to so we can malloc() and free() a * regdomain once. The reason we use reg_rules_intersect() here * is it will return -EINVAL if the rule computed makes no sense. * All rules that do check out OK are valid. */ for (x = 0; x < rd1->n_reg_rules; x++) { rule1 = &rd1->reg_rules[x]; for (y = 0; y < rd2->n_reg_rules; y++) { rule2 = &rd2->reg_rules[y]; if (!reg_rules_intersect(rule1, rule2, intersected_rule)) num_rules++; memset(intersected_rule, 0, sizeof(struct ieee80211_reg_rule)); } } if (!num_rules) return NULL; size_of_regd = sizeof(struct ieee80211_regdomain) + ((num_rules + 1) * sizeof(struct ieee80211_reg_rule)); rd = kzalloc(size_of_regd, GFP_KERNEL); if (!rd) return NULL; for (x = 0; x < rd1->n_reg_rules; x++) { rule1 = &rd1->reg_rules[x]; for (y = 0; y < rd2->n_reg_rules; y++) { rule2 = &rd2->reg_rules[y]; /* * This time around instead of using the stack lets * write to the target rule directly saving ourselves * a memcpy() */ intersected_rule = &rd->reg_rules[rule_idx]; r = reg_rules_intersect(rule1, rule2, intersected_rule); /* * No need to memset here the intersected rule here as * we're not using the stack anymore */ if (r) continue; rule_idx++; } } if (rule_idx != num_rules) { kfree(rd); return NULL; } rd->n_reg_rules = num_rules; rd->alpha2[0] = '9'; rd->alpha2[1] = '8'; return rd; } /* * XXX: add support for the rest of enum nl80211_reg_rule_flags, we may * want to just have the channel structure use these */ static u32 map_regdom_flags(u32 rd_flags) { u32 channel_flags = 0; if (rd_flags & NL80211_RRF_PASSIVE_SCAN) channel_flags |= IEEE80211_CHAN_PASSIVE_SCAN; if (rd_flags & NL80211_RRF_NO_IBSS) channel_flags |= IEEE80211_CHAN_NO_IBSS; if (rd_flags & NL80211_RRF_DFS) channel_flags |= IEEE80211_CHAN_RADAR; return channel_flags; } static int freq_reg_info_regd(struct wiphy *wiphy, u32 center_freq, u32 desired_bw_khz, const struct ieee80211_reg_rule **reg_rule, const struct ieee80211_regdomain *custom_regd) { int i; bool band_rule_found = false; const struct ieee80211_regdomain *regd; bool bw_fits = false; if (!desired_bw_khz) desired_bw_khz = MHZ_TO_KHZ(20); regd = custom_regd ? custom_regd : cfg80211_regdomain; /* * Follow the driver's regulatory domain, if present, unless a country * IE has been processed or a user wants to help complaince further */ if (!custom_regd && last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE && last_request->initiator != NL80211_REGDOM_SET_BY_USER && wiphy->regd) regd = wiphy->regd; if (!regd) return -EINVAL; for (i = 0; i < regd->n_reg_rules; i++) { const struct ieee80211_reg_rule *rr; const struct ieee80211_freq_range *fr = NULL; rr = &regd->reg_rules[i]; fr = &rr->freq_range; /* * We only need to know if one frequency rule was * was in center_freq's band, that's enough, so lets * not overwrite it once found */ if (!band_rule_found) band_rule_found = freq_in_rule_band(fr, center_freq); bw_fits = reg_does_bw_fit(fr, center_freq, desired_bw_khz); if (band_rule_found && bw_fits) { *reg_rule = rr; return 0; } } if (!band_rule_found) return -ERANGE; return -EINVAL; } int freq_reg_info(struct wiphy *wiphy, u32 center_freq, u32 desired_bw_khz, const struct ieee80211_reg_rule **reg_rule) { assert_cfg80211_lock(); return freq_reg_info_regd(wiphy, center_freq, desired_bw_khz, reg_rule, NULL); } EXPORT_SYMBOL(freq_reg_info); #ifdef CONFIG_CFG80211_REG_DEBUG static const char *reg_initiator_name(enum nl80211_reg_initiator initiator) { switch (initiator) { case NL80211_REGDOM_SET_BY_CORE: return "Set by core"; case NL80211_REGDOM_SET_BY_USER: return "Set by user"; case NL80211_REGDOM_SET_BY_DRIVER: return "Set by driver"; case NL80211_REGDOM_SET_BY_COUNTRY_IE: return "Set by country IE"; default: WARN_ON(1); return "Set by bug"; } } static void chan_reg_rule_print_dbg(struct ieee80211_channel *chan, u32 desired_bw_khz, const struct ieee80211_reg_rule *reg_rule) { const struct ieee80211_power_rule *power_rule; const struct ieee80211_freq_range *freq_range; char max_antenna_gain[32]; power_rule = &reg_rule->power_rule; freq_range = &reg_rule->freq_range; if (!power_rule->max_antenna_gain) snprintf(max_antenna_gain, 32, "N/A"); else snprintf(max_antenna_gain, 32, "%d", power_rule->max_antenna_gain); REG_DBG_PRINT("Updating information on frequency %d MHz " "for a %d MHz width channel with regulatory rule:\n", chan->center_freq, KHZ_TO_MHZ(desired_bw_khz)); REG_DBG_PRINT("%d KHz - %d KHz @ KHz), (%s mBi, %d mBm)\n", freq_range->start_freq_khz, freq_range->end_freq_khz, max_antenna_gain, power_rule->max_eirp); } #else static void chan_reg_rule_print_dbg(struct ieee80211_channel *chan, u32 desired_bw_khz, const struct ieee80211_reg_rule *reg_rule) { return; } #endif /* * Note that right now we assume the desired channel bandwidth * is always 20 MHz for each individual channel (HT40 uses 20 MHz * per channel, the primary and the extension channel). To support * smaller custom bandwidths such as 5 MHz or 10 MHz we'll need a * new ieee80211_channel.target_bw and re run the regulatory check * on the wiphy with the target_bw specified. Then we can simply use * that below for the desired_bw_khz below. */ static void handle_channel(struct wiphy *wiphy, enum nl80211_reg_initiator initiator, enum ieee80211_band band, unsigned int chan_idx) { int r; u32 flags, bw_flags = 0; u32 desired_bw_khz = MHZ_TO_KHZ(20); const struct ieee80211_reg_rule *reg_rule = NULL; const struct ieee80211_power_rule *power_rule = NULL; const struct ieee80211_freq_range *freq_range = NULL; struct ieee80211_supported_band *sband; struct ieee80211_channel *chan; struct wiphy *request_wiphy = NULL; assert_cfg80211_lock(); request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx); sband = wiphy->bands[band]; BUG_ON(chan_idx >= sband->n_channels); chan = &sband->channels[chan_idx]; flags = chan->orig_flags; r = freq_reg_info(wiphy, MHZ_TO_KHZ(chan->center_freq), desired_bw_khz, &reg_rule); if (r) { /* * We will disable all channels that do not match our * received regulatory rule unless the hint is coming * from a Country IE and the Country IE had no information * about a band. The IEEE 802.11 spec allows for an AP * to send only a subset of the regulatory rules allowed, * so an AP in the US that only supports 2.4 GHz may only send * a country IE with information for the 2.4 GHz band * while 5 GHz is still supported. */ if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE && r == -ERANGE) return; REG_DBG_PRINT("Disabling freq %d MHz\n", chan->center_freq); chan->flags = IEEE80211_CHAN_DISABLED; return; } chan_reg_rule_print_dbg(chan, desired_bw_khz, reg_rule); power_rule = &reg_rule->power_rule; freq_range = &reg_rule->freq_range; if (freq_range->max_bandwidth_khz < MHZ_TO_KHZ(40)) bw_flags = IEEE80211_CHAN_NO_HT40; if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER && request_wiphy && request_wiphy == wiphy && request_wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY) { /* * This guarantees the driver's requested regulatory domain * will always be used as a base for further regulatory * settings */ chan->flags = chan->orig_flags = map_regdom_flags(reg_rule->flags) | bw_flags; chan->max_antenna_gain = chan->orig_mag = (int) MBI_TO_DBI(power_rule->max_antenna_gain); chan->max_power = chan->orig_mpwr = (int) MBM_TO_DBM(power_rule->max_eirp); return; } chan->beacon_found = false; chan->flags = flags | bw_flags | map_regdom_flags(reg_rule->flags); chan->max_antenna_gain = min(chan->orig_mag, (int) MBI_TO_DBI(power_rule->max_antenna_gain)); if (chan->orig_mpwr) { /* * Devices that have their own custom regulatory domain * but also use WIPHY_FLAG_STRICT_REGULATORY will follow the * passed country IE power settings. */ if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE && wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY && wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY) { chan->max_power = MBM_TO_DBM(power_rule->max_eirp); } else { chan->max_power = min(chan->orig_mpwr, (int) MBM_TO_DBM(power_rule->max_eirp)); } } else chan->max_power = (int) MBM_TO_DBM(power_rule->max_eirp); } static void handle_band(struct wiphy *wiphy, enum ieee80211_band band, enum nl80211_reg_initiator initiator) { unsigned int i; struct ieee80211_supported_band *sband; BUG_ON(!wiphy->bands[band]); sband = wiphy->bands[band]; for (i = 0; i < sband->n_channels; i++) handle_channel(wiphy, initiator, band, i); } static bool ignore_reg_update(struct wiphy *wiphy, enum nl80211_reg_initiator initiator) { if (!last_request) { REG_DBG_PRINT("Ignoring regulatory request %s since " "last_request is not set\n", reg_initiator_name(initiator)); return true; } if (initiator == NL80211_REGDOM_SET_BY_CORE && wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY) { REG_DBG_PRINT("Ignoring regulatory request %s " "since the driver uses its own custom " "regulatory domain ", reg_initiator_name(initiator)); return true; } /* * wiphy->regd will be set once the device has its own * desired regulatory domain set */ if (wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY && !wiphy->regd && initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE && !is_world_regdom(last_request->alpha2)) { REG_DBG_PRINT("Ignoring regulatory request %s " "since the driver requires its own regulaotry " "domain to be set first", reg_initiator_name(initiator)); return true; } return false; } static void update_all_wiphy_regulatory(enum nl80211_reg_initiator initiator) { struct cfg80211_registered_device *rdev; struct wiphy *wiphy; list_for_each_entry(rdev, &cfg80211_rdev_list, list) { wiphy = &rdev->wiphy; wiphy_update_regulatory(wiphy, initiator); /* * Regulatory updates set by CORE are ignored for custom * regulatory cards. Let us notify the changes to the driver, * as some drivers used this to restore its orig_* reg domain. */ if (initiator == NL80211_REGDOM_SET_BY_CORE && wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY && wiphy->reg_notifier) wiphy->reg_notifier(wiphy, last_request); } } static void handle_reg_beacon(struct wiphy *wiphy, unsigned int chan_idx, struct reg_beacon *reg_beacon) { struct ieee80211_supported_band *sband; struct ieee80211_channel *chan; bool channel_changed = false; struct ieee80211_channel chan_before; assert_cfg80211_lock(); sband = wiphy->bands[reg_beacon->chan.band]; chan = &sband->channels[chan_idx]; if (likely(chan->center_freq != reg_beacon->chan.center_freq)) return; if (chan->beacon_found) return; chan->beacon_found = true; if (wiphy->flags & WIPHY_FLAG_DISABLE_BEACON_HINTS) return; chan_before.center_freq = chan->center_freq; chan_before.flags = chan->flags; if (chan->flags & IEEE80211_CHAN_PASSIVE_SCAN) { chan->flags &= ~IEEE80211_CHAN_PASSIVE_SCAN; channel_changed = true; } if (chan->flags & IEEE80211_CHAN_NO_IBSS) { chan->flags &= ~IEEE80211_CHAN_NO_IBSS; channel_changed = true; } if (channel_changed) nl80211_send_beacon_hint_event(wiphy, &chan_before, chan); } /* * Called when a scan on a wiphy finds a beacon on * new channel */ static void wiphy_update_new_beacon(struct wiphy *wiphy, struct reg_beacon *reg_beacon) { unsigned int i; struct ieee80211_supported_band *sband; assert_cfg80211_lock(); if (!wiphy->bands[reg_beacon->chan.band]) return; sband = wiphy->bands[reg_beacon->chan.band]; for (i = 0; i < sband->n_channels; i++) handle_reg_beacon(wiphy, i, reg_beacon); } /* * Called upon reg changes or a new wiphy is added */ static void wiphy_update_beacon_reg(struct wiphy *wiphy) { unsigned int i; struct ieee80211_supported_band *sband; struct reg_beacon *reg_beacon; assert_cfg80211_lock(); if (list_empty(&reg_beacon_list)) return; list_for_each_entry(reg_beacon, &reg_beacon_list, list) { if (!wiphy->bands[reg_beacon->chan.band]) continue; sband = wiphy->bands[reg_beacon->chan.band]; for (i = 0; i < sband->n_channels; i++) handle_reg_beacon(wiphy, i, reg_beacon); } } static bool reg_is_world_roaming(struct wiphy *wiphy) { if (is_world_regdom(cfg80211_regdomain->alpha2) || (wiphy->regd && is_world_regdom(wiphy->regd->alpha2))) return true; if (last_request && last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE && wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY) return true; return false; } /* Reap the advantages of previously found beacons */ static void reg_process_beacons(struct wiphy *wiphy) { /* * Means we are just firing up cfg80211, so no beacons would * have been processed yet. */ if (!last_request) return; if (!reg_is_world_roaming(wiphy)) return; wiphy_update_beacon_reg(wiphy); } static bool is_ht40_not_allowed(struct ieee80211_channel *chan) { if (!chan) return true; if (chan->flags & IEEE80211_CHAN_DISABLED) return true; /* This would happen when regulatory rules disallow HT40 completely */ if (IEEE80211_CHAN_NO_HT40 == (chan->flags & (IEEE80211_CHAN_NO_HT40))) return true; return false; } static void reg_process_ht_flags_channel(struct wiphy *wiphy, enum ieee80211_band band, unsigned int chan_idx) { struct ieee80211_supported_band *sband; struct ieee80211_channel *channel; struct ieee80211_channel *channel_before = NULL, *channel_after = NULL; unsigned int i; assert_cfg80211_lock(); sband = wiphy->bands[band]; BUG_ON(chan_idx >= sband->n_channels); channel = &sband->channels[chan_idx]; if (is_ht40_not_allowed(channel)) { channel->flags |= IEEE80211_CHAN_NO_HT40; return; } /* * We need to ensure the extension channels exist to * be able to use HT40- or HT40+, this finds them (or not) */ for (i = 0; i < sband->n_channels; i++) { struct ieee80211_channel *c = &sband->channels[i]; if (c->center_freq == (channel->center_freq - 20)) channel_before = c; if (c->center_freq == (channel->center_freq + 20)) channel_after = c; } /* * Please note that this assumes target bandwidth is 20 MHz, * if that ever changes we also need to change the below logic * to include that as well. */ if (is_ht40_not_allowed(channel_before)) channel->flags |= IEEE80211_CHAN_NO_HT40MINUS; else channel->flags &= ~IEEE80211_CHAN_NO_HT40MINUS; if (is_ht40_not_allowed(channel_after)) channel->flags |= IEEE80211_CHAN_NO_HT40PLUS; else channel->flags &= ~IEEE80211_CHAN_NO_HT40PLUS; } static void reg_process_ht_flags_band(struct wiphy *wiphy, enum ieee80211_band band) { unsigned int i; struct ieee80211_supported_band *sband; BUG_ON(!wiphy->bands[band]); sband = wiphy->bands[band]; for (i = 0; i < sband->n_channels; i++) reg_process_ht_flags_channel(wiphy, band, i); } static void reg_process_ht_flags(struct wiphy *wiphy) { enum ieee80211_band band; if (!wiphy) return; for (band = 0; band < IEEE80211_NUM_BANDS; band++) { if (wiphy->bands[band]) reg_process_ht_flags_band(wiphy, band); } } void wiphy_update_regulatory(struct wiphy *wiphy, enum nl80211_reg_initiator initiator) { enum ieee80211_band band; if (ignore_reg_update(wiphy, initiator)) return; for (band = 0; band < IEEE80211_NUM_BANDS; band++) { if (wiphy->bands[band]) handle_band(wiphy, band, initiator); } reg_process_beacons(wiphy); reg_process_ht_flags(wiphy); if (wiphy->reg_notifier) wiphy->reg_notifier(wiphy, last_request); } static void handle_channel_custom(struct wiphy *wiphy, enum ieee80211_band band, unsigned int chan_idx, const struct ieee80211_regdomain *regd) { int r; u32 desired_bw_khz = MHZ_TO_KHZ(20); u32 bw_flags = 0; const struct ieee80211_reg_rule *reg_rule = NULL; const struct ieee80211_power_rule *power_rule = NULL; const struct ieee80211_freq_range *freq_range = NULL; struct ieee80211_supported_band *sband; struct ieee80211_channel *chan; assert_reg_lock(); sband = wiphy->bands[band]; BUG_ON(chan_idx >= sband->n_channels); chan = &sband->channels[chan_idx]; r = freq_reg_info_regd(wiphy, MHZ_TO_KHZ(chan->center_freq), desired_bw_khz, &reg_rule, regd); if (r) { REG_DBG_PRINT("Disabling freq %d MHz as custom " "regd has no rule that fits a %d MHz " "wide channel\n", chan->center_freq, KHZ_TO_MHZ(desired_bw_khz)); chan->flags = IEEE80211_CHAN_DISABLED; return; } chan_reg_rule_print_dbg(chan, desired_bw_khz, reg_rule); power_rule = &reg_rule->power_rule; freq_range = &reg_rule->freq_range; if (freq_range->max_bandwidth_khz < MHZ_TO_KHZ(40)) bw_flags = IEEE80211_CHAN_NO_HT40; chan->flags |= map_regdom_flags(reg_rule->flags) | bw_flags; chan->max_antenna_gain = (int) MBI_TO_DBI(power_rule->max_antenna_gain); chan->max_power = (int) MBM_TO_DBM(power_rule->max_eirp); } static void handle_band_custom(struct wiphy *wiphy, enum ieee80211_band band, const struct ieee80211_regdomain *regd) { unsigned int i; struct ieee80211_supported_band *sband; BUG_ON(!wiphy->bands[band]); sband = wiphy->bands[band]; for (i = 0; i < sband->n_channels; i++) handle_channel_custom(wiphy, band, i, regd); } /* Used by drivers prior to wiphy registration */ void wiphy_apply_custom_regulatory(struct wiphy *wiphy, const struct ieee80211_regdomain *regd) { enum ieee80211_band band; unsigned int bands_set = 0; mutex_lock(&reg_mutex); for (band = 0; band < IEEE80211_NUM_BANDS; band++) { if (!wiphy->bands[band]) continue; handle_band_custom(wiphy, band, regd); bands_set++; } mutex_unlock(&reg_mutex); /* * no point in calling this if it won't have any effect * on your device's supportd bands. */ WARN_ON(!bands_set); } EXPORT_SYMBOL(wiphy_apply_custom_regulatory); /* * Return value which can be used by ignore_request() to indicate * it has been determined we should intersect two regulatory domains */ #define REG_INTERSECT 1 /* This has the logic which determines when a new request * should be ignored. */ static int ignore_request(struct wiphy *wiphy, struct regulatory_request *pending_request) { struct wiphy *last_wiphy = NULL; assert_cfg80211_lock(); /* All initial requests are respected */ if (!last_request) return 0; switch (pending_request->initiator) { case NL80211_REGDOM_SET_BY_CORE: return 0; case NL80211_REGDOM_SET_BY_COUNTRY_IE: last_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx); if (unlikely(!is_an_alpha2(pending_request->alpha2))) return -EINVAL; if (last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE) { if (last_wiphy != wiphy) { /* * Two cards with two APs claiming different * Country IE alpha2s. We could * intersect them, but that seems unlikely * to be correct. Reject second one for now. */ if (regdom_changes(pending_request->alpha2)) return -EOPNOTSUPP; return -EALREADY; } /* * Two consecutive Country IE hints on the same wiphy. * This should be picked up early by the driver/stack */ if (WARN_ON(regdom_changes(pending_request->alpha2))) return 0; return -EALREADY; } return 0; case NL80211_REGDOM_SET_BY_DRIVER: if (last_request->initiator == NL80211_REGDOM_SET_BY_CORE) { if (regdom_changes(pending_request->alpha2)) return 0; return -EALREADY; } /* * This would happen if you unplug and plug your card * back in or if you add a new device for which the previously * loaded card also agrees on the regulatory domain. */ if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER && !regdom_changes(pending_request->alpha2)) return -EALREADY; return REG_INTERSECT; case NL80211_REGDOM_SET_BY_USER: if (last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE) return REG_INTERSECT; /* * If the user knows better the user should set the regdom * to their country before the IE is picked up */ if (last_request->initiator == NL80211_REGDOM_SET_BY_USER && last_request->intersect) return -EOPNOTSUPP; /* * Process user requests only after previous user/driver/core * requests have been processed */ if (last_request->initiator == NL80211_REGDOM_SET_BY_CORE || last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER || last_request->initiator == NL80211_REGDOM_SET_BY_USER) { if (regdom_changes(last_request->alpha2)) return -EAGAIN; } if (!regdom_changes(pending_request->alpha2)) return -EALREADY; return 0; } return -EINVAL; } static void reg_set_request_processed(void) { bool need_more_processing = false; last_request->processed = true; spin_lock(&reg_requests_lock); if (!list_empty(&reg_requests_list)) need_more_processing = true; spin_unlock(&reg_requests_lock); if (last_request->initiator == NL80211_REGDOM_SET_BY_USER) cancel_delayed_work_sync(&reg_timeout); if (need_more_processing) schedule_work(&reg_work); } /** * __regulatory_hint - hint to the wireless core a regulatory domain * @wiphy: if the hint comes from country information from an AP, this * is required to be set to the wiphy that received the information * @pending_request: the regulatory request currently being processed * * The Wireless subsystem can use this function to hint to the wireless core * what it believes should be the current regulatory domain. * * Returns zero if all went fine, %-EALREADY if a regulatory domain had * already been set or other standard error codes. * * Caller must hold &cfg80211_mutex and &reg_mutex */ static int __regulatory_hint(struct wiphy *wiphy, struct regulatory_request *pending_request) { bool intersect = false; int r = 0; assert_cfg80211_lock(); r = ignore_request(wiphy, pending_request); if (r == REG_INTERSECT) { if (pending_request->initiator == NL80211_REGDOM_SET_BY_DRIVER) { r = reg_copy_regd(&wiphy->regd, cfg80211_regdomain); if (r) { kfree(pending_request); return r; } } intersect = true; } else if (r) { /* * If the regulatory domain being requested by the * driver has already been set just copy it to the * wiphy */ if (r == -EALREADY && pending_request->initiator == NL80211_REGDOM_SET_BY_DRIVER) { r = reg_copy_regd(&wiphy->regd, cfg80211_regdomain); if (r) { kfree(pending_request); return r; } r = -EALREADY; goto new_request; } kfree(pending_request); return r; } new_request: kfree(last_request); last_request = pending_request; last_request->intersect = intersect; pending_request = NULL; if (last_request->initiator == NL80211_REGDOM_SET_BY_USER) { user_alpha2[0] = last_request->alpha2[0]; user_alpha2[1] = last_request->alpha2[1]; } /* When r == REG_INTERSECT we do need to call CRDA */ if (r < 0) { /* * Since CRDA will not be called in this case as we already * have applied the requested regulatory domain before we just * inform userspace we have processed the request */ if (r == -EALREADY) { nl80211_send_reg_change_event(last_request); reg_set_request_processed(); } return r; } return call_crda(last_request->alpha2); } /* This processes *all* regulatory hints */ static void reg_process_hint(struct regulatory_request *reg_request) { int r = 0; struct wiphy *wiphy = NULL; enum nl80211_reg_initiator initiator = reg_request->initiator; BUG_ON(!reg_request->alpha2); if (wiphy_idx_valid(reg_request->wiphy_idx)) wiphy = wiphy_idx_to_wiphy(reg_request->wiphy_idx); if (reg_request->initiator == NL80211_REGDOM_SET_BY_DRIVER && !wiphy) { kfree(reg_request); return; } r = __regulatory_hint(wiphy, reg_request); /* This is required so that the orig_* parameters are saved */ if (r == -EALREADY && wiphy && wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY) { wiphy_update_regulatory(wiphy, initiator); return; } /* * We only time out user hints, given that they should be the only * source of bogus requests. */ if (r != -EALREADY && reg_request->initiator == NL80211_REGDOM_SET_BY_USER) schedule_delayed_work(&reg_timeout, msecs_to_jiffies(3142)); } /* * Processes regulatory hints, this is all the NL80211_REGDOM_SET_BY_* * Regulatory hints come on a first come first serve basis and we * must process each one atomically. */ static void reg_process_pending_hints(void) { struct regulatory_request *reg_request; mutex_lock(&cfg80211_mutex); mutex_lock(&reg_mutex); /* When last_request->processed becomes true this will be rescheduled */ if (last_request && !last_request->processed) { REG_DBG_PRINT("Pending regulatory request, waiting " "for it to be processed..."); goto out; } spin_lock(&reg_requests_lock); if (list_empty(&reg_requests_list)) { spin_unlock(&reg_requests_lock); goto out; } reg_request = list_first_entry(&reg_requests_list, struct regulatory_request, list); list_del_init(&reg_request->list); spin_unlock(&reg_requests_lock); reg_process_hint(reg_request); out: mutex_unlock(&reg_mutex); mutex_unlock(&cfg80211_mutex); } /* Processes beacon hints -- this has nothing to do with country IEs */ static void reg_process_pending_beacon_hints(void) { struct cfg80211_registered_device *rdev; struct reg_beacon *pending_beacon, *tmp; /* * No need to hold the reg_mutex here as we just touch wiphys * and do not read or access regulatory variables. */ mutex_lock(&cfg80211_mutex); /* This goes through the _pending_ beacon list */ spin_lock_bh(&reg_pending_beacons_lock); if (list_empty(&reg_pending_beacons)) { spin_unlock_bh(&reg_pending_beacons_lock); goto out; } list_for_each_entry_safe(pending_beacon, tmp, &reg_pending_beacons, list) { list_del_init(&pending_beacon->list); /* Applies the beacon hint to current wiphys */ list_for_each_entry(rdev, &cfg80211_rdev_list, list) wiphy_update_new_beacon(&rdev->wiphy, pending_beacon); /* Remembers the beacon hint for new wiphys or reg changes */ list_add_tail(&pending_beacon->list, &reg_beacon_list); } spin_unlock_bh(&reg_pending_beacons_lock); out: mutex_unlock(&cfg80211_mutex); } static void reg_todo(struct work_struct *work) { reg_process_pending_hints(); reg_process_pending_beacon_hints(); } static void queue_regulatory_request(struct regulatory_request *request) { if (isalpha(request->alpha2[0])) request->alpha2[0] = toupper(request->alpha2[0]); if (isalpha(request->alpha2[1])) request->alpha2[1] = toupper(request->alpha2[1]); spin_lock(&reg_requests_lock); list_add_tail(&request->list, &reg_requests_list); spin_unlock(&reg_requests_lock); schedule_work(&reg_work); } /* * Core regulatory hint -- happens during cfg80211_init() * and when we restore regulatory settings. */ static int regulatory_hint_core(const char *alpha2) { struct regulatory_request *request; kfree(last_request); last_request = NULL; request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL); if (!request) return -ENOMEM; request->alpha2[0] = alpha2[0]; request->alpha2[1] = alpha2[1]; request->initiator = NL80211_REGDOM_SET_BY_CORE; queue_regulatory_request(request); return 0; } /* User hints */ int regulatory_hint_user(const char *alpha2) { struct regulatory_request *request; BUG_ON(!alpha2); request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL); if (!request) return -ENOMEM; request->wiphy_idx = WIPHY_IDX_STALE; request->alpha2[0] = alpha2[0]; request->alpha2[1] = alpha2[1]; request->initiator = NL80211_REGDOM_SET_BY_USER; queue_regulatory_request(request); return 0; } /* Driver hints */ int regulatory_hint(struct wiphy *wiphy, const char *alpha2) { struct regulatory_request *request; BUG_ON(!alpha2); BUG_ON(!wiphy); request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL); if (!request) return -ENOMEM; request->wiphy_idx = get_wiphy_idx(wiphy); /* Must have registered wiphy first */ BUG_ON(!wiphy_idx_valid(request->wiphy_idx)); request->alpha2[0] = alpha2[0]; request->alpha2[1] = alpha2[1]; request->initiator = NL80211_REGDOM_SET_BY_DRIVER; queue_regulatory_request(request); return 0; } EXPORT_SYMBOL(regulatory_hint); /* * We hold wdev_lock() here so we cannot hold cfg80211_mutex() and * therefore cannot iterate over the rdev list here. */ void regulatory_hint_11d(struct wiphy *wiphy, enum ieee80211_band band, u8 *country_ie, u8 country_ie_len) { char alpha2[2]; enum environment_cap env = ENVIRON_ANY; struct regulatory_request *request; mutex_lock(&reg_mutex); if (unlikely(!last_request)) goto out; /* IE len must be evenly divisible by 2 */ if (country_ie_len & 0x01) goto out; if (country_ie_len < IEEE80211_COUNTRY_IE_MIN_LEN) goto out; alpha2[0] = country_ie[0]; alpha2[1] = country_ie[1]; if (country_ie[2] == 'I') env = ENVIRON_INDOOR; else if (country_ie[2] == 'O') env = ENVIRON_OUTDOOR; /* * We will run this only upon a successful connection on cfg80211. * We leave conflict resolution to the workqueue, where can hold * cfg80211_mutex. */ if (likely(last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE && wiphy_idx_valid(last_request->wiphy_idx))) goto out; request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL); if (!request) goto out; request->wiphy_idx = get_wiphy_idx(wiphy); request->alpha2[0] = alpha2[0]; request->alpha2[1] = alpha2[1]; request->initiator = NL80211_REGDOM_SET_BY_COUNTRY_IE; request->country_ie_env = env; mutex_unlock(&reg_mutex); queue_regulatory_request(request); return; out: mutex_unlock(&reg_mutex); } static void restore_alpha2(char *alpha2, bool reset_user) { /* indicates there is no alpha2 to consider for restoration */ alpha2[0] = '9'; alpha2[1] = '7'; /* The user setting has precedence over the module parameter */ if (is_user_regdom_saved()) { /* Unless we're asked to ignore it and reset it */ if (reset_user) { REG_DBG_PRINT("Restoring regulatory settings " "including user preference\n"); user_alpha2[0] = '9'; user_alpha2[1] = '7'; /* * If we're ignoring user settings, we still need to * check the module parameter to ensure we put things * back as they were for a full restore. */ if (!is_world_regdom(ieee80211_regdom)) { REG_DBG_PRINT("Keeping preference on " "module parameter ieee80211_regdom: %c%c\n", ieee80211_regdom[0], ieee80211_regdom[1]); alpha2[0] = ieee80211_regdom[0]; alpha2[1] = ieee80211_regdom[1]; } } else { REG_DBG_PRINT("Restoring regulatory settings " "while preserving user preference for: %c%c\n", user_alpha2[0], user_alpha2[1]); alpha2[0] = user_alpha2[0]; alpha2[1] = user_alpha2[1]; } } else if (!is_world_regdom(ieee80211_regdom)) { REG_DBG_PRINT("Keeping preference on " "module parameter ieee80211_regdom: %c%c\n", ieee80211_regdom[0], ieee80211_regdom[1]); alpha2[0] = ieee80211_regdom[0]; alpha2[1] = ieee80211_regdom[1]; } else REG_DBG_PRINT("Restoring regulatory settings\n"); } static void restore_custom_reg_settings(struct wiphy *wiphy) { struct ieee80211_supported_band *sband; enum ieee80211_band band; struct ieee80211_channel *chan; int i; for (band = 0; band < IEEE80211_NUM_BANDS; band++) { sband = wiphy->bands[band]; if (!sband) continue; for (i = 0; i < sband->n_channels; i++) { chan = &sband->channels[i]; chan->flags = chan->orig_flags; chan->max_antenna_gain = chan->orig_mag; chan->max_power = chan->orig_mpwr; } } } /* * Restoring regulatory settings involves ingoring any * possibly stale country IE information and user regulatory * settings if so desired, this includes any beacon hints * learned as we could have traveled outside to another country * after disconnection. To restore regulatory settings we do * exactly what we did at bootup: * * - send a core regulatory hint * - send a user regulatory hint if applicable * * Device drivers that send a regulatory hint for a specific country * keep their own regulatory domain on wiphy->regd so that does does * not need to be remembered. */ static void restore_regulatory_settings(bool reset_user) { char alpha2[2]; struct reg_beacon *reg_beacon, *btmp; struct regulatory_request *reg_request, *tmp; LIST_HEAD(tmp_reg_req_list); struct cfg80211_registered_device *rdev; mutex_lock(&cfg80211_mutex); mutex_lock(&reg_mutex); reset_regdomains(); restore_alpha2(alpha2, reset_user); /* * If there's any pending requests we simply * stash them to a temporary pending queue and * add then after we've restored regulatory * settings. */ spin_lock(&reg_requests_lock); if (!list_empty(&reg_requests_list)) { list_for_each_entry_safe(reg_request, tmp, &reg_requests_list, list) { if (reg_request->initiator != NL80211_REGDOM_SET_BY_USER) continue; list_del(&reg_request->list); list_add_tail(&reg_request->list, &tmp_reg_req_list); } } spin_unlock(&reg_requests_lock); /* Clear beacon hints */ spin_lock_bh(&reg_pending_beacons_lock); if (!list_empty(&reg_pending_beacons)) { list_for_each_entry_safe(reg_beacon, btmp, &reg_pending_beacons, list) { list_del(&reg_beacon->list); kfree(reg_beacon); } } spin_unlock_bh(&reg_pending_beacons_lock); if (!list_empty(&reg_beacon_list)) { list_for_each_entry_safe(reg_beacon, btmp, &reg_beacon_list, list) { list_del(&reg_beacon->list); kfree(reg_beacon); } } /* First restore to the basic regulatory settings */ cfg80211_regdomain = cfg80211_world_regdom; list_for_each_entry(rdev, &cfg80211_rdev_list, list) { if (rdev->wiphy.flags & WIPHY_FLAG_CUSTOM_REGULATORY) restore_custom_reg_settings(&rdev->wiphy); } mutex_unlock(&reg_mutex); mutex_unlock(&cfg80211_mutex); regulatory_hint_core(cfg80211_regdomain->alpha2); /* * This restores the ieee80211_regdom module parameter * preference or the last user requested regulatory * settings, user regulatory settings takes precedence. */ if (is_an_alpha2(alpha2)) regulatory_hint_user(user_alpha2); if (list_empty(&tmp_reg_req_list)) return; mutex_lock(&cfg80211_mutex); mutex_lock(&reg_mutex); spin_lock(&reg_requests_lock); list_for_each_entry_safe(reg_request, tmp, &tmp_reg_req_list, list) { REG_DBG_PRINT("Adding request for country %c%c back " "into the queue\n", reg_request->alpha2[0], reg_request->alpha2[1]); list_del(&reg_request->list); list_add_tail(&reg_request->list, &reg_requests_list); } spin_unlock(&reg_requests_lock); mutex_unlock(&reg_mutex); mutex_unlock(&cfg80211_mutex); REG_DBG_PRINT("Kicking the queue\n"); schedule_work(&reg_work); } void regulatory_hint_disconnect(void) { REG_DBG_PRINT("All devices are disconnected, going to " "restore regulatory settings\n"); restore_regulatory_settings(false); } static bool freq_is_chan_12_13_14(u16 freq) { if (freq == ieee80211_channel_to_frequency(12, IEEE80211_BAND_2GHZ) || freq == ieee80211_channel_to_frequency(13, IEEE80211_BAND_2GHZ) || freq == ieee80211_channel_to_frequency(14, IEEE80211_BAND_2GHZ)) return true; return false; } int regulatory_hint_found_beacon(struct wiphy *wiphy, struct ieee80211_channel *beacon_chan, gfp_t gfp) { struct reg_beacon *reg_beacon; if (likely((beacon_chan->beacon_found || (beacon_chan->flags & IEEE80211_CHAN_RADAR) || (beacon_chan->band == IEEE80211_BAND_2GHZ && !freq_is_chan_12_13_14(beacon_chan->center_freq))))) return 0; reg_beacon = kzalloc(sizeof(struct reg_beacon), gfp); if (!reg_beacon) return -ENOMEM; REG_DBG_PRINT("Found new beacon on " "frequency: %d MHz (Ch %d) on %s\n", beacon_chan->center_freq, ieee80211_frequency_to_channel(beacon_chan->center_freq), wiphy_name(wiphy)); memcpy(&reg_beacon->chan, beacon_chan, sizeof(struct ieee80211_channel)); /* * Since we can be called from BH or and non-BH context * we must use spin_lock_bh() */ spin_lock_bh(&reg_pending_beacons_lock); list_add_tail(&reg_beacon->list, &reg_pending_beacons); spin_unlock_bh(&reg_pending_beacons_lock); schedule_work(&reg_work); return 0; } static void print_rd_rules(const struct ieee80211_regdomain *rd) { unsigned int i; const struct ieee80211_reg_rule *reg_rule = NULL; const struct ieee80211_freq_range *freq_range = NULL; const struct ieee80211_power_rule *power_rule = NULL; pr_info(" (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)\n"); for (i = 0; i < rd->n_reg_rules; i++) { reg_rule = &rd->reg_rules[i]; freq_range = &reg_rule->freq_range; power_rule = &reg_rule->power_rule; /* * There may not be documentation for max antenna gain * in certain regions */ if (power_rule->max_antenna_gain) pr_info(" (%d KHz - %d KHz @ %d KHz), (%d mBi, %d mBm)\n", freq_range->start_freq_khz, freq_range->end_freq_khz, freq_range->max_bandwidth_khz, power_rule->max_antenna_gain, power_rule->max_eirp); else pr_info(" (%d KHz - %d KHz @ %d KHz), (N/A, %d mBm)\n", freq_range->start_freq_khz, freq_range->end_freq_khz, freq_range->max_bandwidth_khz, power_rule->max_eirp); } } static void print_regdomain(const struct ieee80211_regdomain *rd) { if (is_intersected_alpha2(rd->alpha2)) { if (last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE) { struct cfg80211_registered_device *rdev; rdev = cfg80211_rdev_by_wiphy_idx( last_request->wiphy_idx); if (rdev) { pr_info("Current regulatory domain updated by AP to: %c%c\n", rdev->country_ie_alpha2[0], rdev->country_ie_alpha2[1]); } else pr_info("Current regulatory domain intersected:\n"); } else pr_info("Current regulatory domain intersected:\n"); } else if (is_world_regdom(rd->alpha2)) pr_info("World regulatory domain updated:\n"); else { if (is_unknown_alpha2(rd->alpha2)) pr_info("Regulatory domain changed to driver built-in settings (unknown country)\n"); else pr_info("Regulatory domain changed to country: %c%c\n", rd->alpha2[0], rd->alpha2[1]); } print_rd_rules(rd); } static void print_regdomain_info(const struct ieee80211_regdomain *rd) { pr_info("Regulatory domain: %c%c\n", rd->alpha2[0], rd->alpha2[1]); print_rd_rules(rd); } /* Takes ownership of rd only if it doesn't fail */ static int __set_regdom(const struct ieee80211_regdomain *rd) { const struct ieee80211_regdomain *intersected_rd = NULL; struct cfg80211_registered_device *rdev = NULL; struct wiphy *request_wiphy; /* Some basic sanity checks first */ if (is_world_regdom(rd->alpha2)) { if (WARN_ON(!reg_is_valid_request(rd->alpha2))) return -EINVAL; update_world_regdomain(rd); return 0; } if (!is_alpha2_set(rd->alpha2) && !is_an_alpha2(rd->alpha2) && !is_unknown_alpha2(rd->alpha2)) return -EINVAL; if (!last_request) return -EINVAL; /* * Lets only bother proceeding on the same alpha2 if the current * rd is non static (it means CRDA was present and was used last) * and the pending request came in from a country IE */ if (last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE) { /* * If someone else asked us to change the rd lets only bother * checking if the alpha2 changes if CRDA was already called */ if (!regdom_changes(rd->alpha2)) return -EINVAL; } /* * Now lets set the regulatory domain, update all driver channels * and finally inform them of what we have done, in case they want * to review or adjust their own settings based on their own * internal EEPROM data */ if (WARN_ON(!reg_is_valid_request(rd->alpha2))) return -EINVAL; if (!is_valid_rd(rd)) { pr_err("Invalid regulatory domain detected:\n"); print_regdomain_info(rd); return -EINVAL; } request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx); if (!last_request->intersect) { int r; if (last_request->initiator != NL80211_REGDOM_SET_BY_DRIVER) { reset_regdomains(); cfg80211_regdomain = rd; return 0; } /* * For a driver hint, lets copy the regulatory domain the * driver wanted to the wiphy to deal with conflicts */ /* * Userspace could have sent two replies with only * one kernel request. */ if (request_wiphy->regd) return -EALREADY; r = reg_copy_regd(&request_wiphy->regd, rd); if (r) return r; reset_regdomains(); cfg80211_regdomain = rd; return 0; } /* Intersection requires a bit more work */ if (last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE) { intersected_rd = regdom_intersect(rd, cfg80211_regdomain); if (!intersected_rd) return -EINVAL; /* * We can trash what CRDA provided now. * However if a driver requested this specific regulatory * domain we keep it for its private use */ if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER) request_wiphy->regd = rd; else kfree(rd); rd = NULL; reset_regdomains(); cfg80211_regdomain = intersected_rd; return 0; } if (!intersected_rd) return -EINVAL; rdev = wiphy_to_dev(request_wiphy); rdev->country_ie_alpha2[0] = rd->alpha2[0]; rdev->country_ie_alpha2[1] = rd->alpha2[1]; rdev->env = last_request->country_ie_env; BUG_ON(intersected_rd == rd); kfree(rd); rd = NULL; reset_regdomains(); cfg80211_regdomain = intersected_rd; return 0; } /* * Use this call to set the current regulatory domain. Conflicts with * multiple drivers can be ironed out later. Caller must've already * kmalloc'd the rd structure. Caller must hold cfg80211_mutex */ int set_regdom(const struct ieee80211_regdomain *rd) { int r; assert_cfg80211_lock(); mutex_lock(&reg_mutex); /* Note that this doesn't update the wiphys, this is done below */ r = __set_regdom(rd); if (r) { kfree(rd); mutex_unlock(&reg_mutex); return r; } /* This would make this whole thing pointless */ if (!last_request->intersect) BUG_ON(rd != cfg80211_regdomain); /* update all wiphys now with the new established regulatory domain */ update_all_wiphy_regulatory(last_request->initiator); print_regdomain(cfg80211_regdomain); nl80211_send_reg_change_event(last_request); reg_set_request_processed(); mutex_unlock(&reg_mutex); return r; } #ifdef CONFIG_HOTPLUG int reg_device_uevent(struct device *dev, struct kobj_uevent_env *env) { if (last_request && !last_request->processed) { if (add_uevent_var(env, "COUNTRY=%c%c", last_request->alpha2[0], last_request->alpha2[1])) return -ENOMEM; } return 0; } #else int reg_device_uevent(struct device *dev, struct kobj_uevent_env *env) { return -ENODEV; } #endif /* CONFIG_HOTPLUG */ /* Caller must hold cfg80211_mutex */ void reg_device_remove(struct wiphy *wiphy) { struct wiphy *request_wiphy = NULL; assert_cfg80211_lock(); mutex_lock(&reg_mutex); kfree(wiphy->regd); if (last_request) request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx); if (!request_wiphy || request_wiphy != wiphy) goto out; last_request->wiphy_idx = WIPHY_IDX_STALE; last_request->country_ie_env = ENVIRON_ANY; out: mutex_unlock(&reg_mutex); } static void reg_timeout_work(struct work_struct *work) { REG_DBG_PRINT("Timeout while waiting for CRDA to reply, " "restoring regulatory settings"); restore_regulatory_settings(true); } int __init regulatory_init(void) { int err = 0; reg_pdev = platform_device_register_simple("regulatory", 0, NULL, 0); if (IS_ERR(reg_pdev)) return PTR_ERR(reg_pdev); reg_pdev->dev.type = &reg_device_type; spin_lock_init(&reg_requests_lock); spin_lock_init(&reg_pending_beacons_lock); cfg80211_regdomain = cfg80211_world_regdom; user_alpha2[0] = '9'; user_alpha2[1] = '7'; /* We always try to get an update for the static regdomain */ err = regulatory_hint_core(cfg80211_regdomain->alpha2); if (err) { if (err == -ENOMEM) return err; /* * N.B. kobject_uevent_env() can fail mainly for when we're out * memory which is handled and propagated appropriately above * but it can also fail during a netlink_broadcast() or during * early boot for call_usermodehelper(). For now treat these * errors as non-fatal. */ pr_err("kobject_uevent_env() was unable to call CRDA during init\n"); #ifdef CONFIG_CFG80211_REG_DEBUG /* We want to find out exactly why when debugging */ WARN_ON(err); #endif } /* * Finally, if the user set the module parameter treat it * as a user hint. */ if (!is_world_regdom(ieee80211_regdom)) regulatory_hint_user(ieee80211_regdom); return 0; } void /* __init_or_exit */ regulatory_exit(void) { struct regulatory_request *reg_request, *tmp; struct reg_beacon *reg_beacon, *btmp; cancel_work_sync(&reg_work); cancel_delayed_work_sync(&reg_timeout); mutex_lock(&cfg80211_mutex); mutex_lock(&reg_mutex); reset_regdomains(); kfree(last_request); platform_device_unregister(reg_pdev); spin_lock_bh(&reg_pending_beacons_lock); if (!list_empty(&reg_pending_beacons)) { list_for_each_entry_safe(reg_beacon, btmp, &reg_pending_beacons, list) { list_del(&reg_beacon->list); kfree(reg_beacon); } } spin_unlock_bh(&reg_pending_beacons_lock); if (!list_empty(&reg_beacon_list)) { list_for_each_entry_safe(reg_beacon, btmp, &reg_beacon_list, list) { list_del(&reg_beacon->list); kfree(reg_beacon); } } spin_lock(&reg_requests_lock); if (!list_empty(&reg_requests_list)) { list_for_each_entry_safe(reg_request, tmp, &reg_requests_list, list) { list_del(&reg_request->list); kfree(reg_request); } } spin_unlock(&reg_requests_lock); mutex_unlock(&reg_mutex); mutex_unlock(&cfg80211_mutex); }
Java
/* Copyright (C) 2004 - 2009 Versant Inc. http://www.db4o.com */ using Db4objects.Db4o.Query; using Db4objects.Db4o.Tests.Common.Soda.Util; using Sharpen; namespace Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed { public class STArrIntegerTNTestCase : SodaBaseTestCase { public int[][][] intArr; public STArrIntegerTNTestCase() { } public STArrIntegerTNTestCase(int[][][] arr) { intArr = arr; } public override object[] CreateData() { Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase[] arr = new Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase[5]; arr[0] = new Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase (); int[][][] content = new int[][][] { }; arr[1] = new Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase (content); content = new int[][][] { new int[][] { new int[3], new int[3] } }; content[0][0][1] = 0; content[0][1][0] = 0; arr[2] = new Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase (content); content = new int[][][] { new int[][] { new int[3], new int[3] } }; content[0][0][0] = 1; content[0][1][0] = 17; content[0][1][1] = int.MaxValue - 1; arr[3] = new Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase (content); content = new int[][][] { new int[][] { new int[2], new int[2] } }; content[0][0][0] = 3; content[0][0][1] = 17; content[0][1][0] = 25; content[0][1][1] = int.MaxValue - 2; arr[4] = new Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase (content); object[] ret = new object[arr.Length]; System.Array.Copy(arr, 0, ret, 0, arr.Length); return ret; } public virtual void TestDefaultContainsOne() { IQuery q = NewQuery(); int[][][] content = new int[][][] { new int[][] { new int[1] } }; content[0][0][0] = 17; q.Constrain(new Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase (content)); Expect(q, new int[] { 3, 4 }); } public virtual void TestDefaultContainsTwo() { IQuery q = NewQuery(); int[][][] content = new int[][][] { new int[][] { new int[1] }, new int[][] { new int[1] } }; content[0][0][0] = 17; content[1][0][0] = 25; q.Constrain(new Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase (content)); Expect(q, new int[] { 4 }); } public virtual void TestDescendOne() { IQuery q = NewQuery(); q.Constrain(typeof(Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase )); q.Descend("intArr").Constrain(17); Expect(q, new int[] { 3, 4 }); } public virtual void TestDescendTwo() { IQuery q = NewQuery(); q.Constrain(typeof(Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase )); IQuery qElements = q.Descend("intArr"); qElements.Constrain(17); qElements.Constrain(25); Expect(q, new int[] { 4 }); } public virtual void TestDescendSmaller() { IQuery q = NewQuery(); q.Constrain(typeof(Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase )); IQuery qElements = q.Descend("intArr"); qElements.Constrain(3).Smaller(); Expect(q, new int[] { 2, 3 }); } public virtual void TestDescendNotSmaller() { IQuery q = NewQuery(); q.Constrain(typeof(Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase )); IQuery qElements = q.Descend("intArr"); qElements.Constrain(3).Smaller(); Expect(q, new int[] { 2, 3 }); } } }
Java
showWord(["","Wayòm ki te nan pati Sidwès peyi Ispayola. Se Boyekyo ki te chèf endyen nan wayòm sa a. Kapital wayòm sa a te Lagwana, kounye a yo rele l Leogàn." ])
Java
#include "steadystatetest.hh" #include <models/REmodel.hh> #include <models/LNAmodel.hh> #include <models/IOSmodel.hh> #include <models/sseinterpreter.hh> #include <models/steadystateanalysis.hh> #include <eval/jit/engine.hh> #include <parser/sbml/sbml.hh> using namespace iNA; SteadyStateTest::~SteadyStateTest() { // pass... } void SteadyStateTest::testEnzymeKineticsRE() { // Read doc and check for errors: Ast::Model sbml_model; Parser::Sbml::importModel(sbml_model, "test/regression-tests/extended_goodwin.xml"); // Construct RE model to integrate Models::REmodel model(sbml_model); // Perform analysis: Eigen::VectorXd state(model.getDimension()); Models::SteadyStateAnalysis<Models::REmodel> analysis(model); analysis.setMaxIterations(1000); analysis.calcSteadyState(state); } void SteadyStateTest::testEnzymeKineticsLNA() { // Read doc and check for errors: Ast::Model sbml_model; Parser::Sbml::importModel(sbml_model, "test/regression-tests/extended_goodwin.xml"); // Construct LNA model to integrate Models::LNAmodel model(sbml_model); // Perform analysis: Eigen::VectorXd state(model.getDimension()); Models::SteadyStateAnalysis<Models::LNAmodel> analysis(model); analysis.setMaxIterations(1000); analysis.calcSteadyState(state); } void SteadyStateTest::testEnzymeKineticsIOS() { // Read doc and check for errors: Ast::Model sbml_model; Parser::Sbml::importModel(sbml_model, "test/regression-tests/extended_goodwin.xml"); // Construct model to integrate Models::IOSmodel model(sbml_model); // Perform analysis: Eigen::VectorXd state(model.getDimension()); Models::SteadyStateAnalysis<Models::IOSmodel> analysis(model); analysis.setMaxIterations(1000); analysis.calcSteadyState(state); } UnitTest::TestSuite * SteadyStateTest::suite() { UnitTest::TestSuite *s = new UnitTest::TestSuite("Steady State Tests"); s->addTest(new UnitTest::TestCaller<SteadyStateTest>( "EnzymeKinetics Model (RE)", &SteadyStateTest::testEnzymeKineticsRE)); s->addTest(new UnitTest::TestCaller<SteadyStateTest>( "EnzymeKinetics Model (LNA)", &SteadyStateTest::testEnzymeKineticsLNA)); s->addTest(new UnitTest::TestCaller<SteadyStateTest>( "EnzymeKinetics Model (IOS)", &SteadyStateTest::testEnzymeKineticsIOS)); return s; }
Java
-- 17/03/2011 9h3min12s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Element (AD_Client_ID,AD_Element_ID,AD_Org_ID,ColumnName,Created,CreatedBy,Description,EntityType,Help,IsActive,Name,PrintName,Updated,UpdatedBy) VALUES (0,1120054,0,'lbr_TaxStatusPIS',TO_TIMESTAMP('2011-03-17 09:03:10','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (PIS)','LBRA','Defines the Tax Status (PIS)','Y','Tax Status (PIS)','Tax Status (PIS)',TO_TIMESTAMP('2011-03-17 09:03:10','YYYY-MM-DD HH24:MI:SS'),100) ; -- 17/03/2011 9h3min12s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Element_Trl (AD_Language,AD_Element_ID, Description,Help,Name,PO_Description,PO_Help,PO_Name,PO_PrintName,PrintName, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Element_ID, t.Description,t.Help,t.Name,t.PO_Description,t.PO_Help,t.PO_Name,t.PO_PrintName,t.PrintName, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Element t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Element_ID=1120054 AND NOT EXISTS (SELECT * FROM AD_Element_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Element_ID=t.AD_Element_ID) ; -- 17/03/2011 9h3min43s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator UPDATE AD_Element_Trl SET IsTranslated='Y',Name='Situação Tributária (PIS)',PrintName='Situação Tributária (PIS)',Description='Defines a Situação Tributária (PIS)',Help='Defines a Situação Tributária (PIS)',Updated=TO_TIMESTAMP('2011-03-17 09:03:43','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Element_ID=1120054 AND AD_Language='pt_BR' ; -- 17/03/2011 9h4min44s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Reference (AD_Client_ID,AD_Org_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,IsOrderByValue,Name,Updated,UpdatedBy,ValidationType) VALUES (0,0,1120023,TO_TIMESTAMP('2011-03-17 09:04:43','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','N','lbr_TaxStatusPIS_COFINS',TO_TIMESTAMP('2011-03-17 09:04:43','YYYY-MM-DD HH24:MI:SS'),100,'L') ; -- 17/03/2011 9h4min44s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Reference_Trl (AD_Language,AD_Reference_ID, Description,Help,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Reference_ID, t.Description,t.Help,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Reference t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Reference_ID=1120023 AND NOT EXISTS (SELECT * FROM AD_Reference_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Reference_ID=t.AD_Reference_ID) ; -- 17/03/2011 9h5min17s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120096,1120023,TO_TIMESTAMP('2011-03-17 09:05:17','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','01 - Operação Tributável com Alíquota Básica',TO_TIMESTAMP('2011-03-17 09:05:17','YYYY-MM-DD HH24:MI:SS'),100,'01') ; -- 17/03/2011 9h5min17s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120096 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 9h5min32s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120097,1120023,TO_TIMESTAMP('2011-03-17 09:05:32','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','02 - Operação Tributável com Alíquota Diferenciada',TO_TIMESTAMP('2011-03-17 09:05:32','YYYY-MM-DD HH24:MI:SS'),100,'02') ; -- 17/03/2011 9h5min32s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120097 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 9h5min47s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120098,1120023,TO_TIMESTAMP('2011-03-17 09:05:46','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','03 - Operação Tributável com Alíquota por Unidade de Medida de Produto',TO_TIMESTAMP('2011-03-17 09:05:46','YYYY-MM-DD HH24:MI:SS'),100,'03') ; -- 17/03/2011 9h5min47s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120098 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 9h6min4s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120099,1120023,TO_TIMESTAMP('2011-03-17 09:06:04','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','04 - Operação Tributável Monofásica - Revenda a Alíquota Zero',TO_TIMESTAMP('2011-03-17 09:06:04','YYYY-MM-DD HH24:MI:SS'),100,'04') ; -- 17/03/2011 9h6min4s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120099 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 9h6min25s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120100,1120023,TO_TIMESTAMP('2011-03-17 09:06:24','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','05 - Operação Tributável por Substituição Tributária',TO_TIMESTAMP('2011-03-17 09:06:24','YYYY-MM-DD HH24:MI:SS'),100,'05') ; -- 17/03/2011 9h6min25s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120100 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 9h6min58s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120101,1120023,TO_TIMESTAMP('2011-03-17 09:06:57','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','06 - Operação Tributável a Alíquota Zero',TO_TIMESTAMP('2011-03-17 09:06:57','YYYY-MM-DD HH24:MI:SS'),100,'06') ; -- 17/03/2011 9h6min58s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120101 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 9h7min12s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120102,1120023,TO_TIMESTAMP('2011-03-17 09:07:12','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','07 - Operação Isenta da Contribuição',TO_TIMESTAMP('2011-03-17 09:07:12','YYYY-MM-DD HH24:MI:SS'),100,'07') ; -- 17/03/2011 9h7min12s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120102 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 9h9min1s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120103,1120023,TO_TIMESTAMP('2011-03-17 09:09:00','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','08 - Operação sem Incidência da Contribuição',TO_TIMESTAMP('2011-03-17 09:09:00','YYYY-MM-DD HH24:MI:SS'),100,'08') ; -- 17/03/2011 9h9min1s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120103 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 9h9min15s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120104,1120023,TO_TIMESTAMP('2011-03-17 09:09:14','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','09 - Operação com Suspensão da Contribuição',TO_TIMESTAMP('2011-03-17 09:09:14','YYYY-MM-DD HH24:MI:SS'),100,'09') ; -- 17/03/2011 9h9min15s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120104 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 9h9min31s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120105,1120023,TO_TIMESTAMP('2011-03-17 09:09:31','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','49 - Outras Operações de Saída',TO_TIMESTAMP('2011-03-17 09:09:31','YYYY-MM-DD HH24:MI:SS'),100,'49') ; -- 17/03/2011 9h9min31s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120105 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 9h9min49s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120106,1120023,TO_TIMESTAMP('2011-03-17 09:09:48','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','50 - Operação com Direito a Crédito - Vinculada Exclusivamente a Receita Tributada no Mercado Interno',TO_TIMESTAMP('2011-03-17 09:09:48','YYYY-MM-DD HH24:MI:SS'),100,'50') ; -- 17/03/2011 9h9min49s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120106 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 9h10min8s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120107,1120023,TO_TIMESTAMP('2011-03-17 09:10:07','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','51 - Operação com Direito a Crédito – Vinculada Exclusivamente a Receita Não Tributada no Mercado Interno',TO_TIMESTAMP('2011-03-17 09:10:07','YYYY-MM-DD HH24:MI:SS'),100,'51') ; -- 17/03/2011 9h10min8s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120107 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 9h10min24s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120108,1120023,TO_TIMESTAMP('2011-03-17 09:10:24','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','52 - Operação com Direito a Crédito - Vinculada Exclusivamente a Receita de Exportação',TO_TIMESTAMP('2011-03-17 09:10:24','YYYY-MM-DD HH24:MI:SS'),100,'52') ; -- 17/03/2011 9h10min24s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120108 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 9h10min38s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120109,1120023,TO_TIMESTAMP('2011-03-17 09:10:37','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','53 - Operação com Direito a Crédito - Vinculada a Receitas Tributadas e Não-Tributadas no Mercado Interno',TO_TIMESTAMP('2011-03-17 09:10:37','YYYY-MM-DD HH24:MI:SS'),100,'53') ; -- 17/03/2011 9h10min38s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120109 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 9h11min0s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120110,1120023,TO_TIMESTAMP('2011-03-17 09:11:00','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','54 - Operação com Direito a Crédito - Vinculada a Receitas Tributadas no Mercado Interno e de Exportação',TO_TIMESTAMP('2011-03-17 09:11:00','YYYY-MM-DD HH24:MI:SS'),100,'54') ; -- 17/03/2011 9h11min0s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120110 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 9h11min20s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120111,1120023,TO_TIMESTAMP('2011-03-17 09:11:20','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','55 - Operação com Direito a Crédito - Vinculada a Receitas Não-Tributadas no Mercado Interno e de Exportação',TO_TIMESTAMP('2011-03-17 09:11:20','YYYY-MM-DD HH24:MI:SS'),100,'55') ; -- 17/03/2011 9h11min20s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120111 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h6min3s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120112,1120023,TO_TIMESTAMP('2011-03-17 10:06:02','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','56 - Operação com Direito a Crédito - Vinculada a Receitas Tributadas e Não-Tributadas no Mercado Interno, e de Exportação',TO_TIMESTAMP('2011-03-17 10:06:02','YYYY-MM-DD HH24:MI:SS'),100,'56') ; -- 17/03/2011 10h6min3s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120112 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h6min21s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120113,1120023,TO_TIMESTAMP('2011-03-17 10:06:20','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','60 - Crédito Presumido - Operação de Aquisição Vinculada Exclusivamente a Receita Tributada no Mercado Interno',TO_TIMESTAMP('2011-03-17 10:06:20','YYYY-MM-DD HH24:MI:SS'),100,'60') ; -- 17/03/2011 10h6min21s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120113 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h6min44s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120114,1120023,TO_TIMESTAMP('2011-03-17 10:06:43','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','61 - Crédito Presumido - Operação de Aquisição Vinculada Exclusivamente a Receita Não-Tributada no Mercado Interno',TO_TIMESTAMP('2011-03-17 10:06:43','YYYY-MM-DD HH24:MI:SS'),100,'61') ; -- 17/03/2011 10h6min44s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120114 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h7min13s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120115,1120023,TO_TIMESTAMP('2011-03-17 10:07:13','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','62 - Crédito Presumido - Operação de Aquisição Vinculada Exclusivamente a Receita de Exportação',TO_TIMESTAMP('2011-03-17 10:07:13','YYYY-MM-DD HH24:MI:SS'),100,'62') ; -- 17/03/2011 10h7min13s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120115 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h7min28s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120116,1120023,TO_TIMESTAMP('2011-03-17 10:07:27','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','63 - Crédito Presumido - Operação de Aquisição Vinculada a Receitas Tributadas e Não-Tributadas no Mercado Interno',TO_TIMESTAMP('2011-03-17 10:07:27','YYYY-MM-DD HH24:MI:SS'),100,'63') ; -- 17/03/2011 10h7min28s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120116 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h7min44s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120117,1120023,TO_TIMESTAMP('2011-03-17 10:07:43','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','64 - Crédito Presumido - Operação de Aquisição Vinculada a Receitas Tributadas no Mercado Interno e de Exportação',TO_TIMESTAMP('2011-03-17 10:07:43','YYYY-MM-DD HH24:MI:SS'),100,'64') ; -- 17/03/2011 10h7min44s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120117 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h8min0s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120118,1120023,TO_TIMESTAMP('2011-03-17 10:07:59','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','65 - Crédito Presumido - Operação de Aquisição Vinculada a Receitas Não-Tributadas no Mercado Interno e de Exportação',TO_TIMESTAMP('2011-03-17 10:07:59','YYYY-MM-DD HH24:MI:SS'),100,'65') ; -- 17/03/2011 10h8min0s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120118 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h8min28s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120119,1120023,TO_TIMESTAMP('2011-03-17 10:08:27','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','66 - Crédito Presumido - Operação de Aquisição Vinculada a Receitas Tributadas e Não-Tributadas no Mercado Interno e Exp.',TO_TIMESTAMP('2011-03-17 10:08:27','YYYY-MM-DD HH24:MI:SS'),100,'66') ; -- 17/03/2011 10h8min28s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120119 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h8min45s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120120,1120023,TO_TIMESTAMP('2011-03-17 10:08:44','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','67 - Crédito Presumido - Outras Operações',TO_TIMESTAMP('2011-03-17 10:08:44','YYYY-MM-DD HH24:MI:SS'),100,'67') ; -- 17/03/2011 10h8min45s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120120 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h9min11s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120121,1120023,TO_TIMESTAMP('2011-03-17 10:09:11','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','70 - Operação de Aquisição sem Direito a Crédito',TO_TIMESTAMP('2011-03-17 10:09:11','YYYY-MM-DD HH24:MI:SS'),100,'70') ; -- 17/03/2011 10h9min11s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120121 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h10min31s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120122,1120023,TO_TIMESTAMP('2011-03-17 10:10:30','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','71 - Operação de Aquisição com Isenção',TO_TIMESTAMP('2011-03-17 10:10:30','YYYY-MM-DD HH24:MI:SS'),100,'71') ; -- 17/03/2011 10h10min31s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120122 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h10min55s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120123,1120023,TO_TIMESTAMP('2011-03-17 10:10:54','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','72 - Operação de Aquisição com Suspensão',TO_TIMESTAMP('2011-03-17 10:10:54','YYYY-MM-DD HH24:MI:SS'),100,'72') ; -- 17/03/2011 10h10min55s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120123 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h16min20s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120124,1120023,TO_TIMESTAMP('2011-03-17 10:16:19','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','73 - Operação de Aquisição a Alíquota Zero',TO_TIMESTAMP('2011-03-17 10:16:19','YYYY-MM-DD HH24:MI:SS'),100,'73') ; -- 17/03/2011 10h16min20s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120124 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h16min35s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120125,1120023,TO_TIMESTAMP('2011-03-17 10:16:35','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','74 - Operação de Aquisição sem Incidência da Contribuição',TO_TIMESTAMP('2011-03-17 10:16:35','YYYY-MM-DD HH24:MI:SS'),100,'74') ; -- 17/03/2011 10h16min35s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120125 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h16min52s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120126,1120023,TO_TIMESTAMP('2011-03-17 10:16:52','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','75 - Operação de Aquisição por Substituição Tributária',TO_TIMESTAMP('2011-03-17 10:16:52','YYYY-MM-DD HH24:MI:SS'),100,'75') ; -- 17/03/2011 10h16min52s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120126 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h17min8s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120127,1120023,TO_TIMESTAMP('2011-03-17 10:17:07','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','98 - Outras Operações de Entrada',TO_TIMESTAMP('2011-03-17 10:17:07','YYYY-MM-DD HH24:MI:SS'),100,'98') ; -- 17/03/2011 10h17min8s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120127 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h17min20s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120128,1120023,TO_TIMESTAMP('2011-03-17 10:17:19','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','99 - Outras Operações',TO_TIMESTAMP('2011-03-17 10:17:19','YYYY-MM-DD HH24:MI:SS'),100,'99') ; -- 17/03/2011 10h17min20s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120128 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID) ; -- 17/03/2011 10h17min50s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Column (AD_Client_ID,AD_Column_ID,AD_Element_ID,AD_Org_ID,AD_Reference_ID,AD_Reference_Value_ID,AD_Table_ID,ColumnName,Created,CreatedBy,Description,EntityType,FieldLength,Help,IsActive,IsAllowLogging,IsAlwaysUpdateable,IsAutocomplete,IsEncrypted,IsIdentifier,IsKey,IsMandatory,IsParent,IsSelectionColumn,IsSyncDatabase,IsTranslated,IsUpdateable,Name,SeqNo,Updated,UpdatedBy,Version) VALUES (0,1120265,1120054,0,17,1120023,333,'lbr_TaxStatusPIS',TO_TIMESTAMP('2011-03-17 10:17:49','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (PIS)','LBRA',2,'Defines the Tax Status (PIS)','Y','Y','N','N','N','N','N','N','N','N','N','N','Y','Tax Status (PIS)',0,TO_TIMESTAMP('2011-03-17 10:17:49','YYYY-MM-DD HH24:MI:SS'),100,0) ; -- 17/03/2011 10h17min50s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Column_Trl (AD_Language,AD_Column_ID, Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Column_ID, t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Column t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Column_ID=1120265 AND NOT EXISTS (SELECT * FROM AD_Column_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Column_ID=t.AD_Column_ID) ; -- 17/03/2011 10h17min52s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator ALTER TABLE C_InvoiceLine ADD COLUMN lbr_TaxStatusPIS VARCHAR(2) DEFAULT NULL ; -- 17/03/2011 10h26min38s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Element (AD_Client_ID,AD_Element_ID,AD_Org_ID,ColumnName,Created,CreatedBy,Description,EntityType,Help,IsActive,Name,PrintName,Updated,UpdatedBy) VALUES (0,1120055,0,'lbr_TaxStatusCOFINS',TO_TIMESTAMP('2011-03-17 10:26:37','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (COFINS)','LBRA','Defines the Tax Status (COFINS)','Y','Tax Status (COFINS)','Tax Status (COFINS)',TO_TIMESTAMP('2011-03-17 10:26:37','YYYY-MM-DD HH24:MI:SS'),100) ; -- 17/03/2011 10h26min38s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Element_Trl (AD_Language,AD_Element_ID, Description,Help,Name,PO_Description,PO_Help,PO_Name,PO_PrintName,PrintName, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Element_ID, t.Description,t.Help,t.Name,t.PO_Description,t.PO_Help,t.PO_Name,t.PO_PrintName,t.PrintName, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Element t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Element_ID=1120055 AND NOT EXISTS (SELECT * FROM AD_Element_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Element_ID=t.AD_Element_ID) ; -- 17/03/2011 10h27min16s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator UPDATE AD_Element_Trl SET IsTranslated='Y',Name='Situação Tributária (COFINS)',PrintName='Situação Tributária (COFINS)',Description='Defines a Situação Tributária (COFINS)',Help='Defines a Situação Tributária (COFINS)',Updated=TO_TIMESTAMP('2011-03-17 10:27:16','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Element_ID=1120055 AND AD_Language='pt_BR' ; -- 17/03/2011 10h27min29s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Column (AD_Client_ID,AD_Column_ID,AD_Element_ID,AD_Org_ID,AD_Reference_ID,AD_Reference_Value_ID,AD_Table_ID,ColumnName,Created,CreatedBy,Description,EntityType,FieldLength,Help,IsActive,IsAllowLogging,IsAlwaysUpdateable,IsAutocomplete,IsEncrypted,IsIdentifier,IsKey,IsMandatory,IsParent,IsSelectionColumn,IsSyncDatabase,IsTranslated,IsUpdateable,Name,SeqNo,Updated,UpdatedBy,Version) VALUES (0,1120266,1120055,0,17,1120023,333,'lbr_TaxStatusCOFINS',TO_TIMESTAMP('2011-03-17 10:27:28','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (COFINS)','LBRA',2,'Defines the Tax Status (COFINS)','Y','Y','N','N','N','N','N','N','N','N','N','N','Y','Tax Status (COFINS)',0,TO_TIMESTAMP('2011-03-17 10:27:28','YYYY-MM-DD HH24:MI:SS'),100,0) ; -- 17/03/2011 10h27min29s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Column_Trl (AD_Language,AD_Column_ID, Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Column_ID, t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Column t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Column_ID=1120266 AND NOT EXISTS (SELECT * FROM AD_Column_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Column_ID=t.AD_Column_ID) ; -- 17/03/2011 10h27min30s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator ALTER TABLE C_InvoiceLine ADD COLUMN lbr_TaxStatusCOFINS VARCHAR(2) DEFAULT NULL ; -- 17/03/2011 11h40min3s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Column (AD_Client_ID,AD_Column_ID,AD_Element_ID,AD_Org_ID,AD_Reference_ID,AD_Reference_Value_ID,AD_Table_ID,ColumnName,Created,CreatedBy,Description,EntityType,FieldLength,Help,IsActive,IsAllowLogging,IsAlwaysUpdateable,IsAutocomplete,IsEncrypted,IsIdentifier,IsKey,IsMandatory,IsParent,IsSelectionColumn,IsSyncDatabase,IsTranslated,IsUpdateable,Name,SeqNo,Updated,UpdatedBy,Version) VALUES (0,1120267,1120054,0,17,1120023,1000028,'lbr_TaxStatusPIS',TO_TIMESTAMP('2011-03-17 11:40:01','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (PIS)','LBRA',2,'Defines the Tax Status (PIS)','Y','Y','N','N','N','N','N','N','N','N','N','N','Y','Tax Status (PIS)',0,TO_TIMESTAMP('2011-03-17 11:40:01','YYYY-MM-DD HH24:MI:SS'),100,0) ; -- 17/03/2011 11h40min3s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Column_Trl (AD_Language,AD_Column_ID, Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Column_ID, t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Column t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Column_ID=1120267 AND NOT EXISTS (SELECT * FROM AD_Column_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Column_ID=t.AD_Column_ID) ; -- 17/03/2011 11h41min24s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator ALTER TABLE LBR_NotaFiscalLine ADD COLUMN lbr_TaxStatusPIS VARCHAR(2) DEFAULT NULL ; -- 17/03/2011 11h41min47s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Column (AD_Client_ID,AD_Column_ID,AD_Element_ID,AD_Org_ID,AD_Reference_ID,AD_Reference_Value_ID,AD_Table_ID,ColumnName,Created,CreatedBy,Description,EntityType,FieldLength,Help,IsActive,IsAllowLogging,IsAlwaysUpdateable,IsAutocomplete,IsEncrypted,IsIdentifier,IsKey,IsMandatory,IsParent,IsSelectionColumn,IsSyncDatabase,IsTranslated,IsUpdateable,Name,SeqNo,Updated,UpdatedBy,Version) VALUES (0,1120268,1120055,0,17,1120023,1000028,'lbr_TaxStatusCOFINS',TO_TIMESTAMP('2011-03-17 11:41:47','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (COFINS)','LBRA',2,'Defines the Tax Status (COFINS)','Y','Y','N','N','N','N','N','N','N','N','N','N','Y','Tax Status (COFINS)',0,TO_TIMESTAMP('2011-03-17 11:41:47','YYYY-MM-DD HH24:MI:SS'),100,0) ; -- 17/03/2011 11h41min47s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Column_Trl (AD_Language,AD_Column_ID, Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Column_ID, t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Column t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Column_ID=1120268 AND NOT EXISTS (SELECT * FROM AD_Column_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Column_ID=t.AD_Column_ID) ; -- 17/03/2011 11h41min49s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator ALTER TABLE LBR_NotaFiscalLine ADD COLUMN lbr_TaxStatusCOFINS VARCHAR(2) DEFAULT NULL ; -- 17/03/2011 11h42min48s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Field (AD_Client_ID,AD_Column_ID,AD_Field_ID,AD_Org_ID,AD_Tab_ID,Created,CreatedBy,Description,DisplayLength,EntityType,Help,IsActive,IsCentrallyMaintained,IsDisplayed,IsEncrypted,IsFieldOnly,IsHeading,IsReadOnly,IsSameLine,Name,SeqNo,Updated,UpdatedBy) VALUES (0,1120267,1120196,0,1000021,TO_TIMESTAMP('2011-03-17 11:42:47','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (PIS)',2,'LBRA','Defines the Tax Status (PIS)','Y','Y','Y','N','N','N','N','N','Tax Status (PIS)',201,TO_TIMESTAMP('2011-03-17 11:42:47','YYYY-MM-DD HH24:MI:SS'),100) ; -- 17/03/2011 11h42min48s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Field_Trl (AD_Language,AD_Field_ID, Description,Help,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Field_ID, t.Description,t.Help,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Field t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Field_ID=1120196 AND NOT EXISTS (SELECT * FROM AD_Field_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Field_ID=t.AD_Field_ID) ; -- 17/03/2011 11h43min16s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Field (AD_Client_ID,AD_Column_ID,AD_Field_ID,AD_Org_ID,AD_Tab_ID,Created,CreatedBy,Description,DisplayLength,EntityType,Help,IsActive,IsCentrallyMaintained,IsDisplayed,IsEncrypted,IsFieldOnly,IsHeading,IsReadOnly,IsSameLine,Name,SeqNo,Updated,UpdatedBy) VALUES (0,1120268,1120197,0,1000021,TO_TIMESTAMP('2011-03-17 11:43:15','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (COFINS)',2,'LBRA','Defines the Tax Status (COFINS)','Y','Y','Y','N','N','N','N','Y','Tax Status (COFINS)',202,TO_TIMESTAMP('2011-03-17 11:43:15','YYYY-MM-DD HH24:MI:SS'),100) ; -- 17/03/2011 11h43min16s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Field_Trl (AD_Language,AD_Field_ID, Description,Help,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Field_ID, t.Description,t.Help,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Field t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Field_ID=1120197 AND NOT EXISTS (SELECT * FROM AD_Field_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Field_ID=t.AD_Field_ID) ; -- 17/03/2011 11h44min9s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Field (AD_Client_ID,AD_Column_ID,AD_Field_ID,AD_Org_ID,AD_Tab_ID,Created,CreatedBy,Description,DisplayLength,EntityType,Help,IsActive,IsCentrallyMaintained,IsDisplayed,IsEncrypted,IsFieldOnly,IsHeading,IsReadOnly,IsSameLine,Name,SeqNo,Updated,UpdatedBy) VALUES (0,1120267,1120198,0,1000030,TO_TIMESTAMP('2011-03-17 11:44:08','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (PIS)',2,'LBRA','Defines the Tax Status (PIS)','Y','Y','Y','N','N','N','N','N','Tax Status (PIS)',251,TO_TIMESTAMP('2011-03-17 11:44:08','YYYY-MM-DD HH24:MI:SS'),100) ; -- 17/03/2011 11h44min9s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Field_Trl (AD_Language,AD_Field_ID, Description,Help,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Field_ID, t.Description,t.Help,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Field t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Field_ID=1120198 AND NOT EXISTS (SELECT * FROM AD_Field_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Field_ID=t.AD_Field_ID) ; -- 17/03/2011 11h44min32s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Field (AD_Client_ID,AD_Column_ID,AD_Field_ID,AD_Org_ID,AD_Tab_ID,Created,CreatedBy,Description,DisplayLength,EntityType,Help,IsActive,IsCentrallyMaintained,IsDisplayed,IsEncrypted,IsFieldOnly,IsHeading,IsReadOnly,IsSameLine,Name,SeqNo,Updated,UpdatedBy) VALUES (0,1120268,1120199,0,1000030,TO_TIMESTAMP('2011-03-17 11:44:31','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (COFINS)',2,'LBRA','Defines the Tax Status (COFINS)','Y','Y','Y','N','N','N','N','Y','Tax Status (COFINS)',252,TO_TIMESTAMP('2011-03-17 11:44:31','YYYY-MM-DD HH24:MI:SS'),100) ; -- 17/03/2011 11h44min32s BRT -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator INSERT INTO AD_Field_Trl (AD_Language,AD_Field_ID, Description,Help,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Field_ID, t.Description,t.Help,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Field t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Field_ID=1120199 AND NOT EXISTS (SELECT * FROM AD_Field_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Field_ID=t.AD_Field_ID) ; UPDATE AD_SysConfig SET Value='360-trunk/040-FR_3220195.sql' WHERE AD_SysConfig_ID=1100006;
Java
/* * pcm audio input device * * Copyright (C) 2008 Google, Inc. * Copyright (C) 2008 HTC Corporation * Copyright (c) 2009-2010, Code Aurora Forum. All rights reserved. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <mach/debug_audio_mm.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/miscdevice.h> #include <linux/uaccess.h> #include <linux/sched.h> #include <linux/wait.h> #include <linux/dma-mapping.h> #include <linux/msm_audio.h> #include <asm/atomic.h> #include <asm/ioctls.h> #include <mach/msm_adsp.h> #include <mach/qdsp5v2/qdsp5audreccmdi.h> #include <mach/qdsp5v2/qdsp5audrecmsg.h> #include <mach/qdsp5v2/audpreproc.h> #include <mach/qdsp5v2/audio_dev_ctl.h> /* FRAME_NUM must be a power of two */ #define FRAME_NUM (8) #define FRAME_SIZE (2052 * 2) #define MONO_DATA_SIZE (2048) #define STEREO_DATA_SIZE (MONO_DATA_SIZE * 2) #define DMASZ (FRAME_SIZE * FRAME_NUM) struct buffer { void *data; uint32_t size; uint32_t read; uint32_t addr; }; struct audio_in { struct buffer in[FRAME_NUM]; spinlock_t dsp_lock; atomic_t in_bytes; atomic_t in_samples; struct mutex lock; struct mutex read_lock; wait_queue_head_t wait; wait_queue_head_t wait_enable; struct msm_adsp_module *audrec; /* configuration to use on next enable */ uint32_t samp_rate; uint32_t channel_mode; uint32_t buffer_size; /* 2048 for mono, 4096 for stereo */ uint32_t enc_type; uint32_t dsp_cnt; uint32_t in_head; /* next buffer dsp will write */ uint32_t in_tail; /* next buffer read() will read */ uint32_t in_count; /* number of buffers available to read() */ const char *module_name; unsigned queue_ids; uint16_t enc_id; /* Session Id */ uint16_t source; /* Encoding source bit mask */ uint32_t device_events; /* device events interested in */ uint32_t dev_cnt; spinlock_t dev_lock; /* data allocated for various buffers */ char *data; dma_addr_t phys; int opened; int enabled; int running; int stopped; /* set when stopped, cleared on flush */ int abort; /* set when error, like sample rate mismatch */ }; static struct audio_in the_audio_in; struct audio_frame { uint16_t frame_count_lsw; uint16_t frame_count_msw; uint16_t frame_length; uint16_t erased_pcm; unsigned char raw_bitstream[]; /* samples */ } __attribute__((packed)); /* Audrec Queue command sent macro's */ #define audrec_send_bitstreamqueue(audio, cmd, len) \ msm_adsp_write(audio->audrec, ((audio->queue_ids & 0xFFFF0000) >> 16),\ cmd, len) #define audrec_send_audrecqueue(audio, cmd, len) \ msm_adsp_write(audio->audrec, (audio->queue_ids & 0x0000FFFF),\ cmd, len) /* DSP command send functions */ static int audpcm_in_enc_config(struct audio_in *audio, int enable); static int audpcm_in_param_config(struct audio_in *audio); static int audpcm_in_mem_config(struct audio_in *audio); static int audpcm_in_record_config(struct audio_in *audio, int enable); static int audpcm_dsp_read_buffer(struct audio_in *audio, uint32_t read_cnt); static void audpcm_in_get_dsp_frames(struct audio_in *audio); static void audpcm_in_flush(struct audio_in *audio); static void pcm_in_listener(u32 evt_id, union auddev_evt_data *evt_payload, void *private_data) { struct audio_in *audio = (struct audio_in *) private_data; unsigned long flags; MM_DBG("evt_id = 0x%8x\n", evt_id); switch (evt_id) { case AUDDEV_EVT_DEV_RDY: { MM_DBG("AUDDEV_EVT_DEV_RDY\n"); spin_lock_irqsave(&audio->dev_lock, flags); audio->dev_cnt++; audio->source |= (0x1 << evt_payload->routing_id); spin_unlock_irqrestore(&audio->dev_lock, flags); if ((audio->running == 1) && (audio->enabled == 1)) audpcm_in_record_config(audio, 1); break; } case AUDDEV_EVT_DEV_RLS: { MM_DBG("AUDDEV_EVT_DEV_RLS\n"); spin_lock_irqsave(&audio->dev_lock, flags); audio->dev_cnt--; audio->source &= ~(0x1 << evt_payload->routing_id); spin_unlock_irqrestore(&audio->dev_lock, flags); if (!audio->running || !audio->enabled) break; /* Turn of as per source */ if (audio->source) audpcm_in_record_config(audio, 1); else /* Turn off all */ audpcm_in_record_config(audio, 0); break; } case AUDDEV_EVT_FREQ_CHG: { MM_DBG("Encoder Driver got sample rate change event\n"); MM_DBG("sample rate %d\n", evt_payload->freq_info.sample_rate); MM_DBG("dev_type %d\n", evt_payload->freq_info.dev_type); MM_DBG("acdb_dev_id %d\n", evt_payload->freq_info.acdb_dev_id); if (audio->running == 1) { /* Stop Recording sample rate does not match with device sample rate */ if (evt_payload->freq_info.sample_rate != audio->samp_rate) { audpcm_in_record_config(audio, 0); audio->abort = 1; wake_up(&audio->wait); } } break; } default: MM_ERR("wrong event %d\n", evt_id); break; } } /* ------------------- dsp preproc event handler--------------------- */ static void audpreproc_dsp_event(void *data, unsigned id, void *msg) { struct audio_in *audio = data; switch (id) { case AUDPREPROC_ERROR_MSG: { struct audpreproc_err_msg *err_msg = msg; MM_ERR("ERROR_MSG: stream id %d err idx %d\n", err_msg->stream_id, err_msg->aud_preproc_err_idx); /* Error case */ wake_up(&audio->wait_enable); break; } case AUDPREPROC_CMD_CFG_DONE_MSG: { MM_DBG("CMD_CFG_DONE_MSG \n"); break; } case AUDPREPROC_CMD_ENC_CFG_DONE_MSG: { struct audpreproc_cmd_enc_cfg_done_msg *enc_cfg_msg = msg; MM_DBG("CMD_ENC_CFG_DONE_MSG: stream id %d enc type \ 0x%8x\n", enc_cfg_msg->stream_id, enc_cfg_msg->rec_enc_type); /* Encoder enable success */ if (enc_cfg_msg->rec_enc_type & ENCODE_ENABLE) audpcm_in_param_config(audio); else { /* Encoder disable success */ audio->running = 0; audpcm_in_record_config(audio, 0); } break; } case AUDPREPROC_CMD_ENC_PARAM_CFG_DONE_MSG: { MM_DBG("CMD_ENC_PARAM_CFG_DONE_MSG \n"); audpcm_in_mem_config(audio); break; } case AUDPREPROC_AFE_CMD_AUDIO_RECORD_CFG_DONE_MSG: { MM_DBG("AFE_CMD_AUDIO_RECORD_CFG_DONE_MSG \n"); wake_up(&audio->wait_enable); break; } default: MM_ERR("Unknown Event id %d\n", id); } } /* ------------------- dsp audrec event handler--------------------- */ static void audrec_dsp_event(void *data, unsigned id, size_t len, void (*getevent)(void *ptr, size_t len)) { struct audio_in *audio = data; switch (id) { case AUDREC_CMD_MEM_CFG_DONE_MSG: { MM_DBG("CMD_MEM_CFG_DONE MSG DONE\n"); audio->running = 1; if (audio->dev_cnt > 0) audpcm_in_record_config(audio, 1); break; } case AUDREC_FATAL_ERR_MSG: { struct audrec_fatal_err_msg fatal_err_msg; getevent(&fatal_err_msg, AUDREC_FATAL_ERR_MSG_LEN); MM_ERR("FATAL_ERR_MSG: err id %d\n", fatal_err_msg.audrec_err_id); /* Error stop the encoder */ audio->stopped = 1; wake_up(&audio->wait); break; } case AUDREC_UP_PACKET_READY_MSG: { struct audrec_up_pkt_ready_msg pkt_ready_msg; getevent(&pkt_ready_msg, AUDREC_UP_PACKET_READY_MSG_LEN); MM_DBG("UP_PACKET_READY_MSG: write cnt lsw %d \ write cnt msw %d read cnt lsw %d read cnt msw %d \n",\ pkt_ready_msg.audrec_packet_write_cnt_lsw, \ pkt_ready_msg.audrec_packet_write_cnt_msw, \ pkt_ready_msg.audrec_up_prev_read_cnt_lsw, \ pkt_ready_msg.audrec_up_prev_read_cnt_msw); audpcm_in_get_dsp_frames(audio); break; } default: MM_ERR("Unknown Event id %d\n", id); } } static void audpcm_in_get_dsp_frames(struct audio_in *audio) { struct audio_frame *frame; uint32_t index; unsigned long flags; index = audio->in_head; frame = (void *) (((char *)audio->in[index].data) - \ sizeof(*frame)); spin_lock_irqsave(&audio->dsp_lock, flags); audio->in[index].size = frame->frame_length; /* statistics of read */ atomic_add(audio->in[index].size, &audio->in_bytes); atomic_add(1, &audio->in_samples); audio->in_head = (audio->in_head + 1) & (FRAME_NUM - 1); /* If overflow, move the tail index foward. */ if (audio->in_head == audio->in_tail) audio->in_tail = (audio->in_tail + 1) & (FRAME_NUM - 1); else audio->in_count++; audpcm_dsp_read_buffer(audio, audio->dsp_cnt++); spin_unlock_irqrestore(&audio->dsp_lock, flags); wake_up(&audio->wait); } struct msm_adsp_ops audrec_adsp_ops = { .event = audrec_dsp_event, }; static int audpcm_in_enc_config(struct audio_in *audio, int enable) { struct audpreproc_audrec_cmd_enc_cfg cmd; memset(&cmd, 0, sizeof(cmd)); cmd.cmd_id = AUDPREPROC_AUDREC_CMD_ENC_CFG; cmd.stream_id = audio->enc_id; if (enable) cmd.audrec_enc_type = audio->enc_type | ENCODE_ENABLE; else cmd.audrec_enc_type &= ~(ENCODE_ENABLE); return audpreproc_send_audreccmdqueue(&cmd, sizeof(cmd)); } static int audpcm_in_param_config(struct audio_in *audio) { struct audpreproc_audrec_cmd_parm_cfg_wav cmd; memset(&cmd, 0, sizeof(cmd)); cmd.common.cmd_id = AUDPREPROC_AUDREC_CMD_PARAM_CFG; cmd.common.stream_id = audio->enc_id; cmd.aud_rec_samplerate_idx = audio->samp_rate; cmd.aud_rec_stereo_mode = audio->channel_mode; return audpreproc_send_audreccmdqueue(&cmd, sizeof(cmd)); } /* To Do: msm_snddev_route_enc(audio->enc_id); */ static int audpcm_in_record_config(struct audio_in *audio, int enable) { struct audpreproc_afe_cmd_audio_record_cfg cmd; memset(&cmd, 0, sizeof(cmd)); cmd.cmd_id = AUDPREPROC_AFE_CMD_AUDIO_RECORD_CFG; cmd.stream_id = audio->enc_id; if (enable) cmd.destination_activity = AUDIO_RECORDING_TURN_ON; else cmd.destination_activity = AUDIO_RECORDING_TURN_OFF; cmd.source_mix_mask = audio->source; return audpreproc_send_audreccmdqueue(&cmd, sizeof(cmd)); } static int audpcm_in_mem_config(struct audio_in *audio) { struct audrec_cmd_arecmem_cfg cmd; uint16_t *data = (void *) audio->data; int n; memset(&cmd, 0, sizeof(cmd)); cmd.cmd_id = AUDREC_CMD_MEM_CFG_CMD; cmd.audrec_up_pkt_intm_count = 1; cmd.audrec_ext_pkt_start_addr_msw = audio->phys >> 16; cmd.audrec_ext_pkt_start_addr_lsw = audio->phys; cmd.audrec_ext_pkt_buf_number = FRAME_NUM; /* prepare buffer pointers: * Mono: 1024 samples + 4 halfword header * Stereo: 2048 samples + 4 halfword header */ for (n = 0; n < FRAME_NUM; n++) { audio->in[n].data = data + 4; data += (4 + (audio->channel_mode ? 2048 : 1024)); MM_DBG("0x%8x\n", (int)(audio->in[n].data - 8)); } return audrec_send_audrecqueue(audio, &cmd, sizeof(cmd)); } static int audpcm_dsp_read_buffer(struct audio_in *audio, uint32_t read_cnt) { struct up_audrec_packet_ext_ptr cmd; memset(&cmd, 0, sizeof(cmd)); cmd.cmd_id = UP_AUDREC_PACKET_EXT_PTR; cmd.audrec_up_curr_read_count_msw = read_cnt >> 16; cmd.audrec_up_curr_read_count_lsw = read_cnt; return audrec_send_bitstreamqueue(audio, &cmd, sizeof(cmd)); } /* must be called with audio->lock held */ static int audpcm_in_enable(struct audio_in *audio) { if (audio->enabled) return 0; if (audpreproc_enable(audio->enc_id, &audpreproc_dsp_event, audio)) { MM_ERR("msm_adsp_enable(audpreproc) failed\n"); return -ENODEV; } if (msm_adsp_enable(audio->audrec)) { MM_ERR("msm_adsp_enable(audrec) failed\n"); audpreproc_disable(audio->enc_id, audio); return -ENODEV; } audio->enabled = 1; audpcm_in_enc_config(audio, 1); return 0; } /* must be called with audio->lock held */ static int audpcm_in_disable(struct audio_in *audio) { if (audio->enabled) { audio->enabled = 0; audpcm_in_enc_config(audio, 0); wake_up(&audio->wait); wait_event_interruptible_timeout(audio->wait_enable, audio->running == 0, 1*HZ); msm_adsp_disable(audio->audrec); audpreproc_disable(audio->enc_id, audio); } return 0; } static void audpcm_in_flush(struct audio_in *audio) { int i; audio->dsp_cnt = 0; audio->in_head = 0; audio->in_tail = 0; audio->in_count = 0; for (i = 0; i < FRAME_NUM; i++) { audio->in[i].size = 0; audio->in[i].read = 0; } MM_DBG("in_bytes %d\n", atomic_read(&audio->in_bytes)); MM_DBG("in_samples %d\n", atomic_read(&audio->in_samples)); atomic_set(&audio->in_bytes, 0); atomic_set(&audio->in_samples, 0); } /* ------------------- device --------------------- */ static long audpcm_in_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct audio_in *audio = file->private_data; int rc = 0; if (cmd == AUDIO_GET_STATS) { struct msm_audio_stats stats; stats.byte_count = atomic_read(&audio->in_bytes); stats.sample_count = atomic_read(&audio->in_samples); if (copy_to_user((void *) arg, &stats, sizeof(stats))) return -EFAULT; return rc; } mutex_lock(&audio->lock); switch (cmd) { case AUDIO_START: { uint32_t freq; /* Poll at 48KHz always */ freq = 48000; MM_DBG("AUDIO_START\n"); rc = msm_snddev_request_freq(&freq, audio->enc_id, SNDDEV_CAP_TX, AUDDEV_CLNT_ENC); MM_DBG("sample rate configured %d sample rate requested %d\n", freq, audio->samp_rate); if (rc < 0) { MM_DBG("sample rate can not be set, return code %d\n",\ rc); msm_snddev_withdraw_freq(audio->enc_id, SNDDEV_CAP_TX, AUDDEV_CLNT_ENC); MM_DBG("msm_snddev_withdraw_freq\n"); break; } rc = audpcm_in_enable(audio); if (!rc) { rc = wait_event_interruptible_timeout(audio->wait_enable, audio->running != 0, 1*HZ); MM_DBG("state %d rc = %d\n", audio->running, rc); if (audio->running == 0) rc = -ENODEV; else rc = 0; } break; } case AUDIO_STOP: { rc = audpcm_in_disable(audio); rc = msm_snddev_withdraw_freq(audio->enc_id, SNDDEV_CAP_TX, AUDDEV_CLNT_ENC); MM_DBG("msm_snddev_withdraw_freq\n"); audio->stopped = 1; audio->abort = 0; break; } case AUDIO_FLUSH: { if (audio->stopped) { /* Make sure we're stopped and we wake any threads * that might be blocked holding the read_lock. * While audio->stopped read threads will always * exit immediately. */ wake_up(&audio->wait); mutex_lock(&audio->read_lock); audpcm_in_flush(audio); mutex_unlock(&audio->read_lock); } break; } case AUDIO_SET_CONFIG: { struct msm_audio_config cfg; if (copy_from_user(&cfg, (void *) arg, sizeof(cfg))) { rc = -EFAULT; break; } if (cfg.channel_count == 1) { cfg.channel_count = AUDREC_CMD_MODE_MONO; } else if (cfg.channel_count == 2) { cfg.channel_count = AUDREC_CMD_MODE_STEREO; } else { rc = -EINVAL; break; } audio->samp_rate = cfg.sample_rate; audio->channel_mode = cfg.channel_count; audio->buffer_size = audio->channel_mode ? STEREO_DATA_SIZE : \ MONO_DATA_SIZE; break; } case AUDIO_GET_CONFIG: { struct msm_audio_config cfg; memset(&cfg, 0, sizeof(cfg)); cfg.buffer_size = audio->buffer_size; cfg.buffer_count = FRAME_NUM; cfg.sample_rate = audio->samp_rate; if (audio->channel_mode == AUDREC_CMD_MODE_MONO) cfg.channel_count = 1; else cfg.channel_count = 2; if (copy_to_user((void *) arg, &cfg, sizeof(cfg))) rc = -EFAULT; break; } case AUDIO_GET_SESSION_ID: { if (copy_to_user((void *) arg, &audio->enc_id, sizeof(unsigned short))) { rc = -EFAULT; } break; } default: rc = -EINVAL; } mutex_unlock(&audio->lock); return rc; } static ssize_t audpcm_in_read(struct file *file, char __user *buf, size_t count, loff_t *pos) { struct audio_in *audio = file->private_data; unsigned long flags; const char __user *start = buf; void *data; uint32_t index; uint32_t size; int rc = 0; mutex_lock(&audio->read_lock); while (count > 0) { rc = wait_event_interruptible( audio->wait, (audio->in_count > 0) || audio->stopped || audio->abort); if (rc < 0) break; if (audio->stopped && !audio->in_count) { MM_DBG("Driver in stop state, No more buffer to read"); rc = 0;/* End of File */ break; } if (audio->abort) { rc = -EPERM; /* Not permitted due to abort */ break; } index = audio->in_tail; data = (uint8_t *) audio->in[index].data; size = audio->in[index].size; if (count >= size) { if (copy_to_user(buf, data, size)) { rc = -EFAULT; break; } spin_lock_irqsave(&audio->dsp_lock, flags); if (index != audio->in_tail) { /* overrun -- data is * invalid and we need to retry */ spin_unlock_irqrestore(&audio->dsp_lock, flags); continue; } audio->in[index].size = 0; audio->in_tail = (audio->in_tail + 1) & (FRAME_NUM - 1); audio->in_count--; spin_unlock_irqrestore(&audio->dsp_lock, flags); count -= size; buf += size; } else { MM_ERR("short read\n"); break; } } mutex_unlock(&audio->read_lock); if (buf > start) return buf - start; return rc; } static ssize_t audpcm_in_write(struct file *file, const char __user *buf, size_t count, loff_t *pos) { return -EINVAL; } static int audpcm_in_release(struct inode *inode, struct file *file) { struct audio_in *audio = file->private_data; mutex_lock(&audio->lock); /* with draw frequency for session incase not stopped the driver */ msm_snddev_withdraw_freq(audio->enc_id, SNDDEV_CAP_TX, AUDDEV_CLNT_ENC); auddev_unregister_evt_listner(AUDDEV_CLNT_ENC, audio->enc_id); audpcm_in_disable(audio); audpcm_in_flush(audio); msm_adsp_put(audio->audrec); audpreproc_aenc_free(audio->enc_id); audio->audrec = NULL; audio->opened = 0; mutex_unlock(&audio->lock); return 0; } static int audpcm_in_open(struct inode *inode, struct file *file) { struct audio_in *audio = &the_audio_in; int rc; int encid; mutex_lock(&audio->lock); if (audio->opened) { rc = -EBUSY; goto done; } /* Settings will be re-config at AUDIO_SET_CONFIG, * but at least we need to have initial config */ audio->channel_mode = AUDREC_CMD_MODE_MONO; audio->buffer_size = MONO_DATA_SIZE; audio->samp_rate = 8000; audio->enc_type = ENC_TYPE_WAV; audio->source = INTERNAL_CODEC_TX_SOURCE_MIX_MASK; encid = audpreproc_aenc_alloc(audio->enc_type, &audio->module_name, &audio->queue_ids); if (encid < 0) { MM_ERR("No free encoder available\n"); rc = -ENODEV; goto done; } audio->enc_id = encid; rc = msm_adsp_get(audio->module_name, &audio->audrec, &audrec_adsp_ops, audio); if (rc) { audpreproc_aenc_free(audio->enc_id); goto done; } audio->stopped = 0; audio->source = 0; audio->abort = 0; audpcm_in_flush(audio); audio->device_events = AUDDEV_EVT_DEV_RDY | AUDDEV_EVT_DEV_RLS | AUDDEV_EVT_FREQ_CHG; rc = auddev_register_evt_listner(audio->device_events, AUDDEV_CLNT_ENC, audio->enc_id, pcm_in_listener, (void *) audio); if (rc) { MM_ERR("failed to register device event listener\n"); goto evt_error; } file->private_data = audio; audio->opened = 1; rc = 0; done: mutex_unlock(&audio->lock); return rc; evt_error: msm_adsp_put(audio->audrec); audpreproc_aenc_free(audio->enc_id); mutex_unlock(&audio->lock); return rc; } static const struct file_operations audio_in_fops = { .owner = THIS_MODULE, .open = audpcm_in_open, .release = audpcm_in_release, .read = audpcm_in_read, .write = audpcm_in_write, .unlocked_ioctl = audpcm_in_ioctl, }; struct miscdevice audio_in_misc = { .minor = MISC_DYNAMIC_MINOR, .name = "msm_pcm_in", .fops = &audio_in_fops, }; static int __init audpcm_in_init(void) { the_audio_in.data = dma_alloc_coherent(NULL, DMASZ, &the_audio_in.phys, GFP_KERNEL); MM_DBG("Memory addr = 0x%8x phy addr = 0x%8x ---- \n", \ (int) the_audio_in.data, (int) the_audio_in.phys); if (!the_audio_in.data) { MM_ERR("Unable to allocate DMA buffer\n"); return -ENOMEM; } mutex_init(&the_audio_in.lock); mutex_init(&the_audio_in.read_lock); spin_lock_init(&the_audio_in.dsp_lock); spin_lock_init(&the_audio_in.dev_lock); init_waitqueue_head(&the_audio_in.wait); init_waitqueue_head(&the_audio_in.wait_enable); return misc_register(&audio_in_misc); } device_initcall(audpcm_in_init);
Java
table, th, td {border: 1px solid black; border-collapse: collapse} .right {text-align: right} tr.even {background-color: #FFEEEE} td.right {text-align: right} a {color: #880000; text-decoration: none} a:hover {background-color:#FFCCCC} tr.click:hover {background-color:#FFCCCC} img.right {float: right} div.bar {background-color: #EEEEEE; width: 100%; padding: 10px; border: 1px solid black}
Java
/**! * The MIT License * * Copyright (c) 2010-2012 Google, Inc. http://angularjs.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * angular-google-maps * https://github.com/nlaplante/angular-google-maps * * @author Nicolas Laplante https://plus.google.com/108189012221374960701 */ (function () { "use strict"; /* * Utility functions */ /** * Check if 2 floating point numbers are equal * * @see http://stackoverflow.com/a/588014 */ function floatEqual (f1, f2) { return (Math.abs(f1 - f2) < 0.000001); } /* * Create the model in a self-contained class where map-specific logic is * done. This model will be used in the directive. */ var MapModel = (function () { var _defaults = { zoom: 8, draggable: false, container: null }; /** * */ function PrivateMapModel(opts) { var _instance = null, _markers = [], // caches the instances of google.maps.Marker _handlers = [], // event handlers _windows = [], // InfoWindow objects o = angular.extend({}, _defaults, opts), that = this, currentInfoWindow = null; this.center = opts.center; this.zoom = o.zoom; this.draggable = o.draggable; this.dragging = false; this.selector = o.container; this.markers = []; this.options = o.options; this.draw = function () { if (that.center == null) { // TODO log error return; } if (_instance == null) { // Create a new map instance _instance = new google.maps.Map(that.selector, angular.extend(that.options, { center: that.center, zoom: that.zoom, draggable: that.draggable, mapTypeId : google.maps.MapTypeId.ROADMAP })); google.maps.event.addListener(_instance, "dragstart", function () { that.dragging = true; } ); google.maps.event.addListener(_instance, "idle", function () { that.dragging = false; } ); google.maps.event.addListener(_instance, "drag", function () { that.dragging = true; } ); google.maps.event.addListener(_instance, "zoom_changed", function () { that.zoom = _instance.getZoom(); that.center = _instance.getCenter(); } ); google.maps.event.addListener(_instance, "center_changed", function () { that.center = _instance.getCenter(); } ); // Attach additional event listeners if needed if (_handlers.length) { angular.forEach(_handlers, function (h, i) { google.maps.event.addListener(_instance, h.on, h.handler); }); } } else { // Refresh the existing instance google.maps.event.trigger(_instance, "resize"); var instanceCenter = _instance.getCenter(); if (!floatEqual(instanceCenter.lat(), that.center.lat()) || !floatEqual(instanceCenter.lng(), that.center.lng())) { _instance.setCenter(that.center); } if (_instance.getZoom() != that.zoom) { _instance.setZoom(that.zoom); } } }; this.fit = function () { if (_instance && _markers.length) { var bounds = new google.maps.LatLngBounds(); angular.forEach(_markers, function (m, i) { bounds.extend(m.getPosition()); }); _instance.fitBounds(bounds); } }; this.on = function(event, handler) { _handlers.push({ "on": event, "handler": handler }); }; this.addMarker = function (lat, lng, icon, infoWindowContent, label, url, thumbnail) { if (that.findMarker(lat, lng) != null) { return; } var marker = new google.maps.Marker({ position: new google.maps.LatLng(lat, lng), map: _instance, icon: icon }); if (label) { } if (url) { } if (infoWindowContent != null) { var infoWindow = new google.maps.InfoWindow({ content: infoWindowContent }); google.maps.event.addListener(marker, 'click', function() { if (currentInfoWindow != null) { currentInfoWindow.close(); } infoWindow.open(_instance, marker); currentInfoWindow = infoWindow; }); } // Cache marker _markers.unshift(marker); // Cache instance of our marker for scope purposes that.markers.unshift({ "lat": lat, "lng": lng, "draggable": false, "icon": icon, "infoWindowContent": infoWindowContent, "label": label, "url": url, "thumbnail": thumbnail }); // Return marker instance return marker; }; this.findMarker = function (lat, lng) { for (var i = 0; i < _markers.length; i++) { var pos = _markers[i].getPosition(); if (floatEqual(pos.lat(), lat) && floatEqual(pos.lng(), lng)) { return _markers[i]; } } return null; }; this.findMarkerIndex = function (lat, lng) { for (var i = 0; i < _markers.length; i++) { var pos = _markers[i].getPosition(); if (floatEqual(pos.lat(), lat) && floatEqual(pos.lng(), lng)) { return i; } } return -1; }; this.addInfoWindow = function (lat, lng, html) { var win = new google.maps.InfoWindow({ content: html, position: new google.maps.LatLng(lat, lng) }); _windows.push(win); return win; }; this.hasMarker = function (lat, lng) { return that.findMarker(lat, lng) !== null; }; this.getMarkerInstances = function () { return _markers; }; this.removeMarkers = function (markerInstances) { var s = this; angular.forEach(markerInstances, function (v, i) { var pos = v.getPosition(), lat = pos.lat(), lng = pos.lng(), index = s.findMarkerIndex(lat, lng); // Remove from local arrays _markers.splice(index, 1); s.markers.splice(index, 1); // Remove from map v.setMap(null); }); }; } // Done return PrivateMapModel; }()); // End model // Start Angular directive var googleMapsModule = angular.module("google-maps", []); /** * Map directive */ googleMapsModule.directive("googleMap", ["$log", "$timeout", "$filter", function ($log, $timeout, $filter) { var controller = function ($scope, $element) { var _m = $scope.map; self.addInfoWindow = function (lat, lng, content) { _m.addInfoWindow(lat, lng, content); }; }; controller.$inject = ['$scope', '$element']; return { restrict: "EC", priority: 100, transclude: true, template: "<div class='angular-google-map' ng-transclude></div>", replace: false, scope: { center: "=center", // required markers: "=markers", // optional latitude: "=latitude", // required longitude: "=longitude", // required zoom: "=zoom", // required refresh: "&refresh", // optional windows: "=windows" // optional" }, controller: controller, link: function (scope, element, attrs, ctrl) { // Center property must be specified and provide lat & // lng properties if (!angular.isDefined(scope.center) || (!angular.isDefined(scope.center.lat) || !angular.isDefined(scope.center.lng))) { $log.error("angular-google-maps: ould not find a valid center property"); return; } if (!angular.isDefined(scope.zoom)) { $log.error("angular-google-maps: map zoom property not set"); return; } angular.element(element).addClass("angular-google-map"); // Parse options var opts = {options: {}}; if (attrs.options) { opts.options = angular.fromJson(attrs.options); } // Create our model var _m = new MapModel(angular.extend(opts, { container: element[0], center: new google.maps.LatLng(scope.center.lat, scope.center.lng), draggable: attrs.draggable == "true", zoom: scope.zoom })); _m.on("drag", function () { var c = _m.center; $timeout(function () { scope.$apply(function (s) { scope.center.lat = c.lat(); scope.center.lng = c.lng(); }); }); }); _m.on("zoom_changed", function () { if (scope.zoom != _m.zoom) { $timeout(function () { scope.$apply(function (s) { scope.zoom = _m.zoom; }); }); } }); _m.on("center_changed", function () { var c = _m.center; $timeout(function () { scope.$apply(function (s) { if (!_m.dragging) { scope.center.lat = c.lat(); scope.center.lng = c.lng(); } }); }); }); if (attrs.markClick == "true") { (function () { var cm = null; _m.on("click", function (e) { if (cm == null) { cm = { latitude: e.latLng.lat(), longitude: e.latLng.lng() }; scope.markers.push(cm); } else { cm.latitude = e.latLng.lat(); cm.longitude = e.latLng.lng(); } $timeout(function () { scope.latitude = cm.latitude; scope.longitude = cm.longitude; scope.$apply(); }); }); }()); } // Put the map into the scope scope.map = _m; // Check if we need to refresh the map if (angular.isUndefined(scope.refresh())) { // No refresh property given; draw the map immediately _m.draw(); } else { scope.$watch("refresh()", function (newValue, oldValue) { if (newValue && !oldValue) { _m.draw(); } }); } // Markers scope.$watch("markers", function (newValue, oldValue) { $timeout(function () { angular.forEach(newValue, function (v, i) { if (!_m.hasMarker(v.latitude, v.longitude)) { _m.addMarker(v.latitude, v.longitude, v.icon, v.infoWindow); } }); // Clear orphaned markers var orphaned = []; angular.forEach(_m.getMarkerInstances(), function (v, i) { // Check our scope if a marker with equal latitude and longitude. // If not found, then that marker has been removed form the scope. var pos = v.getPosition(), lat = pos.lat(), lng = pos.lng(), found = false; // Test against each marker in the scope for (var si = 0; si < scope.markers.length; si++) { var sm = scope.markers[si]; if (floatEqual(sm.latitude, lat) && floatEqual(sm.longitude, lng)) { // Map marker is present in scope too, don't remove found = true; } } // Marker in map has not been found in scope. Remove. if (!found) { orphaned.push(v); } }); orphaned.length && _m.removeMarkers(orphaned); // Fit map when there are more than one marker. // This will change the map center coordinates if (attrs.fit == "true" && newValue.length > 1) { _m.fit(); } }); }, true); // Update map when center coordinates change scope.$watch("center", function (newValue, oldValue) { if (newValue === oldValue) { return; } if (!_m.dragging) { _m.center = new google.maps.LatLng(newValue.lat, newValue.lng); _m.draw(); } }, true); scope.$watch("zoom", function (newValue, oldValue) { if (newValue === oldValue) { return; } _m.zoom = newValue; _m.draw(); }); } }; }]); }());
Java
<?php die("Access Denied"); ?>#x#s:4516:" 1448241693 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-tw" lang="zh-tw"> <head> <script type="text/javascript"> var siteurl='/'; var tmplurl='/templates/ja_mendozite/'; var isRTL = false; </script> <base href="http://www.zon.com.tw/zh/component/mailto/" /> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="generator" content="榮憶橡膠工業股份有限公司" /> <title>榮憶橡膠工業股份有限公司 | 榮憶橡膠工業股份有限公司</title> <link href="http://www.zon.com.tw/zh/component/mailto/?link=5b01b8f2ca3ca1e431fb7082348e60a75d09bcb4&amp;template=ja_mendozite&amp;tmpl=component" rel="canonical" /> <link rel="stylesheet" href="/t3-assets/css_9ce88.css" type="text/css" /> <link rel="stylesheet" href="/t3-assets/css_31cec.css" type="text/css" /> <script src="/en/?jat3action=gzip&amp;jat3type=js&amp;jat3file=t3-assets%2Fjs_7f13c.js" type="text/javascript"></script> <script type="text/javascript"> function keepAlive() { var myAjax = new Request({method: "get", url: "index.php"}).send();} window.addEvent("domready", function(){ keepAlive.periodical(840000); }); </script> <script type="text/javascript"> var akoption = { "colorTable" : true , "opacityEffect" : true , "foldContent" : true , "fixingElement" : true , "smoothScroll" : false } ; var akconfig = new Object(); akconfig.root = 'http://www.zon.com.tw/' ; akconfig.host = 'http://'+location.host+'/' ; AsikartEasySet.init( akoption , akconfig ); </script> <link href="/plugins/system/jat3/jat3/base-themes/default/images/favicon.ico" rel="shortcut icon" type="image/x-icon" /> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-60602086-1', 'auto'); ga('send', 'pageview'); </script> <link rel="stylesheet" href="http://www.zon.com.tw/easyset/css/custom-typo.css" type="text/css" /> <link rel="stylesheet" href="http://www.zon.com.tw/easyset/css/custom.css" type="text/css" /> </head> <body id="bd" class="fs3 com_mailto contentpane"> <div id="system-message-container"> <div id="system-message"> </div> </div> <script type="text/javascript"> Joomla.submitbutton = function(pressbutton) { var form = document.getElementById('mailtoForm'); // do field validation if (form.mailto.value == "" || form.from.value == "") { alert('請提供正確的電子郵件。'); return false; } form.submit(); } </script> <div id="mailto-window"> <h2> 推薦此連結給朋友。 </h2> <div class="mailto-close"> <a href="javascript: void window.close()" title="關閉視窗"> <span>關閉視窗 </span></a> </div> <form action="http://www.zon.com.tw/index.php" id="mailtoForm" method="post"> <div class="formelm"> <label for="mailto_field">寄信給</label> <input type="text" id="mailto_field" name="mailto" class="inputbox" size="25" value=""/> </div> <div class="formelm"> <label for="sender_field"> 寄件者</label> <input type="text" id="sender_field" name="sender" class="inputbox" value="" size="25" /> </div> <div class="formelm"> <label for="from_field"> 您的郵件</label> <input type="text" id="from_field" name="from" class="inputbox" value="" size="25" /> </div> <div class="formelm"> <label for="subject_field"> 主旨</label> <input type="text" id="subject_field" name="subject" class="inputbox" value="" size="25" /> </div> <p> <button class="button" onclick="return Joomla.submitbutton('send');"> 送出 </button> <button class="button" onclick="window.close();return false;"> 取消 </button> </p> <input type="hidden" name="layout" value="default" /> <input type="hidden" name="option" value="com_mailto" /> <input type="hidden" name="task" value="send" /> <input type="hidden" name="tmpl" value="component" /> <input type="hidden" name="link" value="5b01b8f2ca3ca1e431fb7082348e60a75d09bcb4" /> <input type="hidden" name="3431db301dbcf490ccf76011c9360ad9" value="1" /> </form> </div> </body> </html>";
Java
<?php foreach ($content as $key => $value): ?> <div class="product-item-viewed product-node-id-<?php print $key; ?>"> <?php print l($value['title'], $value['path']); ?> <?php if (isset($value['image'])): ?> <div class='image-viewed'><img src='<?php print $value['image']; ?>' /></div> <?php endif; ?> </div> <?php endforeach; ?>
Java
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("LetsSolveIt.WebService.SmokeTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Pioneer Hi-Bred")] [assembly: AssemblyProduct("LetsSolveIt.WebService.SmokeTest")] [assembly: AssemblyCopyright("Copyright © Pioneer Hi-Bred 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f01d6f18-3205-4e06-91be-4e20781b83c5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Java
package kieranvs.avatar.bending.earth; import java.util.Arrays; import java.util.concurrent.ConcurrentHashMap; import net.minecraft.block.Block; import net.minecraft.entity.EntityLivingBase; import net.minecraft.init.Blocks; import kieranvs.avatar.Protection; import kieranvs.avatar.bending.Ability; import kieranvs.avatar.bending.AsynchronousAbility; import kieranvs.avatar.bukkit.BlockBukkit; import kieranvs.avatar.bukkit.Location; import kieranvs.avatar.bukkit.Vector; import kieranvs.avatar.util.AvatarDamageSource; import kieranvs.avatar.util.BendingUtils; public class EarthStream extends AsynchronousAbility { private long interval = 200L; private long risetime = 600L; private ConcurrentHashMap<BlockBukkit, Long> movedBlocks = new ConcurrentHashMap<BlockBukkit, Long>(); private Location origin; private Location location; private Vector direction; private int range; private long time; private boolean finished = false; public EarthStream(EntityLivingBase user, Location location, Vector direction, int range) { super(user, 2000); this.time = System.currentTimeMillis(); this.range = range; this.origin = location.clone(); this.location = location.clone(); this.direction = direction.clone(); this.direction.setY(0); this.direction.normalize(); this.location.add(this.direction); } @Override public void update() { for (BlockBukkit block : movedBlocks.keySet()) { long time = movedBlocks.get(block).longValue(); if (System.currentTimeMillis() > time + risetime) { Protection.trySetBlock(user.worldObj, Blocks.air, block.getRelative(BlockBukkit.UP).getX(), block.getRelative(BlockBukkit.UP).getY(), block.getRelative(BlockBukkit.UP).getZ()); movedBlocks.remove(block); } } if (finished) { if (movedBlocks.isEmpty()) { destroy(); } else { return; } } if (System.currentTimeMillis() - time >= interval) { time = System.currentTimeMillis(); location.add(direction); if (location.distance(origin) > range) { finished = true; return; } BlockBukkit block = this.location.getBlock(); if (isMoveable(block)) { moveBlock(block); } if (isMoveable(block.getRelative(BlockBukkit.DOWN))) { moveBlock(block.getRelative(BlockBukkit.DOWN)); location = block.getRelative(BlockBukkit.DOWN).getLocation(); return; } if (isMoveable(block.getRelative(BlockBukkit.UP))) { moveBlock(block.getRelative(BlockBukkit.UP)); location = block.getRelative(BlockBukkit.UP).getLocation(); return; } else { finished = true; } return; } } public void moveBlock(BlockBukkit block) { // block.getRelative(Block.UP).breakNaturally(); //block.getRelative(Block.UP).setType(block.getType()); //movedBlocks.put(block, System.currentTimeMillis()); //damageEntities(block.getLocation()); //BendingUtils.damageEntities(block.getLocation(), 3.5F, AvatarDamageSource.earthbending, 3); Protection.trySetBlock(user.worldObj, Blocks.dirt, block.getRelative(BlockBukkit.UP).getX(), block.getRelative(BlockBukkit.UP).getY(), block.getRelative(BlockBukkit.UP).getZ()); movedBlocks.put(block, System.currentTimeMillis()); } public void damageEntities(Location loc) { for (Object o : loc.getWorld().getLoadedEntityList()) { if (o instanceof EntityLivingBase) { EntityLivingBase e = (EntityLivingBase) o; if (loc.distance(e) < 3.5) { e.attackEntityFrom(AvatarDamageSource.earthbending, 3); } } } } public static boolean isMoveable(BlockBukkit block) { Block[] overwriteable = { Blocks.air, Blocks.sapling, Blocks.tallgrass, Blocks.deadbush, Blocks.yellow_flower, Blocks.red_flower, Blocks.brown_mushroom, Blocks.red_mushroom, Blocks.fire, Blocks.snow, Blocks.torch, Blocks.leaves, Blocks.cactus, Blocks.reeds, Blocks.web, Blocks.waterlily, Blocks.vine }; if (!Arrays.asList(overwriteable).contains(block.getRelative(BlockBukkit.UP).getType())) { return false; } Block[] moveable = { Blocks.brick_block, Blocks.clay, Blocks.coal_ore, Blocks.cobblestone, Blocks.dirt, Blocks.grass, Blocks.gravel, Blocks.mossy_cobblestone, Blocks.mycelium, Blocks.nether_brick, Blocks.netherrack, Blocks.obsidian, Blocks.sand, Blocks.sandstone, Blocks.farmland, Blocks.soul_sand, Blocks.stone }; if (Arrays.asList(moveable).contains(block.getType())) { return true; } return false; } }
Java
#include <iostream> #include <stdint.h> #include <map> #include <set> #include "macros.h" #include <assert.h> using namespace std; #include <fstream> struct defsetcmp { bool operator() (const pair<uint64_t, uint64_t> &l, const pair<uint64_t, uint64_t> &r) { return (l.first < r.first || l.second < r.second); } }; int main(int argc, char *argv[]) { if (argc != 2) { cerr << "Usage: ./parse file" << endl; return(1); } ifstream inFile(argv[1]); map<uint64_t, uint64_t> latestWrite; typedef map<pair<uint64_t, uint64_t>, set<uint64_t>, defsetcmp> defsett; defsett defset; map<uint64_t, bool> localread; map<uint64_t, bool> nonlocalread; map<uint64_t, uint64_t> ins2tid; map<uint64_t, map<uint64_t, bool> > has_read; map<uint64_t, bool> follower; while (inFile.good()) { uint64_t ins, tid, rw, addr; inFile >> ins >> tid >> rw >> addr; if (ins == END && addr == END) { latestWrite.clear(); ins2tid.clear(); has_read.clear(); } else if (rw == READ) { ins2tid[ins] = tid; //if there are no writes to current variable yet then continue if (latestWrite.find(addr) == latestWrite.end()) { continue; } uint64_t latestWriteIns = latestWrite[addr]; //defset defset[make_pair(addr,ins)].insert(latestWriteIns); //local non-local bool isLocal = (tid == ins2tid[latestWriteIns]); if (localread.find(ins) == localread.end()) { localread[ins] = isLocal; nonlocalread[ins] = !isLocal; } else { localread[ins] = localread[ins] && isLocal; nonlocalread[ins] = nonlocalread[ins] && !isLocal; } //follower if (has_read.find(addr) != has_read.end() && has_read[addr].find(tid) != has_read[addr].end()) { if (follower.find(ins) != follower.end()) { follower[ins] = follower[ins] && has_read[addr][tid]; } else { follower[ins] = has_read[addr][tid]; } } has_read[addr][tid] = true; } else { assert(rw == WRITE); ins2tid[ins] = tid; latestWrite[addr] = ins; if(has_read.find(addr) != has_read.end()) { for(map<uint64_t, bool>::iterator titr = has_read[addr].begin(); titr != has_read[addr].end(); ++titr) { titr->second = false; } } } } inFile.close(); //print defset //variable read_ins_addr #writes write_ins_add0 ... for (defsett::const_iterator defsetitr = defset.begin(); defsetitr != defset.end(); ++defsetitr) { cout << defsetitr->first.first << " " << defsetitr->first.second << " "; cout << (defsetitr->second).size() << " "; for (set<uint64_t>::const_iterator witr = (defsetitr->second).begin(); witr != (defsetitr->second).end(); ++witr) { cout << *witr << " "; } cout << endl; } //print local and non local cout << "#local: " << endl; for(map<uint64_t, bool>::const_iterator litr = localread.begin(); litr != localread.end(); ++litr) { if (litr->second) { cout << litr->first << endl; } } cout << "#nonlocal: " << endl; for(map<uint64_t, bool>::const_iterator nlitr = nonlocalread.begin(); nlitr != nonlocalread.end(); ++nlitr) { if (nlitr->second) { cout << nlitr->first << endl; } } //print follower cout << "#follower: " << endl; for(map<uint64_t, bool>::const_iterator fitr = follower.begin(); fitr != follower.end(); ++fitr) { if (fitr->second) { cout << fitr->first << endl; } } return 0; }
Java
/***************************************************************** Copyright (c) 1996-2000 the kicker authors. See file AUTHORS. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************/ #include <qdragobject.h> #include <qstring.h> #include <qstringlist.h> #include <kglobal.h> #include <kiconloader.h> #include <kmimetype.h> #include <klocale.h> #include <kdesktopfile.h> #include <kglobalsettings.h> #include <kapplication.h> #include <kurldrag.h> #include <krecentdocument.h> #include "recentdocsmenu.h" K_EXPORT_KICKER_MENUEXT(recentdocs, RecentDocsMenu) RecentDocsMenu::RecentDocsMenu(QWidget *parent, const char *name, const QStringList &/*args*/) : KPanelMenu(KRecentDocument::recentDocumentDirectory(), parent, name) { } RecentDocsMenu::~RecentDocsMenu() { } void RecentDocsMenu::initialize() { if (initialized()) clear(); insertItem(SmallIconSet("history_clear"), i18n("Clear History"), this, SLOT(slotClearHistory())); insertSeparator(); _fileList = KRecentDocument::recentDocuments(); if (_fileList.isEmpty()) { insertItem(i18n("No Entries"), 0); setItemEnabled(0, false); return; } int id = 0; char alreadyPresentInMenu; QStringList previousEntries; for (QStringList::ConstIterator it = _fileList.begin(); it != _fileList.end(); ++it) { KDesktopFile f(*it, true /* read only */); // Make sure this entry is not already present in the menu alreadyPresentInMenu = 0; for ( QStringList::Iterator previt = previousEntries.begin(); previt != previousEntries.end(); ++previt ) { if (QString::localeAwareCompare(*previt, f.readName().replace('&', QString::fromAscii("&&") )) == 0) { alreadyPresentInMenu = 1; } } if (alreadyPresentInMenu == 0) { // Add item to menu insertItem(SmallIconSet(f.readIcon()), f.readName().replace('&', QString::fromAscii("&&") ), id++); // Append to duplicate checking list previousEntries.append(f.readName().replace('&', QString::fromAscii("&&") )); } } setInitialized(true); } void RecentDocsMenu::slotClearHistory() { KRecentDocument::clear(); reinitialize(); } void RecentDocsMenu::slotExec(int id) { if (id >= 0) { kapp->propagateSessionManager(); KURL u; u.setPath(_fileList[id]); KDEDesktopMimeType::run(u, true); } } void RecentDocsMenu::mousePressEvent(QMouseEvent* e) { _mouseDown = e->pos(); QPopupMenu::mousePressEvent(e); } void RecentDocsMenu::mouseMoveEvent(QMouseEvent* e) { KPanelMenu::mouseMoveEvent(e); if (!(e->state() & LeftButton)) return; if (!rect().contains(_mouseDown)) return; int dragLength = (e->pos() - _mouseDown).manhattanLength(); if (dragLength <= KGlobalSettings::dndEventDelay()) return; // ignore it int id = idAt(_mouseDown); // Don't drag 'manual' items. if (id < 0) return; KDesktopFile f(_fileList[id], true /* read only */); KURL url ( f.readURL() ); if (url.isEmpty()) // What are we to do ? return; KURL::List lst; lst.append(url); KURLDrag* d = new KURLDrag(lst, this); d->setPixmap(SmallIcon(f.readIcon())); d->dragCopy(); close(); } void RecentDocsMenu::slotAboutToShow() { reinitialize(); KPanelMenu::slotAboutToShow(); } #include "recentdocsmenu.moc"
Java
/* linux/arch/arm/mach-s3c2410/mach-bast.c * * Copyright 2003-2008 Simtec Electronics * Ben Dooks <ben@simtec.co.uk> * * http://www.simtec.co.uk/products/EB2410ITX/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/kernel.h> #include <linux/types.h> #include <linux/interrupt.h> #include <linux/list.h> #include <linux/timer.h> #include <linux/init.h> #include <linux/gpio.h> #include <linux/syscore_ops.h> #include <linux/serial_core.h> #include <linux/platform_device.h> #include <linux/dm9000.h> #include <linux/ata_platform.h> #include <linux/i2c.h> #include <linux/io.h> #include <linux/serial_8250.h> #include <linux/mtd/mtd.h> #include <linux/mtd/nand.h> #include <linux/mtd/nand_ecc.h> #include <linux/mtd/partitions.h> #include <linux/platform_data/asoc-s3c24xx_simtec.h> #include <linux/platform_data/hwmon-s3c.h> #include <linux/platform_data/i2c-s3c2410.h> #include <linux/platform_data/mtd-nand-s3c2410.h> #include <net/ax88796.h> #include <asm/irq.h> #include <asm/mach/arch.h> #include <asm/mach/map.h> #include <asm/mach/irq.h> #include <asm/mach-types.h> #include <mach/fb.h> #include <mach/hardware.h> #include <mach/regs-gpio.h> #include <mach/regs-lcd.h> #include <mach/regs-mem.h> #include <plat/clock.h> #include <plat/cpu.h> #include <plat/cpu-freq.h> #include <plat/devs.h> #include <plat/gpio-cfg.h> #include <plat/regs-serial.h> #include "bast.h" #include "common.h" #include "simtec.h" #define COPYRIGHT ", Copyright 2004-2008 Simtec Electronics" /* macros for virtual address mods for the io space entries */ #define VA_C5(item) ((unsigned long)(item) + BAST_VAM_CS5) #define VA_C4(item) ((unsigned long)(item) + BAST_VAM_CS4) #define VA_C3(item) ((unsigned long)(item) + BAST_VAM_CS3) #define VA_C2(item) ((unsigned long)(item) + BAST_VAM_CS2) /* macros to modify the physical addresses for io space */ #define PA_CS2(item) (__phys_to_pfn((item) + S3C2410_CS2)) #define PA_CS3(item) (__phys_to_pfn((item) + S3C2410_CS3)) #define PA_CS4(item) (__phys_to_pfn((item) + S3C2410_CS4)) #define PA_CS5(item) (__phys_to_pfn((item) + S3C2410_CS5)) static struct map_desc bast_iodesc[] __initdata = { /* ISA IO areas */ { .virtual = (u32)S3C24XX_VA_ISA_BYTE, .pfn = PA_CS2(BAST_PA_ISAIO), .length = SZ_16M, .type = MT_DEVICE, }, { .virtual = (u32)S3C24XX_VA_ISA_WORD, .pfn = PA_CS3(BAST_PA_ISAIO), .length = SZ_16M, .type = MT_DEVICE, }, /* bast CPLD control registers, and external interrupt controls */ { .virtual = (u32)BAST_VA_CTRL1, .pfn = __phys_to_pfn(BAST_PA_CTRL1), .length = SZ_1M, .type = MT_DEVICE, }, { .virtual = (u32)BAST_VA_CTRL2, .pfn = __phys_to_pfn(BAST_PA_CTRL2), .length = SZ_1M, .type = MT_DEVICE, }, { .virtual = (u32)BAST_VA_CTRL3, .pfn = __phys_to_pfn(BAST_PA_CTRL3), .length = SZ_1M, .type = MT_DEVICE, }, { .virtual = (u32)BAST_VA_CTRL4, .pfn = __phys_to_pfn(BAST_PA_CTRL4), .length = SZ_1M, .type = MT_DEVICE, }, /* PC104 IRQ mux */ { .virtual = (u32)BAST_VA_PC104_IRQREQ, .pfn = __phys_to_pfn(BAST_PA_PC104_IRQREQ), .length = SZ_1M, .type = MT_DEVICE, }, { .virtual = (u32)BAST_VA_PC104_IRQRAW, .pfn = __phys_to_pfn(BAST_PA_PC104_IRQRAW), .length = SZ_1M, .type = MT_DEVICE, }, { .virtual = (u32)BAST_VA_PC104_IRQMASK, .pfn = __phys_to_pfn(BAST_PA_PC104_IRQMASK), .length = SZ_1M, .type = MT_DEVICE, }, /* peripheral space... one for each of fast/slow/byte/16bit */ /* note, ide is only decoded in word space, even though some registers * are only 8bit */ /* slow, byte */ { VA_C2(BAST_VA_ISAIO), PA_CS2(BAST_PA_ISAIO), SZ_16M, MT_DEVICE }, { VA_C2(BAST_VA_ISAMEM), PA_CS2(BAST_PA_ISAMEM), SZ_16M, MT_DEVICE }, { VA_C2(BAST_VA_SUPERIO), PA_CS2(BAST_PA_SUPERIO), SZ_1M, MT_DEVICE }, /* slow, word */ { VA_C3(BAST_VA_ISAIO), PA_CS3(BAST_PA_ISAIO), SZ_16M, MT_DEVICE }, { VA_C3(BAST_VA_ISAMEM), PA_CS3(BAST_PA_ISAMEM), SZ_16M, MT_DEVICE }, { VA_C3(BAST_VA_SUPERIO), PA_CS3(BAST_PA_SUPERIO), SZ_1M, MT_DEVICE }, /* fast, byte */ { VA_C4(BAST_VA_ISAIO), PA_CS4(BAST_PA_ISAIO), SZ_16M, MT_DEVICE }, { VA_C4(BAST_VA_ISAMEM), PA_CS4(BAST_PA_ISAMEM), SZ_16M, MT_DEVICE }, { VA_C4(BAST_VA_SUPERIO), PA_CS4(BAST_PA_SUPERIO), SZ_1M, MT_DEVICE }, /* fast, word */ { VA_C5(BAST_VA_ISAIO), PA_CS5(BAST_PA_ISAIO), SZ_16M, MT_DEVICE }, { VA_C5(BAST_VA_ISAMEM), PA_CS5(BAST_PA_ISAMEM), SZ_16M, MT_DEVICE }, { VA_C5(BAST_VA_SUPERIO), PA_CS5(BAST_PA_SUPERIO), SZ_1M, MT_DEVICE }, }; #define UCON S3C2410_UCON_DEFAULT | S3C2410_UCON_UCLK #define ULCON S3C2410_LCON_CS8 | S3C2410_LCON_PNONE | S3C2410_LCON_STOPB #define UFCON S3C2410_UFCON_RXTRIG8 | S3C2410_UFCON_FIFOMODE static struct s3c2410_uartcfg bast_uartcfgs[] __initdata = { [0] = { .hwport = 0, .flags = 0, .ucon = UCON, .ulcon = ULCON, .ufcon = UFCON, }, [1] = { .hwport = 1, .flags = 0, .ucon = UCON, .ulcon = ULCON, .ufcon = UFCON, }, /* port 2 is not actually used */ [2] = { .hwport = 2, .flags = 0, .ucon = UCON, .ulcon = ULCON, .ufcon = UFCON, } }; /* NAND Flash on BAST board */ #ifdef CONFIG_PM static int bast_pm_suspend(void) { /* ensure that an nRESET is not generated on resume. */ gpio_direction_output(S3C2410_GPA(21), 1); return 0; } static void bast_pm_resume(void) { s3c_gpio_cfgpin(S3C2410_GPA(21), S3C2410_GPA21_nRSTOUT); } #else #define bast_pm_suspend NULL #define bast_pm_resume NULL #endif static struct syscore_ops bast_pm_syscore_ops = { .suspend = bast_pm_suspend, .resume = bast_pm_resume, }; static int smartmedia_map[] = { 0 }; static int chip0_map[] = { 1 }; static int chip1_map[] = { 2 }; static int chip2_map[] = { 3 }; static struct mtd_partition __initdata bast_default_nand_part[] = { [0] = { .name = "Boot Agent", .size = SZ_16K, .offset = 0, }, [1] = { .name = "/boot", .size = SZ_4M - SZ_16K, .offset = SZ_16K, }, [2] = { .name = "user", .offset = SZ_4M, .size = MTDPART_SIZ_FULL, } }; /* the bast has 4 selectable slots for nand-flash, the three * on-board chip areas, as well as the external SmartMedia * slot. * * Note, there is no current hot-plug support for the SmartMedia * socket. */ static struct s3c2410_nand_set __initdata bast_nand_sets[] = { [0] = { .name = "SmartMedia", .nr_chips = 1, .nr_map = smartmedia_map, .options = NAND_SCAN_SILENT_NODEV, .nr_partitions = ARRAY_SIZE(bast_default_nand_part), .partitions = bast_default_nand_part, }, [1] = { .name = "chip0", .nr_chips = 1, .nr_map = chip0_map, .nr_partitions = ARRAY_SIZE(bast_default_nand_part), .partitions = bast_default_nand_part, }, [2] = { .name = "chip1", .nr_chips = 1, .nr_map = chip1_map, .options = NAND_SCAN_SILENT_NODEV, .nr_partitions = ARRAY_SIZE(bast_default_nand_part), .partitions = bast_default_nand_part, }, [3] = { .name = "chip2", .nr_chips = 1, .nr_map = chip2_map, .options = NAND_SCAN_SILENT_NODEV, .nr_partitions = ARRAY_SIZE(bast_default_nand_part), .partitions = bast_default_nand_part, } }; static void bast_nand_select(struct s3c2410_nand_set *set, int slot) { unsigned int tmp; slot = set->nr_map[slot] & 3; pr_debug("bast_nand: selecting slot %d (set %p,%p)\n", slot, set, set->nr_map); tmp = __raw_readb(BAST_VA_CTRL2); tmp &= BAST_CPLD_CTLR2_IDERST; tmp |= slot; tmp |= BAST_CPLD_CTRL2_WNAND; pr_debug("bast_nand: ctrl2 now %02x\n", tmp); __raw_writeb(tmp, BAST_VA_CTRL2); } static struct s3c2410_platform_nand __initdata bast_nand_info = { .tacls = 30, .twrph0 = 60, .twrph1 = 60, .nr_sets = ARRAY_SIZE(bast_nand_sets), .sets = bast_nand_sets, .select_chip = bast_nand_select, }; /* DM9000 */ static struct resource bast_dm9k_resource[] = { [0] = DEFINE_RES_MEM(S3C2410_CS5 + BAST_PA_DM9000, 4), [1] = DEFINE_RES_MEM(S3C2410_CS5 + BAST_PA_DM9000 + 0x40, 0x40), [2] = DEFINE_RES_NAMED(BAST_IRQ_DM9000 , 1, NULL, IORESOURCE_IRQ \ | IORESOURCE_IRQ_HIGHLEVEL), }; /* for the moment we limit ourselves to 16bit IO until some * better IO routines can be written and tested */ static struct dm9000_plat_data bast_dm9k_platdata = { .flags = DM9000_PLATF_16BITONLY, }; static struct platform_device bast_device_dm9k = { .name = "dm9000", .id = 0, .num_resources = ARRAY_SIZE(bast_dm9k_resource), .resource = bast_dm9k_resource, .dev = { .platform_data = &bast_dm9k_platdata, } }; /* serial devices */ #define SERIAL_BASE (S3C2410_CS2 + BAST_PA_SUPERIO) #define SERIAL_FLAGS (UPF_BOOT_AUTOCONF | UPF_IOREMAP | UPF_SHARE_IRQ) #define SERIAL_CLK (1843200) static struct plat_serial8250_port bast_sio_data[] = { [0] = { .mapbase = SERIAL_BASE + 0x2f8, .irq = BAST_IRQ_PCSERIAL1, .flags = SERIAL_FLAGS, .iotype = UPIO_MEM, .regshift = 0, .uartclk = SERIAL_CLK, }, [1] = { .mapbase = SERIAL_BASE + 0x3f8, .irq = BAST_IRQ_PCSERIAL2, .flags = SERIAL_FLAGS, .iotype = UPIO_MEM, .regshift = 0, .uartclk = SERIAL_CLK, }, { } }; static struct platform_device bast_sio = { .name = "serial8250", .id = PLAT8250_DEV_PLATFORM, .dev = { .platform_data = &bast_sio_data, }, }; /* we have devices on the bus which cannot work much over the * standard 100KHz i2c bus frequency */ static struct s3c2410_platform_i2c __initdata bast_i2c_info = { .flags = 0, .slave_addr = 0x10, .frequency = 100*1000, }; /* Asix AX88796 10/100 ethernet controller */ static struct ax_plat_data bast_asix_platdata = { .flags = AXFLG_MAC_FROMDEV, .wordlength = 2, .dcr_val = 0x48, .rcr_val = 0x40, }; static struct resource bast_asix_resource[] = { [0] = DEFINE_RES_MEM(S3C2410_CS5 + BAST_PA_ASIXNET, 0x18 * 0x20), [1] = DEFINE_RES_MEM(S3C2410_CS5 + BAST_PA_ASIXNET + (0x1f * 0x20), 1), [2] = DEFINE_RES_IRQ(BAST_IRQ_ASIX), }; static struct platform_device bast_device_asix = { .name = "ax88796", .id = 0, .num_resources = ARRAY_SIZE(bast_asix_resource), .resource = bast_asix_resource, .dev = { .platform_data = &bast_asix_platdata } }; /* Asix AX88796 10/100 ethernet controller parallel port */ static struct resource bast_asixpp_resource[] = { [0] = DEFINE_RES_MEM(S3C2410_CS5 + BAST_PA_ASIXNET + (0x18 * 0x20), \ 0x30 * 0x20), }; static struct platform_device bast_device_axpp = { .name = "ax88796-pp", .id = 0, .num_resources = ARRAY_SIZE(bast_asixpp_resource), .resource = bast_asixpp_resource, }; /* LCD/VGA controller */ static struct s3c2410fb_display __initdata bast_lcd_info[] = { { .type = S3C2410_LCDCON1_TFT, .width = 640, .height = 480, .pixclock = 33333, .xres = 640, .yres = 480, .bpp = 4, .left_margin = 40, .right_margin = 20, .hsync_len = 88, .upper_margin = 30, .lower_margin = 32, .vsync_len = 3, .lcdcon5 = 0x00014b02, }, { .type = S3C2410_LCDCON1_TFT, .width = 640, .height = 480, .pixclock = 33333, .xres = 640, .yres = 480, .bpp = 8, .left_margin = 40, .right_margin = 20, .hsync_len = 88, .upper_margin = 30, .lower_margin = 32, .vsync_len = 3, .lcdcon5 = 0x00014b02, }, { .type = S3C2410_LCDCON1_TFT, .width = 640, .height = 480, .pixclock = 33333, .xres = 640, .yres = 480, .bpp = 16, .left_margin = 40, .right_margin = 20, .hsync_len = 88, .upper_margin = 30, .lower_margin = 32, .vsync_len = 3, .lcdcon5 = 0x00014b02, }, }; /* LCD/VGA controller */ static struct s3c2410fb_mach_info __initdata bast_fb_info = { .displays = bast_lcd_info, .num_displays = ARRAY_SIZE(bast_lcd_info), .default_display = 1, }; /* I2C devices fitted. */ static struct i2c_board_info bast_i2c_devs[] __initdata = { { I2C_BOARD_INFO("tlv320aic23", 0x1a), }, { I2C_BOARD_INFO("simtec-pmu", 0x6b), }, { I2C_BOARD_INFO("ch7013", 0x75), }, }; static struct s3c_hwmon_pdata bast_hwmon_info = { /* LCD contrast (0-6.6V) */ .in[0] = &(struct s3c_hwmon_chcfg) { .name = "lcd-contrast", .mult = 3300, .div = 512, }, /* LED current feedback */ .in[1] = &(struct s3c_hwmon_chcfg) { .name = "led-feedback", .mult = 3300, .div = 1024, }, /* LCD feedback (0-6.6V) */ .in[2] = &(struct s3c_hwmon_chcfg) { .name = "lcd-feedback", .mult = 3300, .div = 512, }, /* Vcore (1.8-2.0V), Vref 3.3V */ .in[3] = &(struct s3c_hwmon_chcfg) { .name = "vcore", .mult = 3300, .div = 1024, }, }; /* Standard BAST devices */ // cat /sys/devices/platform/s3c24xx-adc/s3c-hwmon/in_0 static struct platform_device *bast_devices[] __initdata = { &s3c_device_ohci, &s3c_device_lcd, &s3c_device_wdt, &s3c_device_i2c0, &s3c_device_rtc, &s3c_device_nand, &s3c_device_adc, &s3c_device_hwmon, &bast_device_dm9k, &bast_device_asix, &bast_device_axpp, &bast_sio, }; static struct clk *bast_clocks[] __initdata = { &s3c24xx_dclk0, &s3c24xx_dclk1, &s3c24xx_clkout0, &s3c24xx_clkout1, &s3c24xx_uclk, }; static struct s3c_cpufreq_board __initdata bast_cpufreq = { .refresh = 7800, /* 7.8usec */ .auto_io = 1, .need_io = 1, }; static struct s3c24xx_audio_simtec_pdata __initdata bast_audio = { .have_mic = 1, .have_lout = 1, }; static void __init bast_map_io(void) { /* initialise the clocks */ s3c24xx_dclk0.parent = &clk_upll; s3c24xx_dclk0.rate = 12*1000*1000; s3c24xx_dclk1.parent = &clk_upll; s3c24xx_dclk1.rate = 24*1000*1000; s3c24xx_clkout0.parent = &s3c24xx_dclk0; s3c24xx_clkout1.parent = &s3c24xx_dclk1; s3c24xx_uclk.parent = &s3c24xx_clkout1; s3c24xx_register_clocks(bast_clocks, ARRAY_SIZE(bast_clocks)); s3c_hwmon_set_platdata(&bast_hwmon_info); s3c24xx_init_io(bast_iodesc, ARRAY_SIZE(bast_iodesc)); s3c24xx_init_clocks(0); s3c24xx_init_uarts(bast_uartcfgs, ARRAY_SIZE(bast_uartcfgs)); } static void __init bast_init(void) { register_syscore_ops(&bast_pm_syscore_ops); s3c_i2c0_set_platdata(&bast_i2c_info); s3c_nand_set_platdata(&bast_nand_info); s3c24xx_fb_set_platdata(&bast_fb_info); platform_add_devices(bast_devices, ARRAY_SIZE(bast_devices)); i2c_register_board_info(0, bast_i2c_devs, ARRAY_SIZE(bast_i2c_devs)); usb_simtec_init(); nor_simtec_init(); simtec_audio_add(NULL, true, &bast_audio); WARN_ON(gpio_request(S3C2410_GPA(21), "bast nreset")); s3c_cpufreq_setboard(&bast_cpufreq); } MACHINE_START(BAST, "Simtec-BAST") /* Maintainer: Ben Dooks <ben@simtec.co.uk> */ .atag_offset = 0x100, .map_io = bast_map_io, .init_irq = s3c24xx_init_irq, .init_machine = bast_init, .init_time = s3c24xx_timer_init, .restart = s3c2410_restart, MACHINE_END
Java
# Portions Copyright (c) Facebook, Inc. and its affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. # match.py - filename matching # # Copyright 2008, 2009 Matt Mackall <mpm@selenic.com> and others # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from __future__ import absolute_import, print_function import copy import os import re from bindings import pathmatcher from . import error, pathutil, pycompat, util from .i18n import _ from .pycompat import decodeutf8 allpatternkinds = ( "re", "glob", "path", "relglob", "relpath", "relre", "listfile", "listfile0", "set", "include", "subinclude", "rootfilesin", ) cwdrelativepatternkinds = ("relpath", "glob") propertycache = util.propertycache def _rematcher(regex): """compile the regexp with the best available regexp engine and return a matcher function""" m = util.re.compile(regex) try: # slightly faster, provided by facebook's re2 bindings return m.test_match except AttributeError: return m.match def _expandsets(kindpats, ctx): """Returns the kindpats list with the 'set' patterns expanded.""" fset = set() other = [] for kind, pat, source in kindpats: if kind == "set": if not ctx: raise error.ProgrammingError("fileset expression with no " "context") s = ctx.getfileset(pat) fset.update(s) continue other.append((kind, pat, source)) return fset, other def _expandsubinclude(kindpats, root): """Returns the list of subinclude matcher args and the kindpats without the subincludes in it.""" relmatchers = [] other = [] for kind, pat, source in kindpats: if kind == "subinclude": sourceroot = pathutil.dirname(util.normpath(source)) pat = util.pconvert(pat) path = pathutil.join(sourceroot, pat) newroot = pathutil.dirname(path) matcherargs = (newroot, "", [], ["include:%s" % path]) prefix = pathutil.canonpath(root, root, newroot) if prefix: prefix += "/" relmatchers.append((prefix, matcherargs)) else: other.append((kind, pat, source)) return relmatchers, other def _kindpatsalwaysmatch(kindpats): """ "Checks whether the kindspats match everything, as e.g. 'relpath:.' does. """ for kind, pat, source in kindpats: # TODO: update me? if pat != "" or kind not in ["relpath", "glob"]: return False return True def match( root, cwd, patterns=None, include=None, exclude=None, default="glob", exact=False, auditor=None, ctx=None, warn=None, badfn=None, icasefs=False, ): """build an object to match a set of file patterns arguments: root - the canonical root of the tree you're matching against cwd - the current working directory, if relevant patterns - patterns to find include - patterns to include (unless they are excluded) exclude - patterns to exclude (even if they are included) default - if a pattern in patterns has no explicit type, assume this one exact - patterns are actually filenames (include/exclude still apply) warn - optional function used for printing warnings badfn - optional bad() callback for this matcher instead of the default icasefs - make a matcher for wdir on case insensitive filesystems, which normalizes the given patterns to the case in the filesystem a pattern is one of: 'glob:<glob>' - a glob relative to cwd 're:<regexp>' - a regular expression 'path:<path>' - a path relative to repository root, which is matched recursively 'rootfilesin:<path>' - a path relative to repository root, which is matched non-recursively (will not match subdirectories) 'relglob:<glob>' - an unrooted glob (*.c matches C files in all dirs) 'relpath:<path>' - a path relative to cwd 'relre:<regexp>' - a regexp that needn't match the start of a name 'set:<fileset>' - a fileset expression 'include:<path>' - a file of patterns to read and include 'subinclude:<path>' - a file of patterns to match against files under the same directory '<something>' - a pattern of the specified default type """ if auditor is None: auditor = pathutil.pathauditor(root) normalize = _donormalize if icasefs: if exact: raise error.ProgrammingError( "a case-insensitive exact matcher " "doesn't make sense" ) dirstate = ctx.repo().dirstate dsnormalize = dirstate.normalize def normalize(patterns, default, root, cwd, auditor, warn): kp = _donormalize(patterns, default, root, cwd, auditor, warn) kindpats = [] for kind, pats, source in kp: if kind not in ("re", "relre"): # regex can't be normalized p = pats pats = dsnormalize(pats) # Preserve the original to handle a case only rename. if p != pats and p in dirstate: kindpats.append((kind, p, source)) kindpats.append((kind, pats, source)) return kindpats if exact: m = exactmatcher(root, cwd, patterns, badfn) elif patterns: kindpats = normalize(patterns, default, root, cwd, auditor, warn) if _kindpatsalwaysmatch(kindpats): m = alwaysmatcher(root, cwd, badfn, relativeuipath=True) else: m = patternmatcher(root, cwd, kindpats, ctx=ctx, badfn=badfn) else: # It's a little strange that no patterns means to match everything. # Consider changing this to match nothing (probably using nevermatcher). m = alwaysmatcher(root, cwd, badfn) if include: kindpats = normalize(include, "glob", root, cwd, auditor, warn) im = includematcher(root, cwd, kindpats, ctx=ctx, badfn=None) m = intersectmatchers(m, im) if exclude: kindpats = normalize(exclude, "glob", root, cwd, auditor, warn) em = includematcher(root, cwd, kindpats, ctx=ctx, badfn=None) m = differencematcher(m, em) return m def exact(root, cwd, files, badfn=None): return exactmatcher(root, cwd, files, badfn=badfn) def always(root, cwd): return alwaysmatcher(root, cwd) def never(root, cwd): return nevermatcher(root, cwd) def union(matches, root, cwd): """Union a list of matchers. If the list is empty, return nevermatcher. If the list only contains one non-None value, return that matcher. Otherwise return a union matcher. """ matches = list(filter(None, matches)) if len(matches) == 0: return nevermatcher(root, cwd) elif len(matches) == 1: return matches[0] else: return unionmatcher(matches) def badmatch(match, badfn): """Make a copy of the given matcher, replacing its bad method with the given one. """ m = copy.copy(match) m.bad = badfn return m def _donormalize(patterns, default, root, cwd, auditor, warn): """Convert 'kind:pat' from the patterns list to tuples with kind and normalized and rooted patterns and with listfiles expanded.""" kindpats = [] for kind, pat in [_patsplit(p, default) for p in patterns]: if kind in cwdrelativepatternkinds: pat = pathutil.canonpath(root, cwd, pat, auditor) elif kind in ("relglob", "path", "rootfilesin"): pat = util.normpath(pat) elif kind in ("listfile", "listfile0"): try: files = decodeutf8(util.readfile(pat)) if kind == "listfile0": files = files.split("\0") else: files = files.splitlines() files = [f for f in files if f] except EnvironmentError: raise error.Abort(_("unable to read file list (%s)") % pat) for k, p, source in _donormalize(files, default, root, cwd, auditor, warn): kindpats.append((k, p, pat)) continue elif kind == "include": try: fullpath = os.path.join(root, util.localpath(pat)) includepats = readpatternfile(fullpath, warn) for k, p, source in _donormalize( includepats, default, root, cwd, auditor, warn ): kindpats.append((k, p, source or pat)) except error.Abort as inst: raise error.Abort("%s: %s" % (pat, inst[0])) except IOError as inst: if warn: warn( _("skipping unreadable pattern file '%s': %s\n") % (pat, inst.strerror) ) continue # else: re or relre - which cannot be normalized kindpats.append((kind, pat, "")) return kindpats def _testrefastpath(repat): """Test if a re pattern can use fast path. That is, for every "$A/$B" path the pattern matches, "$A" must also be matched, Return True if we're sure it is. Return False otherwise. """ # XXX: It's very hard to implement this. These are what need to be # supported in production and tests. Very hacky. But we plan to get rid # of re matchers eventually. # Rules like "(?!experimental/)" if repat.startswith("(?!") and repat.endswith(")") and repat.count(")") == 1: return True # Rules used in doctest if repat == "(i|j)$": return True return False def _globpatsplit(pat): """Split a glob pattern. Return a list. A naive version is "path.split("/")". This function handles more cases, like "{*,{a,b}*/*}". >>> _globpatsplit("*/**/x/{a,b/c}") ['*', '**', 'x', '{a,b/c}'] """ result = [] buf = "" parentheses = 0 for ch in pat: if ch == "{": parentheses += 1 elif ch == "}": parentheses -= 1 if parentheses == 0 and ch == "/": if buf: result.append(buf) buf = "" else: buf += ch if buf: result.append(buf) return result class _tree(dict): """A tree intended to answer "visitdir" questions with more efficient answers (ex. return "all" or False if possible). """ def __init__(self, *args, **kwargs): # If True, avoid entering subdirectories, and match everything recursively, # unconditionally. self.matchrecursive = False # If True, avoid entering subdirectories, and return "unsure" for # everything. This is set to True when complex re patterns (potentially # including "/") are used. self.unsurerecursive = False # Patterns for matching paths in this directory. self._kindpats = [] # Glob patterns used to match parent directories of another glob # pattern. self._globdirpats = [] super(_tree, self).__init__(*args, **kwargs) def insert(self, path, matchrecursive=True, globpats=None, repats=None): """Insert a directory path to this tree. If matchrecursive is True, mark the directory as unconditionally include files and subdirs recursively. If globpats or repats are specified, append them to the patterns being applied at this directory. The tricky part is those patterns can match "x/y/z" and visit("x"), visit("x/y") need to return True, while we still want visit("x/a") to return False. """ if path == "": self.matchrecursive |= matchrecursive if globpats: # Need to match parent directories too. for pat in globpats: components = _globpatsplit(pat) parentpat = "" for comp in components: if parentpat: parentpat += "/" parentpat += comp if "/" in comp: # Giving up - fallback to slow paths. self.unsurerecursive = True self._globdirpats.append(parentpat) if any("**" in p for p in globpats): # Giving up - "**" matches paths including "/" self.unsurerecursive = True self._kindpats += [("glob", pat, "") for pat in globpats] if repats: if not all(map(_testrefastpath, repats)): # Giving up - fallback to slow paths. self.unsurerecursive = True self._kindpats += [("re", pat, "") for pat in repats] return subdir, rest = self._split(path) self.setdefault(subdir, _tree()).insert(rest, matchrecursive, globpats, repats) def visitdir(self, path): """Similar to matcher.visitdir""" path = normalizerootdir(path, "visitdir") if self.matchrecursive: return "all" elif self.unsurerecursive: return True elif path == "": return True if self._kindpats and self._compiledpats(path): # XXX: This is incorrect. But re patterns are already used in # production. We should kill them! # Need to test "if every string starting with 'path' matches". # Obviously it's impossible to test *every* string with the # standard regex API, therefore pick a random strange path to test # it approximately. if self._compiledpats("%s/*/_/-/0/*" % path): return "all" else: return True if self._globdirpats and self._compileddirpats(path): return True subdir, rest = self._split(path) subtree = self.get(subdir) if subtree is None: return False else: return subtree.visitdir(rest) @util.propertycache def _compiledpats(self): pat, matchfunc = _buildregexmatch(self._kindpats, "") return matchfunc @util.propertycache def _compileddirpats(self): pat, matchfunc = _buildregexmatch( [("glob", p, "") for p in self._globdirpats], "$" ) return matchfunc def _split(self, path): if "/" in path: subdir, rest = path.split("/", 1) else: subdir, rest = path, "" if not subdir: raise error.ProgrammingError("path cannot be absolute") return subdir, rest def _remainingpats(pat, prefix): """list of patterns with prefix stripped >>> _remainingpats("a/b/c", "") ['a/b/c'] >>> _remainingpats("a/b/c", "a") ['b/c'] >>> _remainingpats("a/b/c", "a/b") ['c'] >>> _remainingpats("a/b/c", "a/b/c") [] >>> _remainingpats("", "") [] """ if prefix: if prefix == pat: return [] else: assert pat[len(prefix)] == "/" return [pat[len(prefix) + 1 :]] else: if pat: return [pat] else: return [] def _buildvisitdir(kindpats): """Try to build an efficient visitdir function Return a visitdir function if it's built. Otherwise return None if there are unsupported patterns. >>> _buildvisitdir([('include', 'foo', '')]) >>> _buildvisitdir([('relglob', 'foo', '')]) >>> t = _buildvisitdir([ ... ('glob', 'a/b', ''), ... ('glob', 'c/*.d', ''), ... ('glob', 'e/**/*.c', ''), ... ('re', '^f/(?!g)', ''), # no "$", only match prefix ... ('re', '^h/(i|j)$', ''), ... ('glob', 'i/a*/b*/c*', ''), ... ('glob', 'i/a5/b7/d', ''), ... ('glob', 'j/**.c', ''), ... ]) >>> t('a') True >>> t('a/b') 'all' >>> t('a/b/c') 'all' >>> t('c') True >>> t('c/d') False >>> t('c/rc.d') 'all' >>> t('c/rc.d/foo') 'all' >>> t('e') True >>> t('e/a') True >>> t('e/a/b.c') True >>> t('e/a/b.d') True >>> t('f') True >>> t('f/g') False >>> t('f/g2') False >>> t('f/g/a') False >>> t('f/h') 'all' >>> t('f/h/i') 'all' >>> t('h/i') True >>> t('h/i/k') False >>> t('h/k') False >>> t('i') True >>> t('i/a1') True >>> t('i/b2') False >>> t('i/a/b2/c3') 'all' >>> t('i/a/b2/d4') False >>> t('i/a5/b7/d') 'all' >>> t('j/x/y') True >>> t('z') False """ tree = _tree() for kind, pat, _source in kindpats: if kind == "glob": components = [] for p in pat.split("/"): if "[" in p or "{" in p or "*" in p or "?" in p: break components.append(p) prefix = "/".join(components) matchrecursive = prefix == pat tree.insert( prefix, matchrecursive=matchrecursive, globpats=_remainingpats(pat, prefix), ) elif kind == "re": # Still try to get a plain prefix from the regular expression so we # can still have fast paths. if pat.startswith("^"): # "re" already matches from the beginning, unlike "relre" pat = pat[1:] components = [] for p in pat.split("/"): if re.escape(p) != p: # contains special characters break components.append(p) prefix = "/".join(components) tree.insert( prefix, matchrecursive=False, repats=_remainingpats(pat, prefix) ) else: # Unsupported kind return None return tree.visitdir class basematcher(object): def __init__(self, root, cwd, badfn=None, relativeuipath=True): self._root = root self._cwd = cwd if badfn is not None: self.bad = badfn self._relativeuipath = relativeuipath def __repr__(self): return "<%s>" % self.__class__.__name__ def __call__(self, fn): return self.matchfn(fn) def __iter__(self): for f in self._files: yield f # Callbacks related to how the matcher is used by dirstate.walk. # Subscribers to these events must monkeypatch the matcher object. def bad(self, f, msg): """Callback from dirstate.walk for each explicit file that can't be found/accessed, with an error message.""" # If an traversedir is set, it will be called when a directory discovered # by recursive traversal is visited. traversedir = None def abs(self, f): """Convert a repo path back to path that is relative to the root of the matcher.""" return f def rel(self, f): """Convert repo path back to path that is relative to cwd of matcher.""" return util.pathto(self._root, self._cwd, f) def uipath(self, f): """Convert repo path to a display path. If patterns or -I/-X were used to create this matcher, the display path will be relative to cwd. Otherwise it is relative to the root of the repo.""" return (self._relativeuipath and self.rel(f)) or self.abs(f) @propertycache def _files(self): return [] def files(self): """Explicitly listed files or patterns or roots: if no patterns or .always(): empty list, if exact: list exact files, if not .anypats(): list all files and dirs, else: optimal roots""" return self._files @propertycache def _fileset(self): return set(self._files) def exact(self, f): """Returns True if f is in .files().""" return f in self._fileset def matchfn(self, f): return False def visitdir(self, dir): """Decides whether a directory should be visited based on whether it has potential matches in it or one of its subdirectories. This is based on the match's primary, included, and excluded patterns. Returns the string 'all' if the given directory and all subdirectories should be visited. Otherwise returns True or False indicating whether the given directory should be visited. """ return True def always(self): """Matcher will match everything and .files() will be empty -- optimization might be possible.""" return False def isexact(self): """Matcher will match exactly the list of files in .files() -- optimization might be possible.""" return False def prefix(self): """Matcher will match the paths in .files() recursively -- optimization might be possible.""" return False def anypats(self): """None of .always(), .isexact(), and .prefix() is true -- optimizations will be difficult.""" return not self.always() and not self.isexact() and not self.prefix() class alwaysmatcher(basematcher): """Matches everything.""" def __init__(self, root, cwd, badfn=None, relativeuipath=False): super(alwaysmatcher, self).__init__( root, cwd, badfn, relativeuipath=relativeuipath ) def always(self): return True def matchfn(self, f): return True def visitdir(self, dir): return "all" def __repr__(self): return "<alwaysmatcher>" class nevermatcher(basematcher): """Matches nothing.""" def __init__(self, root, cwd, badfn=None): super(nevermatcher, self).__init__(root, cwd, badfn) # It's a little weird to say that the nevermatcher is an exact matcher # or a prefix matcher, but it seems to make sense to let callers take # fast paths based on either. There will be no exact matches, nor any # prefixes (files() returns []), so fast paths iterating over them should # be efficient (and correct). def isexact(self): return True def prefix(self): return True def visitdir(self, dir): return False def __repr__(self): return "<nevermatcher>" class gitignorematcher(basematcher): """Match files specified by ".gitignore"s""" def __init__(self, root, cwd, badfn=None, gitignorepaths=None): super(gitignorematcher, self).__init__(root, cwd, badfn) gitignorepaths = gitignorepaths or [] self._matcher = pathmatcher.gitignorematcher(root, gitignorepaths) def matchfn(self, f): # XXX: is_dir is set to True here for performance. # It should be set to whether "f" is actually a directory or not. return self._matcher.match_relative(f, True) def explain(self, f): return self._matcher.explain(f, True) def visitdir(self, dir): dir = normalizerootdir(dir, "visitdir") matched = self._matcher.match_relative(dir, True) if matched: # Everything in the directory is selected (ignored) return "all" else: # Not sure return True def __repr__(self): return "<gitignorematcher>" class treematcher(basematcher): """Match glob patterns with negative pattern support. Have a smarter 'visitdir' implementation. """ def __init__(self, root, cwd, badfn=None, rules=[]): super(treematcher, self).__init__(root, cwd, badfn) rules = list(rules) self._matcher = pathmatcher.treematcher(rules) self._rules = rules def matchfn(self, f): return self._matcher.matches(f) def visitdir(self, dir): matched = self._matcher.match_recursive(dir) if matched is None: return True elif matched is True: return "all" else: assert matched is False return False def __repr__(self): return "<treematcher rules=%r>" % self._rules def normalizerootdir(dir, funcname): if dir == ".": util.nouideprecwarn( "match.%s() no longer accepts '.', use '' instead." % funcname, "20190805" ) return "" return dir def _kindpatstoglobs(kindpats, recursive=False): """Attempt to convert 'kindpats' to glob patterns that can be used in a treematcher. kindpats should be already normalized to be relative to repo root. If recursive is True, `glob:a*` will match both `a1/b` and `a1`, otherwise `glob:a*` will only match `a1` but not `a1/b`. Return None if there are unsupported patterns (ex. regular expressions). """ if not _usetreematcher: return None globs = [] for kindpat in kindpats: kind, pat = kindpat[0:2] if kind == "re": # Attempt to convert the re pat to globs reglobs = _convertretoglobs(pat) if reglobs is not None: globs += reglobs else: return None elif kind == "glob": # The treematcher (man gitignore) does not support csh-style # brackets (ex. "{a,b,c}"). Expand the brackets to patterns. for subpat in pathmatcher.expandcurlybrackets(pat): normalized = pathmatcher.normalizeglob(subpat) if recursive: normalized = _makeglobrecursive(normalized) globs.append(normalized) elif kind == "path": if pat == ".": # Special case. Comes from `util.normpath`. pat = "" else: pat = pathmatcher.plaintoglob(pat) pat = _makeglobrecursive(pat) globs.append(pat) else: return None return globs def _makeglobrecursive(pat): """Make a glob pattern recursive by appending "/**" to it""" if pat.endswith("/") or not pat: return pat + "**" else: return pat + "/**" # re:x/(?!y/) # meaning: include x, but not x/y. _repat1 = re.compile(r"^\^?([\w._/]+)/\(\?\!([\w._/]+)/?\)$") # re:x/(?:.*/)?y # meaning: glob:x/**/y _repat2 = re.compile(r"^\^?([\w._/]+)/\(\?:\.\*/\)\?([\w._]+)(?:\(\?\:\/\|\$\))?$") def _convertretoglobs(repat): """Attempt to convert a regular expression pattern to glob patterns. A single regular expression pattern might be converted into multiple glob patterns. Return None if conversion is unsupported. >>> _convertretoglobs("abc*") is None True >>> _convertretoglobs("xx/yy/(?!zz/kk)") ['xx/yy/**', '!xx/yy/zz/kk/**'] >>> _convertretoglobs("x/y/(?:.*/)?BUCK") ['x/y/**/BUCK'] """ m = _repat1.match(repat) if m: prefix, excluded = m.groups() return ["%s/**" % prefix, "!%s/%s/**" % (prefix, excluded)] m = _repat2.match(repat) if m: prefix, name = m.groups() return ["%s/**/%s" % (prefix, name)] return None class patternmatcher(basematcher): def __init__(self, root, cwd, kindpats, ctx=None, badfn=None): super(patternmatcher, self).__init__(root, cwd, badfn) # kindpats are already normalized to be relative to repo-root. # Can we use tree matcher? rules = _kindpatstoglobs(kindpats, recursive=False) fallback = True if rules is not None: try: matcher = treematcher(root, cwd, badfn=badfn, rules=rules) # Replace self to 'matcher'. self.__dict__ = matcher.__dict__ self.__class__ = matcher.__class__ fallback = False except ValueError: # for example, Regex("Compiled regex exceeds size limit of 10485760 bytes.") pass if fallback: self._prefix = _prefix(kindpats) self._pats, self.matchfn = _buildmatch(ctx, kindpats, "$", root) self._files = _explicitfiles(kindpats) @propertycache def _dirs(self): return set(util.dirs(self._fileset)) def visitdir(self, dir): dir = normalizerootdir(dir, "visitdir") if self._prefix and dir in self._fileset: return "all" if not self._prefix: return True return ( dir in self._fileset or dir in self._dirs or any(parentdir in self._fileset for parentdir in util.finddirs(dir)) ) def prefix(self): return self._prefix def __repr__(self): return "<patternmatcher patterns=%r>" % self._pats class includematcher(basematcher): def __init__(self, root, cwd, kindpats, ctx=None, badfn=None): super(includematcher, self).__init__(root, cwd, badfn) # Can we use tree matcher? rules = _kindpatstoglobs(kindpats, recursive=True) fallback = True if rules is not None: try: matcher = treematcher(root, cwd, badfn=badfn, rules=rules) # Replace self to 'matcher'. self.__dict__ = matcher.__dict__ self.__class__ = matcher.__class__ fallback = False except ValueError: # for example, Regex("Compiled regex exceeds size limit of 10485760 bytes.") pass if fallback: self._pats, self.matchfn = _buildmatch(ctx, kindpats, "(?:/|$)", root) # prefix is True if all patterns are recursive, so certain fast paths # can be enabled. Unfortunately, it's too easy to break it (ex. by # using "glob:*.c", "re:...", etc). self._prefix = _prefix(kindpats) roots, dirs = _rootsanddirs(kindpats) # roots are directories which are recursively included. # If self._prefix is True, then _roots can have a fast path for # visitdir to return "all", marking things included unconditionally. # If self._prefix is False, then that optimization is unsound because # "roots" might contain entries that is not recursive (ex. roots will # include "foo/bar" for pattern "glob:foo/bar/*.c"). self._roots = set(roots) # dirs are directories which are non-recursively included. # That is, files under that directory are included. But not # subdirectories. self._dirs = set(dirs) # Try to use a more efficient visitdir implementation visitdir = _buildvisitdir(kindpats) if visitdir: self.visitdir = visitdir def visitdir(self, dir): dir = normalizerootdir(dir, "visitdir") if self._prefix and dir in self._roots: return "all" return ( dir in self._roots or dir in self._dirs or any(parentdir in self._roots for parentdir in util.finddirs(dir)) ) def __repr__(self): return "<includematcher includes=%r>" % self._pats class exactmatcher(basematcher): """Matches the input files exactly. They are interpreted as paths, not patterns (so no kind-prefixes). """ def __init__(self, root, cwd, files, badfn=None): super(exactmatcher, self).__init__(root, cwd, badfn) if isinstance(files, list): self._files = files else: self._files = list(files) matchfn = basematcher.exact @propertycache def _dirs(self): return set(util.dirs(self._fileset)) def visitdir(self, dir): dir = normalizerootdir(dir, "visitdir") return dir in self._dirs def isexact(self): return True def __repr__(self): return "<exactmatcher files=%r>" % self._files class differencematcher(basematcher): """Composes two matchers by matching if the first matches and the second does not. Well, almost... If the user provides a pattern like "-X foo foo", Mercurial actually does match "foo" against that. That's because exact matches are treated specially. So, since this differencematcher is used for excludes, it needs to special-case exact matching. The second matcher's non-matching-attributes (root, cwd, bad, traversedir) are ignored. TODO: If we want to keep the behavior described above for exact matches, we should consider instead treating the above case something like this: union(exact(foo), difference(pattern(foo), include(foo))) """ def __init__(self, m1, m2): super(differencematcher, self).__init__(m1._root, m1._cwd) self._m1 = m1 self._m2 = m2 self.bad = m1.bad self.traversedir = m1.traversedir def matchfn(self, f): return self._m1(f) and (not self._m2(f) or self._m1.exact(f)) @propertycache def _files(self): if self.isexact(): return [f for f in self._m1.files() if self(f)] # If m1 is not an exact matcher, we can't easily figure out the set of # files, because its files() are not always files. For example, if # m1 is "path:dir" and m2 is "rootfileins:.", we don't # want to remove "dir" from the set even though it would match m2, # because the "dir" in m1 may not be a file. return self._m1.files() def visitdir(self, dir): dir = normalizerootdir(dir, "visitdir") if not self._m2.visitdir(dir): return self._m1.visitdir(dir) if self._m2.visitdir(dir) == "all": # There's a bug here: If m1 matches file 'dir/file' and m2 excludes # 'dir' (recursively), we should still visit 'dir' due to the # exception we have for exact matches. return False return bool(self._m1.visitdir(dir)) def isexact(self): return self._m1.isexact() def __repr__(self): return "<differencematcher m1=%r, m2=%r>" % (self._m1, self._m2) def intersectmatchers(m1, m2): """Composes two matchers by matching if both of them match. The second matcher's non-matching-attributes (root, cwd, bad, traversedir) are ignored. """ if m1 is None or m2 is None: return m1 or m2 if m1.always(): m = copy.copy(m2) # TODO: Consider encapsulating these things in a class so there's only # one thing to copy from m1. m.bad = m1.bad m.traversedir = m1.traversedir m.abs = m1.abs m.rel = m1.rel m._relativeuipath |= m1._relativeuipath return m if m2.always(): m = copy.copy(m1) m._relativeuipath |= m2._relativeuipath return m return intersectionmatcher(m1, m2) class intersectionmatcher(basematcher): def __init__(self, m1, m2): super(intersectionmatcher, self).__init__(m1._root, m1._cwd) self._m1 = m1 self._m2 = m2 self.bad = m1.bad self.traversedir = m1.traversedir @propertycache def _files(self): if self.isexact(): m1, m2 = self._m1, self._m2 if not m1.isexact(): m1, m2 = m2, m1 return [f for f in m1.files() if m2(f)] # It neither m1 nor m2 is an exact matcher, we can't easily intersect # the set of files, because their files() are not always files. For # example, if intersecting a matcher "-I glob:foo.txt" with matcher of # "path:dir2", we don't want to remove "dir2" from the set. return self._m1.files() + self._m2.files() def matchfn(self, f): return self._m1(f) and self._m2(f) def visitdir(self, dir): dir = normalizerootdir(dir, "visitdir") visit1 = self._m1.visitdir(dir) if visit1 == "all": return self._m2.visitdir(dir) # bool() because visit1=True + visit2='all' should not be 'all' return bool(visit1 and self._m2.visitdir(dir)) def always(self): return self._m1.always() and self._m2.always() def isexact(self): return self._m1.isexact() or self._m2.isexact() def __repr__(self): return "<intersectionmatcher m1=%r, m2=%r>" % (self._m1, self._m2) class subdirmatcher(basematcher): """Adapt a matcher to work on a subdirectory only. The paths are remapped to remove/insert the path as needed: >>> from . import pycompat >>> m1 = match(b'root', b'', [b'a.txt', b'sub/b.txt']) >>> m2 = subdirmatcher(b'sub', m1) >>> bool(m2(b'a.txt')) False >>> bool(m2(b'b.txt')) True >>> bool(m2.matchfn(b'a.txt')) False >>> bool(m2.matchfn(b'b.txt')) True >>> m2.files() ['b.txt'] >>> m2.exact(b'b.txt') True >>> util.pconvert(m2.rel(b'b.txt')) 'sub/b.txt' >>> def bad(f, msg): ... print(b"%s: %s" % (f, msg)) >>> m1.bad = bad >>> m2.bad(b'x.txt', b'No such file') sub/x.txt: No such file >>> m2.abs(b'c.txt') 'sub/c.txt' """ def __init__(self, path, matcher): super(subdirmatcher, self).__init__(matcher._root, matcher._cwd) self._path = path self._matcher = matcher self._always = matcher.always() self._files = [ f[len(path) + 1 :] for f in matcher._files if f.startswith(path + "/") ] # If the parent repo had a path to this subrepo and the matcher is # a prefix matcher, this submatcher always matches. if matcher.prefix(): self._always = any(f == path for f in matcher._files) def bad(self, f, msg): self._matcher.bad(self._path + "/" + f, msg) def abs(self, f): return self._matcher.abs(self._path + "/" + f) def rel(self, f): return self._matcher.rel(self._path + "/" + f) def uipath(self, f): return self._matcher.uipath(self._path + "/" + f) def matchfn(self, f): # Some information is lost in the superclass's constructor, so we # can not accurately create the matching function for the subdirectory # from the inputs. Instead, we override matchfn() and visitdir() to # call the original matcher with the subdirectory path prepended. return self._matcher.matchfn(self._path + "/" + f) def visitdir(self, dir): dir = normalizerootdir(dir, "visitdir") if dir == "": dir = self._path else: dir = self._path + "/" + dir return self._matcher.visitdir(dir) def always(self): return self._always def prefix(self): return self._matcher.prefix() and not self._always def __repr__(self): return "<subdirmatcher path=%r, matcher=%r>" % (self._path, self._matcher) class unionmatcher(basematcher): """A matcher that is the union of several matchers. The non-matching-attributes (root, cwd, bad, traversedir) are taken from the first matcher. """ def __init__(self, matchers): m1 = matchers[0] super(unionmatcher, self).__init__(m1._root, m1._cwd) self.traversedir = m1.traversedir self._matchers = matchers def matchfn(self, f): for match in self._matchers: if match(f): return True return False def visitdir(self, dir): r = False for m in self._matchers: v = m.visitdir(dir) if v == "all": return v r |= v return r def __repr__(self): return "<unionmatcher matchers=%r>" % self._matchers class xormatcher(basematcher): """A matcher that is the xor of two matchers i.e. match returns true if there's at least one false and one true. The non-matching-attributes (root, cwd, bad, traversedir) are taken from the first matcher. """ def __init__(self, m1, m2): super(xormatcher, self).__init__(m1._root, m1._cwd) self.traversedir = m1.traversedir self.m1 = m1 self.m2 = m2 def matchfn(self, f): return bool(self.m1(f)) ^ bool(self.m2(f)) def visitdir(self, dir): m1dir = self.m1.visitdir(dir) m2dir = self.m2.visitdir(dir) # if both matchers return "all" then we know for sure we don't need # to visit this directory. Same if all matchers return False. In all # other case we have to visit a directory. if m1dir == "all" and m2dir == "all": return False if not m1dir and not m2dir: return False return True def __repr__(self): return "<xormatcher matchers=%r>" % self._matchers class recursivematcher(basematcher): """Make matchers recursive. If "a/b/c" matches, match "a/b/c/**". It is intended to be used by hgignore only. Other matchers would want to fix "visitdir" and "matchfn" to take parent directories into consideration. """ def __init__(self, matcher): self._matcher = matcher def matchfn(self, f): match = self._matcher return match(f) or any(map(match, util.dirs((f,)))) def visitdir(self, dir): if self(dir): return "all" return self._matcher.visitdir(dir) def __repr__(self): return "<recursivematcher %r>" % self._matcher def patkind(pattern, default=None): """If pattern is 'kind:pat' with a known kind, return kind.""" return _patsplit(pattern, default)[0] def _patsplit(pattern, default): """Split a string into the optional pattern kind prefix and the actual pattern.""" if ":" in pattern: kind, pat = pattern.split(":", 1) if kind in allpatternkinds: return kind, pat return default, pattern def _globre(pat): r"""Convert an extended glob string to a regexp string. >>> from . import pycompat >>> def bprint(s): ... print(s) >>> bprint(_globre(br'?')) . >>> bprint(_globre(br'*')) [^/]* >>> bprint(_globre(br'**')) .* >>> bprint(_globre(br'**/a')) (?:.*/)?a >>> bprint(_globre(br'a/**/b')) a/(?:.*/)?b >>> bprint(_globre(br'[a*?!^][^b][!c]')) [a*?!^][\^b][^c] >>> bprint(_globre(br'{a,b}')) (?:a|b) >>> bprint(_globre(br'.\*\?')) \.\*\? """ i, n = 0, len(pat) res = "" group = 0 escape = util.re.escape def peek(): return i < n and pat[i : i + 1] while i < n: c = pat[i : i + 1] i += 1 if c not in "*?[{},\\": res += escape(c) elif c == "*": if peek() == "*": i += 1 if peek() == "/": i += 1 res += "(?:.*/)?" else: res += ".*" else: res += "[^/]*" elif c == "?": res += "." elif c == "[": j = i if j < n and pat[j : j + 1] in "!]": j += 1 while j < n and pat[j : j + 1] != "]": j += 1 if j >= n: res += "\\[" else: stuff = pat[i:j].replace("\\", "\\\\") i = j + 1 if stuff[0:1] == "!": stuff = "^" + stuff[1:] elif stuff[0:1] == "^": stuff = "\\" + stuff res = "%s[%s]" % (res, stuff) elif c == "{": group += 1 res += "(?:" elif c == "}" and group: res += ")" group -= 1 elif c == "," and group: res += "|" elif c == "\\": p = peek() if p: i += 1 res += escape(p) else: res += escape(c) else: res += escape(c) return res def _regex(kind, pat, globsuffix): """Convert a (normalized) pattern of any kind into a regular expression. globsuffix is appended to the regexp of globs.""" if not pat and kind in ("glob", "relpath"): return "" if kind == "re": return pat if kind in ("path", "relpath"): if pat == ".": return "" return util.re.escape(pat) + "(?:/|$)" if kind == "rootfilesin": if pat == ".": escaped = "" else: # Pattern is a directory name. escaped = util.re.escape(pat) + "/" # Anything after the pattern must be a non-directory. return escaped + "[^/]+$" if kind == "relglob": return "(?:|.*/)" + _globre(pat) + globsuffix if kind == "relre": if pat.startswith("^"): return pat return ".*" + pat return _globre(pat) + globsuffix def _buildmatch(ctx, kindpats, globsuffix, root): """Return regexp string and a matcher function for kindpats. globsuffix is appended to the regexp of globs.""" matchfuncs = [] subincludes, kindpats = _expandsubinclude(kindpats, root) if subincludes: submatchers = {} def matchsubinclude(f): for prefix, matcherargs in subincludes: if f.startswith(prefix): mf = submatchers.get(prefix) if mf is None: mf = match(*matcherargs) submatchers[prefix] = mf if mf(f[len(prefix) :]): return True return False matchfuncs.append(matchsubinclude) fset, kindpats = _expandsets(kindpats, ctx) if fset: matchfuncs.append(fset.__contains__) regex = "" if kindpats: regex, mf = _buildregexmatch(kindpats, globsuffix) matchfuncs.append(mf) if len(matchfuncs) == 1: return regex, matchfuncs[0] else: return regex, lambda f: any(mf(f) for mf in matchfuncs) def _buildregexmatch(kindpats, globsuffix): """Build a match function from a list of kinds and kindpats, return regexp string and a matcher function.""" try: regex = "(?:%s)" % "|".join( [_regex(k, p, globsuffix) for (k, p, s) in kindpats] ) if len(regex) > 20000: raise OverflowError return regex, _rematcher(regex) except OverflowError: # We're using a Python with a tiny regex engine and we # made it explode, so we'll divide the pattern list in two # until it works l = len(kindpats) if l < 2: raise regexa, a = _buildregexmatch(kindpats[: l // 2], globsuffix) regexb, b = _buildregexmatch(kindpats[l // 2 :], globsuffix) return regex, lambda s: a(s) or b(s) except re.error: for k, p, s in kindpats: try: _rematcher("(?:%s)" % _regex(k, p, globsuffix)) except re.error: if s: raise error.Abort(_("%s: invalid pattern (%s): %s") % (s, k, p)) else: raise error.Abort(_("invalid pattern (%s): %s") % (k, p)) raise error.Abort(_("invalid pattern")) def _patternrootsanddirs(kindpats): """Returns roots and directories corresponding to each pattern. This calculates the roots and directories exactly matching the patterns and returns a tuple of (roots, dirs) for each. It does not return other directories which may also need to be considered, like the parent directories. """ r = [] d = [] for kind, pat, source in kindpats: if kind == "glob": # find the non-glob prefix root = [] for p in pat.split("/"): if "[" in p or "{" in p or "*" in p or "?" in p: break root.append(p) r.append("/".join(root)) elif kind in ("relpath", "path"): if pat == ".": pat = "" r.append(pat) elif kind in ("rootfilesin",): if pat == ".": pat = "" d.append(pat) else: # relglob, re, relre r.append("") return r, d def _roots(kindpats): """Returns root directories to match recursively from the given patterns.""" roots, dirs = _patternrootsanddirs(kindpats) return roots def _rootsanddirs(kindpats): """Returns roots and exact directories from patterns. roots are directories to match recursively, whereas exact directories should be matched non-recursively. The returned (roots, dirs) tuple will also include directories that need to be implicitly considered as either, such as parent directories. >>> _rootsanddirs( ... [(b'glob', b'g/h/*', b''), (b'glob', b'g/h', b''), ... (b'glob', b'g*', b'')]) (['g/h', 'g/h', ''], ['', 'g']) >>> _rootsanddirs( ... [(b'rootfilesin', b'g/h', b''), (b'rootfilesin', b'', b'')]) ([], ['g/h', '', '', 'g']) >>> _rootsanddirs( ... [(b'relpath', b'r', b''), (b'path', b'p/p', b''), ... (b'path', b'', b'')]) (['r', 'p/p', ''], ['', 'p']) >>> _rootsanddirs( ... [(b'relglob', b'rg*', b''), (b're', b're/', b''), ... (b'relre', b'rr', b'')]) (['', '', ''], ['']) """ r, d = _patternrootsanddirs(kindpats) # Append the parents as non-recursive/exact directories, since they must be # scanned to get to either the roots or the other exact directories. d.extend(sorted(util.dirs(d))) d.extend(sorted(util.dirs(r))) return r, d def _explicitfiles(kindpats): """Returns the potential explicit filenames from the patterns. >>> _explicitfiles([(b'path', b'foo/bar', b'')]) ['foo/bar'] >>> _explicitfiles([(b'rootfilesin', b'foo/bar', b'')]) [] """ # Keep only the pattern kinds where one can specify filenames (vs only # directory names). filable = [kp for kp in kindpats if kp[0] not in ("rootfilesin",)] return _roots(filable) def _prefix(kindpats): """Whether all the patterns match a prefix (i.e. recursively)""" for kind, pat, source in kindpats: if kind not in ("path", "relpath"): return False return True _commentre = None def readpatternfile(filepath, warn, sourceinfo=False): """parse a pattern file, returning a list of patterns. These patterns should be given to compile() to be validated and converted into a match function. trailing white space is dropped. the escape character is backslash. comments start with #. empty lines are skipped. lines can be of the following formats: syntax: regexp # defaults following lines to non-rooted regexps syntax: glob # defaults following lines to non-rooted globs re:pattern # non-rooted regular expression glob:pattern # non-rooted glob pattern # pattern of the current default type if sourceinfo is set, returns a list of tuples: (pattern, lineno, originalline). This is useful to debug ignore patterns. """ syntaxes = { "re": "relre:", "regexp": "relre:", "glob": "relglob:", "include": "include", "subinclude": "subinclude", } syntax = "relre:" patterns = [] fp = open(filepath, "rb") for lineno, line in enumerate(util.iterfile(fp), start=1): if "#" in line: global _commentre if not _commentre: _commentre = util.re.compile(br"((?:^|[^\\])(?:\\\\)*)#.*") # remove comments prefixed by an even number of escapes m = _commentre.search(line) if m: line = line[: m.end(1)] # fixup properly escaped comments that survived the above line = line.replace("\\#", "#") line = line.rstrip() if not line: continue if line.startswith("syntax:"): s = line[7:].strip() try: syntax = syntaxes[s] except KeyError: if warn: warn(_("%s: ignoring invalid syntax '%s'\n") % (filepath, s)) continue linesyntax = syntax for s, rels in pycompat.iteritems(syntaxes): if line.startswith(rels): linesyntax = rels line = line[len(rels) :] break elif line.startswith(s + ":"): linesyntax = rels line = line[len(s) + 1 :] break if sourceinfo: patterns.append((linesyntax + line, lineno, line)) else: patterns.append(linesyntax + line) fp.close() return patterns _usetreematcher = True def init(ui): global _usetreematcher _usetreematcher = ui.configbool("experimental", "treematcher")
Java
import numpy as np from OpenGL.GL import * from OpenGL.GLU import * import time import freenect import calibkinect import pykinectwindow as wxwindow # I probably need more help with these! try: TEXTURE_TARGET = GL_TEXTURE_RECTANGLE except: TEXTURE_TARGET = GL_TEXTURE_RECTANGLE_ARB if not 'win' in globals(): win = wxwindow.Window(size=(640, 480)) def refresh(): win.Refresh() print type(win) if not 'rotangles' in globals(): rotangles = [0,0] if not 'zoomdist' in globals(): zoomdist = 1 if not 'projpts' in globals(): projpts = (None, None) if not 'rgb' in globals(): rgb = None def create_texture(): global rgbtex rgbtex = glGenTextures(1) glBindTexture(TEXTURE_TARGET, rgbtex) glTexImage2D(TEXTURE_TARGET,0,GL_RGB,640,480,0,GL_RGB,GL_UNSIGNED_BYTE,None) if not '_mpos' in globals(): _mpos = None @win.eventx def EVT_LEFT_DOWN(event): global _mpos _mpos = event.Position @win.eventx def EVT_LEFT_UP(event): global _mpos _mpos = None @win.eventx def EVT_MOTION(event): global _mpos if event.LeftIsDown(): if _mpos: (x,y),(mx,my) = event.Position,_mpos rotangles[0] += y-my rotangles[1] += x-mx refresh() _mpos = event.Position @win.eventx def EVT_MOUSEWHEEL(event): global zoomdist dy = event.WheelRotation zoomdist *= np.power(0.95, -dy) refresh() clearcolor = [0,0,0,0] @win.event def on_draw(): if not 'rgbtex' in globals(): create_texture() xyz, uv = projpts if xyz is None: return if not rgb is None: rgb_ = (rgb.astype(np.float32) * 4 + 70).clip(0,255).astype(np.uint8) glBindTexture(TEXTURE_TARGET, rgbtex) glTexSubImage2D(TEXTURE_TARGET, 0, 0, 0, 640, 480, GL_RGB, GL_UNSIGNED_BYTE, rgb_); glClearColor(*clearcolor) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glEnable(GL_DEPTH_TEST) # flush that stack in case it's broken from earlier glPushMatrix() glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60, 4/3., 0.3, 200) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def mouse_rotate(xAngle, yAngle, zAngle): glRotatef(xAngle, 1.0, 0.0, 0.0); glRotatef(yAngle, 0.0, 1.0, 0.0); glRotatef(zAngle, 0.0, 0.0, 1.0); glScale(zoomdist,zoomdist,1) glTranslate(0, 0,-3.5) mouse_rotate(rotangles[0], rotangles[1], 0); glTranslate(0,0,1.5) #glTranslate(0, 0,-1) # Draw some axes if 0: glBegin(GL_LINES) glColor3f(1,0,0); glVertex3f(0,0,0); glVertex3f(1,0,0) glColor3f(0,1,0); glVertex3f(0,0,0); glVertex3f(0,1,0) glColor3f(0,0,1); glVertex3f(0,0,0); glVertex3f(0,0,1) glEnd() # We can either project the points ourselves, or embed it in the opengl matrix if 0: dec = 4 v,u = mgrid[:480,:640].astype(np.uint16) points = np.vstack((u[::dec,::dec].flatten(), v[::dec,::dec].flatten(), depth[::dec,::dec].flatten())).transpose() points = points[points[:,2]<2047,:] glMatrixMode(GL_TEXTURE) glLoadIdentity() glMultMatrixf(calibkinect.uv_matrix().transpose()) glMultMatrixf(calibkinect.xyz_matrix().transpose()) glTexCoordPointers(np.array(points)) glMatrixMode(GL_MODELVIEW) glPushMatrix() glMultMatrixf(calibkinect.xyz_matrix().transpose()) glVertexPointers(np.array(points)) else: glMatrixMode(GL_TEXTURE) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glPushMatrix() glVertexPointerf(xyz) glTexCoordPointerf(uv) # Draw the points glPointSize(2) glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_TEXTURE_COORD_ARRAY) glEnable(TEXTURE_TARGET) glColor3f(1,1,1) glDrawElementsui(GL_POINTS, np.array(range(xyz.shape[0]))) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_TEXTURE_COORD_ARRAY) glDisable(TEXTURE_TARGET) glPopMatrix() # if 0: inds = np.nonzero(xyz[:,2]>-0.55) glPointSize(10) glColor3f(0,1,1) glEnableClientState(GL_VERTEX_ARRAY) glDrawElementsui(GL_POINTS, np.array(inds)) glDisableClientState(GL_VERTEX_ARRAY) if 0: # Draw only the points in the near plane glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_BLEND) glColor(0.9,0.9,1.0,0.8) glPushMatrix() glTranslate(0,0,-0.55) glScale(0.6,0.6,1) glBegin(GL_QUADS) glVertex3f(-1,-1,0); glVertex3f( 1,-1,0); glVertex3f( 1, 1,0); glVertex3f(-1, 1,0); glEnd() glPopMatrix() glDisable(GL_BLEND) glPopMatrix() # A silly loop that shows you can busy the ipython thread while opengl runs def playcolors(): while 1: global clearcolor clearcolor = [np.random.random(),0,0,0] time.sleep(0.1) refresh() # Update the point cloud from the shell or from a background thread! def update(dt=0): global projpts, rgb, depth depth,_ = freenect.sync_get_depth() rgb,_ = freenect.sync_get_video() q = depth X,Y = np.meshgrid(range(640),range(480)) # YOU CAN CHANGE THIS AND RERUN THE PROGRAM! # Point cloud downsampling d = 4 projpts = calibkinect.depth2xyzuv(q[::d,::d],X[::d,::d],Y[::d,::d]) refresh() def update_join(): update_on() try: _thread.join() except: update_off() def update_on(): global _updating if not '_updating' in globals(): _updating = False if _updating: return _updating = True from threading import Thread global _thread def _run(): while _updating: update() _thread = Thread(target=_run) _thread.start() def update_off(): global _updating _updating = False # Get frames in a loop and display with opencv def loopcv(): import cv while 1: cv.ShowImage('hi',get_depth().astype(np.uint8)) cv.WaitKey(10) update() #update_on()
Java
/*#discipline{ margin-right: 8px; } .list li p{ font-size: 14px; } .list li h3{ font-size: 16px; margin-bottom: -4px; margin-top: 8px; } .pagination, .pag-nav{ width: 100%; position: relative; left: -25px; list-style: none; } .pag-nav{ margin-bottom:-29.5px; } .pag-nav li{ position: relative; z-index: 10; } .pagination{ box-sizing:border-box; } .img-wrap{ display:flex; justify-content:center; align-items:center; overflow:hidden; min-height: 127px; max-height: 127px; } .img-wrap img { flex-shrink:2; min-width:100%; min-height:100%; min-height: 127px; } .catagories{ display: inline-block; margin-top:8px; float:left; margin-right:20px; } .pagination li, .pag-nav li{ background:#eee; width: 19.5px; height: 19.5px; display: inline-block; padding:5px; text-align: center; } .pagination li.active, .pagination li.active:hover{ background:#1B8ABA; } .pagination li.active a{ color:white; } .pagination li:hover, .pag-nav li:hover{ background: rgba(0, 0, 0, 0.1); } .pag-nav li{ background:rgba(0,0,0,.05); } .pag-nav li:last-child{ float:right; } .list { font-family:sans-serif; margin:0; padding:20px 0 0; } .list > li { display:block; background-color: #eee; box-shadow: inset 0 1px 0 #fff; box-sizing: border-box; margin-right: 1.5%; margin-bottom: 1.5%; float: left; box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1); /* 480*/ } /* #programList .weak, #programList #found{ display: none !important; } */ .list > li .content{ padding:10px; height: 116px; /*border: 1px solid rgba(0, 0, 0, 0.05);*/ } @media (max-width: 480px) { .list > li{ width:100%; margin-right:0px; } .catagories{ margin-left: -8px; } } .avatar { max-width: 150px; } img { max-width: 100%; } h3 { font-size: 16px; margin:0 0 0.3rem; font-weight: normal; font-weight:bold; } p { margin:0; } input { border:solid 1px #ccc; border-radius: 5px; padding:7px 14px; margin-bottom:10px } input:focus { outline:none; border-color:#aaa; } .sort { padding:8px 30px; border-radius: 6px; border:none; display:inline-block; color:#fff; text-decoration: none; background-color: #DDE028; height:30px; } .sort:hover { text-decoration: none; background-color:#1b8aba; } .sort:focus { outline:none; } .sort:after { width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-bottom: 5px solid transparent; content:""; position: relative; top:-10px; right:-5px; } .sort.asc:after { width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-top: 5px solid #fff; content:""; position: relative; top:13px; right:-5px; } .sort.desc:after { width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-bottom: 5px solid #fff; content:""; position: relative; top:-10px; right:-5px; } #question{ text-align: center; min-height: 50vh; } #programs{ display: none; } #change{ color:#DDE028; text-decoration: underline; } /*MULTI SELECT STUFF*/ .list { font-family:sans-serif; margin:0; /*padding:20px 0 0;*/ } .list > li { display:block; background-color: #eee; /*padding:10px;*/ box-shadow: inset 0 1px 0 #fff; } .avatar { max-width: 150px; } img { max-width: 100%; } h3 { font-size: 16px; margin:0 0 0.3rem; font-weight: normal; font-weight:bold; } p { margin:0; } input { border:solid 1px #ccc; border-radius: 5px; padding:7px 14px; margin-bottom:10px } input:focus { outline:none; border-color:#aaa; } .sort { padding:8px 30px; border-radius: 6px; border:none; display:inline-block; color:#fff; text-decoration: none; background-color: #DDE028; height:30px; } .sort:hover { text-decoration: none; background-color:#E0D228; } .sort:focus { outline:none; } .sort:after { width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-bottom: 5px solid transparent; content:""; position: relative; top:-10px; right:-5px; } .sort.asc:after { width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-top: 5px solid #fff; content:""; position: relative; top:13px; right:-5px; } .sort.desc:after { width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-bottom: 5px solid #fff; content:""; position: relative; top:-10px; right:-5px; } #catagories, .search{ float:left !important; /*margin-top:1rem;*/ } .search{ margin-right:2rem; } #programList{ display: none; } #programList .content{ padding: .5rem 0rem .5rem 1rem !important; } #programList .content *{ display: inline-block; } #programList ul.list{ padding-left: 0rem !important; } #programList thead td{ padding: 0px 0px 0px 0px; } #programList td .sort{ border-radius: 0; width: 100%; box-sizing: border-box; padding-left: .75rem; border: 0PX; FONT-WEIGHT: 700; TEXT-TRANSFORM: UPPERCASE } #catagories{ margin-right:0px !important; } .ms-choice{ width: 307px; } .ms-drop.bottom ul{ width: 307px; box-sizing:border-box; padding-left:1rem; }
Java
using GitHubWin8Phone.Resources; namespace GitHubWin8Phone { /// <summary> /// Provides access to string resources. /// </summary> public class LocalizedStrings { private static AppResources _localizedResources = new AppResources(); public AppResources LocalizedResources { get { return _localizedResources; } } } }
Java
showWord(["np. ","Avoka, politisyen. Madanm prezidan Jean Bertrand Aristide." ])
Java
/* * Copyright (c) 2011-2012, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only 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. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/io.h> #include <linux/delay.h> #include <linux/mutex.h> #include <linux/err.h> #include <linux/errno.h> #include <linux/cpufreq.h> #include <linux/cpu.h> #include <linux/console.h> #include <linux/regulator/consumer.h> #include <asm/mach-types.h> #include <asm/cpu.h> #include <mach/board.h> #include <mach/msm_iomap.h> #include <mach/socinfo.h> #include <mach/msm-krait-l2-accessors.h> #include <mach/rpm-regulator.h> #include <mach/rpm-regulator-smd.h> #include <mach/msm_bus.h> #include <mach/msm_dcvs.h> #include "acpuclock.h" #include "acpuclock-krait.h" #include "avs.h" #ifdef CONFIG_SEC_DEBUG_DCVS_LOG #include <mach/sec_debug.h> #endif /* MUX source selects. */ #define PRI_SRC_SEL_SEC_SRC 0 #define PRI_SRC_SEL_HFPLL 1 #define PRI_SRC_SEL_HFPLL_DIV2 2 #define SECCLKAGD BIT(4) #ifdef CONFIG_SEC_DEBUG_SUBSYS int boost_uv; int speed_bin; int pvs_bin; #endif static DEFINE_MUTEX(driver_lock); static DEFINE_SPINLOCK(l2_lock); static struct drv_data { struct acpu_level *acpu_freq_tbl; const struct l2_level *l2_freq_tbl; struct scalable *scalable; struct hfpll_data *hfpll_data; u32 bus_perf_client; struct msm_bus_scale_pdata *bus_scale; int boost_uv; struct device *dev; } drv; static unsigned long acpuclk_krait_get_rate(int cpu) { return drv.scalable[cpu].cur_speed->khz; } /* Select a source on the primary MUX. */ static void set_pri_clk_src(struct scalable *sc, u32 pri_src_sel) { u32 regval; regval = get_l2_indirect_reg(sc->l2cpmr_iaddr); regval &= ~0x3; regval |= (pri_src_sel & 0x3); set_l2_indirect_reg(sc->l2cpmr_iaddr, regval); /* Wait for switch to complete. */ mb(); udelay(1); } /* Select a source on the secondary MUX. */ static void __cpuinit set_sec_clk_src(struct scalable *sc, u32 sec_src_sel) { u32 regval; /* 8064 Errata: disable sec_src clock gating during switch. */ regval = get_l2_indirect_reg(sc->l2cpmr_iaddr); regval |= SECCLKAGD; set_l2_indirect_reg(sc->l2cpmr_iaddr, regval); /* Program the MUX */ regval &= ~(0x3 << 2); regval |= ((sec_src_sel & 0x3) << 2); set_l2_indirect_reg(sc->l2cpmr_iaddr, regval); /* 8064 Errata: re-enabled sec_src clock gating. */ regval &= ~SECCLKAGD; set_l2_indirect_reg(sc->l2cpmr_iaddr, regval); /* Wait for switch to complete. */ mb(); udelay(1); } static int enable_rpm_vreg(struct vreg *vreg) { int ret = 0; if (vreg->rpm_reg) { ret = rpm_regulator_enable(vreg->rpm_reg); if (ret) dev_err(drv.dev, "%s regulator enable failed (%d)\n", vreg->name, ret); } return ret; } static void disable_rpm_vreg(struct vreg *vreg) { int rc; if (vreg->rpm_reg) { rc = rpm_regulator_disable(vreg->rpm_reg); if (rc) dev_err(drv.dev, "%s regulator disable failed (%d)\n", vreg->name, rc); } } /* Enable an already-configured HFPLL. */ static void hfpll_enable(struct scalable *sc, bool skip_regulators) { if (!skip_regulators) { /* Enable regulators required by the HFPLL. */ enable_rpm_vreg(&sc->vreg[VREG_HFPLL_A]); enable_rpm_vreg(&sc->vreg[VREG_HFPLL_B]); } /* Disable PLL bypass mode. */ writel_relaxed(0x2, sc->hfpll_base + drv.hfpll_data->mode_offset); /* * H/W requires a 5us delay between disabling the bypass and * de-asserting the reset. Delay 10us just to be safe. */ mb(); udelay(10); /* De-assert active-low PLL reset. */ writel_relaxed(0x6, sc->hfpll_base + drv.hfpll_data->mode_offset); /* Wait for PLL to lock. */ mb(); udelay(60); /* Enable PLL output. */ writel_relaxed(0x7, sc->hfpll_base + drv.hfpll_data->mode_offset); } /* Disable a HFPLL for power-savings or while it's being reprogrammed. */ static void hfpll_disable(struct scalable *sc, bool skip_regulators) { /* * Disable the PLL output, disable test mode, enable the bypass mode, * and assert the reset. */ writel_relaxed(0, sc->hfpll_base + drv.hfpll_data->mode_offset); if (!skip_regulators) { /* Remove voltage votes required by the HFPLL. */ disable_rpm_vreg(&sc->vreg[VREG_HFPLL_B]); disable_rpm_vreg(&sc->vreg[VREG_HFPLL_A]); } } /* Program the HFPLL rate. Assumes HFPLL is already disabled. */ static void hfpll_set_rate(struct scalable *sc, const struct core_speed *tgt_s) { void __iomem *base = sc->hfpll_base; u32 regval; writel_relaxed(tgt_s->pll_l_val, base + drv.hfpll_data->l_offset); if (drv.hfpll_data->has_user_reg) { regval = readl_relaxed(base + drv.hfpll_data->user_offset); if (tgt_s->pll_l_val <= drv.hfpll_data->low_vco_l_max) regval &= ~drv.hfpll_data->user_vco_mask; else regval |= drv.hfpll_data->user_vco_mask; writel_relaxed(regval, base + drv.hfpll_data->user_offset); } } /* Return the L2 speed that should be applied. */ static unsigned int compute_l2_level(struct scalable *sc, unsigned int vote_l) { unsigned int new_l = 0; int cpu; /* Find max L2 speed vote. */ sc->l2_vote = vote_l; for_each_present_cpu(cpu) new_l = max(new_l, drv.scalable[cpu].l2_vote); return new_l; } /* Update the bus bandwidth request. */ static void set_bus_bw(unsigned int bw) { int ret; /* Update bandwidth if request has changed. This may sleep. */ ret = msm_bus_scale_client_update_request(drv.bus_perf_client, bw); if (ret) dev_err(drv.dev, "bandwidth request failed (%d)\n", ret); } /* Set the CPU or L2 clock speed. */ static void set_speed(struct scalable *sc, const struct core_speed *tgt_s, bool skip_regulators) { const struct core_speed *strt_s = sc->cur_speed; if (strt_s == tgt_s) return; if (strt_s->src == HFPLL && tgt_s->src == HFPLL) { /* * Move to an always-on source running at a frequency * that does not require an elevated CPU voltage. */ set_pri_clk_src(sc, PRI_SRC_SEL_SEC_SRC); /* Re-program HFPLL. */ hfpll_disable(sc, true); hfpll_set_rate(sc, tgt_s); hfpll_enable(sc, true); /* Move to HFPLL. */ set_pri_clk_src(sc, tgt_s->pri_src_sel); } else if (strt_s->src == HFPLL && tgt_s->src != HFPLL) { set_pri_clk_src(sc, tgt_s->pri_src_sel); hfpll_disable(sc, skip_regulators); } else if (strt_s->src != HFPLL && tgt_s->src == HFPLL) { hfpll_set_rate(sc, tgt_s); hfpll_enable(sc, skip_regulators); set_pri_clk_src(sc, tgt_s->pri_src_sel); } sc->cur_speed = tgt_s; } struct vdd_data { int vdd_mem; int vdd_dig; int vdd_core; int ua_core; }; /* Apply any per-cpu voltage increases. */ static int increase_vdd(int cpu, struct vdd_data *data, enum setrate_reason reason) { struct scalable *sc = &drv.scalable[cpu]; int rc; /* * Increase vdd_mem active-set before vdd_dig. * vdd_mem should be >= vdd_dig. */ if (data->vdd_mem > sc->vreg[VREG_MEM].cur_vdd) { rc = rpm_regulator_set_voltage(sc->vreg[VREG_MEM].rpm_reg, data->vdd_mem, sc->vreg[VREG_MEM].max_vdd); if (rc) { dev_err(drv.dev, "vdd_mem (cpu%d) increase failed (%d)\n", cpu, rc); return rc; } sc->vreg[VREG_MEM].cur_vdd = data->vdd_mem; } /* Increase vdd_dig active-set vote. */ if (data->vdd_dig > sc->vreg[VREG_DIG].cur_vdd) { rc = rpm_regulator_set_voltage(sc->vreg[VREG_DIG].rpm_reg, data->vdd_dig, sc->vreg[VREG_DIG].max_vdd); if (rc) { dev_err(drv.dev, "vdd_dig (cpu%d) increase failed (%d)\n", cpu, rc); return rc; } sc->vreg[VREG_DIG].cur_vdd = data->vdd_dig; } /* Increase current request. */ if (data->ua_core > sc->vreg[VREG_CORE].cur_ua) { rc = regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg, data->ua_core); if (rc < 0) { dev_err(drv.dev, "regulator_set_optimum_mode(%s) failed (%d)\n", sc->vreg[VREG_CORE].name, rc); return rc; } sc->vreg[VREG_CORE].cur_ua = data->ua_core; } /* * Update per-CPU core voltage. Don't do this for the hotplug path for * which it should already be correct. Attempting to set it is bad * because we don't know what CPU we are running on at this point, but * the CPU regulator API requires we call it from the affected CPU. */ if (data->vdd_core > sc->vreg[VREG_CORE].cur_vdd && reason != SETRATE_HOTPLUG) { rc = regulator_set_voltage(sc->vreg[VREG_CORE].reg, data->vdd_core, sc->vreg[VREG_CORE].max_vdd); if (rc) { dev_err(drv.dev, "vdd_core (cpu%d) increase failed (%d)\n", cpu, rc); return rc; } sc->vreg[VREG_CORE].cur_vdd = data->vdd_core; } return 0; } /* Apply any per-cpu voltage decreases. */ static void decrease_vdd(int cpu, struct vdd_data *data, enum setrate_reason reason) { struct scalable *sc = &drv.scalable[cpu]; int ret; /* * Update per-CPU core voltage. This must be called on the CPU * that's being affected. Don't do this in the hotplug remove path, * where the rail is off and we're executing on the other CPU. */ if (data->vdd_core < sc->vreg[VREG_CORE].cur_vdd && reason != SETRATE_HOTPLUG) { ret = regulator_set_voltage(sc->vreg[VREG_CORE].reg, data->vdd_core, sc->vreg[VREG_CORE].max_vdd); if (ret) { dev_err(drv.dev, "vdd_core (cpu%d) decrease failed (%d)\n", cpu, ret); return; } sc->vreg[VREG_CORE].cur_vdd = data->vdd_core; } /* Decrease current request. */ if (data->ua_core < sc->vreg[VREG_CORE].cur_ua) { ret = regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg, data->ua_core); if (ret < 0) { dev_err(drv.dev, "regulator_set_optimum_mode(%s) failed (%d)\n", sc->vreg[VREG_CORE].name, ret); return; } sc->vreg[VREG_CORE].cur_ua = data->ua_core; } /* Decrease vdd_dig active-set vote. */ if (data->vdd_dig < sc->vreg[VREG_DIG].cur_vdd) { ret = rpm_regulator_set_voltage(sc->vreg[VREG_DIG].rpm_reg, data->vdd_dig, sc->vreg[VREG_DIG].max_vdd); if (ret) { dev_err(drv.dev, "vdd_dig (cpu%d) decrease failed (%d)\n", cpu, ret); return; } sc->vreg[VREG_DIG].cur_vdd = data->vdd_dig; } /* * Decrease vdd_mem active-set after vdd_dig. * vdd_mem should be >= vdd_dig. */ if (data->vdd_mem < sc->vreg[VREG_MEM].cur_vdd) { ret = rpm_regulator_set_voltage(sc->vreg[VREG_MEM].rpm_reg, data->vdd_mem, sc->vreg[VREG_MEM].max_vdd); if (ret) { dev_err(drv.dev, "vdd_mem (cpu%d) decrease failed (%d)\n", cpu, ret); return; } sc->vreg[VREG_MEM].cur_vdd = data->vdd_mem; } } static int calculate_vdd_mem(const struct acpu_level *tgt) { return drv.l2_freq_tbl[tgt->l2_level].vdd_mem; } static int get_src_dig(const struct core_speed *s) { const int *hfpll_vdd = drv.hfpll_data->vdd; const u32 low_vdd_l_max = drv.hfpll_data->low_vdd_l_max; const u32 nom_vdd_l_max = drv.hfpll_data->nom_vdd_l_max; if (s->src != HFPLL) return hfpll_vdd[HFPLL_VDD_NONE]; else if (s->pll_l_val > nom_vdd_l_max) return hfpll_vdd[HFPLL_VDD_HIGH]; else if (s->pll_l_val > low_vdd_l_max) return hfpll_vdd[HFPLL_VDD_NOM]; else return hfpll_vdd[HFPLL_VDD_LOW]; } static int calculate_vdd_dig(const struct acpu_level *tgt) { int l2_pll_vdd_dig, cpu_pll_vdd_dig; l2_pll_vdd_dig = get_src_dig(&drv.l2_freq_tbl[tgt->l2_level].speed); cpu_pll_vdd_dig = get_src_dig(&tgt->speed); return max(drv.l2_freq_tbl[tgt->l2_level].vdd_dig, max(l2_pll_vdd_dig, cpu_pll_vdd_dig)); } static bool enable_boost = true; module_param_named(boost, enable_boost, bool, S_IRUGO | S_IWUSR); static int calculate_vdd_core(const struct acpu_level *tgt) { return tgt->vdd_core + (enable_boost ? drv.boost_uv : 0); } static DEFINE_MUTEX(l2_regulator_lock); static int l2_vreg_count; static int enable_l2_regulators(void) { int ret = 0; mutex_lock(&l2_regulator_lock); if (l2_vreg_count == 0) { ret = enable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_A]); if (ret) goto out; ret = enable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_B]); if (ret) { disable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_A]); goto out; } } l2_vreg_count++; out: mutex_unlock(&l2_regulator_lock); return ret; } static void disable_l2_regulators(void) { mutex_lock(&l2_regulator_lock); if (WARN(!l2_vreg_count, "L2 regulator votes are unbalanced!")) goto out; if (l2_vreg_count == 1) { disable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_B]); disable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_A]); } l2_vreg_count--; out: mutex_unlock(&l2_regulator_lock); } static int minus_vc; module_param_named( mclk, minus_vc, int, S_IRUGO | S_IWUSR | S_IWGRP ); /* Set the CPU's clock rate and adjust the L2 rate, voltage and BW requests. */ static int acpuclk_krait_set_rate(int cpu, unsigned long rate, enum setrate_reason reason) { const struct core_speed *strt_acpu_s, *tgt_acpu_s; const struct acpu_level *tgt; int tgt_l2_l; enum src_id prev_l2_src = NUM_SRC_ID; struct vdd_data vdd_data; bool skip_regulators; int rc = 0; if (cpu > num_possible_cpus()) return -EINVAL; if (reason == SETRATE_CPUFREQ || reason == SETRATE_HOTPLUG) mutex_lock(&driver_lock); strt_acpu_s = drv.scalable[cpu].cur_speed; /* Return early if rate didn't change. */ if (rate == strt_acpu_s->khz) goto out; /* Find target frequency. */ for (tgt = drv.acpu_freq_tbl; tgt->speed.khz != 0; tgt++) { if (tgt->speed.khz == rate) { tgt_acpu_s = &tgt->speed; break; } } if (tgt->speed.khz == 0) { rc = -EINVAL; goto out; } /* Calculate voltage requirements for the current CPU. */ vdd_data.vdd_mem = calculate_vdd_mem(tgt); vdd_data.vdd_dig = calculate_vdd_dig(tgt); vdd_data.vdd_core = calculate_vdd_core(tgt) + minus_vc; vdd_data.ua_core = tgt->ua_core; /* Disable AVS before voltage switch */ if (reason == SETRATE_CPUFREQ && drv.scalable[cpu].avs_enabled) { AVS_DISABLE(cpu); drv.scalable[cpu].avs_enabled = false; } /* Increase VDD levels if needed. */ if (reason == SETRATE_CPUFREQ || reason == SETRATE_HOTPLUG) { rc = increase_vdd(cpu, &vdd_data, reason); if (rc) goto out; prev_l2_src = drv.l2_freq_tbl[drv.scalable[cpu].l2_vote].speed.src; /* Vote for the L2 regulators here if necessary. */ if (drv.l2_freq_tbl[tgt->l2_level].speed.src == HFPLL) { rc = enable_l2_regulators(); if (rc) goto out; } } dev_dbg(drv.dev, "Switching from ACPU%d rate %lu KHz -> %lu KHz\n", cpu, strt_acpu_s->khz, tgt_acpu_s->khz); /* * If we are setting the rate as part of power collapse or in the resume * path after power collapse, skip the vote for the HFPLL regulators, * which are active-set-only votes that will be removed when apps enters * its sleep set. This is needed to avoid voting for regulators with * sleeping APIs from an atomic context. */ skip_regulators = (reason == SETRATE_PC); #ifdef CONFIG_SEC_DEBUG_DCVS_LOG sec_debug_dcvs_log(cpu, strt_acpu_s->khz, tgt_acpu_s->khz); #endif /* Set the new CPU speed. */ set_speed(&drv.scalable[cpu], tgt_acpu_s, skip_regulators); /* * Update the L2 vote and apply the rate change. A spinlock is * necessary to ensure L2 rate is calculated and set atomically * with the CPU frequency, even if acpuclk_krait_set_rate() is * called from an atomic context and the driver_lock mutex is not * acquired. */ spin_lock(&l2_lock); tgt_l2_l = compute_l2_level(&drv.scalable[cpu], tgt->l2_level); set_speed(&drv.scalable[L2], &drv.l2_freq_tbl[tgt_l2_l].speed, true); spin_unlock(&l2_lock); /* Nothing else to do for power collapse or SWFI. */ if (reason == SETRATE_PC || reason == SETRATE_SWFI) goto out; /* * Remove the vote for the L2 HFPLL regulators only if the L2 * was already on an HFPLL source. */ if (prev_l2_src == HFPLL) disable_l2_regulators(); /* Update bus bandwith request. */ set_bus_bw(drv.l2_freq_tbl[tgt_l2_l].bw_level); /* Drop VDD levels if we can. */ decrease_vdd(cpu, &vdd_data, reason); /* Re-enable AVS */ if (reason == SETRATE_CPUFREQ && tgt->avsdscr_setting) { AVS_ENABLE(cpu, tgt->avsdscr_setting); drv.scalable[cpu].avs_enabled = true; } dev_dbg(drv.dev, "ACPU%d speed change complete\n", cpu); out: if (reason == SETRATE_CPUFREQ || reason == SETRATE_HOTPLUG) mutex_unlock(&driver_lock); return rc; } static struct acpuclk_data acpuclk_krait_data = { .set_rate = acpuclk_krait_set_rate, .get_rate = acpuclk_krait_get_rate, }; /* Initialize a HFPLL at a given rate and enable it. */ static void __cpuinit hfpll_init(struct scalable *sc, const struct core_speed *tgt_s) { dev_dbg(drv.dev, "Initializing HFPLL%d\n", sc - drv.scalable); /* Disable the PLL for re-programming. */ hfpll_disable(sc, true); /* Configure PLL parameters for integer mode. */ writel_relaxed(drv.hfpll_data->config_val, sc->hfpll_base + drv.hfpll_data->config_offset); writel_relaxed(0, sc->hfpll_base + drv.hfpll_data->m_offset); writel_relaxed(1, sc->hfpll_base + drv.hfpll_data->n_offset); if (drv.hfpll_data->has_user_reg) writel_relaxed(drv.hfpll_data->user_val, sc->hfpll_base + drv.hfpll_data->user_offset); /* Program droop controller, if supported */ if (drv.hfpll_data->has_droop_ctl) writel_relaxed(drv.hfpll_data->droop_val, sc->hfpll_base + drv.hfpll_data->droop_offset); /* Set an initial PLL rate. */ hfpll_set_rate(sc, tgt_s); } static int __cpuinit rpm_regulator_init(struct scalable *sc, enum vregs vreg, int vdd, bool enable) { int ret; if (!sc->vreg[vreg].name) return 0; sc->vreg[vreg].rpm_reg = rpm_regulator_get(drv.dev, sc->vreg[vreg].name); if (IS_ERR(sc->vreg[vreg].rpm_reg)) { ret = PTR_ERR(sc->vreg[vreg].rpm_reg); dev_err(drv.dev, "rpm_regulator_get(%s) failed (%d)\n", sc->vreg[vreg].name, ret); goto err_get; } ret = rpm_regulator_set_voltage(sc->vreg[vreg].rpm_reg, vdd, sc->vreg[vreg].max_vdd); if (ret) { dev_err(drv.dev, "%s initialization failed (%d)\n", sc->vreg[vreg].name, ret); goto err_conf; } sc->vreg[vreg].cur_vdd = vdd; if (enable) { ret = enable_rpm_vreg(&sc->vreg[vreg]); if (ret) goto err_conf; } return 0; err_conf: rpm_regulator_put(sc->vreg[vreg].rpm_reg); err_get: return ret; } static void __cpuinit rpm_regulator_cleanup(struct scalable *sc, enum vregs vreg) { if (!sc->vreg[vreg].rpm_reg) return; disable_rpm_vreg(&sc->vreg[vreg]); rpm_regulator_put(sc->vreg[vreg].rpm_reg); } /* Voltage regulator initialization. */ static int __cpuinit regulator_init(struct scalable *sc, const struct acpu_level *acpu_level) { int ret, vdd_mem, vdd_dig, vdd_core; vdd_mem = calculate_vdd_mem(acpu_level); ret = rpm_regulator_init(sc, VREG_MEM, vdd_mem, true); if (ret) goto err_mem; vdd_dig = calculate_vdd_dig(acpu_level); ret = rpm_regulator_init(sc, VREG_DIG, vdd_dig, true); if (ret) goto err_dig; ret = rpm_regulator_init(sc, VREG_HFPLL_A, sc->vreg[VREG_HFPLL_A].max_vdd, false); if (ret) goto err_hfpll_a; ret = rpm_regulator_init(sc, VREG_HFPLL_B, sc->vreg[VREG_HFPLL_B].max_vdd, false); if (ret) goto err_hfpll_b; /* Setup Krait CPU regulators and initial core voltage. */ sc->vreg[VREG_CORE].reg = regulator_get(drv.dev, sc->vreg[VREG_CORE].name); if (IS_ERR(sc->vreg[VREG_CORE].reg)) { ret = PTR_ERR(sc->vreg[VREG_CORE].reg); dev_err(drv.dev, "regulator_get(%s) failed (%d)\n", sc->vreg[VREG_CORE].name, ret); goto err_core_get; } ret = regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg, acpu_level->ua_core); if (ret < 0) { dev_err(drv.dev, "regulator_set_optimum_mode(%s) failed (%d)\n", sc->vreg[VREG_CORE].name, ret); goto err_core_conf; } sc->vreg[VREG_CORE].cur_ua = acpu_level->ua_core; vdd_core = calculate_vdd_core(acpu_level); ret = regulator_set_voltage(sc->vreg[VREG_CORE].reg, vdd_core, sc->vreg[VREG_CORE].max_vdd); if (ret) { dev_err(drv.dev, "regulator_set_voltage(%s) (%d)\n", sc->vreg[VREG_CORE].name, ret); goto err_core_conf; } sc->vreg[VREG_CORE].cur_vdd = vdd_core; ret = regulator_enable(sc->vreg[VREG_CORE].reg); if (ret) { dev_err(drv.dev, "regulator_enable(%s) failed (%d)\n", sc->vreg[VREG_CORE].name, ret); goto err_core_conf; } /* * Increment the L2 HFPLL regulator refcount if _this_ CPU's frequency * requires a corresponding target L2 frequency that needs the L2 to * run off of an HFPLL. */ if (drv.l2_freq_tbl[acpu_level->l2_level].speed.src == HFPLL) l2_vreg_count++; return 0; err_core_conf: regulator_put(sc->vreg[VREG_CORE].reg); err_core_get: rpm_regulator_cleanup(sc, VREG_HFPLL_B); err_hfpll_b: rpm_regulator_cleanup(sc, VREG_HFPLL_A); err_hfpll_a: rpm_regulator_cleanup(sc, VREG_DIG); err_dig: rpm_regulator_cleanup(sc, VREG_MEM); err_mem: return ret; } static void __cpuinit regulator_cleanup(struct scalable *sc) { regulator_disable(sc->vreg[VREG_CORE].reg); regulator_put(sc->vreg[VREG_CORE].reg); rpm_regulator_cleanup(sc, VREG_HFPLL_B); rpm_regulator_cleanup(sc, VREG_HFPLL_A); rpm_regulator_cleanup(sc, VREG_DIG); rpm_regulator_cleanup(sc, VREG_MEM); } /* Set initial rate for a given core. */ static int __cpuinit init_clock_sources(struct scalable *sc, const struct core_speed *tgt_s) { u32 regval; void __iomem *aux_reg; /* Program AUX source input to the secondary MUX. */ if (sc->aux_clk_sel_phys) { aux_reg = ioremap(sc->aux_clk_sel_phys, 4); if (!aux_reg) return -ENOMEM; writel_relaxed(sc->aux_clk_sel, aux_reg); iounmap(aux_reg); } /* Switch away from the HFPLL while it's re-initialized. */ set_sec_clk_src(sc, sc->sec_clk_sel); set_pri_clk_src(sc, PRI_SRC_SEL_SEC_SRC); hfpll_init(sc, tgt_s); /* Set PRI_SRC_SEL_HFPLL_DIV2 divider to div-2. */ regval = get_l2_indirect_reg(sc->l2cpmr_iaddr); regval &= ~(0x3 << 6); set_l2_indirect_reg(sc->l2cpmr_iaddr, regval); /* Enable and switch to the target clock source. */ if (tgt_s->src == HFPLL) hfpll_enable(sc, false); set_pri_clk_src(sc, tgt_s->pri_src_sel); sc->cur_speed = tgt_s; return 0; } static void __cpuinit fill_cur_core_speed(struct core_speed *s, struct scalable *sc) { s->pri_src_sel = get_l2_indirect_reg(sc->l2cpmr_iaddr) & 0x3; s->pll_l_val = readl_relaxed(sc->hfpll_base + drv.hfpll_data->l_offset); } static bool __cpuinit speed_equal(const struct core_speed *s1, const struct core_speed *s2) { return (s1->pri_src_sel == s2->pri_src_sel && s1->pll_l_val == s2->pll_l_val); } static const struct acpu_level __cpuinit *find_cur_acpu_level(int cpu) { struct scalable *sc = &drv.scalable[cpu]; const struct acpu_level *l; struct core_speed cur_speed; fill_cur_core_speed(&cur_speed, sc); for (l = drv.acpu_freq_tbl; l->speed.khz != 0; l++) if (speed_equal(&l->speed, &cur_speed)) return l; return NULL; } static const struct l2_level __init *find_cur_l2_level(void) { struct scalable *sc = &drv.scalable[L2]; const struct l2_level *l; struct core_speed cur_speed; fill_cur_core_speed(&cur_speed, sc); for (l = drv.l2_freq_tbl; l->speed.khz != 0; l++) if (speed_equal(&l->speed, &cur_speed)) return l; return NULL; } static const struct acpu_level __cpuinit *find_min_acpu_level(void) { struct acpu_level *l; for (l = drv.acpu_freq_tbl; l->speed.khz != 0; l++) if (l->use_for_scaling) return l; return NULL; } static int __cpuinit per_cpu_init(int cpu) { struct scalable *sc = &drv.scalable[cpu]; const struct acpu_level *acpu_level; int ret; sc->hfpll_base = ioremap(sc->hfpll_phys_base, SZ_32); if (!sc->hfpll_base) { ret = -ENOMEM; goto err_ioremap; } acpu_level = find_cur_acpu_level(cpu); if (!acpu_level) { acpu_level = find_min_acpu_level(); if (!acpu_level) { ret = -ENODEV; goto err_table; } dev_dbg(drv.dev, "CPU%d is running at an unknown rate. Defaulting to %lu KHz.\n", cpu, acpu_level->speed.khz); } else { dev_dbg(drv.dev, "CPU%d is running at %lu KHz\n", cpu, acpu_level->speed.khz); } ret = regulator_init(sc, acpu_level); if (ret) goto err_regulators; ret = init_clock_sources(sc, &acpu_level->speed); if (ret) goto err_clocks; sc->l2_vote = acpu_level->l2_level; sc->initialized = true; return 0; err_clocks: regulator_cleanup(sc); err_regulators: err_table: iounmap(sc->hfpll_base); err_ioremap: return ret; } /* Register with bus driver. */ static void __init bus_init(const struct l2_level *l2_level) { int ret; drv.bus_perf_client = msm_bus_scale_register_client(drv.bus_scale); if (!drv.bus_perf_client) { dev_err(drv.dev, "unable to register bus client\n"); BUG(); } ret = msm_bus_scale_client_update_request(drv.bus_perf_client, l2_level->bw_level); if (ret) dev_err(drv.dev, "initial bandwidth req failed (%d)\n", ret); } #ifdef CONFIG_CPU_FREQ_MSM static struct cpufreq_frequency_table freq_table[NR_CPUS][35]; extern int console_batt_stat; static void __init cpufreq_table_init(void) { int cpu; for_each_possible_cpu(cpu) { int i, freq_cnt = 0; /* Construct the freq_table tables from acpu_freq_tbl. */ for (i = 0; drv.acpu_freq_tbl[i].speed.khz != 0 && freq_cnt < ARRAY_SIZE(*freq_table); i++) { if (drv.acpu_freq_tbl[i].use_for_scaling) { #ifdef CONFIG_SEC_FACTORY // if factory_condition, set the core freq limit. //QMCK if (console_set_on_cmdline && drv.acpu_freq_tbl[i].speed.khz > 1000000) { if(console_batt_stat == 1) { continue; } } //QMCK #endif freq_table[cpu][freq_cnt].index = freq_cnt; freq_table[cpu][freq_cnt].frequency = drv.acpu_freq_tbl[i].speed.khz; freq_cnt++; } } /* freq_table not big enough to store all usable freqs. */ BUG_ON(drv.acpu_freq_tbl[i].speed.khz != 0); freq_table[cpu][freq_cnt].index = freq_cnt; freq_table[cpu][freq_cnt].frequency = CPUFREQ_TABLE_END; dev_info(drv.dev, "CPU%d: %d frequencies supported\n", cpu, freq_cnt); /* Register table with CPUFreq. */ cpufreq_frequency_table_get_attr(freq_table[cpu], cpu); } } #else static void __init cpufreq_table_init(void) {} #endif static void __init dcvs_freq_init(void) { int i; for (i = 0; drv.acpu_freq_tbl[i].speed.khz != 0; i++) if (drv.acpu_freq_tbl[i].use_for_scaling) msm_dcvs_register_cpu_freq( drv.acpu_freq_tbl[i].speed.khz, drv.acpu_freq_tbl[i].vdd_core / 1000); } static int __cpuinit acpuclk_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) { static int prev_khz[NR_CPUS]; int rc, cpu = (int)hcpu; struct scalable *sc = &drv.scalable[cpu]; unsigned long hot_unplug_khz = acpuclk_krait_data.power_collapse_khz; switch (action & ~CPU_TASKS_FROZEN) { case CPU_DEAD: prev_khz[cpu] = acpuclk_krait_get_rate(cpu); /* Fall through. */ case CPU_UP_CANCELED: acpuclk_krait_set_rate(cpu, hot_unplug_khz, SETRATE_HOTPLUG); regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg, 0); break; case CPU_UP_PREPARE: if (!sc->initialized) { rc = per_cpu_init(cpu); if (rc) return NOTIFY_BAD; break; } if (WARN_ON(!prev_khz[cpu])) return NOTIFY_BAD; rc = regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg, sc->vreg[VREG_CORE].cur_ua); if (rc < 0) return NOTIFY_BAD; acpuclk_krait_set_rate(cpu, prev_khz[cpu], SETRATE_HOTPLUG); break; default: break; } return NOTIFY_OK; } static struct notifier_block __cpuinitdata acpuclk_cpu_notifier = { .notifier_call = acpuclk_cpu_callback, }; static const int krait_needs_vmin(void) { switch (read_cpuid_id()) { case 0x511F04D0: /* KR28M2A20 */ case 0x511F04D1: /* KR28M2A21 */ case 0x510F06F0: /* KR28M4A10 */ return 1; default: return 0; }; } static void krait_apply_vmin(struct acpu_level *tbl) { for (; tbl->speed.khz != 0; tbl++) { if (tbl->vdd_core < 1150000) tbl->vdd_core = 1150000; tbl->avsdscr_setting = 0; } } static int __init get_speed_bin(u32 pte_efuse) { uint32_t speed_bin; speed_bin = pte_efuse & 0xF; if (speed_bin == 0xF) speed_bin = (pte_efuse >> 4) & 0xF; if (speed_bin == 0xF) { speed_bin = 0; dev_warn(drv.dev, "SPEED BIN: Defaulting to %d\n", speed_bin); } else { dev_info(drv.dev, "SPEED BIN: %d\n", speed_bin); } return speed_bin; } static int __init get_pvs_bin(u32 pte_efuse) { uint32_t pvs_bin; pvs_bin = (pte_efuse >> 10) & 0x7; if (pvs_bin == 0x7) pvs_bin = (pte_efuse >> 13) & 0x7; if (pvs_bin == 0x7) { pvs_bin = 0; dev_warn(drv.dev, "ACPU PVS: Defaulting to %d\n", pvs_bin); } else { dev_info(drv.dev, "ACPU PVS: %d\n", pvs_bin); } return pvs_bin; } static struct pvs_table * __init select_freq_plan(u32 pte_efuse_phys, struct pvs_table (*pvs_tables)[NUM_PVS]) { void __iomem *pte_efuse; u32 pte_efuse_val, tbl_idx, bin_idx; pte_efuse = ioremap(pte_efuse_phys, 4); if (!pte_efuse) { dev_err(drv.dev, "Unable to map QFPROM base\n"); return NULL; } pte_efuse_val = readl_relaxed(pte_efuse); iounmap(pte_efuse); /* Select frequency tables. */ bin_idx = get_speed_bin(pte_efuse_val); tbl_idx = get_pvs_bin(pte_efuse_val); #ifdef CONFIG_SEC_DEBUG_SUBSYS speed_bin = bin_idx; pvs_bin = tbl_idx; #endif return &pvs_tables[bin_idx][tbl_idx]; } static void __init drv_data_init(struct device *dev, const struct acpuclk_krait_params *params) { struct pvs_table *pvs; drv.dev = dev; drv.scalable = kmemdup(params->scalable, params->scalable_size, GFP_KERNEL); BUG_ON(!drv.scalable); drv.hfpll_data = kmemdup(params->hfpll_data, sizeof(*drv.hfpll_data), GFP_KERNEL); BUG_ON(!drv.hfpll_data); drv.l2_freq_tbl = kmemdup(params->l2_freq_tbl, params->l2_freq_tbl_size, GFP_KERNEL); BUG_ON(!drv.l2_freq_tbl); drv.bus_scale = kmemdup(params->bus_scale, sizeof(*drv.bus_scale), GFP_KERNEL); BUG_ON(!drv.bus_scale); drv.bus_scale->usecase = kmemdup(drv.bus_scale->usecase, drv.bus_scale->num_usecases * sizeof(*drv.bus_scale->usecase), GFP_KERNEL); BUG_ON(!drv.bus_scale->usecase); pvs = select_freq_plan(params->pte_efuse_phys, params->pvs_tables); BUG_ON(!pvs->table); drv.acpu_freq_tbl = kmemdup(pvs->table, pvs->size, GFP_KERNEL); BUG_ON(!drv.acpu_freq_tbl); drv.boost_uv = pvs->boost_uv; #ifdef CONFIG_SEC_DEBUG_SUBSYS boost_uv = drv.boost_uv; #endif acpuclk_krait_data.power_collapse_khz = params->stby_khz; acpuclk_krait_data.wait_for_irq_khz = params->stby_khz; } static void __init hw_init(void) { struct scalable *l2 = &drv.scalable[L2]; const struct l2_level *l2_level; int cpu, rc; if (krait_needs_vmin()) krait_apply_vmin(drv.acpu_freq_tbl); l2->hfpll_base = ioremap(l2->hfpll_phys_base, SZ_32); BUG_ON(!l2->hfpll_base); rc = rpm_regulator_init(l2, VREG_HFPLL_A, l2->vreg[VREG_HFPLL_A].max_vdd, false); BUG_ON(rc); rc = rpm_regulator_init(l2, VREG_HFPLL_B, l2->vreg[VREG_HFPLL_B].max_vdd, false); BUG_ON(rc); l2_level = find_cur_l2_level(); if (!l2_level) { l2_level = drv.l2_freq_tbl; dev_dbg(drv.dev, "L2 is running at an unknown rate. Defaulting to %lu KHz.\n", l2_level->speed.khz); } else { dev_dbg(drv.dev, "L2 is running at %lu KHz\n", l2_level->speed.khz); } rc = init_clock_sources(l2, &l2_level->speed); BUG_ON(rc); for_each_online_cpu(cpu) { rc = per_cpu_init(cpu); BUG_ON(rc); } bus_init(l2_level); } int __init acpuclk_krait_init(struct device *dev, const struct acpuclk_krait_params *params) { drv_data_init(dev, params); hw_init(); cpufreq_table_init(); dcvs_freq_init(); acpuclk_register(&acpuclk_krait_data); register_hotcpu_notifier(&acpuclk_cpu_notifier); return 0; }
Java
package org.erc.qmm.mq; import java.util.EventListener; /** * The listener interface for receiving messageReaded events. * The class that is interested in processing a messageReaded * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addMessageReadedListener<code> method. When * the messageReaded event occurs, that object's appropriate * method is invoked. * * @see MessageReadedEvent */ public interface MessageReadedListener extends EventListener { /** * Message readed. * * @param message the message */ void messageReaded(JMQMessage message); }
Java
import re p = re.compile(r'(\w+) (\w+)(?P<sign>.*)', re.DOTALL) print re.DOTALL print "p.pattern:", p.pattern print "p.flags:", p.flags print "p.groups:", p.groups print "p.groupindex:", p.groupindex
Java
/* Copyright (c) 2012-2014, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only 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. */ #include <linux/slab.h> #include <linux/wait.h> #include <linux/sched.h> #include <linux/jiffies.h> #include <linux/uaccess.h> #include <linux/atomic.h> #include <linux/wait.h> #include <sound/apr_audio-v2.h> #include <linux/qdsp6v2/apr.h> #include <sound/q6adm-v2.h> #include <sound/q6audio-v2.h> #include <sound/q6afe-v2.h> #include <sound/hw_audio_log.h> #include "audio_acdb.h" #define TIMEOUT_MS 1000 #define RESET_COPP_ID 99 #define INVALID_COPP_ID 0xFF /* Used for inband payload copy, max size is 4k */ /* 2 is to account for module & param ID in payload */ #define ADM_GET_PARAMETER_LENGTH (4096 - APR_HDR_SIZE - 2 * sizeof(uint32_t)) #define ULL_SUPPORTED_SAMPLE_RATE 48000 enum { ADM_RX_AUDPROC_CAL, ADM_TX_AUDPROC_CAL, ADM_RX_AUDVOL_CAL, ADM_TX_AUDVOL_CAL, ADM_CUSTOM_TOP_CAL, ADM_RTAC, ADM_MAX_CAL_TYPES }; struct adm_ctl { void *apr; atomic_t copp_id[AFE_MAX_PORTS]; atomic_t copp_cnt[AFE_MAX_PORTS]; atomic_t copp_low_latency_id[AFE_MAX_PORTS]; atomic_t copp_low_latency_cnt[AFE_MAX_PORTS]; atomic_t copp_perf_mode[AFE_MAX_PORTS]; atomic_t copp_stat[AFE_MAX_PORTS]; wait_queue_head_t wait[AFE_MAX_PORTS]; struct acdb_cal_block mem_addr_audproc[MAX_AUDPROC_TYPES]; struct acdb_cal_block mem_addr_audvol[MAX_AUDPROC_TYPES]; atomic_t mem_map_cal_handles[ADM_MAX_CAL_TYPES]; atomic_t mem_map_cal_index; int set_custom_topology; int ec_ref_rx; }; static struct adm_ctl this_adm; struct adm_multi_ch_map { bool set_channel_map; char channel_mapping[PCM_FORMAT_MAX_NUM_CHANNEL]; }; static struct adm_multi_ch_map multi_ch_map = { false, {0, 0, 0, 0, 0, 0, 0, 0} }; static int adm_get_parameters[ADM_GET_PARAMETER_LENGTH]; int srs_trumedia_open(int port_id, int srs_tech_id, void *srs_params) { struct adm_cmd_set_pp_params_inband_v5 *adm_params = NULL; int ret = 0, sz = 0; int index; ad_logd("SRS - %s", __func__); switch (srs_tech_id) { case SRS_ID_GLOBAL: { struct srs_trumedia_params_GLOBAL *glb_params = NULL; sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) + sizeof(struct srs_trumedia_params_GLOBAL); adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed\n", __func__); return -ENOMEM; } adm_params->payload_size = sizeof(struct srs_trumedia_params_GLOBAL) + sizeof(struct adm_param_data_v5); adm_params->params.param_id = SRS_TRUMEDIA_PARAMS; adm_params->params.param_size = sizeof(struct srs_trumedia_params_GLOBAL); glb_params = (struct srs_trumedia_params_GLOBAL *) ((u8 *)adm_params + sizeof(struct adm_cmd_set_pp_params_inband_v5)); memcpy(glb_params, srs_params, sizeof(struct srs_trumedia_params_GLOBAL)); ad_logd("SRS - %s: Global params - 1 = %x, 2 = %x, 3 = %x, 4 = %x, 5 = %x, 6 = %x, 7 = %x, 8 = %x\n", __func__, (int)glb_params->v1, (int)glb_params->v2, (int)glb_params->v3, (int)glb_params->v4, (int)glb_params->v5, (int)glb_params->v6, (int)glb_params->v7, (int)glb_params->v8); break; } case SRS_ID_WOWHD: { struct srs_trumedia_params_WOWHD *whd_params = NULL; sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) + sizeof(struct srs_trumedia_params_WOWHD); adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed\n", __func__); return -ENOMEM; } adm_params->payload_size = sizeof(struct srs_trumedia_params_WOWHD) + sizeof(struct adm_param_data_v5); adm_params->params.param_id = SRS_TRUMEDIA_PARAMS_WOWHD; adm_params->params.param_size = sizeof(struct srs_trumedia_params_WOWHD); whd_params = (struct srs_trumedia_params_WOWHD *) ((u8 *)adm_params + sizeof(struct adm_cmd_set_pp_params_inband_v5)); memcpy(whd_params, srs_params, sizeof(struct srs_trumedia_params_WOWHD)); ad_logd("SRS - %s: WOWHD params - 1 = %x, 2 = %x, 3 = %x, 4 = %x, 5 = %x, 6 = %x, 7 = %x, 8 = %x, 9 = %x, 10 = %x, 11 = %x\n", __func__, (int)whd_params->v1, (int)whd_params->v2, (int)whd_params->v3, (int)whd_params->v4, (int)whd_params->v5, (int)whd_params->v6, (int)whd_params->v7, (int)whd_params->v8, (int)whd_params->v9, (int)whd_params->v10, (int)whd_params->v11); break; } case SRS_ID_CSHP: { struct srs_trumedia_params_CSHP *chp_params = NULL; sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) + sizeof(struct srs_trumedia_params_CSHP); adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed\n", __func__); return -ENOMEM; } adm_params->payload_size = sizeof(struct srs_trumedia_params_CSHP) + sizeof(struct adm_param_data_v5); adm_params->params.param_id = SRS_TRUMEDIA_PARAMS_CSHP; adm_params->params.param_size = sizeof(struct srs_trumedia_params_CSHP); chp_params = (struct srs_trumedia_params_CSHP *) ((u8 *)adm_params + sizeof(struct adm_cmd_set_pp_params_inband_v5)); memcpy(chp_params, srs_params, sizeof(struct srs_trumedia_params_CSHP)); ad_logd("SRS - %s: CSHP params - 1 = %x, 2 = %x, 3 = %x, 4 = %x, 5 = %x, 6 = %x, 7 = %x, 8 = %x, 9 = %x\n", __func__, (int)chp_params->v1, (int)chp_params->v2, (int)chp_params->v3, (int)chp_params->v4, (int)chp_params->v5, (int)chp_params->v6, (int)chp_params->v7, (int)chp_params->v8, (int)chp_params->v9); break; } case SRS_ID_HPF: { struct srs_trumedia_params_HPF *hpf_params = NULL; sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) + sizeof(struct srs_trumedia_params_HPF); adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed\n", __func__); return -ENOMEM; } adm_params->payload_size = sizeof(struct srs_trumedia_params_HPF) + sizeof(struct adm_param_data_v5); adm_params->params.param_id = SRS_TRUMEDIA_PARAMS_HPF; adm_params->params.param_size = sizeof(struct srs_trumedia_params_HPF); hpf_params = (struct srs_trumedia_params_HPF *) ((u8 *)adm_params + sizeof(struct adm_cmd_set_pp_params_inband_v5)); memcpy(hpf_params, srs_params, sizeof(struct srs_trumedia_params_HPF)); ad_logd("SRS - %s: HPF params - 1 = %x\n", __func__, (int)hpf_params->v1); break; } case SRS_ID_PEQ: { struct srs_trumedia_params_PEQ *peq_params = NULL; sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) + sizeof(struct srs_trumedia_params_PEQ); adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed\n", __func__); return -ENOMEM; } adm_params->payload_size = sizeof(struct srs_trumedia_params_PEQ) + sizeof(struct adm_param_data_v5); adm_params->params.param_id = SRS_TRUMEDIA_PARAMS_PEQ; adm_params->params.param_size = sizeof(struct srs_trumedia_params_PEQ); peq_params = (struct srs_trumedia_params_PEQ *) ((u8 *)adm_params + sizeof(struct adm_cmd_set_pp_params_inband_v5)); memcpy(peq_params, srs_params, sizeof(struct srs_trumedia_params_PEQ)); ad_logd("SRS - %s: PEQ params - 1 = %x 2 = %x, 3 = %x, 4 = %x\n", __func__, (int)peq_params->v1, (int)peq_params->v2, (int)peq_params->v3, (int)peq_params->v4); break; } case SRS_ID_HL: { struct srs_trumedia_params_HL *hl_params = NULL; sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) + sizeof(struct srs_trumedia_params_HL); adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed\n", __func__); return -ENOMEM; } adm_params->payload_size = sizeof(struct srs_trumedia_params_HL) + sizeof(struct adm_param_data_v5); adm_params->params.param_id = SRS_TRUMEDIA_PARAMS_HL; adm_params->params.param_size = sizeof(struct srs_trumedia_params_HL); hl_params = (struct srs_trumedia_params_HL *) ((u8 *)adm_params + sizeof(struct adm_cmd_set_pp_params_inband_v5)); memcpy(hl_params, srs_params, sizeof(struct srs_trumedia_params_HL)); ad_logd("SRS - %s: HL params - 1 = %x, 2 = %x, 3 = %x, 4 = %x, 5 = %x, 6 = %x, 7 = %x\n", __func__, (int)hl_params->v1, (int)hl_params->v2, (int)hl_params->v3, (int)hl_params->v4, (int)hl_params->v5, (int)hl_params->v6, (int)hl_params->v7); break; } default: goto fail_cmd; } adm_params->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); adm_params->hdr.pkt_size = sz; adm_params->hdr.src_svc = APR_SVC_ADM; adm_params->hdr.src_domain = APR_DOMAIN_APPS; adm_params->hdr.src_port = port_id; adm_params->hdr.dest_svc = APR_SVC_ADM; adm_params->hdr.dest_domain = APR_DOMAIN_ADSP; index = afe_get_port_index(port_id); if (index < 0 || index >= AFE_MAX_PORTS) { ad_loge("%s: invalid port idx %d portid %#x\n", __func__, index, port_id); ret = -EINVAL; goto fail_cmd; } adm_params->hdr.dest_port = atomic_read(&this_adm.copp_id[index]); adm_params->hdr.token = port_id; adm_params->hdr.opcode = ADM_CMD_SET_PP_PARAMS_V5; adm_params->payload_addr_lsw = 0; adm_params->payload_addr_msw = 0; adm_params->mem_map_handle = 0; adm_params->params.module_id = SRS_TRUMEDIA_MODULE_ID; adm_params->params.reserved = 0; ad_logd("SRS - %s: Command was sent now check Q6 - port id = %d, size %d, module id %x, param id %x.\n", __func__, adm_params->hdr.dest_port, adm_params->payload_size, adm_params->params.module_id, adm_params->params.param_id); ret = apr_send_pkt(this_adm.apr, (uint32_t *)adm_params); if (ret < 0) { ad_loge("SRS - %s: ADM enable for port %d failed\n", __func__, port_id); ret = -EINVAL; goto fail_cmd; } /* Wait for the callback with copp id */ ret = wait_event_timeout(this_adm.wait[index], 1, msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { ad_loge("%s: SRS set params timed out port = %d\n", __func__, port_id); ret = -EINVAL; goto fail_cmd; } fail_cmd: kfree(adm_params); return ret; } int adm_set_stereo_to_custom_stereo(int port_id, unsigned int session_id, char *params, uint32_t params_length) { struct adm_cmd_set_pspd_mtmx_strtr_params_v5 *adm_params = NULL; int sz, rc = 0, index = afe_get_port_index(port_id); ad_logd("%s\n", __func__); if (index < 0 || index >= AFE_MAX_PORTS) { ad_loge("%s: invalid port idx %d port_id %#x\n", __func__, index, port_id); return -EINVAL; } sz = sizeof(struct adm_cmd_set_pspd_mtmx_strtr_params_v5) + params_length; adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed\n", __func__); return -ENOMEM; } memcpy(((u8 *)adm_params + sizeof(struct adm_cmd_set_pspd_mtmx_strtr_params_v5)), params, params_length); adm_params->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); adm_params->hdr.pkt_size = sz; adm_params->hdr.src_svc = APR_SVC_ADM; adm_params->hdr.src_domain = APR_DOMAIN_APPS; adm_params->hdr.src_port = port_id; adm_params->hdr.dest_svc = APR_SVC_ADM; adm_params->hdr.dest_domain = APR_DOMAIN_ADSP; adm_params->hdr.dest_port = atomic_read(&this_adm.copp_id[index]); adm_params->hdr.token = port_id; adm_params->hdr.opcode = ADM_CMD_SET_PSPD_MTMX_STRTR_PARAMS_V5; adm_params->payload_addr_lsw = 0; adm_params->payload_addr_msw = 0; adm_params->mem_map_handle = 0; adm_params->payload_size = params_length; /* direction RX as 0 */ adm_params->direction = 0; /* session id for this cmd to be applied on */ adm_params->sessionid = session_id; /* valid COPP id for LPCM */ adm_params->deviceid = atomic_read(&this_adm.copp_id[index]); adm_params->reserved = 0; ad_logd("%s: deviceid %d, session_id %d, src_port %d, dest_port %d\n", __func__, adm_params->deviceid, adm_params->sessionid, adm_params->hdr.src_port, adm_params->hdr.dest_port); atomic_set(&this_adm.copp_stat[index], 0); rc = apr_send_pkt(this_adm.apr, (uint32_t *)adm_params); if (rc < 0) { ad_loge("%s: Set params failed port = %#x\n", __func__, port_id); rc = -EINVAL; goto set_stereo_to_custom_stereo_return; } /* Wait for the callback */ rc = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!rc) { ad_loge("%s: Set params timed out port = %#x\n", __func__, port_id); rc = -EINVAL; goto set_stereo_to_custom_stereo_return; } rc = 0; set_stereo_to_custom_stereo_return: kfree(adm_params); return rc; } int adm_dolby_dap_send_params(int port_id, char *params, uint32_t params_length) { struct adm_cmd_set_pp_params_v5 *adm_params = NULL; int sz, rc = 0, index = afe_get_port_index(port_id); ad_logd("%s\n", __func__); if (index < 0 || index >= AFE_MAX_PORTS) { ad_loge("%s: invalid port idx %d portid %#x\n", __func__, index, port_id); return -EINVAL; } sz = sizeof(struct adm_cmd_set_pp_params_v5) + params_length; adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed", __func__); return -ENOMEM; } memcpy(((u8 *)adm_params + sizeof(struct adm_cmd_set_pp_params_v5)), params, params_length); adm_params->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); adm_params->hdr.pkt_size = sz; adm_params->hdr.src_svc = APR_SVC_ADM; adm_params->hdr.src_domain = APR_DOMAIN_APPS; adm_params->hdr.src_port = port_id; adm_params->hdr.dest_svc = APR_SVC_ADM; adm_params->hdr.dest_domain = APR_DOMAIN_ADSP; adm_params->hdr.dest_port = atomic_read(&this_adm.copp_id[index]); adm_params->hdr.token = port_id; adm_params->hdr.opcode = ADM_CMD_SET_PP_PARAMS_V5; adm_params->payload_addr_lsw = 0; adm_params->payload_addr_msw = 0; adm_params->mem_map_handle = 0; adm_params->payload_size = params_length; atomic_set(&this_adm.copp_stat[index], 0); rc = apr_send_pkt(this_adm.apr, (uint32_t *)adm_params); if (rc < 0) { ad_loge("%s: Set params failed port = %#x\n", __func__, port_id); rc = -EINVAL; goto dolby_dap_send_param_return; } /* Wait for the callback */ rc = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!rc) { ad_loge("%s: Set params timed out port = %#x\n", __func__, port_id); rc = -EINVAL; goto dolby_dap_send_param_return; } rc = 0; dolby_dap_send_param_return: kfree(adm_params); return rc; } int adm_get_params(int port_id, uint32_t module_id, uint32_t param_id, uint32_t params_length, char *params) { struct adm_cmd_get_pp_params_v5 *adm_params = NULL; int sz, rc = 0, i = 0, index = afe_get_port_index(port_id); int *params_data = (int *)params; if (index < 0 || index >= AFE_MAX_PORTS) { ad_loge("%s: invalid port idx %d portid %#x\n", __func__, index, port_id); return -EINVAL; } sz = sizeof(struct adm_cmd_get_pp_params_v5) + params_length; adm_params = kzalloc(sz, GFP_KERNEL); if (!adm_params) { ad_loge("%s, adm params memory alloc failed", __func__); return -ENOMEM; } memcpy(((u8 *)adm_params + sizeof(struct adm_cmd_get_pp_params_v5)), params, params_length); adm_params->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); adm_params->hdr.pkt_size = sz; adm_params->hdr.src_svc = APR_SVC_ADM; adm_params->hdr.src_domain = APR_DOMAIN_APPS; adm_params->hdr.src_port = port_id; adm_params->hdr.dest_svc = APR_SVC_ADM; adm_params->hdr.dest_domain = APR_DOMAIN_ADSP; adm_params->hdr.dest_port = atomic_read(&this_adm.copp_id[index]); adm_params->hdr.token = port_id; adm_params->hdr.opcode = ADM_CMD_GET_PP_PARAMS_V5; adm_params->data_payload_addr_lsw = 0; adm_params->data_payload_addr_msw = 0; adm_params->mem_map_handle = 0; adm_params->module_id = module_id; adm_params->param_id = param_id; adm_params->param_max_size = params_length; adm_params->reserved = 0; atomic_set(&this_adm.copp_stat[index], 0); rc = apr_send_pkt(this_adm.apr, (uint32_t *)adm_params); if (rc < 0) { ad_loge("%s: Failed to Get Params on port %d\n", __func__, port_id); rc = -EINVAL; goto adm_get_param_return; } /* Wait for the callback with copp id */ rc = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!rc) { ad_loge("%s: get params timed out port = %d\n", __func__, port_id); rc = -EINVAL; goto adm_get_param_return; } if ((params_data) && (ARRAY_SIZE(adm_get_parameters) >= (1+adm_get_parameters[0])) && (params_length/sizeof(int) >= adm_get_parameters[0])) { for (i = 0; i < adm_get_parameters[0]; i++) params_data[i] = adm_get_parameters[1+i]; } else { pr_err("%s: Get param data not copied! get_param array size %zd, index %d, params array size %zd, index %d\n", __func__, ARRAY_SIZE(adm_get_parameters), (1+adm_get_parameters[0]), params_length/sizeof(int), adm_get_parameters[0]); } rc = 0; adm_get_param_return: kfree(adm_params); return rc; } static void adm_callback_debug_print(struct apr_client_data *data) { uint32_t *payload; payload = data->payload; if (data->payload_size >= 8) ad_logd("%s: code = 0x%x PL#0[%x], PL#1[%x], size = %d\n", __func__, data->opcode, payload[0], payload[1], data->payload_size); else if (data->payload_size >= 4) ad_logd("%s: code = 0x%x PL#0[%x], size = %d\n", __func__, data->opcode, payload[0], data->payload_size); else ad_logd("%s: code = 0x%x, size = %d\n", __func__, data->opcode, data->payload_size); } void adm_set_multi_ch_map(char *channel_map) { memcpy(multi_ch_map.channel_mapping, channel_map, PCM_FORMAT_MAX_NUM_CHANNEL); multi_ch_map.set_channel_map = true; } void adm_get_multi_ch_map(char *channel_map) { if (multi_ch_map.set_channel_map) { memcpy(channel_map, multi_ch_map.channel_mapping, PCM_FORMAT_MAX_NUM_CHANNEL); } } static int32_t adm_callback(struct apr_client_data *data, void *priv) { uint32_t *payload; int i, index; if (data == NULL) { ad_loge("%s: data paramter is null\n", __func__); return -EINVAL; } payload = data->payload; if (data->opcode == RESET_EVENTS) { ad_logd("adm_callback: Reset event is received: %d %d apr[%p]\n", data->reset_event, data->reset_proc, this_adm.apr); if (this_adm.apr) { apr_reset(this_adm.apr); for (i = 0; i < AFE_MAX_PORTS; i++) { atomic_set(&this_adm.copp_id[i], RESET_COPP_ID); atomic_set(&this_adm.copp_low_latency_id[i], RESET_COPP_ID); atomic_set(&this_adm.copp_cnt[i], 0); atomic_set(&this_adm.copp_low_latency_cnt[i], 0); atomic_set(&this_adm.copp_perf_mode[i], 0); atomic_set(&this_adm.copp_stat[i], 0); } this_adm.apr = NULL; reset_custom_topology_flags(); this_adm.set_custom_topology = 1; for (i = 0; i < ADM_MAX_CAL_TYPES; i++) atomic_set(&this_adm.mem_map_cal_handles[i], 0); rtac_clear_mapping(ADM_RTAC_CAL); } ad_logd("Resetting calibration blocks"); for (i = 0; i < MAX_AUDPROC_TYPES; i++) { /* Device calibration */ this_adm.mem_addr_audproc[i].cal_size = 0; this_adm.mem_addr_audproc[i].cal_kvaddr = 0; this_adm.mem_addr_audproc[i].cal_paddr = 0; /* Volume calibration */ this_adm.mem_addr_audvol[i].cal_size = 0; this_adm.mem_addr_audvol[i].cal_kvaddr = 0; this_adm.mem_addr_audvol[i].cal_paddr = 0; } return 0; } adm_callback_debug_print(data); if (data->payload_size) { index = q6audio_get_port_index(data->token); if (index < 0 || index >= AFE_MAX_PORTS) { ad_loge("%s: invalid port idx %d token %d\n", __func__, index, data->token); return 0; } if (data->opcode == APR_BASIC_RSP_RESULT) { ad_logd("APR_BASIC_RSP_RESULT id %x\n", payload[0]); if (payload[1] != 0) { ad_loge("%s: cmd = 0x%x returned error = 0x%x\n", __func__, payload[0], payload[1]); } switch (payload[0]) { case ADM_CMD_SET_PP_PARAMS_V5: ad_logd("%s: ADM_CMD_SET_PP_PARAMS_V5\n", __func__); if (rtac_make_adm_callback( payload, data->payload_size)) { break; } case ADM_CMD_DEVICE_CLOSE_V5: case ADM_CMD_SHARED_MEM_UNMAP_REGIONS: case ADM_CMD_MATRIX_MAP_ROUTINGS_V5: case ADM_CMD_ADD_TOPOLOGIES: ad_logd("%s: Basic callback received, wake up.\n", __func__); atomic_set(&this_adm.copp_stat[index], 1); wake_up(&this_adm.wait[index]); break; case ADM_CMD_SHARED_MEM_MAP_REGIONS: ad_logd("%s: ADM_CMD_SHARED_MEM_MAP_REGIONS\n", __func__); /* Should only come here if there is an APR */ /* error or malformed APR packet. Otherwise */ /* response will be returned as */ if (payload[1] != 0) { ad_loge("%s: ADM map error, resuming\n", __func__); atomic_set(&this_adm.copp_stat[index], 1); wake_up(&this_adm.wait[index]); } break; case ADM_CMD_GET_PP_PARAMS_V5: ad_logd("%s: ADM_CMD_GET_PP_PARAMS_V5\n", __func__); /* Should only come here if there is an APR */ /* error or malformed APR packet. Otherwise */ /* response will be returned as */ /* ADM_CMDRSP_GET_PP_PARAMS_V5 */ if (payload[1] != 0) { ad_loge("%s: ADM get param error = %d, resuming\n", __func__, payload[1]); rtac_make_adm_callback(payload, data->payload_size); } break; case ADM_CMD_SET_PSPD_MTMX_STRTR_PARAMS_V5: ad_logd("%s:ADM_CMD_SET_PSPD_MTMX_STRTR_PARAMS_V5\n", __func__); atomic_set(&this_adm.copp_stat[index], 1); wake_up(&this_adm.wait[index]); break; default: ad_loge("%s: Unknown Cmd: 0x%x\n", __func__, payload[0]); break; } return 0; } switch (data->opcode) { case ADM_CMDRSP_DEVICE_OPEN_V5: { struct adm_cmd_rsp_device_open_v5 *open = (struct adm_cmd_rsp_device_open_v5 *)data->payload; if (open->copp_id == INVALID_COPP_ID) { ad_loge("%s: invalid coppid rxed %d\n", __func__, open->copp_id); atomic_set(&this_adm.copp_stat[index], 1); wake_up(&this_adm.wait[index]); break; } if (atomic_read(&this_adm.copp_perf_mode[index])) { atomic_set(&this_adm.copp_low_latency_id[index], open->copp_id); } else { atomic_set(&this_adm.copp_id[index], open->copp_id); } atomic_set(&this_adm.copp_stat[index], 1); ad_logd("%s: coppid rxed=%d\n", __func__, open->copp_id); wake_up(&this_adm.wait[index]); } break; case ADM_CMDRSP_GET_PP_PARAMS_V5: ad_logd("%s: ADM_CMDRSP_GET_PP_PARAMS_V5\n", __func__); if (payload[0] != 0) ad_loge("%s: ADM_CMDRSP_GET_PP_PARAMS_V5 returned error = 0x%x\n", __func__, payload[0]); if (rtac_make_adm_callback(payload, data->payload_size)) break; if ((payload[0] == 0) && (data->payload_size > (4 * sizeof(*payload))) && (data->payload_size/sizeof(*payload)-4 >= payload[3]) && (ARRAY_SIZE(adm_get_parameters)-1 >= payload[3])) { adm_get_parameters[0] = payload[3]; pr_debug("%s: GET_PP PARAM:received parameter length: 0x%x\n", __func__, adm_get_parameters[0]); /* storing param size then params */ for (i = 0; i < payload[3]; i++) adm_get_parameters[1+i] = payload[4+i]; } else { adm_get_parameters[0] = -1; pr_err("%s: GET_PP_PARAMS failed, setting size to %d\n", __func__, adm_get_parameters[0]); } atomic_set(&this_adm.copp_stat[index], 1); wake_up(&this_adm.wait[index]); break; case ADM_CMDRSP_SHARED_MEM_MAP_REGIONS: ad_logd("%s: ADM_CMDRSP_SHARED_MEM_MAP_REGIONS\n", __func__); atomic_set(&this_adm.mem_map_cal_handles[ atomic_read(&this_adm.mem_map_cal_index)], *payload); atomic_set(&this_adm.copp_stat[index], 1); wake_up(&this_adm.wait[index]); break; default: ad_loge("%s: Unknown cmd:0x%x\n", __func__, data->opcode); break; } } return 0; } void send_adm_custom_topology(int port_id) { struct acdb_cal_block cal_block; struct cmd_set_topologies adm_top; int index; int result; int size = 4096; get_adm_custom_topology(&cal_block); if (cal_block.cal_size == 0) { ad_logd("%s: no cal to send addr= 0x%pa\n", __func__, &cal_block.cal_paddr); goto done; } index = afe_get_port_index(port_id); if (index < 0 || index >= AFE_MAX_PORTS) { ad_loge("%s: invalid port idx %d portid %#x\n", __func__, index, port_id); goto done; } if (this_adm.set_custom_topology) { /* specific index 4 for adm topology memory */ atomic_set(&this_adm.mem_map_cal_index, ADM_CUSTOM_TOP_CAL); /* Only call this once */ this_adm.set_custom_topology = 0; result = adm_memory_map_regions(port_id, &cal_block.cal_paddr, 0, &size, 1); if (result < 0) { ad_loge("%s: mmap did not work! addr = 0x%pa, size = %zd\n", __func__, &cal_block.cal_paddr, cal_block.cal_size); goto done; } } adm_top.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(20), APR_PKT_VER); adm_top.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(adm_top)); adm_top.hdr.src_svc = APR_SVC_ADM; adm_top.hdr.src_domain = APR_DOMAIN_APPS; adm_top.hdr.src_port = port_id; adm_top.hdr.dest_svc = APR_SVC_ADM; adm_top.hdr.dest_domain = APR_DOMAIN_ADSP; adm_top.hdr.dest_port = atomic_read(&this_adm.copp_id[index]); adm_top.hdr.token = port_id; adm_top.hdr.opcode = ADM_CMD_ADD_TOPOLOGIES; adm_top.payload_addr_lsw = lower_32_bits(cal_block.cal_paddr); adm_top.payload_addr_msw = upper_32_bits(cal_block.cal_paddr); adm_top.mem_map_handle = atomic_read(&this_adm.mem_map_cal_handles[ADM_CUSTOM_TOP_CAL]); adm_top.payload_size = cal_block.cal_size; atomic_set(&this_adm.copp_stat[index], 0); ad_logd("%s: Sending ADM_CMD_ADD_TOPOLOGIES payload = 0x%x, size = %d\n", __func__, adm_top.payload_addr_lsw, adm_top.payload_size); result = apr_send_pkt(this_adm.apr, (uint32_t *)&adm_top); if (result < 0) { ad_loge("%s: Set topologies failed port = 0x%x payload = 0x%pa\n", __func__, port_id, &cal_block.cal_paddr); goto done; } /* Wait for the callback */ result = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!result) { ad_loge("%s: Set topologies timed out port = 0x%x, payload = 0x%pa\n", __func__, port_id, &cal_block.cal_paddr); goto done; } done: return; } static int send_adm_cal_block(int port_id, struct acdb_cal_block *aud_cal, int perf_mode) { s32 result = 0; struct adm_cmd_set_pp_params_v5 adm_params; int index = afe_get_port_index(port_id); if (index < 0 || index >= AFE_MAX_PORTS) { ad_loge("%s: invalid port idx %d portid %#x\n", __func__, index, port_id); return 0; } ad_logd("%s: Port id %#x, index %d\n", __func__, port_id, index); if (!aud_cal || aud_cal->cal_size == 0) { ad_logd("%s: No ADM cal to send for port_id = %#x!\n", __func__, port_id); result = -EINVAL; goto done; } adm_params.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(20), APR_PKT_VER); adm_params.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(adm_params)); adm_params.hdr.src_svc = APR_SVC_ADM; adm_params.hdr.src_domain = APR_DOMAIN_APPS; adm_params.hdr.src_port = port_id; adm_params.hdr.dest_svc = APR_SVC_ADM; adm_params.hdr.dest_domain = APR_DOMAIN_ADSP; if (perf_mode == LEGACY_PCM_MODE) adm_params.hdr.dest_port = atomic_read(&this_adm.copp_id[index]); else adm_params.hdr.dest_port = atomic_read(&this_adm.copp_low_latency_id[index]); adm_params.hdr.token = port_id; adm_params.hdr.opcode = ADM_CMD_SET_PP_PARAMS_V5; adm_params.payload_addr_lsw = lower_32_bits(aud_cal->cal_paddr); adm_params.payload_addr_msw = upper_32_bits(aud_cal->cal_paddr); adm_params.mem_map_handle = atomic_read(&this_adm.mem_map_cal_handles[ atomic_read(&this_adm.mem_map_cal_index)]); adm_params.payload_size = aud_cal->cal_size; atomic_set(&this_adm.copp_stat[index], 0); ad_logd("%s: Sending SET_PARAMS payload = 0x%x, size = %d\n", __func__, adm_params.payload_addr_lsw, adm_params.payload_size); result = apr_send_pkt(this_adm.apr, (uint32_t *)&adm_params); if (result < 0) { ad_loge("%s: Set params failed port = %#x payload = 0x%pa\n", __func__, port_id, &aud_cal->cal_paddr); result = -EINVAL; goto done; } /* Wait for the callback */ result = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!result) { ad_loge("%s: Set params timed out port = %#x, payload = 0x%pa\n", __func__, port_id, &aud_cal->cal_paddr); result = -EINVAL; goto done; } result = 0; done: return result; } static void send_adm_cal(int port_id, int path, int perf_mode) { int result = 0; s32 acdb_path; struct acdb_cal_block aud_cal; int size; ad_logd("%s\n", __func__); /* Maps audio_dev_ctrl path definition to ACDB definition */ acdb_path = path - 1; if (acdb_path == TX_CAL) size = 4096 * 4; else size = 4096; ad_logd("%s: Sending audproc cal\n", __func__); get_audproc_cal(acdb_path, &aud_cal); /* map & cache buffers used */ atomic_set(&this_adm.mem_map_cal_index, acdb_path); if (((this_adm.mem_addr_audproc[acdb_path].cal_paddr != aud_cal.cal_paddr) && (aud_cal.cal_size > 0)) || (aud_cal.cal_size > this_adm.mem_addr_audproc[acdb_path].cal_size)) { if (this_adm.mem_addr_audproc[acdb_path].cal_paddr != 0) adm_memory_unmap_regions(port_id); result = adm_memory_map_regions(port_id, &aud_cal.cal_paddr, 0, &size, 1); if (result < 0) { ad_loge("ADM audproc mmap did not work! path = %d, addr = 0x%pa, size = %zd\n", acdb_path, &aud_cal.cal_paddr, aud_cal.cal_size); } else { this_adm.mem_addr_audproc[acdb_path].cal_paddr = aud_cal.cal_paddr; this_adm.mem_addr_audproc[acdb_path].cal_size = size; } } if (!send_adm_cal_block(port_id, &aud_cal, perf_mode)) ad_logd("%s: Audproc cal sent for port id: %#x, path %d\n", __func__, port_id, acdb_path); else ad_logd("%s: Audproc cal not sent for port id: %#x, path %d\n", __func__, port_id, acdb_path); ad_logd("%s: Sending audvol cal\n", __func__); get_audvol_cal(acdb_path, &aud_cal); /* map & cache buffers used */ atomic_set(&this_adm.mem_map_cal_index, (acdb_path + MAX_AUDPROC_TYPES)); if (((this_adm.mem_addr_audvol[acdb_path].cal_paddr != aud_cal.cal_paddr) && (aud_cal.cal_size > 0)) || (aud_cal.cal_size > this_adm.mem_addr_audvol[acdb_path].cal_size)) { if (this_adm.mem_addr_audvol[acdb_path].cal_paddr != 0) adm_memory_unmap_regions(port_id); result = adm_memory_map_regions(port_id, &aud_cal.cal_paddr, 0, &size, 1); if (result < 0) { ad_loge("ADM audvol mmap did not work! path = %d, addr = 0x%pa, size = %zd\n", acdb_path, &aud_cal.cal_paddr, aud_cal.cal_size); } else { this_adm.mem_addr_audvol[acdb_path].cal_paddr = aud_cal.cal_paddr; this_adm.mem_addr_audvol[acdb_path].cal_size = size; } } if (!send_adm_cal_block(port_id, &aud_cal, perf_mode)) ad_logd("%s: Audvol cal sent for port id: %#x, path %d\n", __func__, port_id, acdb_path); else ad_logd("%s: Audvol cal not sent for port id: %#x, path %d\n", __func__, port_id, acdb_path); } int adm_map_rtac_block(struct rtac_cal_block_data *cal_block) { int result = 0; ad_logd("%s\n", __func__); if (cal_block == NULL) { ad_loge("%s: cal_block is NULL!\n", __func__); result = -EINVAL; goto done; } if (cal_block->cal_data.paddr == 0) { ad_logd("%s: No address to map!\n", __func__); result = -EINVAL; goto done; } if (cal_block->map_data.map_size == 0) { ad_logd("%s: map size is 0!\n", __func__); result = -EINVAL; goto done; } /* valid port ID needed for callback use primary I2S */ atomic_set(&this_adm.mem_map_cal_index, ADM_RTAC); result = adm_memory_map_regions(PRIMARY_I2S_RX, &cal_block->cal_data.paddr, 0, &cal_block->map_data.map_size, 1); if (result < 0) { ad_loge("%s: RTAC mmap did not work! addr = 0x%pa, size = %d\n", __func__, &cal_block->cal_data.paddr, cal_block->map_data.map_size); goto done; } cal_block->map_data.map_handle = atomic_read( &this_adm.mem_map_cal_handles[ADM_RTAC]); done: return result; } int adm_unmap_rtac_block(uint32_t *mem_map_handle) { int result = 0; ad_logd("%s\n", __func__); if (mem_map_handle == NULL) { ad_logd("%s: Map handle is NULL, nothing to unmap\n", __func__); goto done; } if (*mem_map_handle == 0) { ad_logd("%s: Map handle is 0, nothing to unmap\n", __func__); goto done; } if (*mem_map_handle != atomic_read( &this_adm.mem_map_cal_handles[ADM_RTAC])) { ad_loge("%s: Map handles do not match! Unmapping RTAC, RTAC map 0x%x, ADM map 0x%x\n", __func__, *mem_map_handle, atomic_read( &this_adm.mem_map_cal_handles[ADM_RTAC])); /* if mismatch use handle passed in to unmap */ atomic_set(&this_adm.mem_map_cal_handles[ADM_RTAC], *mem_map_handle); } /* valid port ID needed for callback use primary I2S */ atomic_set(&this_adm.mem_map_cal_index, ADM_RTAC); result = adm_memory_unmap_regions(PRIMARY_I2S_RX); if (result < 0) { ad_logd("%s: adm_memory_unmap_regions failed, error %d\n", __func__, result); } else { atomic_set(&this_adm.mem_map_cal_handles[ADM_RTAC], 0); *mem_map_handle = 0; } done: return result; } int adm_unmap_cal_blocks(void) { int i; int result = 0; int result2 = 0; for (i = 0; i < ADM_MAX_CAL_TYPES; i++) { if (atomic_read(&this_adm.mem_map_cal_handles[i]) != 0) { if (i <= ADM_TX_AUDPROC_CAL) { this_adm.mem_addr_audproc[i].cal_paddr = 0; this_adm.mem_addr_audproc[i].cal_size = 0; } else if (i <= ADM_TX_AUDVOL_CAL) { this_adm.mem_addr_audvol [(i - ADM_RX_AUDVOL_CAL)].cal_paddr = 0; this_adm.mem_addr_audvol [(i - ADM_RX_AUDVOL_CAL)].cal_size = 0; } else if (i == ADM_CUSTOM_TOP_CAL) { this_adm.set_custom_topology = 1; } else { continue; } /* valid port ID needed for callback use primary I2S */ atomic_set(&this_adm.mem_map_cal_index, i); result2 = adm_memory_unmap_regions(PRIMARY_I2S_RX); if (result2 < 0) { ad_loge("%s: adm_memory_unmap_regions failed, err %d\n", __func__, result2); result = result2; } else { atomic_set(&this_adm.mem_map_cal_handles[i], 0); } } } return result; } int adm_connect_afe_port(int mode, int session_id, int port_id) { struct adm_cmd_connect_afe_port_v5 cmd; int ret = 0; int index; ad_logd("%s: port %d session id:%d mode:%d\n", __func__, port_id, session_id, mode); port_id = afe_convert_virtual_to_portid(port_id); if (afe_validate_port(port_id) < 0) { ad_loge("%s port idi[%d] is invalid\n", __func__, port_id); return -ENODEV; } if (this_adm.apr == NULL) { this_adm.apr = apr_register("ADSP", "ADM", adm_callback, 0xFFFFFFFF, &this_adm); if (this_adm.apr == NULL) { ad_loge("%s: Unable to register ADM\n", __func__); ret = -ENODEV; return ret; } rtac_set_adm_handle(this_adm.apr); } index = afe_get_port_index(port_id); ad_logd("%s: Port ID %#x, index %d\n", __func__, port_id, index); cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cmd.hdr.pkt_size = sizeof(cmd); cmd.hdr.src_svc = APR_SVC_ADM; cmd.hdr.src_domain = APR_DOMAIN_APPS; cmd.hdr.src_port = port_id; cmd.hdr.dest_svc = APR_SVC_ADM; cmd.hdr.dest_domain = APR_DOMAIN_ADSP; cmd.hdr.dest_port = port_id; cmd.hdr.token = port_id; cmd.hdr.opcode = ADM_CMD_CONNECT_AFE_PORT_V5; cmd.mode = mode; cmd.session_id = session_id; cmd.afe_port_id = port_id; atomic_set(&this_adm.copp_stat[index], 0); ret = apr_send_pkt(this_adm.apr, (uint32_t *)&cmd); if (ret < 0) { ad_loge("%s:ADM enable for port %#x failed\n", __func__, port_id); ret = -EINVAL; goto fail_cmd; } /* Wait for the callback with copp id */ ret = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { ad_loge("%s ADM connect AFE failed for port %#x\n", __func__, port_id); ret = -EINVAL; goto fail_cmd; } atomic_inc(&this_adm.copp_cnt[index]); return 0; fail_cmd: return ret; } int adm_open(int port_id, int path, int rate, int channel_mode, int topology, int perf_mode, uint16_t bits_per_sample) { struct adm_cmd_device_open_v5 open; int ret = 0; int index; int tmp_port = q6audio_get_port_id(port_id); ad_logd("%s: port %#x path:%d rate:%d mode:%d perf_mode:%d\n", __func__, port_id, path, rate, channel_mode, perf_mode); port_id = q6audio_convert_virtual_to_portid(port_id); if (q6audio_validate_port(port_id) < 0) { ad_loge("%s port idi[%#x] is invalid\n", __func__, port_id); return -ENODEV; } index = q6audio_get_port_index(port_id); ad_logd("%s: Port ID %#x, index %d\n", __func__, port_id, index); if (this_adm.apr == NULL) { this_adm.apr = apr_register("ADSP", "ADM", adm_callback, 0xFFFFFFFF, &this_adm); if (this_adm.apr == NULL) { ad_loge("%s: Unable to register ADM\n", __func__); ret = -ENODEV; return ret; } rtac_set_adm_handle(this_adm.apr); } if (perf_mode == LEGACY_PCM_MODE) { atomic_set(&this_adm.copp_perf_mode[index], 0); send_adm_custom_topology(port_id); } else { atomic_set(&this_adm.copp_perf_mode[index], 1); } /* Create a COPP if port id are not enabled */ if ((perf_mode == LEGACY_PCM_MODE && (atomic_read(&this_adm.copp_cnt[index]) == 0)) || (perf_mode != LEGACY_PCM_MODE && (atomic_read(&this_adm.copp_low_latency_cnt[index]) == 0))) { ad_logd("%s:opening ADM: perf_mode: %d\n", __func__, perf_mode); open.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); open.hdr.pkt_size = sizeof(open); open.hdr.src_svc = APR_SVC_ADM; open.hdr.src_domain = APR_DOMAIN_APPS; open.hdr.src_port = tmp_port; open.hdr.dest_svc = APR_SVC_ADM; open.hdr.dest_domain = APR_DOMAIN_ADSP; open.hdr.dest_port = tmp_port; open.hdr.token = port_id; open.hdr.opcode = ADM_CMD_DEVICE_OPEN_V5; if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE) open.flags = ADM_ULTRA_LOW_LATENCY_DEVICE_SESSION; else if (perf_mode == LOW_LATENCY_PCM_MODE) open.flags = ADM_LOW_LATENCY_DEVICE_SESSION; else open.flags = ADM_LEGACY_DEVICE_SESSION; open.mode_of_operation = path; open.endpoint_id_1 = tmp_port; if (this_adm.ec_ref_rx == -1) { open.endpoint_id_2 = 0xFFFF; } else if (this_adm.ec_ref_rx && (path != 1)) { open.endpoint_id_2 = this_adm.ec_ref_rx; this_adm.ec_ref_rx = -1; } open.topology_id = topology; if ((open.topology_id == VPM_TX_SM_ECNS_COPP_TOPOLOGY) || (open.topology_id == VPM_TX_DM_FLUENCE_COPP_TOPOLOGY) || (open.topology_id == VPM_TX_DM_RFECNS_COPP_TOPOLOGY)) rate = 16000; if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE) { open.topology_id = NULL_COPP_TOPOLOGY; rate = ULL_SUPPORTED_SAMPLE_RATE; } else if (perf_mode == LOW_LATENCY_PCM_MODE) { if ((open.topology_id == DOLBY_ADM_COPP_TOPOLOGY_ID) || (open.topology_id == SRS_TRUMEDIA_TOPOLOGY_ID)) open.topology_id = DEFAULT_COPP_TOPOLOGY; } open.dev_num_channel = channel_mode & 0x00FF; open.bit_width = bits_per_sample; WARN_ON(perf_mode == ULTRA_LOW_LATENCY_PCM_MODE && (rate != 48000)); open.sample_rate = rate; memset(open.dev_channel_mapping, 0, 8); if (channel_mode == 1) { open.dev_channel_mapping[0] = PCM_CHANNEL_FC; } else if (channel_mode == 2) { open.dev_channel_mapping[0] = PCM_CHANNEL_FL; open.dev_channel_mapping[1] = PCM_CHANNEL_FR; } else if (channel_mode == 3) { open.dev_channel_mapping[0] = PCM_CHANNEL_FL; open.dev_channel_mapping[1] = PCM_CHANNEL_FR; open.dev_channel_mapping[2] = PCM_CHANNEL_FC; } else if (channel_mode == 4) { open.dev_channel_mapping[0] = PCM_CHANNEL_FL; open.dev_channel_mapping[1] = PCM_CHANNEL_FR; open.dev_channel_mapping[2] = PCM_CHANNEL_RB; open.dev_channel_mapping[3] = PCM_CHANNEL_LB; } else if (channel_mode == 5) { open.dev_channel_mapping[0] = PCM_CHANNEL_FL; open.dev_channel_mapping[1] = PCM_CHANNEL_FR; open.dev_channel_mapping[2] = PCM_CHANNEL_FC; open.dev_channel_mapping[3] = PCM_CHANNEL_LB; open.dev_channel_mapping[4] = PCM_CHANNEL_RB; } else if (channel_mode == 6) { open.dev_channel_mapping[0] = PCM_CHANNEL_FL; open.dev_channel_mapping[1] = PCM_CHANNEL_FR; open.dev_channel_mapping[2] = PCM_CHANNEL_LFE; open.dev_channel_mapping[3] = PCM_CHANNEL_FC; open.dev_channel_mapping[4] = PCM_CHANNEL_LS; open.dev_channel_mapping[5] = PCM_CHANNEL_RS; } else if (channel_mode == 8) { open.dev_channel_mapping[0] = PCM_CHANNEL_FL; open.dev_channel_mapping[1] = PCM_CHANNEL_FR; open.dev_channel_mapping[2] = PCM_CHANNEL_LFE; open.dev_channel_mapping[3] = PCM_CHANNEL_FC; open.dev_channel_mapping[4] = PCM_CHANNEL_LB; open.dev_channel_mapping[5] = PCM_CHANNEL_RB; open.dev_channel_mapping[6] = PCM_CHANNEL_FLC; open.dev_channel_mapping[7] = PCM_CHANNEL_FRC; } else { ad_loge("%s invalid num_chan %d\n", __func__, channel_mode); return -EINVAL; } if ((open.dev_num_channel > 2) && multi_ch_map.set_channel_map) memcpy(open.dev_channel_mapping, multi_ch_map.channel_mapping, PCM_FORMAT_MAX_NUM_CHANNEL); ad_logd("%s: port_id=%#x rate=%d topology_id=0x%X\n", __func__, open.endpoint_id_1, open.sample_rate, open.topology_id); atomic_set(&this_adm.copp_stat[index], 0); ret = apr_send_pkt(this_adm.apr, (uint32_t *)&open); if (ret < 0) { ad_loge("%s:ADM enable for port %#x for[%d] failed\n", __func__, tmp_port, port_id); ret = -EINVAL; goto fail_cmd; } /* Wait for the callback with copp id */ ret = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { ad_loge("%s ADM open failed for port %#x for [%d]\n", __func__, tmp_port, port_id); ret = -EINVAL; goto fail_cmd; } } if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE || perf_mode == LOW_LATENCY_PCM_MODE) { atomic_inc(&this_adm.copp_low_latency_cnt[index]); ad_logd("%s: index: %d coppid: %d", __func__, index, atomic_read(&this_adm.copp_low_latency_id[index])); } else { atomic_inc(&this_adm.copp_cnt[index]); ad_logd("%s: index: %d coppid: %d", __func__, index, atomic_read(&this_adm.copp_id[index])); } return 0; fail_cmd: return ret; } int adm_multi_ch_copp_open(int port_id, int path, int rate, int channel_mode, int topology, int perf_mode, uint16_t bits_per_sample) { int ret = 0; ret = adm_open(port_id, path, rate, channel_mode, topology, perf_mode, bits_per_sample); return ret; } int adm_matrix_map(int session_id, int path, int num_copps, unsigned int *port_id, int copp_id, int perf_mode) { struct adm_cmd_matrix_map_routings_v5 *route; struct adm_session_map_node_v5 *node; uint16_t *copps_list; int cmd_size = 0; int ret = 0, i = 0; void *payload = NULL; void *matrix_map = NULL; /* Assumes port_ids have already been validated during adm_open */ int index = q6audio_get_port_index(copp_id); if (index < 0 || index >= AFE_MAX_PORTS) { ad_loge("%s: invalid port idx %d token %d\n", __func__, index, copp_id); return 0; } cmd_size = (sizeof(struct adm_cmd_matrix_map_routings_v5) + sizeof(struct adm_session_map_node_v5) + (sizeof(uint32_t) * num_copps)); matrix_map = kzalloc(cmd_size, GFP_KERNEL); if (matrix_map == NULL) { ad_loge("%s: Mem alloc failed\n", __func__); ret = -EINVAL; return ret; } route = (struct adm_cmd_matrix_map_routings_v5 *)matrix_map; ad_logd("%s: session 0x%x path:%d num_copps:%d port_id[0]:%#x coppid[%d]\n", __func__, session_id, path, num_copps, port_id[0], copp_id); route->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); route->hdr.pkt_size = cmd_size; route->hdr.src_svc = 0; route->hdr.src_domain = APR_DOMAIN_APPS; route->hdr.src_port = copp_id; route->hdr.dest_svc = APR_SVC_ADM; route->hdr.dest_domain = APR_DOMAIN_ADSP; if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE || perf_mode == LOW_LATENCY_PCM_MODE) { route->hdr.dest_port = atomic_read(&this_adm.copp_low_latency_id[index]); } else { route->hdr.dest_port = atomic_read(&this_adm.copp_id[index]); } route->hdr.token = copp_id; route->hdr.opcode = ADM_CMD_MATRIX_MAP_ROUTINGS_V5; route->num_sessions = 1; switch (path) { case 0x1: route->matrix_id = ADM_MATRIX_ID_AUDIO_RX; break; case 0x2: case 0x3: route->matrix_id = ADM_MATRIX_ID_AUDIO_TX; break; default: ad_loge("%s: Wrong path set[%d]\n", __func__, path); break; } payload = ((u8 *)matrix_map + sizeof(struct adm_cmd_matrix_map_routings_v5)); node = (struct adm_session_map_node_v5 *)payload; node->session_id = session_id; node->num_copps = num_copps; payload = (u8 *)node + sizeof(struct adm_session_map_node_v5); copps_list = (uint16_t *)payload; for (i = 0; i < num_copps; i++) { int tmp; port_id[i] = q6audio_convert_virtual_to_portid(port_id[i]); tmp = q6audio_get_port_index(port_id[i]); if (tmp >= 0 && tmp < AFE_MAX_PORTS) { if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE || perf_mode == LOW_LATENCY_PCM_MODE) copps_list[i] = atomic_read(&this_adm.copp_low_latency_id[tmp]); else copps_list[i] = atomic_read(&this_adm.copp_id[tmp]); } else continue; ad_logd("%s: port_id[%#x]: %d, index: %d act coppid[0x%x]\n", __func__, i, port_id[i], tmp, copps_list[i]); } atomic_set(&this_adm.copp_stat[index], 0); ret = apr_send_pkt(this_adm.apr, (uint32_t *)matrix_map); if (ret < 0) { ad_loge("%s: ADM routing for port %#x failed\n", __func__, port_id[0]); ret = -EINVAL; goto fail_cmd; } ret = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { ad_loge("%s: ADM cmd Route failed for port %#x\n", __func__, port_id[0]); ret = -EINVAL; goto fail_cmd; } if (perf_mode != ULTRA_LOW_LATENCY_PCM_MODE) { for (i = 0; i < num_copps; i++) send_adm_cal(port_id[i], path, perf_mode); for (i = 0; i < num_copps; i++) { int tmp, copp_id; tmp = afe_get_port_index(port_id[i]); if (tmp >= 0 && tmp < AFE_MAX_PORTS) { if (perf_mode == LEGACY_PCM_MODE) copp_id = atomic_read( &this_adm.copp_id[tmp]); else copp_id = atomic_read( &this_adm.copp_low_latency_id[tmp]); rtac_add_adm_device(port_id[i], copp_id, path, session_id); ad_logd("%s, copp_id: %d\n", __func__, copp_id); } else ad_logd("%s: Invalid port index %d", __func__, tmp); } } fail_cmd: kfree(matrix_map); return ret; } int adm_memory_map_regions(int port_id, phys_addr_t *buf_add, uint32_t mempool_id, uint32_t *bufsz, uint32_t bufcnt) { struct avs_cmd_shared_mem_map_regions *mmap_regions = NULL; struct avs_shared_map_region_payload *mregions = NULL; void *mmap_region_cmd = NULL; void *payload = NULL; int ret = 0; int i = 0; int cmd_size = 0; int index = 0; ad_logd("%s\n", __func__); if (this_adm.apr == NULL) { this_adm.apr = apr_register("ADSP", "ADM", adm_callback, 0xFFFFFFFF, &this_adm); if (this_adm.apr == NULL) { ad_loge("%s: Unable to register ADM\n", __func__); ret = -ENODEV; return ret; } rtac_set_adm_handle(this_adm.apr); } port_id = q6audio_convert_virtual_to_portid(port_id); if (q6audio_validate_port(port_id) < 0) { ad_loge("%s port id[%#x] is invalid\n", __func__, port_id); return -ENODEV; } index = q6audio_get_port_index(port_id); cmd_size = sizeof(struct avs_cmd_shared_mem_map_regions) + sizeof(struct avs_shared_map_region_payload) * bufcnt; mmap_region_cmd = kzalloc(cmd_size, GFP_KERNEL); if (!mmap_region_cmd) { ad_loge("%s: allocate mmap_region_cmd failed\n", __func__); return -ENOMEM; } mmap_regions = (struct avs_cmd_shared_mem_map_regions *)mmap_region_cmd; mmap_regions->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mmap_regions->hdr.pkt_size = cmd_size; mmap_regions->hdr.src_port = 0; mmap_regions->hdr.dest_port = atomic_read(&this_adm.copp_id[index]); mmap_regions->hdr.token = port_id; mmap_regions->hdr.opcode = ADM_CMD_SHARED_MEM_MAP_REGIONS; mmap_regions->mem_pool_id = ADSP_MEMORY_MAP_SHMEM8_4K_POOL & 0x00ff; mmap_regions->num_regions = bufcnt & 0x00ff; mmap_regions->property_flag = 0x00; ad_logd("%s: map_regions->num_regions = %d\n", __func__, mmap_regions->num_regions); payload = ((u8 *) mmap_region_cmd + sizeof(struct avs_cmd_shared_mem_map_regions)); mregions = (struct avs_shared_map_region_payload *)payload; for (i = 0; i < bufcnt; i++) { mregions->shm_addr_lsw = lower_32_bits(buf_add[i]); mregions->shm_addr_msw = upper_32_bits(buf_add[i]); mregions->mem_size_bytes = bufsz[i]; ++mregions; } atomic_set(&this_adm.copp_stat[index], 0); ret = apr_send_pkt(this_adm.apr, (uint32_t *) mmap_region_cmd); if (ret < 0) { ad_loge("%s: mmap_regions op[0x%x]rc[%d]\n", __func__, mmap_regions->hdr.opcode, ret); ret = -EINVAL; goto fail_cmd; } ret = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), 5 * HZ); if (!ret) { ad_loge("%s: timeout. waited for memory_map\n", __func__); ret = -EINVAL; goto fail_cmd; } fail_cmd: kfree(mmap_region_cmd); return ret; } int adm_memory_unmap_regions(int32_t port_id) { struct avs_cmd_shared_mem_unmap_regions unmap_regions; int ret = 0; int index = 0; ad_logd("%s\n", __func__); if (this_adm.apr == NULL) { ad_loge("%s APR handle NULL\n", __func__); return -EINVAL; } port_id = q6audio_convert_virtual_to_portid(port_id); if (q6audio_validate_port(port_id) < 0) { ad_loge("%s port idi[%d] is invalid\n", __func__, port_id); return -ENODEV; } index = q6audio_get_port_index(port_id); unmap_regions.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); unmap_regions.hdr.pkt_size = sizeof(unmap_regions); unmap_regions.hdr.src_port = 0; unmap_regions.hdr.dest_port = atomic_read(&this_adm.copp_id[index]); unmap_regions.hdr.token = port_id; unmap_regions.hdr.opcode = ADM_CMD_SHARED_MEM_UNMAP_REGIONS; unmap_regions.mem_map_handle = atomic_read(&this_adm. mem_map_cal_handles[atomic_read(&this_adm.mem_map_cal_index)]); atomic_set(&this_adm.copp_stat[index], 0); ret = apr_send_pkt(this_adm.apr, (uint32_t *) &unmap_regions); if (ret < 0) { ad_loge("%s: mmap_regions op[0x%x]rc[%d]\n", __func__, unmap_regions.hdr.opcode, ret); ret = -EINVAL; goto fail_cmd; } ret = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), 5 * HZ); if (!ret) { ad_loge("%s: timeout. waited for memory_unmap index %d\n", __func__, index); ret = -EINVAL; goto fail_cmd; } else { ad_logd("%s: Unmap handle 0x%x succeeded\n", __func__, unmap_regions.mem_map_handle); } fail_cmd: return ret; } #ifdef CONFIG_RTAC int adm_get_copp_id(int port_index) { int copp_id; ad_logd("%s\n", __func__); if (port_index < 0) { ad_loge("%s: invalid port_id = %d\n", __func__, port_index); return -EINVAL; } copp_id = atomic_read(&this_adm.copp_id[port_index]); if (copp_id == RESET_COPP_ID) copp_id = atomic_read( &this_adm.copp_low_latency_id[port_index]); return copp_id; } int adm_get_lowlatency_copp_id(int port_index) { ad_logd("%s\n", __func__); if (port_index < 0) { ad_loge("%s: invalid port_id = %d\n", __func__, port_index); return -EINVAL; } return atomic_read(&this_adm.copp_low_latency_id[port_index]); } #else int adm_get_copp_id(int port_index) { return -EINVAL; } int adm_get_lowlatency_copp_id(int port_index) { return -EINVAL; } #endif /* #ifdef CONFIG_RTAC */ void adm_ec_ref_rx_id(int port_id) { this_adm.ec_ref_rx = port_id; ad_logd("%s ec_ref_rx:%d", __func__, this_adm.ec_ref_rx); } int adm_close(int port_id, int perf_mode) { struct apr_hdr close; int ret = 0; int index = 0; int copp_id = RESET_COPP_ID; port_id = q6audio_convert_virtual_to_portid(port_id); index = q6audio_get_port_index(port_id); if (q6audio_validate_port(port_id) < 0) return -EINVAL; ad_logd("%s port_id=%#x index %d perf_mode: %d\n", __func__, port_id, index, perf_mode); if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE || perf_mode == LOW_LATENCY_PCM_MODE) { if (!(atomic_read(&this_adm.copp_low_latency_cnt[index]))) { ad_loge("%s: copp count for port[%#x]is 0\n", __func__, port_id); goto fail_cmd; } atomic_dec(&this_adm.copp_low_latency_cnt[index]); } else { if (!(atomic_read(&this_adm.copp_cnt[index]))) { ad_loge("%s: copp count for port[%#x]is 0\n", __func__, port_id); goto fail_cmd; } atomic_dec(&this_adm.copp_cnt[index]); } if ((perf_mode == LEGACY_PCM_MODE && !(atomic_read(&this_adm.copp_cnt[index]))) || ((perf_mode != LEGACY_PCM_MODE) && !(atomic_read(&this_adm.copp_low_latency_cnt[index])))) { ad_logd("%s:Closing ADM: perf_mode: %d\n", __func__, perf_mode); close.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); close.pkt_size = sizeof(close); close.src_svc = APR_SVC_ADM; close.src_domain = APR_DOMAIN_APPS; close.src_port = port_id; close.dest_svc = APR_SVC_ADM; close.dest_domain = APR_DOMAIN_ADSP; if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE || perf_mode == LOW_LATENCY_PCM_MODE) close.dest_port = atomic_read(&this_adm.copp_low_latency_id[index]); else close.dest_port = atomic_read(&this_adm.copp_id[index]); close.token = port_id; close.opcode = ADM_CMD_DEVICE_CLOSE_V5; atomic_set(&this_adm.copp_stat[index], 0); if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE || perf_mode == LOW_LATENCY_PCM_MODE) { copp_id = atomic_read( &this_adm.copp_low_latency_id[index]); ad_logd("%s:coppid %d portid=%#x index=%d coppcnt=%d\n", __func__, copp_id, port_id, index, atomic_read( &this_adm.copp_low_latency_cnt[index])); atomic_set(&this_adm.copp_low_latency_id[index], RESET_COPP_ID); } else { copp_id = atomic_read(&this_adm.copp_id[index]); ad_logd("%s:coppid %d portid=%#x index=%d coppcnt=%d\n", __func__, copp_id, port_id, index, atomic_read(&this_adm.copp_cnt[index])); atomic_set(&this_adm.copp_id[index], RESET_COPP_ID); } ret = apr_send_pkt(this_adm.apr, (uint32_t *)&close); if (ret < 0) { ad_loge("%s ADM close failed\n", __func__); ret = -EINVAL; goto fail_cmd; } ret = wait_event_timeout(this_adm.wait[index], atomic_read(&this_adm.copp_stat[index]), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { ad_loge("%s: ADM cmd Route failed for port %#x\n", __func__, port_id); ret = -EINVAL; goto fail_cmd; } } if (perf_mode != ULTRA_LOW_LATENCY_PCM_MODE) { ad_logd("%s: remove adm device from rtac\n", __func__); rtac_remove_adm_device(port_id, copp_id); } fail_cmd: return ret; } static int __init adm_init(void) { int i = 0; this_adm.apr = NULL; this_adm.set_custom_topology = 1; this_adm.ec_ref_rx = -1; for (i = 0; i < AFE_MAX_PORTS; i++) { atomic_set(&this_adm.copp_id[i], RESET_COPP_ID); atomic_set(&this_adm.copp_low_latency_id[i], RESET_COPP_ID); atomic_set(&this_adm.copp_cnt[i], 0); atomic_set(&this_adm.copp_low_latency_cnt[i], 0); atomic_set(&this_adm.copp_stat[i], 0); atomic_set(&this_adm.copp_perf_mode[i], 0); init_waitqueue_head(&this_adm.wait[i]); } return 0; } device_initcall(adm_init);
Java
/* * PROJECT: ReactOS i8042 (ps/2 keyboard-mouse controller) driver * LICENSE: GPL - See COPYING in the top level directory * FILE: drivers/input/i8042prt/pnp.c * PURPOSE: IRP_MJ_PNP operations * PROGRAMMERS: Copyright 2006-2007 Hervé Poussineau (hpoussin@reactos.org) * Copyright 2008 Colin Finck (mail@colinfinck.de) */ /* INCLUDES ******************************************************************/ #include "i8042prt.h" #include <debug.h> /* FUNCTIONS *****************************************************************/ /* This is all pretty confusing. There's more than one way to * disable/enable the keyboard. You can send KBD_ENABLE to the * keyboard, and it will start scanning keys. Sending KBD_DISABLE * will disable the key scanning but also reset the parameters to * defaults. * * You can also send 0xAE to the controller for enabling the * keyboard clock line and 0xAD for disabling it. Then it'll * automatically get turned on at the next command. The last * way is by modifying the bit that drives the clock line in the * 'command byte' of the controller. This is almost, but not quite, * the same as the AE/AD thing. The difference can be used to detect * some really old broken keyboard controllers which I hope won't be * necessary. * * We change the command byte, sending KBD_ENABLE/DISABLE seems to confuse * some kvm switches. */ BOOLEAN i8042ChangeMode( IN PPORT_DEVICE_EXTENSION DeviceExtension, IN UCHAR FlagsToDisable, IN UCHAR FlagsToEnable) { UCHAR Value; NTSTATUS Status; if (!i8042Write(DeviceExtension, DeviceExtension->ControlPort, KBD_READ_MODE)) { WARN_(I8042PRT, "Can't read i8042 mode\n"); return FALSE; } Status = i8042ReadDataWait(DeviceExtension, &Value); if (!NT_SUCCESS(Status)) { WARN_(I8042PRT, "No response after read i8042 mode\n"); return FALSE; } Value &= ~FlagsToDisable; Value |= FlagsToEnable; if (!i8042Write(DeviceExtension, DeviceExtension->ControlPort, KBD_WRITE_MODE)) { WARN_(I8042PRT, "Can't set i8042 mode\n"); return FALSE; } if (!i8042Write(DeviceExtension, DeviceExtension->DataPort, Value)) { WARN_(I8042PRT, "Can't send i8042 mode\n"); return FALSE; } return TRUE; } static NTSTATUS i8042BasicDetect( IN PPORT_DEVICE_EXTENSION DeviceExtension) { NTSTATUS Status; ULONG ResendIterations; UCHAR Value = 0; /* Don't enable keyboard and mouse interrupts, disable keyboard/mouse */ i8042Flush(DeviceExtension); if (!i8042ChangeMode(DeviceExtension, CCB_KBD_INT_ENAB | CCB_MOUSE_INT_ENAB, CCB_KBD_DISAB | CCB_MOUSE_DISAB)) return STATUS_IO_DEVICE_ERROR; i8042Flush(DeviceExtension); /* Issue a CTRL_SELF_TEST command to check if this is really an i8042 controller */ ResendIterations = DeviceExtension->Settings.ResendIterations + 1; while (ResendIterations--) { if (!i8042Write(DeviceExtension, DeviceExtension->ControlPort, CTRL_SELF_TEST)) { WARN_(I8042PRT, "Writing CTRL_SELF_TEST command failed\n"); return STATUS_IO_TIMEOUT; } Status = i8042ReadDataWait(DeviceExtension, &Value); if (!NT_SUCCESS(Status)) { WARN_(I8042PRT, "Failed to read CTRL_SELF_TEST response, status 0x%08lx\n", Status); return Status; } if (Value == KBD_SELF_TEST_OK) { INFO_(I8042PRT, "CTRL_SELF_TEST completed successfully!\n"); break; } else if (Value == KBD_RESEND) { TRACE_(I8042PRT, "Resending...\n"); KeStallExecutionProcessor(50); } else { WARN_(I8042PRT, "Got 0x%02x instead of 0x55\n", Value); return STATUS_IO_DEVICE_ERROR; } } return STATUS_SUCCESS; } static VOID i8042DetectKeyboard( IN PPORT_DEVICE_EXTENSION DeviceExtension) { NTSTATUS Status; /* Set LEDs (that is not fatal if some error occurs) */ Status = i8042SynchWritePort(DeviceExtension, 0, KBD_CMD_SET_LEDS, TRUE); if (NT_SUCCESS(Status)) { Status = i8042SynchWritePort(DeviceExtension, 0, 0, TRUE); if (!NT_SUCCESS(Status)) { WARN_(I8042PRT, "Can't finish SET_LEDS (0x%08lx)\n", Status); return; } } else { WARN_(I8042PRT, "Warning: can't write SET_LEDS (0x%08lx)\n", Status); } /* Turn on translation and SF (Some machines don't reboot if SF is not set, see ReactOS bug CORE-1713) */ if (!i8042ChangeMode(DeviceExtension, 0, CCB_TRANSLATE | CCB_SYSTEM_FLAG)) return; /* * We used to send a KBD_LINE_TEST (0xAB) command, but on at least HP * Pavilion notebooks the response to that command was incorrect. * So now we just assume that a keyboard is attached. */ DeviceExtension->Flags |= KEYBOARD_PRESENT; INFO_(I8042PRT, "Keyboard detected\n"); } static VOID i8042DetectMouse( IN PPORT_DEVICE_EXTENSION DeviceExtension) { NTSTATUS Status; UCHAR Value; UCHAR ExpectedReply[] = { MOUSE_ACK, 0xAA }; UCHAR ReplyByte; /* First do a mouse line test */ if (i8042Write(DeviceExtension, DeviceExtension->ControlPort, MOUSE_LINE_TEST)) { Status = i8042ReadDataWait(DeviceExtension, &Value); if (!NT_SUCCESS(Status) || Value != 0) { WARN_(I8042PRT, "Mouse line test failed\n"); goto failure; } } /* Now reset the mouse */ i8042Flush(DeviceExtension); if(!i8042IsrWritePort(DeviceExtension, MOU_CMD_RESET, CTRL_WRITE_MOUSE)) { WARN_(I8042PRT, "Failed to write reset command to mouse\n"); goto failure; } /* The implementation of the "Mouse Reset" command differs much from chip to chip. By default, the first byte is an ACK, when the mouse is plugged in and working and NACK when it's not. On success, the next bytes are 0xAA and 0x00. But on some systems (like ECS K7S5A Pro, SiS 735 chipset), we always get an ACK and 0xAA. Only the last byte indicates, whether a mouse is plugged in. It is either sent or not, so there is no byte, which indicates a failure here. After the Mouse Reset command was issued, it usually takes some time until we get a response. So get the first two bytes in a loop. */ for (ReplyByte = 0; ReplyByte < sizeof(ExpectedReply) / sizeof(ExpectedReply[0]); ReplyByte++) { ULONG Counter = 500; do { Status = i8042ReadDataWait(DeviceExtension, &Value); if(!NT_SUCCESS(Status)) { /* Wait some time before trying again */ KeStallExecutionProcessor(50); } } while (Status == STATUS_IO_TIMEOUT && Counter--); if (!NT_SUCCESS(Status)) { WARN_(I8042PRT, "No ACK after mouse reset, status 0x%08lx\n", Status); goto failure; } else if (Value != ExpectedReply[ReplyByte]) { WARN_(I8042PRT, "Unexpected reply: 0x%02x (expected 0x%02x)\n", Value, ExpectedReply[ReplyByte]); goto failure; } } /* Finally get the third byte, but only try it one time (see above). Otherwise this takes around 45 seconds on a K7S5A Pro, when no mouse is plugged in. */ Status = i8042ReadDataWait(DeviceExtension, &Value); if(!NT_SUCCESS(Status)) { WARN_(I8042PRT, "Last byte was not transmitted after mouse reset, status 0x%08lx\n", Status); goto failure; } else if(Value != 0x00) { WARN_(I8042PRT, "Last byte after mouse reset was not 0x00, but 0x%02x\n", Value); goto failure; } DeviceExtension->Flags |= MOUSE_PRESENT; INFO_(I8042PRT, "Mouse detected\n"); return; failure: /* There is probably no mouse present. On some systems, the probe locks the entire keyboard controller. Let's try to get access to the keyboard again by sending a reset */ i8042Flush(DeviceExtension); i8042Write(DeviceExtension, DeviceExtension->ControlPort, CTRL_SELF_TEST); i8042ReadDataWait(DeviceExtension, &Value); i8042Flush(DeviceExtension); INFO_(I8042PRT, "Mouse not detected\n"); } static NTSTATUS i8042ConnectKeyboardInterrupt( IN PI8042_KEYBOARD_EXTENSION DeviceExtension) { PPORT_DEVICE_EXTENSION PortDeviceExtension; KIRQL DirqlMax; NTSTATUS Status; TRACE_(I8042PRT, "i8042ConnectKeyboardInterrupt()\n"); PortDeviceExtension = DeviceExtension->Common.PortDeviceExtension; DirqlMax = MAX( PortDeviceExtension->KeyboardInterrupt.Dirql, PortDeviceExtension->MouseInterrupt.Dirql); INFO_(I8042PRT, "KeyboardInterrupt.Vector %lu\n", PortDeviceExtension->KeyboardInterrupt.Vector); INFO_(I8042PRT, "KeyboardInterrupt.Dirql %lu\n", PortDeviceExtension->KeyboardInterrupt.Dirql); INFO_(I8042PRT, "KeyboardInterrupt.DirqlMax %lu\n", DirqlMax); INFO_(I8042PRT, "KeyboardInterrupt.InterruptMode %s\n", PortDeviceExtension->KeyboardInterrupt.InterruptMode == LevelSensitive ? "LevelSensitive" : "Latched"); INFO_(I8042PRT, "KeyboardInterrupt.ShareInterrupt %s\n", PortDeviceExtension->KeyboardInterrupt.ShareInterrupt ? "yes" : "no"); INFO_(I8042PRT, "KeyboardInterrupt.Affinity 0x%lx\n", PortDeviceExtension->KeyboardInterrupt.Affinity); Status = IoConnectInterrupt( &PortDeviceExtension->KeyboardInterrupt.Object, i8042KbdInterruptService, DeviceExtension, &PortDeviceExtension->SpinLock, PortDeviceExtension->KeyboardInterrupt.Vector, PortDeviceExtension->KeyboardInterrupt.Dirql, DirqlMax, PortDeviceExtension->KeyboardInterrupt.InterruptMode, PortDeviceExtension->KeyboardInterrupt.ShareInterrupt, PortDeviceExtension->KeyboardInterrupt.Affinity, FALSE); if (!NT_SUCCESS(Status)) { WARN_(I8042PRT, "IoConnectInterrupt() failed with status 0x%08x\n", Status); return Status; } if (DirqlMax == PortDeviceExtension->KeyboardInterrupt.Dirql) PortDeviceExtension->HighestDIRQLInterrupt = PortDeviceExtension->KeyboardInterrupt.Object; PortDeviceExtension->Flags |= KEYBOARD_INITIALIZED; return STATUS_SUCCESS; } static NTSTATUS i8042ConnectMouseInterrupt( IN PI8042_MOUSE_EXTENSION DeviceExtension) { PPORT_DEVICE_EXTENSION PortDeviceExtension; KIRQL DirqlMax; NTSTATUS Status; TRACE_(I8042PRT, "i8042ConnectMouseInterrupt()\n"); Status = i8042MouInitialize(DeviceExtension); if (!NT_SUCCESS(Status)) return Status; PortDeviceExtension = DeviceExtension->Common.PortDeviceExtension; DirqlMax = MAX( PortDeviceExtension->KeyboardInterrupt.Dirql, PortDeviceExtension->MouseInterrupt.Dirql); INFO_(I8042PRT, "MouseInterrupt.Vector %lu\n", PortDeviceExtension->MouseInterrupt.Vector); INFO_(I8042PRT, "MouseInterrupt.Dirql %lu\n", PortDeviceExtension->MouseInterrupt.Dirql); INFO_(I8042PRT, "MouseInterrupt.DirqlMax %lu\n", DirqlMax); INFO_(I8042PRT, "MouseInterrupt.InterruptMode %s\n", PortDeviceExtension->MouseInterrupt.InterruptMode == LevelSensitive ? "LevelSensitive" : "Latched"); INFO_(I8042PRT, "MouseInterrupt.ShareInterrupt %s\n", PortDeviceExtension->MouseInterrupt.ShareInterrupt ? "yes" : "no"); INFO_(I8042PRT, "MouseInterrupt.Affinity 0x%lx\n", PortDeviceExtension->MouseInterrupt.Affinity); Status = IoConnectInterrupt( &PortDeviceExtension->MouseInterrupt.Object, i8042MouInterruptService, DeviceExtension, &PortDeviceExtension->SpinLock, PortDeviceExtension->MouseInterrupt.Vector, PortDeviceExtension->MouseInterrupt.Dirql, DirqlMax, PortDeviceExtension->MouseInterrupt.InterruptMode, PortDeviceExtension->MouseInterrupt.ShareInterrupt, PortDeviceExtension->MouseInterrupt.Affinity, FALSE); if (!NT_SUCCESS(Status)) { WARN_(I8042PRT, "IoConnectInterrupt() failed with status 0x%08x\n", Status); goto cleanup; } if (DirqlMax == PortDeviceExtension->MouseInterrupt.Dirql) PortDeviceExtension->HighestDIRQLInterrupt = PortDeviceExtension->MouseInterrupt.Object; PortDeviceExtension->Flags |= MOUSE_INITIALIZED; Status = STATUS_SUCCESS; cleanup: if (!NT_SUCCESS(Status)) { PortDeviceExtension->Flags &= ~MOUSE_INITIALIZED; if (PortDeviceExtension->MouseInterrupt.Object) { IoDisconnectInterrupt(PortDeviceExtension->MouseInterrupt.Object); PortDeviceExtension->HighestDIRQLInterrupt = PortDeviceExtension->KeyboardInterrupt.Object; } } return Status; } static NTSTATUS EnableInterrupts( IN PPORT_DEVICE_EXTENSION DeviceExtension, IN UCHAR FlagsToDisable, IN UCHAR FlagsToEnable) { i8042Flush(DeviceExtension); if (!i8042ChangeMode(DeviceExtension, FlagsToDisable, FlagsToEnable)) return STATUS_UNSUCCESSFUL; return STATUS_SUCCESS; } static NTSTATUS StartProcedure( IN PPORT_DEVICE_EXTENSION DeviceExtension) { NTSTATUS Status = STATUS_UNSUCCESSFUL; UCHAR FlagsToDisable = 0; UCHAR FlagsToEnable = 0; KIRQL Irql; if (DeviceExtension->DataPort == 0) { /* Unable to do something at the moment */ return STATUS_SUCCESS; } if (!(DeviceExtension->Flags & (KEYBOARD_PRESENT | MOUSE_PRESENT))) { /* Try to detect them */ TRACE_(I8042PRT, "Check if the controller is really a i8042\n"); Status = i8042BasicDetect(DeviceExtension); if (!NT_SUCCESS(Status)) { WARN_(I8042PRT, "i8042BasicDetect() failed with status 0x%08lx\n", Status); return STATUS_UNSUCCESSFUL; } /* First detect the mouse and then the keyboard! If we do it the other way round, some systems throw away settings like the keyboard translation, when detecting the mouse. */ TRACE_(I8042PRT, "Detecting mouse\n"); i8042DetectMouse(DeviceExtension); TRACE_(I8042PRT, "Detecting keyboard\n"); i8042DetectKeyboard(DeviceExtension); INFO_(I8042PRT, "Keyboard present: %s\n", DeviceExtension->Flags & KEYBOARD_PRESENT ? "YES" : "NO"); INFO_(I8042PRT, "Mouse present : %s\n", DeviceExtension->Flags & MOUSE_PRESENT ? "YES" : "NO"); TRACE_(I8042PRT, "Enabling i8042 interrupts\n"); if (DeviceExtension->Flags & KEYBOARD_PRESENT) { FlagsToDisable |= CCB_KBD_DISAB; FlagsToEnable |= CCB_KBD_INT_ENAB; } if (DeviceExtension->Flags & MOUSE_PRESENT) { FlagsToDisable |= CCB_MOUSE_DISAB; FlagsToEnable |= CCB_MOUSE_INT_ENAB; } Status = EnableInterrupts(DeviceExtension, FlagsToDisable, FlagsToEnable); if (!NT_SUCCESS(Status)) { WARN_(I8042PRT, "EnableInterrupts failed: %lx\n", Status); DeviceExtension->Flags &= ~(KEYBOARD_PRESENT | MOUSE_PRESENT); return Status; } } /* Connect interrupts */ if (DeviceExtension->Flags & KEYBOARD_PRESENT && DeviceExtension->Flags & KEYBOARD_CONNECTED && DeviceExtension->Flags & KEYBOARD_STARTED && !(DeviceExtension->Flags & KEYBOARD_INITIALIZED)) { /* Keyboard is ready to be initialized */ Status = i8042ConnectKeyboardInterrupt(DeviceExtension->KeyboardExtension); if (NT_SUCCESS(Status)) { DeviceExtension->Flags |= KEYBOARD_INITIALIZED; } else { WARN_(I8042PRT, "i8042ConnectKeyboardInterrupt failed: %lx\n", Status); } } if (DeviceExtension->Flags & MOUSE_PRESENT && DeviceExtension->Flags & MOUSE_CONNECTED && DeviceExtension->Flags & MOUSE_STARTED && !(DeviceExtension->Flags & MOUSE_INITIALIZED)) { /* Mouse is ready to be initialized */ Status = i8042ConnectMouseInterrupt(DeviceExtension->MouseExtension); if (NT_SUCCESS(Status)) { DeviceExtension->Flags |= MOUSE_INITIALIZED; } else { WARN_(I8042PRT, "i8042ConnectMouseInterrupt failed: %lx\n", Status); } /* Start the mouse */ Irql = KeAcquireInterruptSpinLock(DeviceExtension->HighestDIRQLInterrupt); /* HACK: the mouse has already been reset in i8042DetectMouse. This second reset prevents some touchpads/mice from working (Dell D531, D600). See CORE-6901 */ if (!(i8042HwFlags & FL_INITHACK)) { i8042IsrWritePort(DeviceExtension, MOU_CMD_RESET, CTRL_WRITE_MOUSE); } KeReleaseInterruptSpinLock(DeviceExtension->HighestDIRQLInterrupt, Irql); } return Status; } static NTSTATUS i8042PnpStartDevice( IN PDEVICE_OBJECT DeviceObject, IN PCM_RESOURCE_LIST AllocatedResources, IN PCM_RESOURCE_LIST AllocatedResourcesTranslated) { PFDO_DEVICE_EXTENSION DeviceExtension; PPORT_DEVICE_EXTENSION PortDeviceExtension; PCM_PARTIAL_RESOURCE_DESCRIPTOR ResourceDescriptor, ResourceDescriptorTranslated; INTERRUPT_DATA InterruptData = { NULL }; BOOLEAN FoundDataPort = FALSE; BOOLEAN FoundControlPort = FALSE; BOOLEAN FoundIrq = FALSE; ULONG i; NTSTATUS Status; TRACE_(I8042PRT, "i8042PnpStartDevice(%p)\n", DeviceObject); DeviceExtension = (PFDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension; PortDeviceExtension = DeviceExtension->PortDeviceExtension; ASSERT(DeviceExtension->PnpState == dsStopped); if (!AllocatedResources) { WARN_(I8042PRT, "No allocated resources sent to driver\n"); return STATUS_INSUFFICIENT_RESOURCES; } if (AllocatedResources->Count != 1) { WARN_(I8042PRT, "Wrong number of allocated resources sent to driver\n"); return STATUS_INSUFFICIENT_RESOURCES; } if (AllocatedResources->List[0].PartialResourceList.Version != 1 || AllocatedResources->List[0].PartialResourceList.Revision != 1 || AllocatedResourcesTranslated->List[0].PartialResourceList.Version != 1 || AllocatedResourcesTranslated->List[0].PartialResourceList.Revision != 1) { WARN_(I8042PRT, "Revision mismatch: %u.%u != 1.1 or %u.%u != 1.1\n", AllocatedResources->List[0].PartialResourceList.Version, AllocatedResources->List[0].PartialResourceList.Revision, AllocatedResourcesTranslated->List[0].PartialResourceList.Version, AllocatedResourcesTranslated->List[0].PartialResourceList.Revision); return STATUS_REVISION_MISMATCH; } /* Get Irq and optionally control port and data port */ for (i = 0; i < AllocatedResources->List[0].PartialResourceList.Count; i++) { ResourceDescriptor = &AllocatedResources->List[0].PartialResourceList.PartialDescriptors[i]; ResourceDescriptorTranslated = &AllocatedResourcesTranslated->List[0].PartialResourceList.PartialDescriptors[i]; switch (ResourceDescriptor->Type) { case CmResourceTypePort: { if (ResourceDescriptor->u.Port.Length == 1) { /* We assume that the first resource will * be the control port and the second one * will be the data port... */ if (!FoundDataPort) { PortDeviceExtension->DataPort = ULongToPtr(ResourceDescriptor->u.Port.Start.u.LowPart); INFO_(I8042PRT, "Found data port: %p\n", PortDeviceExtension->DataPort); FoundDataPort = TRUE; } else if (!FoundControlPort) { PortDeviceExtension->ControlPort = ULongToPtr(ResourceDescriptor->u.Port.Start.u.LowPart); INFO_(I8042PRT, "Found control port: %p\n", PortDeviceExtension->ControlPort); FoundControlPort = TRUE; } else { /* FIXME: implement PS/2 Active Multiplexing */ ERR_(I8042PRT, "Unhandled I/O ranges provided: 0x%lx\n", ResourceDescriptor->u.Port.Length); } } else WARN_(I8042PRT, "Invalid I/O range length: 0x%lx\n", ResourceDescriptor->u.Port.Length); break; } case CmResourceTypeInterrupt: { if (FoundIrq) return STATUS_INVALID_PARAMETER; InterruptData.Dirql = (KIRQL)ResourceDescriptorTranslated->u.Interrupt.Level; InterruptData.Vector = ResourceDescriptorTranslated->u.Interrupt.Vector; InterruptData.Affinity = ResourceDescriptorTranslated->u.Interrupt.Affinity; if (ResourceDescriptorTranslated->Flags & CM_RESOURCE_INTERRUPT_LATCHED) InterruptData.InterruptMode = Latched; else InterruptData.InterruptMode = LevelSensitive; InterruptData.ShareInterrupt = (ResourceDescriptorTranslated->ShareDisposition == CmResourceShareShared); INFO_(I8042PRT, "Found irq resource: %lu\n", ResourceDescriptor->u.Interrupt.Level); FoundIrq = TRUE; break; } default: WARN_(I8042PRT, "Unknown resource descriptor type 0x%x\n", ResourceDescriptor->Type); } } if (!FoundIrq) { WARN_(I8042PRT, "Interrupt resource was not found in allocated resources list\n"); return STATUS_INSUFFICIENT_RESOURCES; } else if (DeviceExtension->Type == Keyboard && (!FoundDataPort || !FoundControlPort)) { WARN_(I8042PRT, "Some required resources were not found in allocated resources list\n"); return STATUS_INSUFFICIENT_RESOURCES; } else if (DeviceExtension->Type == Mouse && (FoundDataPort || FoundControlPort)) { WARN_(I8042PRT, "Too much resources were provided in allocated resources list\n"); return STATUS_INVALID_PARAMETER; } switch (DeviceExtension->Type) { case Keyboard: { RtlCopyMemory( &PortDeviceExtension->KeyboardInterrupt, &InterruptData, sizeof(INTERRUPT_DATA)); PortDeviceExtension->Flags |= KEYBOARD_STARTED; Status = StartProcedure(PortDeviceExtension); break; } case Mouse: { RtlCopyMemory( &PortDeviceExtension->MouseInterrupt, &InterruptData, sizeof(INTERRUPT_DATA)); PortDeviceExtension->Flags |= MOUSE_STARTED; Status = StartProcedure(PortDeviceExtension); break; } default: { WARN_(I8042PRT, "Unknown FDO type %u\n", DeviceExtension->Type); ASSERT(!(PortDeviceExtension->Flags & KEYBOARD_CONNECTED) || !(PortDeviceExtension->Flags & MOUSE_CONNECTED)); Status = STATUS_INVALID_DEVICE_REQUEST; } } if (NT_SUCCESS(Status)) DeviceExtension->PnpState = dsStarted; return Status; } static VOID i8042RemoveDevice( IN PDEVICE_OBJECT DeviceObject) { PI8042_DRIVER_EXTENSION DriverExtension; KIRQL OldIrql; PFDO_DEVICE_EXTENSION DeviceExtension; DriverExtension = (PI8042_DRIVER_EXTENSION)IoGetDriverObjectExtension(DeviceObject->DriverObject, DeviceObject->DriverObject); DeviceExtension = (PFDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension; KeAcquireSpinLock(&DriverExtension->DeviceListLock, &OldIrql); RemoveEntryList(&DeviceExtension->ListEntry); KeReleaseSpinLock(&DriverExtension->DeviceListLock, OldIrql); IoDetachDevice(DeviceExtension->LowerDevice); IoDeleteDevice(DeviceObject); } NTSTATUS NTAPI i8042Pnp( IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { PIO_STACK_LOCATION Stack; ULONG MinorFunction; I8042_DEVICE_TYPE DeviceType; ULONG_PTR Information = 0; NTSTATUS Status; Stack = IoGetCurrentIrpStackLocation(Irp); MinorFunction = Stack->MinorFunction; DeviceType = ((PFDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension)->Type; switch (MinorFunction) { case IRP_MN_START_DEVICE: /* 0x00 */ { TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_START_DEVICE\n"); /* Call lower driver (if any) */ if (DeviceType != PhysicalDeviceObject) { Status = ForwardIrpAndWait(DeviceObject, Irp); if (NT_SUCCESS(Status)) Status = i8042PnpStartDevice( DeviceObject, Stack->Parameters.StartDevice.AllocatedResources, Stack->Parameters.StartDevice.AllocatedResourcesTranslated); } else Status = STATUS_SUCCESS; break; } case IRP_MN_QUERY_DEVICE_RELATIONS: /* (optional) 0x07 */ { switch (Stack->Parameters.QueryDeviceRelations.Type) { case BusRelations: { TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_QUERY_DEVICE_RELATIONS / BusRelations\n"); return ForwardIrpAndForget(DeviceObject, Irp); } case RemovalRelations: { TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_QUERY_DEVICE_RELATIONS / RemovalRelations\n"); return ForwardIrpAndForget(DeviceObject, Irp); } default: ERR_(I8042PRT, "IRP_MJ_PNP / IRP_MN_QUERY_DEVICE_RELATIONS / Unknown type 0x%lx\n", Stack->Parameters.QueryDeviceRelations.Type); return ForwardIrpAndForget(DeviceObject, Irp); } break; } case IRP_MN_FILTER_RESOURCE_REQUIREMENTS: /* (optional) 0x0d */ { TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_FILTER_RESOURCE_REQUIREMENTS\n"); return ForwardIrpAndForget(DeviceObject, Irp); } case IRP_MN_QUERY_PNP_DEVICE_STATE: /* 0x14 */ { TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_QUERY_PNP_DEVICE_STATE\n"); return ForwardIrpAndForget(DeviceObject, Irp); } case IRP_MN_QUERY_REMOVE_DEVICE: { TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_QUERY_REMOVE_DEVICE\n"); return ForwardIrpAndForget(DeviceObject, Irp); } case IRP_MN_CANCEL_REMOVE_DEVICE: { TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_CANCEL_REMOVE_DEVICE\n"); return ForwardIrpAndForget(DeviceObject, Irp); } case IRP_MN_REMOVE_DEVICE: { TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_REMOVE_DEVICE\n"); Status = ForwardIrpAndForget(DeviceObject, Irp); i8042RemoveDevice(DeviceObject); return Status; } default: { ERR_(I8042PRT, "IRP_MJ_PNP / unknown minor function 0x%x\n", MinorFunction); return ForwardIrpAndForget(DeviceObject, Irp); } } Irp->IoStatus.Information = Information; Irp->IoStatus.Status = Status; IoCompleteRequest(Irp, IO_NO_INCREMENT); return Status; }
Java
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Exception.php 20978 2010-02-08 15:35:25Z matthew $ */ /** * @category Zend * @package Zend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Qlick_Sauth_SocialException extends Exception { /** * @var null|Exception */ private $_previous = null; /** * Construct the exception * * @param string $msg * @param int $code * @param Exception $previous * @return void */ public function __construct($msg = '', $code = 0, Exception $previous = null) { if (version_compare(PHP_VERSION, '5.3.0', '<')) { parent::__construct($msg, (int) $code); $this->_previous = $previous; } else { parent::__construct($msg, (int) $code, $previous); } } /** * Overloading * * For PHP < 5.3.0, provides access to the getPrevious() method. * * @param string $method * @param array $args * @return mixed */ public function __call($method, array $args) { if ('getprevious' == strtolower($method)) { return $this->_getPrevious(); } return null; } /** * String representation of the exception * * @return string */ public function __toString() { if (version_compare(PHP_VERSION, '5.3.0', '<')) { if (null !== ($e = $this->getPrevious())) { return $e->__toString() . "\n\nNext " . parent::__toString(); } } return parent::__toString(); } /** * Returns previous Exception * * @return Exception|null */ protected function _getPrevious() { return $this->_previous; } }
Java
#!/usr/bin/perl # # Controller - is4web.com.br # 2007 - 2011 package Controller; require 5.008; require Exporter; #use strict; use vars qw(@ISA $VERSION $INSTANCE %SWITCH); #CONTROLLER use Controller::DBConnector; use Controller::SQL; use Controller::LOG; use Controller::Date; use Controller::iUtils; use Controller::Is; use Controller::Mail; #use Controller::Financeiro; use Error; #TODO ver pra q e usar neh use File::Find; use Scalar::Util qw(looks_like_number); #use open ':utf8', ':std'; #Desta forma eu abro o Controller e tenho todos os modulos, é melhor escolher o modulo e ele conter o controller: @ISA = qw( Controller::Date Controller::DBConnector Controller::LOG Controller::Date Controller::iUtils Controller::Registros Controller::Financeiro Exporter); @ISA = qw( Controller::Date Controller::DBConnector Controller::SQL Controller::LOG Controller::iUtils Controller::Is Controller::Mail Exporter); #modulos básicos #@EXPORT = qw(); #@EXPORT_OK = qw(); $VERSION = "2.0"; =pod ########### ChangeLog ####################################################### VERSION # =item variable # # - Added # 1.6 # =item constant # # - Added accurancy # 1.7 # =item staffGroups # # - Added staffGroups # 1.9 # =item constant # # - Added constants # 2.0 # ############################################################################# # =cut ##CONSTANTS## use constant { TICKETS_OWNER_USER => 0, TICKETS_OWNER_STAFF => 1, TICKETS_OWNER_SYSTEM => 2, TICKETS_OWNER_ACTION => 3, TICKETS_METHOD_SYSTEM => 'ss', TICKETS_METHOD_HD => 'hd', TICKETS_METHOD_EMAIL => 'em', TICKETS_METHOD_CALL => 'cc', VISIBLE => 1, HIDDEN => 0, SERVICE_STATUS_BLOQUEADO => 'B', SERVICE_STATUS_CONGELADO => 'P', SERVICE_STATUS_CANCELADO => 'C', SERVICE_STATUS_FINALIZADO => 'F', SERVICE_STATUS_TRAFEGO => 'T', SERVICE_STATUS_ESPACO => 'E', SERVICE_STATUS_ATIVO => 'A', SERVICE_STATUS_SOLICITADO => 'S', SERVICE_ACTION_CREATE => 'C', SERVICE_ACTION_MODIFY => 'M', SERVICE_ACTION_SUSPEND => 'B', SERVICE_ACTION_SUSPENDRES => 'P', SERVICE_ACTION_REMOVE => 'R', SERVICE_ACTION_ACTIVATE => 'A', SERVICE_ACTION_RENEW => 'A', SERVICE_ACTION_NOTHINGTODO => 'N', SERVICE_ACTION_TRAFEGO => 'T', SERVICE_ACTION_ESPACO => 'E', INVOICE_STATUS_PENDENTE => 'P', INVOICE_STATUS_QUITADO => 'Q', INVOICE_STATUS_CANCELED => 'D', INVOICE_STATUS_CONFIRMATION => 'C', TABLE_STAFFS => 'staff', TABLE_USERS => 'users', TABLE_SERVICES => 'servicos', TABLE_INVOICES => 'invoices', #TODO COLOCAR NOME DE TABELAS COM CONSTANTES TABLE_ACCOUNTS => 'cc', TABLE_BALANCES => 'saldos', TABLE_CREDITS => 'creditos', TABLE_CALLS => 'calls', TABLE_NOTES => 'notes', TABLE_CREDITCARDS => 'cc_info', TABLE_PLANS => 'planos', TABLE_PAYMENTS => 'pagamento', TABLE_FORMS => 'formularios', TABLE_STATS => 'stats', TABLE_PERMS => 'security', TABLE_PERMSGROUP => 'securitygroups', TABLE_SERVERS => 'servidores', TABLE_SETTINGS => 'settings', TABLE_USERS_CONFIG=> 'users_config', VALOR_M => 30, VALOR_A => 360, VALOR_D => 1, VALOR_U => -1, accuracy => '%.5f', }; sub new { my $proto = shift; my $class = ref($proto) || $proto; #Provide a unique instance $INSTANCE and return($INSTANCE); my $self = { @_ }; %{ $self->{configs} } = @_; my $log = Controller::LOG->new(@_); %$self = ( %$self, %$log, ); bless($self, $class); $INSTANCE = $self; #cache instance $SIG{'__DIE__'} = sub { $self->traceback($_[0]); }; $self->connect() || return $self; $self->_setswitchs; $self->_settings;#Init settings $self->_setlang($self->setting('language')); #set default language; $self->_setskin($self->setting('skin'));#Init default interface settings $self->_setCGI; $self->_setqueries; $self->_country_codes; $self->_feriados; $self->_templates; $self->get_time;#Init time return $self; } sub reDie { my $self = shift; $SIG{'__DIE__'} = sub { $self->traceback($_[0]); }; } sub configs { my $self = shift; return %{ $self->{configs} }; } # Abolir esse uso #sub _username { # my ($self) = shift; # # $self->{'username'} = shift; # # return 1; #} sub error_code { my $self = shift; return $self->{'errorCode'}=undef unless $self->error; $self->{'errorCode'} = $_[0] if $_[0] >= 0 && !$self->{'errorCode'} && $self->error && $Controller::SWITCH{skip_error} != 1; return $self->{'errorCode'}; } sub set_error { my $self = shift; $self->{ERR} = "@_" if "@_" ne "" && !$self->error && $Controller::SWITCH{skip_error} != 1; return 0; #para poder utilizar com o return $self->set_error, assim se está retornando erro deve voltar 0 } #TODO fazer todo {ERR} virar error e {ERR} = virar set_error sub error { #TODO modificar o erro pra ser o cara q so mostra o erro e nao apaga my $self = shift; return $self->{ERR}; } sub clear_error { my $self = shift; my $handle = $self->{ERR}; $self->{ERR} = undef; #Error Acknowledge return $handle; } sub nice_error { my $self = shift; return undef unless $self->error; local $Controller::SWITCH{skip_error} = 1; # Skip the first frame [0], because it's the call to dotb. # Skip the second frame [1], because it's the call to die, with redirection my $frame = 0; my $tab = 1; while (my ($package, $filename, $line, $sub) = caller($frame++)) { if ($package eq 'main') { $sub =~ s/main:://; push(@trace, trim("$sub() called from $filename on line $line")); } else { return undef if $sub eq '(eval)'; #O Pacote tem direito de chamar um eval para fazer seu próprio handle de erro #CASO: cPanel::PublicAPI.pm eval { require $module; } if ( !$@ ) { }; push(@trace, trim("$package::$sub() called from $filename on line $line\n")); } } my $mess = "Traceback (most recent call last):\n"; $mess .= join("\n", map { " "x$tab++ . $_ } reverse(@trace) )."\n"; $mess .= "Package error: ".$self->clear_error."\n"; $self->logevent($mess); $self->email (To => $self->setting('controller_mail'), From => $self->setting('adminemail'), Subject => $self->lang('sbj_nice_error'), Body => "Error: $mess" ); return $self->lang(1); } sub soft_reset { my $self = shift; foreach (keys %$self) { delete $self->{$_} if $_ =~ m/^_current/; } } sub hard_reset { my $self = shift; my $class = ref($self); my %configs = $self->configs; $INSTANCE = undef; $self = undef; $self = new Controller ( %configs ); # bless($self, $class); return $self; } #save itens info sub save { @_ = @_; my $self = shift; return if $self->error; return unless @{$_[2]}; do { $self->set_error($self->lang(51,'save')); return undef; } unless @{$_[1]} == @{$_[2]} && @{$_[3]} == @{$_[4]}; $self->execute_sql(qq|UPDATE `$_[0]` SET |.Controller::iSQLjoin($_[1],1,",") .qq| WHERE |.Controller::iSQLjoin($_[3],1,","), @{$_[2]}, @{$_[4]}); return $self->error ? 0 : 1; } #Itens info sub sid { #independente my $self = shift; $self->{_currentsid} = $self->num($_[0]) if exists $_[0]; #nao tem logica verificar isso $self->set_error($self->lang(3,'sid')) if exists $_[0] && $_[0] ne $self->service('id'); return $self->{_currentsid}; } sub pid {#pode depender my $self = shift; if (exists $_[0]) { #Forçando um pid então não está cuidando de um serviço $self->{_currentpid} = $self->num($_[0]) ; $self->sid(0);#Liberando dependencia } else { #return $self->{_currentpid} = $self->service('servicos') if !$self->{_currentpid} && $self->sid; $self->{_currentpid} = $self->service('servicos') if $self->sid > 0; $self->set_error($self->lang(3,'pid')) if $self->{_currentpid} <= 0 && ($self->sid > 0); } return $self->{_currentpid}; } sub uid { #Nao eh mais #uid(0) é o real username do servico my $self = shift; if (exists $_[0]) { #Forçando um uid então não está cuidando de um usuario $self->{_currentuid} = $self->num($_[0]); $self->sid(0);#Liberando dependencia $self->balanceid(0); $self->invid(0); $self->callid(0); } else { $self->{_currentuid} = $self->service('username') if $self->sid > 0; $self->{_currentuid} = $self->balance('username') if $self->balanceid > 0; $self->{_currentuid} = $self->invoice('username') if $self->invid > 0; $self->{_currentuid} = $self->call('username') if $self->callid > 0 && $self->call('username') > 0; $self->set_error($self->lang(3,'uid')) if $self->{_currentuid} <= 0 && ($self->sid > 0 || $self->balanceid > 0 || $self->invid > 0 || ($self->callid > 0 && $self->call('username') > 0) ); } return $self->{_currentuid}; } sub srvid {#pode depender @_=@_; my $self = shift; if (exists $_[0]) { $self->{_currentsrvid} = $self->num($_[0]) ; $self->sid(0);#Liberando dependencia } else { $self->{_currentsrvid} = $self->service('servidor') if $self->sid > 0; $self->set_error($self->lang(3,'srvid')) if $self->{_currentsrvid} <= 0 && ($self->sid > 0); } return $self->{_currentsrvid}; } sub payid {#pode depender my $self = shift; if (exists $_[0]) { $self->{_currentpayid} = $self->num($_[0]) ; $self->sid(0);#Liberando dependencia } else { $self->{_currentpayid} = $self->service('pg') if $self->sid > 0; $self->set_error($self->lang(3,'payid')) if $self->{_currentpayid} <= 0 && ($self->sid > 0); } return $self->{_currentpayid}; } sub callid { my $self = shift; $self->{_currentcallid} = $self->num($_[0]) if exists $_[0]; return $self->{_currentcallid}; } sub creditid { my $self = shift; $self->{_currentcreditid} = $self->num($_[0]) if exists $_[0]; return $self->{_currentcreditid}; } sub balanceid { my $self = shift; $self->{_currentbalanceid} = $self->num($_[0]) if exists $_[0]; return $self->{_currentbalanceid}; } sub actid { my $self = shift; $self->{_currentaccountid} = $self->num($_[0]) if exists $_[0]; return $self->{_currentaccountid}; } sub invid { my $self = shift; $self->{_currentinvoiceid} = $self->num($_[0]) if exists $_[0]; return $self->{_currentinvoiceid}; } sub ccid { my $self = shift; $self->{_currentccid} = $self->num($_[0]) if exists $_[0]; return $self->{_currentccid}; } sub tid { my $self = shift; $self->{_currenttid} = $self->num($_[0]) if exists $_[0]; return $self->{_currenttid}; } sub staffid { my $self = shift; $self->{_currentstaffid} = $_[0] if exists $_[0]; return $self->{_currentstaffid}; } sub entid { my $self = shift; $self->{_currententid} = $self->num($_[0]) if exists $_[0]; return $self->{_currententid}; } sub deptid { my $self = shift; $self->{_currentdeptid} = $self->num($_[0]) if exists $_[0]; return $self->{_currentdeptid}; } sub did { my $self = shift; $self->{_currentdid} = $self->num($_[0]) if exists $_[0]; return $self->{_currentdid}; } sub logmailid { my $self = shift; $self->{_currentlogmailid} = $self->num($_[0]) if exists $_[0]; return $self->{_currentlogmailid}; } sub bankid { my $self = shift; $self->{_currentbankid} = $self->num($_[0]) if exists $_[0]; return $self->{_currentbankid}; } sub formtypeid { my $self = shift; $self->{_currentformtypeid} = $self->num($_[0]) if exists $_[0]; return $self->{_currentformtypeid}; } ########################################## sub payment { my $self = shift; $self->get_payment unless exists $self->{payments}{$self->payid}{$_[0]} || exists $_[1]; $self->{payments}{$self->payid}{$_[0]} = $_[1] if exists $_[1]; return $self->{payments}{$self->payid}{$_[0]}; } sub payments { my ($self) = shift; return $self->get_payments(1034); } sub service { @_ = @_;#See Pel Bug http://rt.perl.org/rt3/Public/Bug/Display.html?id=7508 my $self = shift; return \%{$self->{services}{$self->sid}} unless exists $_[0]; #copy %{ $self->{services}{$self->sid}{changed} } = %{ $_[1] } if $_[0] eq 'changed' && exists $_[1]; return keys %{ $self->{services}{$self->sid}{changed} } if $_[0] eq 'changed'; $self->get_service unless exists $self->{services}{$self->sid}{$_[0]} || $_[0] =~ m/^_/; #Create data hash if not exist my $atual = $_[0] eq 'dados' ? $self->{services}{$self->sid}{$_[0]}{$_[1]} : $self->{services}{$self->sid}{$_[0]}; $self->{services}{$self->sid}{$_[0]}{$_[1]} = $_[2] if $_[0] eq 'dados' && exists $_[1] && exists $_[2];#special field $self->{services}{$self->sid}{$_[0]} = $_[1] if exists $_[1] && $_[0] ne 'dados'; if (looks_like_number($atual)) { # == $self->{services}{$self->sid}{changed}{ $_[0] } = 1 if (exists $_[1] && $_[0] ne 'dados' && $atual != $_[1]) || (exists $_[2] && $_[0] eq 'dados' && $atual != $_[2]); } else { # eq $self->{services}{$self->sid}{changed}{ $_[0] } = 1 if (exists $_[1] && $_[0] ne 'dados' && $atual ne $_[1]) || (exists $_[2] && $_[0] eq 'dados' && $atual ne $_[2]); } #$self->logevent("\nDados: ".join ',', keys %{ $self->{services}{$self->sid}{'dados'} }); #puta faz isso depois nao aki, return $self->action($self->{services}{$self->sid}{$_[0]}) if $_[0] eq 'action'; #special field return $self->{services}{$self->sid}{$_[0]}{$_[1]} if $_[0] eq 'dados' && exists $_[1]; # "$_[1]" BUG de charset no campo de dados return $self->{services}{$self->sid}{$_[0]}; } sub services { my ($self) = shift; $self->set_error($self->lang(3,'services')) and return unless $self->uid; return $self->get_services(781,$self->uid); #select * sobrescrevia alteracoes de runtime, se definisse um proximo, ele lia denovo e sobrescrevia pelo antigo #return grep {$self->{services}{$_}{'username'} == $self->uid} keys %{ $self->{services} }; } sub serviceprop { my ($self) = shift; $self->get_serviceprop unless exists $self->{services}{$self->sid}{'properties'}{$_[0]} || exists $_[1]; #Create data hash if not exist $self->{services}{$self->sid}{'properties'}{$_[0]}{$_[1]}{$_[2]} = $_[3] if $_[0] == 3 && exists $_[1] && exists $_[2] && exists $_[3];#special field $self->{services}{$self->sid}{'properties'}{$_[0]} = $_[1] if exists $_[1] && $_[0] != 3; return $self->{services}{$self->sid}{'properties'}{$_[0]}{$_[1]} if $_[0] == 3 && exists $_[1]; return $self->{services}{$self->sid}{'properties'}{$_[0]}; } sub servicesprop { my ($self,@sids) = @_; $self->set_error($self->lang(3,'servicesprop')) and return unless @sids; $self->get_servicesprop(824,join ',',@sids); } sub plan { my $self = shift; $self->get_plan unless exists $self->{plans}{$self->pid}{$_[0]} || exists $_[1]; $self->{plans}{$self->pid}{$_[0]}{$_[1]} = $_[2] if $_[0] eq 'descontos' && exists $_[1]; $self->{plans}{$self->pid}{$_[0]} = $_[1] if $_[0] ne 'descontos' && exists $_[1]; return $self->{plans}{$self->pid}{$_[0]}{$self->service('pg')} if $_[0] eq 'descontos' && exists $_[1]; return $self->{plans}{$self->pid}{$_[0]}; } sub plans { my ($self) = @_; $self->set_error($self->lang(3,'plans')) and return unless $self->uid; return $self->get_plans(608,'%',$self->uid); } sub server { my $self = shift; $self->get_server unless exists $self->{servers}{$self->srvid}{$_[0]} || exists $_[1]; $self->{servers}{$self->srvid}{$_[0]} = $_[1] if exists $_[1]; return $self->{servers}{$self->srvid}{$_[0]}; } sub servers { #TODO REDO my ($self,@srvids) = @_; $self->set_error($self->lang(3,'servers')) and return unless @srvids; return $self->get_servers(45,join ',', map { $self->{servers}{$_}{'id'} } @srvids); } sub user { my $self = shift; my @__ = @_; #Protect from split and grep return \%{$self->{users}{$self->uid}} unless exists $__[0]; #copy %{ $self->{users}{$self->uid}{changed} } = %{ $__[1] } if $__[0] eq 'changed' && exists $__[1]; return keys %{ $self->{users}{$self->uid}{changed} } if $__[0] eq 'changed'; $self->get_user unless exists $self->{users}{$self->uid}{$__[0]} || $__[0] eq 'emails' || $__[0] =~ m/^_/; my $getter = $__[0] eq 'email' ? join(',', @{ $self->{users}{$self->uid}{$__[0]} }) : $self->{users}{$self->uid}{$__[0]}; if (exists $__[1]) { #Setter my $setter = $__[0] eq 'email' ? join(',', grep { $self->is_valid_email($_) } split(/\s*?[,;]\s*?/,trim($__[1])) ) : $__[1]; if (looks_like_number($getter)) { # == $self->{users}{$self->uid}{changed}{ $__[0] } = 1 if $self->num($getter) != $self->num($setter); } else { # eq $self->{users}{$self->uid}{changed}{ $__[0] } = 1 if $getter ne $setter; } $self->{users}{$self->uid}{$__[0]} = $__[0] eq 'email' ? [ split(',',trim($setter)) ] : $setter; } return join ',', @{ $self->user('email') } if $__[0] eq 'emails'; #use Data::Dumper; #die Dumper \%{$self->{users}{$self->uid}} unless exists $__[1]; return $self->{users}{$self->uid}{$__[0]}; } sub user_config { my $self = shift; my @__ = @_; #Protect from split and grep return \%{$self->{users_config}{$self->uid}} unless exists $__[0]; #copy return keys %{ $self->{users_config}{$self->uid}{changed} } if $__[0] eq 'changed'; $self->get_user_config unless exists $self->{users_config}{$self->uid}{$__[0]} || $__[0] =~ m/^_/; my $getter = $self->{users_config}{$self->uid}{$__[0]}; if (exists $__[1]) { #Setter my $setter = $__[1]; $self->{users_config}{$self->uid}{changed}{ $__[0] } = 1 if $getter ne $setter && $getter != $setter; $self->{users_config}{$self->uid}{$__[0]} = $__[1]; } return $self->{users_config}{$self->uid}{$__[0]}; } sub invoice { @_=@_; my $self = shift; return \%{$self->{invoices}{$self->invid}} unless exists $_[0]; #copy $self->get_invoice unless exists $self->{invoices}{$self->invid}{$_[0]} || exists $_[1]; $self->{invoices}{$self->invid}{$_[0]}{$_[1]} = $_[2] if $_[0] eq 'services' && exists $_[1] && exists $_[2];#special field $self->{invoices}{$self->invid}{$_[0]} = $_[1] if exists $_[1] && $_[0] ne 'services'; return $self->{invoices}{$self->invid}{$_[0]}{$_[1]} if $_[0] eq 'services' && exists $_[1]; return $self->{invoices}{$self->invid}{$_[0]}; } sub invoices { my ($self) = shift; $self->set_error($self->lang(3,'invoices')) and return unless $self->uid; return $self->get_invoices(439,'%',$self->uid); #return grep {$self->{balances}{$_}{'username'} == $self->uid} keys %{ $self->{balances} }; } sub account { my $self = shift; $self->get_account unless exists $self->{accounts}{$self->actid}{$_[0]} || exists $_[1]; $self->{accounts}{$self->actid}{$_[0]} = $_[1] if exists $_[1]; return $self->{accounts}{$self->actid}{$_[0]}; } sub accounts { my $self = shift; # $self->set_error($self->lang(3,'accounts')) and return unless $self->uid; $self->get_accounts(424); return keys %{ $self->{accounts} }; } sub credit { my $self = shift; $self->get_credit unless exists $self->{credits}{$self->creditid}{$_[0]} || exists $_[1]; $self->{credits}{$self->creditid}{$_[0]} = $_[1] if exists $_[1]; return $self->{credits}{$self->creditid}{$_[0]}; } sub credits { my ($self) = shift; $self->set_error($self->lang(3,'credits')) and return unless $self->uid; return $self->get_credits(482,$self->uid); } sub balance { my $self = shift; $self->get_balance unless exists $self->{balances}{$self->balanceid}{$_[0]} || exists $_[1]; $self->{balances}{$self->balanceid}{$_[0]} = $_[1] if exists $_[1]; return $self->{balances}{$self->balanceid}{$_[0]}; } sub balances { my ($self) = shift; $self->set_error($self->lang(3,'balances')) and return unless $self->uid; return $self->get_balances(450,'O',$self->uid); #return grep {$self->{balances}{$_}{'username'} == $self->uid} keys %{ $self->{balances} }; } sub servicebalances { my ($self) = shift; $self->set_error($self->lang(3,'servicebalances')) and return unless $self->sid; return $self->get_balances(454,'O',$self->sid); } sub call { my $self = shift; $self->get_call unless exists $self->{calls}{$self->callid}{$_[0]} || exists $_[1]; $self->{calls}{$self->callid}{$_[0]} = $_[1] if exists $_[1]; return $self->{calls}{$self->callid}{$_[0]}; } sub calls { my ($self) = shift; $self->set_error($self->lang(3,'calls')) and return unless $self->uid; #se tem sid vai ter uid return $self->get_calls(367,$self->sid) if $self->sid; return $self->get_calls(366,$self->uid) if $self->uid; return (); } sub followers { my $self = shift; $self->set_error($self->lang(3,'followers')) and return unless $self->callid; my $sth = $self->select_sql(380,$self->callid); my @followers = map {@{$_}} @{ $sth->fetchall_arrayref() }; $self->finish; return @followers; } sub following { my $self = shift; $self->set_error($self->lang(3,'following')) and return unless $self->staffid; my $sth = $self->select_sql(379,$self->staffid); my @following = map {@{$_}} @{ $sth->fetchall_arrayref() }; $self->finish; return @following; } sub creditcard { my $self = shift; $self->get_creditcard unless exists $self->{creditcards}{$self->ccid}{$_[0]} || exists $_[1]; $self->{creditcards}{$self->ccid}{$_[0]} = $_[1] if exists $_[1]; return $self->{creditcards}{$self->ccid}{$_[0]}; } sub creditcards { my $self = shift; $self->set_error($self->lang(3,'creditcards')) and return unless $self->uid; return $self->get_creditcards(855,$self->uid); #return keys %{ $self->{creditcards} }; } sub creditcard_active { my $self = shift; $self->set_error($self->lang(3,'creditcard_active')) and return unless $self->uid; $self->get_creditcards(852,$self->tid,1,$self->uid); my ($ccid) = grep { $self->{creditcards}{$_}{'active'} == 1 && $self->{creditcards}{$_}{'tarifa'} == $self->tid && $self->{creditcards}{$_}{'username'} == $self->uid} keys %{ $self->{creditcards} }; return $ccid; } sub tax { my $self = shift; $self->get_tax unless exists $self->{taxs}{$self->tid}{$_[0]} || exists $_[1]; $self->{taxs}{$self->tid}{$_[0]} = $_[1] if exists $_[1]; return $self->{taxs}{$self->tid}{$_[0]}; } sub taxs { my $self = shift; # $self->set_error($self->lang(3,'taxs')) and return unless $self->uid; return $self->get_taxs(872); #return keys %{ $self->{taxs} }; } sub enterprise { my $self = shift; $self->get_enterprise unless exists $self->{enterprises}{$self->entid}{$_[0]} || exists $_[1]; $self->{enterprises}{$self->entid}{$_[0]} = $_[1] if exists $_[1]; return $self->{enterprises}{$self->entid}{$_[0]}; } sub enterprises { my $self = shift; return $self->get_enterprises(303); #return keys %{ $self->{enterprises} }; } sub department { my $self = shift; $self->get_department unless exists $self->{departments}{$self->deptid}{$_[0]} || exists $_[1]; $self->{departments}{$self->deptid}{$_[0]} = $_[1] if exists $_[1]; return $self->{departments}{$self->deptid}{$_[0]}; } sub departments { my $self = shift; return $self->get_departments(266); #return keys %{ $self->{departments} }; } sub formtype { my $self = shift; $self->get_formtype unless exists $self->{formtypes}{$self->formtypeid}{$_[0]} || exists $_[1]; $self->{formtypes}{$self->formtypeid}{$_[0]} = $_[1] if exists $_[1]; return $self->{formtypes}{$self->formtypeid}{$_[0]}; } sub staff { my $self = shift; $self->get_staff unless exists $self->{staffs}{$self->staffid}{$_[0]} || exists $_[1]; $self->{staffs}{$self->staffid}{$_[0]} = $_[1] if exists $_[1]; return join ',', @{ $self->{staffs}{$self->staffid}{'email'} } if $_[0] eq 'emails'; return $self->{staffs}{$self->staffid}{$_[0]}; } sub staffGroups { my $self = shift; return undef if $self->error; $self->set_error($self->lang(3,'get_staffGroups')) and return unless $self->staffid; my $sth = $self->select_sql(1083, $self->staffid); my @gids = map {@{$_}} @{ $sth->fetchall_arrayref() }; $self->finish; return @gids; } sub groups { my $self = shift; return undef if $self->error; my $sth = $self->select_sql(1084); my @gids = map {@{$_}} @{ $sth->fetchall_arrayref() }; $self->finish; return @gids; } sub logmail { my $self = shift; $self->get_logmail unless exists $self->{logmails}{$self->logmailid}{$_[0]} || exists $_[1]; $self->{logmails}{$self->logmailid}{$_[0]} = $_[1] if exists $_[1]; return $self->{logmails}{$self->logmailid}{$_[0]}; } sub logmails { my $self = shift; return $self->get_logmails(163); } sub bank { my $self = shift; $self->get_bank unless exists $self->{banks}{$self->bankid}{$_[0]} || exists $_[1]; $self->{banks}{$self->bankid}{$_[0]} = $_[1] if exists $_[1]; return $self->{banks}{$self->bankid}{$_[0]}; } sub banks { my $self = shift; return $self->get_banks(427); } sub perm { my $self = shift; my $id = $self->uid || $self->staffid; $self->set_error($self->lang(3,'perm')) and return unless $id; $self->get_perm unless exists $self->{perms}{$id}; return $self->{perms}{$id}{$_[0]}{$_[1]}{$_[2]} || $self->{perms}{$id}{$_[0]}{'all'}{$_[2]} if exists $_[2]; return \%{ $self->{perms}{$id}{$_[0]}{$_[1]} } if exists $_[1]; #copy return \%{ $self->{perms}{$id}{$_[0]} } if exists $_[0]; #copy return \%{ $self->{perms}{$id} }; #copy } sub perms { #my $self = shift; #my $id = $self->uid || $self->staffid; #$self->set_error($self->lang(3,'perms')) and return unless $id; #return keys %{$self->perm}; } ############################################ #Copy data sub copy_service { my ($self,$source,$target) = @_; $self->sid($source); my $ref = $self->service; $self->sid($target); my $ref2 = $self->service; %$ref2 = %$ref; return $self->sid($source); } sub shadow_copy { my $self = shift; if ($_[0] eq 'services') { my $ref = $self->service; %{ $self->{'shadow'}{$_[0]}{$self->sid} } = %$ref; } return 1; } sub AUTOLOAD { #Holds all undef methods my $self = $_[0]; my $type = ref($self) or die "$AUTOLOAD is not an object"; my $name = $AUTOLOAD; $name =~ s/.*://; # strip fully-qualified portion #Determinar qual modulo usar e importar #use Modulo e chama a funcao, é melhor determinar pelos modulos dos planos, serve para caso #nao tenha buscar os padroes if ($name =~ s/_shadow$//i) { use B::RecDeparse; my $deparse = B::RecDeparse->new; my $newsub = $deparse->coderef2text( eval "\\&Controller::$name" ); $newsub =~ s/\$\$self{(.+?)}/\$self->{'shadow'}{$1}/g; #$newsub =~ s/\$\$self{(.+?)}/\$\$self{'shadow'}{$1}/g; $newsub =~ s/package.*//; eval "sub func $newsub"; # the inverse operation return func(@_); } if ($name =~ /registrar|renew|expire/i) { $self->manual_action; return $self->error ? 0 : 1; } if ($name =~ /availdomain/i) { return 1; #sempre disponivel, já que nao foi consultado } $self->set_error("$name not implemented"); return undef;#Simular erro } ############################################ sub lock_billing { my ($self) = shift; local $Controller::SWITCH{skip_log} = 1; my $date = exists $_[1] ? $_[1] : $self->today(); my $time = exists $_[2] ? $_[2] : undef; $self->execute_sql(21,$self->uid,$date,$time) if $self->uid; return 1; } sub unlock_billing { my ($self) = shift; local $Controller::SWITCH{skip_log} = 1; $self->execute_sql(22,$self->uid) if $self->uid; return 1; } sub action { my $self = shift; my %act = ( 'C' => $self->lang("CREATE"), 'M' => $self->lang("MODIFY"), 'B' => $self->lang("SUSPEND"), 'P' => $self->lang("SUSPENDRES"), 'R' => $self->lang("REMOVE"), 'A' => $self->lang("ACTIVATE"), 'N' => $self->lang("NOTHINGTODO") ); return $act{uc shift}; } sub valor { my ($self,$opt) = @_; if ($opt == 1) { return $self->VALOR_M if $self->plan('valor_tipo') eq 'M'; return $self->VALOR_A if $self->plan('valor_tipo') eq 'A'; return $self->VALOR_D if $self->plan('valor_tipo') eq 'D'; return $self->VALOR_U if $self->plan('valor_tipo') eq 'U'; } else { return $self->lang('Month') if $self->plan('valor_tipo') eq 'M'; return $self->lang('Year') if $self->plan('valor_tipo') eq 'A'; return $self->lang('Day') if $self->plan('valor_tipo') eq 'D'; return $self->lang('Unique') if $self->plan('valor_tipo') eq 'U'; } $self->set_error($self->lang(1003)); die $self->lang(1003); #Valor tipo não reconhecido } sub installment { my $self = shift; my %inst = ( 'S' => $self->lang("INSTALLMENT_S"), 'O' => $self->lang("INSTALLMENT_O"), 'L' => $self->lang("INSTALLMENT_L"), 'D' => $self->lang("INSTALLMENT_D") ); return $inst{uc shift}; } ####################################### #data mount sub mount_service { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { #precisa sim #next if $ref->{"servidor"} == 1; # Não há informações sobre o servidor nenhum my $sid = $ref->{'id'}; push @ids_matched, $sid; foreach my $q (keys %{$sth->{NAME_hash}}) { #next if $q eq 'id'; TODO deixar o id pra verificar consistencia, ver sub sid() if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) { $self->{'services'}{$sid}{lc $q} = $self->date($ref->{$q}); } elsif ($q eq 'dados') { $self->{'services'}{$sid}{lc $q} = undef; foreach (split("::",$ref->{$q})) { my ($col,$val) = split(" : ",$_); $self->{'services'}{$sid}{lc $q}{trim($col)} = trim($val); } } else { $self->{'services'}{$sid}{lc $q} = $ref->{$q}; } } } return @ids_matched; } sub get_service { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_service')) and return unless $self->sid; $self->select_sql(780,$self->sid); $self->mount_service; $self->finish; #$self->logevent("Get DB: ".join ',', keys %{ $self->{services}{$self->sid}{'dados'} }); return $self->error ? 0 : 1; } sub get_services { my ($self,$sql,@params) = @_; return undef if $self->error; $self->set_error($self->lang(3,'get_services')) and return unless $sql; $self->select_sql($sql,@params); my @services = $self->mount_service; $self->finish; return $self->error ? undef : @services; } sub mount_serviceprop { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $sid = $ref->{'servico'}; push @ids_matched, $sid; if ($ref->{'type'} == 3) { #4.90::3,4,5,6::2008|6.65::1,8::2009 foreach ( split('\|',$ref->{'value'}) ) { my($val,$months,$year) = split('::',$_,3); #TODO Ajustar isso para ter valores diferente para cada mês. Valores em porcentagem também serem aceitos para variarem junto com o valor do plano. #Adicionado tipo 7 $self->{services}{$sid}{'properties'}{$ref->{'type'}}{$year} = { 'value' => $val, 'months' => [split ',', $months], } } } elsif ($ref->{'type'} == 7) { #{} hash dump $self->{services}{$sid}{'properties'}{$ref->{'type'}} = eval $ref->{'value'}; } else { my $value = $self->num($ref->{'value'}) < 0 ? 0 : $self->num($ref->{'value'}); $self->{services}{$sid}{'properties'}{$ref->{'type'}} = $value; } } return @ids_matched; } sub get_serviceprop { my ($self) = shift; return 0 if $self->error; #types 1 - dias gratis 2 - Sem taxa de setup 3 - Descontos em meses #4 - Nao se orientar pelo vc do usuario 5 - dias para finalizar 6 - fatura exclusiva #7 - Valores +- por mes/ano % ou $ $self->set_error($self->lang(3,'get_serviceprop')) and return unless $self->sid; $self->select_sql(824,$self->sid); $self->mount_serviceprop; $self->finish; return $self->error ? 0 : 1; } sub get_servicesprop { my ($self,$sql,@params) = @_; return 0 if $self->error; $self->set_error($self->lang(3,'get_serviceprop')) and return unless $sql; $self->select_sql($sql,@params); my @props = $self->mount_serviceprop; $self->finish; return $self->error ? undef : @props; } sub mount_plan { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $pid = $ref->{'servicos'}; push @ids_matched, $pid; foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq 'servicos'; $self->{'plans'}{$pid}{lc $q} = $ref->{$q}; } #isso nao existe, nao tem como acontecer $self->{'plans'}{$pid}{'descontos'}{$ref->{'pg'}} = $ref->{'desconto'}; } return @ids_matched; } sub get_plan { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_plan')) and return unless $self->pid; $self->select_sql(604,$self->pid); $self->mount_plan; $self->finish; return $self->error ? 0 : 1; } sub get_plans { my ($self,$sql,@params) = @_; return undef if $self->error; $self->set_error($self->lang(3,'get_plans')) and return unless $sql; $self->select_sql($sql,@params); my @plans = $self->mount_plan; $self->finish; return $self->error ? 0 : @plans; } sub mount_tax { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $tid = $ref->{'id'}; push @ids_matched, $tid; foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq 'id'; $self->{'taxs'}{$tid}{lc $q} = $ref->{$q}; } } return @ids_matched; } sub get_tax { my ($self) = shift; return 0 if $self->error; # $self->set_error($self->lang(3,'get_tax')) and return unless $self->tid; $self->select_sql(871,$self->tid); $self->mount_tax; $self->finish; return $self->error ? 0 : 1; } sub get_taxs { my ($self,$sql,@params) = @_; return 0 if $self->error; $self->set_error($self->lang(3,'get_taxs')) and return unless $sql; $self->select_sql($sql,@params); my @taxs = $self->mount_tax; $self->finish; return $self->error ? 0 : @taxs; } sub mount_server { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $srvid = $ref->{'id'}; push @ids_matched, $srvid; foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq "id"; $self->{'servers'}{$srvid}{lc $q} = $ref->{$q}; } } return @ids_matched; } sub get_server { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_server')) and return unless $self->srvid; $self->select_sql(45,$self->srvid); $self->mount_server; $self->finish; return $self->error ? 0 : 1; } sub get_servers { my ($self,$sql,@params) = @_; return undef if $self->error; $self->set_error($self->lang(3,'get_servers')) and return unless $sql; $self->select_sql($sql,@params); my @servers = $self->mount_server; $self->finish; return $self->error ? 0 : @servers; } sub mount_payment { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $payid = $ref->{'id'}; push @ids_matched, $payid; foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq "id"; $self->{'payments'}{$payid}{lc $q} = $ref->{$q}; } } return @ids_matched; } sub get_payment { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_payment')) and return unless $self->payid; $self->select_sql(1030,$self->payid); my @payments = $self->mount_payment; $self->finish; return $self->error ? 0 : @payments; } sub get_payments { my ($self,$sql,@params) = @_; return undef if $self->error; $self->set_error($self->lang(3,'get_payments')) and return unless $sql; $self->select_sql($sql,@params); my @payments = $self->mount_payment; $self->finish; return $self->error ? undef : @payments; } sub mount_user { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $uid = $ref->{'username'}; push @ids_matched, $uid; foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq "username"; if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) { $self->{'users'}{$uid}{lc $q} = $self->date($ref->{$q}); } elsif ($q eq 'email') { $self->{'users'}{$uid}{lc $q} = [ grep { $self->is_valid_email($_) } split(/\s*?[,;]\s*?/,trim($ref->{$q})) ]; } else { $self->{'users'}{$uid}{lc $q} = $ref->{$q}; } } } return @ids_matched; } sub mount_user_config { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while($sth and (my $ref = $sth->fetchrow_hashref())) { my $set = lc $ref->{'setting'}; push @ids_matched, $set; $self->{'users_config'}{$ref->{'username'}}{$set} = $ref->{'value'}; } return @ids_matched; } sub get_user { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_user')) and return unless $self->uid; $self->select_sql(680,$self->uid); my @users = $self->mount_user; $self->finish; return $self->error ? 0 : @users; } sub get_user_config { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_user_config')) and return unless $self->uid; $self->select_sql(681,$self->uid); my @configs = $self->mount_user_config; $self->finish; return $self->error ? 0 : @configs; } sub get_users { my ($self,$sql,@params) = @_; return undef if $self->error; $self->set_error($self->lang(3,'get_users')) and return unless $sql; $self->select_sql($sql,@params); my @users = $self->mount_user; $self->finish; return $self->error ? undef : @users; } sub mount_invoice { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $invid = $ref->{'id'}; push @ids_matched, $invid; foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq "id"; if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) { $self->{'invoices'}{$invid}{lc $q} = $self->date($ref->{$q}); } elsif ($q eq 'services') { $self->{'invoices'}{$invid}{lc $q} = {}; #Inicializando $self->{'invoices'}{$invid}{lc $q}{$2} = $1 while $ref->{$q} =~ m/(\d+?)x(\d+?) -\s?/g; } else { $self->{'invoices'}{$invid}{lc $q} = $ref->{$q}; } } } return @ids_matched; } sub get_invoice { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_invoice')) and return unless $self->invid; $self->select_sql(437,$self->invid); $self->mount_invoice; $self->finish; return $self->error ? 0 : 1; } sub get_invoices { my ($self,$sql,@params) = @_; return undef if $self->error; $self->set_error($self->lang(3,'get_invoices')) and return unless $sql; $self->select_sql($sql,@params); my @invoices = $self->mount_invoice; $self->finish; return $self->error ? undef : @invoices; } sub mount_account { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $actid = $ref->{'id'}; push @ids_matched, $actid; foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq "id"; if ($q eq 'agencia') { my ($pre,$pos) = split('-',$ref->{$q}); $self->{'accounts'}{$actid}{lc ($q.'dv')} = $pos; $self->{'accounts'}{$actid}{lc $q} = $pre; } elsif ($q eq 'conta') { my ($pre,$pos) = split('-',$ref->{$q}); $self->{'accounts'}{$actid}{lc ($q.'dv')} =$pos; $self->{'accounts'}{$actid}{lc $q} =$pre; } else { $self->{'accounts'}{$actid}{lc $q} = $ref->{$q}; } } } return @ids_matched; } sub get_account { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_acccount')) and return unless $self->actid; my $sth = $self->select_sql(423,$self->actid); $self->mount_account; $self->finish; return $self->error ? 0 : 1; } sub get_accounts { my ($self,$sql,@params) = @_; return 0 if $self->error; $self->set_error($self->lang(3,'get_accounts')) and return unless $sql; $self->select_sql($sql,@params); my @accounts = $self->mount_account; $self->finish; return $self->error ? undef : @accounts; } sub mount_balance { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $bid = $ref->{'id'}; push @ids_matched, $bid; foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq "id"; $self->{'balances'}{$bid}{lc $q} = $ref->{$q}; } } return @ids_matched; } sub get_balance { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_balance')) and return unless $self->balanceid; $self->select_sql(449,$self->balanceid); $self->mount_balance; $self->finish; return $self->error ? 0 : 1; } sub get_balances { my ($self,$sql,@params) = @_; return 0 if $self->error; $self->set_error($self->lang(3,'get_balances')) and return unless $sql; $self->select_sql($sql,@params); my @balances = $self->mount_balance; $self->finish; return $self->error ? undef : @balances; } sub mount_credit { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $creditid = $ref->{'id'}; push @ids_matched, $creditid; foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq "id"; $self->{'credits'}{$creditid}{lc $q} = $ref->{$q}; } } return @ids_matched; } sub get_credit { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_credit')) and return unless $self->creditid; $self->select_sql(481,$self->creditid); $self->mount_credit; $self->finish; return $self->error ? 0 : 1; } sub get_credits { my ($self,$sql,@params) = @_; return 0 if $self->error; $self->set_error($self->lang(3,'get_credits')) and return unless $sql; $self->select_sql($sql,@params); my @credits = $self->mount_credit; $self->finish; return $self->error ? undef : @credits; } sub mount_call { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $callid = $ref->{'id'}; push @ids_matched, $callid; foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq "id"; $self->{'calls'}{$self->callid}{lc $q} = $ref->{$q}; } } return @ids_matched; } sub get_call { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_call')) and return unless $self->callid; $self->select_sql(365,$self->callid); $self->mount_call; $self->finish; return $self->error ? 0 : 1; } sub get_calls { my ($self,$sql,@params) = @_; return 0 if $self->error; $self->set_error($self->lang(3,'get_calls')) and return unless $sql; $self->select_sql($sql,@params); my @calls = $self->mount_call; $self->finish; return $self->error ? undef : @calls; } sub mount_creditcard { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $ccid = $ref->{'id'}; push @ids_matched, $ccid; #preciso listar mesmo que esteja recusado next if $ref->{'active'} == -1; #recusado foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq "id"; if ($q =~ m/^(?:ccn|cvv2)$/) { #campos criptografados $self->{'creditcards'}{$ccid}{lc $q} = Controller::decrypt_mm($ref->{$q}); } else { $self->{'creditcards'}{$ccid}{lc $q} = $ref->{$q}; } } #TODO ajustar isso, esses langs nem eram pra existir # Vou mudar pra ficar um só cartão de cada tipo my $status = $self->lang('Active') if $ref->{'active'} == 1; $status = $self->lang('Activating') if $ref->{'active'} == 2; $status = $self->lang('Deactivated') if $ref->{'active'} == 0; $status = $self->lang('Refused') if $ref->{'active'} == -1; $self->{'creditcards'}{$ccid}{'status'} = $status; #last if $ref->{'active'} == 1;#1= Ativo -1= Recusado 0= Desativado 2= Ativando } return @ids_matched; } sub get_creditcard { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_creditcard')) and return unless $self->ccid; $self->select_sql(851,$self->ccid); $self->mount_creditcard; $self->finish; return $self->error ? 0 : 1; } sub get_creditcards { my ($self,$sql,@params) = @_; return undef if $self->error; $self->set_error($self->lang(3,'get_creditcards')) and return unless $sql; $self->select_sql($sql,@params); my @creditcards = $self->mount_creditcard; $self->finish; return $self->error ? undef : @creditcards; } sub mount_formtype { my ($self) = shift; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $id = $ref->{'id'}; foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq "id"; if ($q eq 'properties') { #[1=30][3=4.90::3,4,5,6::2008|6.65::1,8::2009] foreach my $propertie ($ref->{$q} =~ /\[(.+?)\]/g) { my ($type,$value) = split('=',$propertie); $self->{'formtypes'}{$id}{'properties'}{$type} = $value; #repassar as info pra salvar, elas processada de nada ainda servem # if ($type == 3) { # foreach ( split('\|',$value) ) { # my($val,$months,$year) = split('::',$_,3); # $self->{'formtypes'}{$id}{'properties'}{$type}{$year} = { # 'value' => $val, # 'months' => [split ',', $months], # } # } # } else { # my $value = $self->num($value) < 0 ? 0 : $self->num($value); # $self->{'formtypes'}{$id}{'properties'}{$type} = $value; # } } } elsif ($q eq 'planos') { $self->{'formtypes'}{$id}{lc $q} = [ split ',', $ref->{$q} ]; } else { $self->{'formtypes'}{$id}{lc $q} = $ref->{$q}; } } } } sub get_formtype { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_formtype')) and return unless $self->formtypeid; $self->select_sql(1050,$self->formtypeid); $self->mount_formtype; $self->finish; return $self->error ? 0 : 1; } sub mount_staff { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $staffid = $ref->{'username'}; push @ids_matched, $staffid; foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq 'username'; $self->{'staffs'}{$staffid}{lc $q} = $ref->{$q}; } } return @ids_matched; } sub get_staff { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_staff')) and return unless $self->staffid; $self->select_sql(331,$self->staffid); $self->mount_staff; $self->finish; return $self->error ? 0 : 1; } sub get_staffs { my ($self,$sql,@params) = @_; return undef if $self->error; $self->set_error($self->lang(3,'get_staffs')) and return unless $sql; $self->select_sql($sql,@params); my @staffs = $self->mount_staff; $self->finish; return $self->error ? undef : @staffs; } sub mount_enterprise { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $entid = $ref->{'id'}; push @ids_matched, $entid; foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq "id"; $self->{'enterprises'}{$entid}{lc $q} = $ref->{$q}; } } return @ids_matched; } sub get_enterprise { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_enterprise')) and return unless $self->entid; $self->select_sql(304,$self->entid); $self->mount_enterprise; $self->finish; return $self->error ? 0 : 1; } sub get_enterprises { my ($self,$sql,@params) = @_; return undef if $self->error; $self->set_error($self->lang(3,'get_enterprises')) and return unless $sql; $self->select_sql($sql,@params); my @enterprises = $self->mount_enterprise; $self->finish; return $self->error ? 0 : @enterprises; } sub mount_department { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $deptid = $ref->{'id'}; push @ids_matched, $deptid; foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq "id"; $self->{'departments'}{$deptid}{lc $q} = $ref->{$q}; } } return @ids_matched; } sub get_department { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_department')) and return unless $self->deptid; $self->select_sql(267,$self->deptid); $self->mount_department; $self->finish; return $self->error ? 0 : 1; } sub get_departments { my ($self,$sql,@params) = @_; return undef if $self->error; $self->set_error($self->lang(3,'get_departments')) and return unless $sql; $self->select_sql($sql,@params); my @departments = $self->mount_department; $self->finish; return $self->error ? undef : @departments; } sub mount_discount { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $did = $ref->{'id'}; push @ids_matched, $did; foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq "id"; $self->{'enterprises'}{$entid}{lc $q} = $ref->{$q}; } } return @ids_matched; } sub get_discount { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_enterprise')) and return unless $self->entid; $self->select_sql(304,$self->entid); $self->mount_enterprise; $self->finish; return $self->error ? 0 : 1; } sub get_discounts { my ($self,$sql,@params) = @_; return undef if $self->error; $self->set_error($self->lang(3,'get_enterprises')) and return unless $sql; $self->select_sql($sql,@params); my @enterprises = $self->mount_enterprise; $self->finish; return $self->error ? 0 : @enterprises; } sub mount_logmail { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $logmailid = $ref->{'id'}; push @ids_matched, $logmailid; foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq "id"; if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) { $self->{'logmails'}{$logmailid}{lc $q} = $self->date($ref->{$q}); } elsif ($q eq 'body') { $self->{'logmails'}{$logmailid}{lc $q} = $ref->{$q}; $self->{'logmails'}{$logmailid}{lc $q} =~ s/\\(\W)/$1/g; #Emails antigos } else { $self->{'logmails'}{$logmailid}{lc $q} = $ref->{$q}; } } } return @ids_matched; } sub get_logmail { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_logmail')) and return unless $self->logmailid; $self->select_sql(164,$self->logmailid); $self->mount_logmail; $self->finish; return $self->error ? 0 : 1; } sub get_logmails { my ($self,$sql,@params) = @_; return undef if $self->error; $self->set_error($self->lang(3,'get_logmails')) and return unless $sql; $self->select_sql($sql,@params); my @logmails = $self->mount_logmail; $self->finish; return $self->error ? 0 : @logmails; } sub mount_bank { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $bankid = $ref->{'codigo'}; push @ids_matched, $bankid; foreach my $q (keys %{$sth->{NAME_hash}}) { next if $q eq "codigo"; $self->{'banks'}{$bankid}{lc $q} = $ref->{$q}; } } return @ids_matched; } sub get_bank { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'get_bank')) and return unless $self->bankid; $self->select_sql(426,$self->bankid); $self->mount_bank; $self->finish; return $self->error ? 0 : 1; } sub get_banks { my ($self,$sql,@params) = @_; return undef if $self->error; $self->set_error($self->lang(3,'get_banks')) and return unless $sql; $self->select_sql($sql,@params); my @banks = $self->mount_bank; $self->finish; return $self->error ? 0 : @banks; } sub mount_perm { my ($self) = shift; my @ids_matched; my $sth = $self->last_select; while(my $ref = $sth->fetchrow_hashref()) { my $permid = $ref->{'username'}; push @ids_matched, $permid; #foreach my $q (keys %{$sth->{NAME_hash}}) { # next if $q eq "username"; my ($module,$type,$name) = split(/:/, $ref->{'right'}, 3); $self->{'perms'}{$permid}{lc $module}{lc $type}{lc $name} = $ref->{'value'} if $module && $type && $name; #} } return @ids_matched; } sub get_perm { my ($self) = shift; return 0 if $self->error; my $id = $self->uid || $self->staffid; $self->set_error($self->lang(3,'get_perm')) and return unless $id; if ($self->staffid && $self->staffGroups) { #Staff groups my $sql_1082 = $self->{queries}{1082}; my @gids = $self->staffGroups; $sql_1082 .= qq| `groupname` IN ('|.join('\',\'', @gids).qq|')| if @gids; $sql_1082 .= qq| ORDER BY (`username` = ?)|; #Permissao individual preferencial $self->select_sql($sql_1082,$id,$id,$id); } else { $self->select_sql(1081,$id); } $self->mount_perm; $self->finish; return $self->error ? 0 : 1; } sub get_perms { my ($self,$sql,@params) = @_; return undef if $self->error; $self->set_error($self->lang(3,'get_perms')) and return unless $sql; $self->select_sql($sql,@params); my @perms = $self->mount_perm; $self->finish; return $self->error ? 0 : @perms; } ########################################## #Search items sub return_username { my ($self) = shift; #TODO sempre atualizar para novas tabelas #MUITO CUIDADO COM O UID ou SID ou OUTRO, POIS PERDE A REFERENCIA $self->invid($_[0]) and return $self->invoice('username') if ($self->TABLE_INVOICES && $_[1] =~ /(?:${\$self->TABLE_INVOICES})(?:,|$)/i); $self->callid($_[0]) and return $self->call('username') if ($self->TABLE_CALLS && $_[1] =~ /(?:${\$self->TABLE_CALLS})(?:,|$)/i); $self->callid($_[0]) and return $self->call('username') if ($self->TABLE_NOTES && $_[1] =~ /(?:${\$self->TABLE_NOTES})(?:,|$)/i); $self->balanceid($_[0]) and return $self->balance('username') if ($self->TABLE_BALANCES && $_[1] =~ /(?:${\$self->TABLE_BALANCES})(?:,|$)/i); $self->creditid($_[0]) and return $self->credit('username') if ($self->TABLE_CREDITS && $_[1] =~ /(?:${\$self->TABLE_CREDITS})(?:,|$)/i); $self->ccid($_[0]) and return $self->creditcard('username') if ($self->TABLE_CREDITCARDS && $_[1] =~ /(?:${\$self->TABLE_CREDITCARDS})(?:,|$)/i); } sub return_sender { my ($self) = shift; if ($_[0] eq 'User' && $self->uid) { my $level = $self->user('level'); #default will be the first $level =~ s/^[:]+//; my $entid = (split('::',$level))[0]; $self->entid($self->num($entid)); $sender = $self->enterprise('mail_account') if $self->entid; } if ($_[0] eq 'Billing' && $self->uid) { my $level = $self->user('level'); #default will be the first $level =~ s/^[:]+//; my $entid = (split('::',$level))[0]; $self->entid($self->num($entid)); $sender = $self->enterprise('mail_billing') if $self->entid; } return $sender || $self->setting('adminemail'); } sub search_srvid { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'search_server')) and return unless $_[0] || $_[1]; my $sth = $self->select_sql(qq|SELECT `id` FROM `servidores` WHERE `$_[0]` = ?|,$_[1]); my ($id) = $sth->fetchrow_array if $sth; $self->finish; return $self->error ? '' : $id; } sub search_sid { my ($self) = shift; return 0 if $self->error; $self->set_error($self->lang(3,'search_service')) and return unless $_[0] || $_[1]; my $op = '='; my $value = $_[1]; if ($_[0] eq 'dados') { $op = 'LIKE'; $value = '%'."$_[1] : $_[2]".'::%'; } my $sth = $self->select_sql(qq|SELECT `id` FROM `servicos` WHERE `$_[0]` $op ?|,$value); return 0 if $sth->rows != 1; my ($id) = $sth->fetchrow_array if $sth; $self->finish; return $self->error ? 0 : $id; } #Template System sub template { @_=@_; my $self = shift; return \%{$self->{templates}} unless exists $_[0]; #copy $self->{templates}{$_[0]} = $_[1] if exists $_[1]; return $self->{templates}{$_[0]}; } sub template_html { @_=@_; my $self = shift; return \%{$self->{templates}} unless exists $_[0]; #copy $self->{templates}{$_[0]} = $_[1] if exists $_[1]; $self->{templates}{$_[0]} =~ s/\n/<br>/g; return $self->{templates}{$_[0]}; } sub template_parse { my ($self,$ctype) = @_; if ($ctype eq 'text/plain') { $_ =~ s/\{(\S+?)\}/$self->template($1)/egi; } else { $_ =~ s/\{(\S+?)\}/$self->template_html($1)/egi; } } #Lang System sub lang_parse { my ($self) = @_; $_ =~ s/(\%(\S*?)\%)/$self->{lang}{$2} ? $self->{lang}{$2} : ( $2 ? "missing_$2": "%")/ge; } sub _setlang { my ($self,$language) = @_; return 0 if !$language; #protect ourself escape(\$language); if (-e $self->setting('app')."/lang/$language/lang.inc") { $self->{_setlang} = $language; our %LANG = (); my $ret = do($self->setting('app')."/lang/$language/lang.inc"); #Problemas com UTF-8, o arquivo tem que estar nesse formato para não deformar os caracteres do sistema die "couldn't parse lang file: $@" if $@; die "couldn't do lang file: $!" unless defined $ret; die "couldn't run lang file" unless $ret; $self->{'lang'} = { %LANG }; return 1; } else { $self->set_error('Lang not found at '.$self->setting('app')."/lang/$language/lang.inc"); return 0; } } sub lang { my ($self,$no,@values) = @_; ($no,@values) = @$no if (ref $no eq "ARRAY"); # return "missing_$no_" unless exists $self->{lang}{$no}; return $no unless exists $self->{lang}{$no}; #Broke non-translations, who needs must override return sprintf("$self->{lang}{$no}",@values); } sub servicos { my ($self) = shift; my @q = split(" ","@_"); return 0 if $self->error; $self->set_error($self->lang(3,'servicos')) and return unless $self->num($self->{'service'}{'id'}); my $sth = $self->select_sql(qq|SELECT * FROM `servicos` INNER JOIN `planos` ON `servicos`.`servicos`=`planos`.`servicos` WHERE `id` = ?|,$self->num($self->{'service'}{'id'})); while(my $ref = $sth->fetchrow_hashref()) { foreach my $q (@q) { # next if $q eq "servidor" && $ref->{$q} eq 1;#pensar em utilizar isso if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) { $self->{'service'}{lc $q} = $self->date($ref->{$q}); } else { $self->{'service'}{lc $q} = $ref->{$q}; } } } $self->finish; return $self->error ? 0 : 1; } #sub invoices { # my ($self) = shift; # my @q = split(" ","@_"); # return 0 if $self->error; # # $self->set_error($self->lang(3,'invoices')) and return unless $self->num($self->{'invoice'}{'id'}); # # my $sth = $self->select_sql(qq|SELECT `invoices`.*, `users`.`vencimento` FROM `invoices` INNER JOIN `users` ON `invoices`.`username`=`users`.`username` WHERE `id` = ?|,$self->num($self->{'invoice'}{'id'})); # while(my $ref = $sth->fetchrow_hashref()) { # foreach my $q (@q) { # if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) { # $self->{'invoice'}{lc $q} = $self->date($ref->{$q}); # } else { # $self->{'invoice'}{lc $q} = $ref->{$q}; # } # } # } # $self->finish; # # return $self->error ? 0 : 1; #} sub users { my ($self) = shift; my @q = split(" ","@_"); return 0 if $self->error; $self->set_error($self->lang(3,'users')) and return unless $self->num($self->{'user'}{'id'}); my $sth = $self->select_sql(qq|SELECT * FROM `users` WHERE `username` = ?|,$self->num($self->{'user'}{'id'})); while(my $ref = $sth->fetchrow_hashref()) { foreach my $q (@q) { if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) { $self->{'user'}{lc $q} = $self->date($ref->{$q}); } else { $self->{'user'}{lc $q} = $ref->{$q}; } } } $self->finish; return $self->error ? 0 : 1; } sub pagamentos { my ($self) = shift; my @q = split(" ","@_"); return 0 if $self->error; $self->set_error($self->lang(3,'pagamentos')) and return unless $self->num($self->{'pagamento'}{'id'}); my $sth = $self->select_sql(qq|SELECT * FROM `pagamento` WHERE `id` = ?|,$self->num($self->{'pagamento'}{'id'})); while(my $ref = $sth->fetchrow_hashref()) { foreach my $q (@q) { if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) { $self->{'pagamento'}{lc $q} = $self->date($ref->{$q}); } else { $self->{'pagamento'}{lc $q} = $ref->{$q}; } } } $self->finish; return $self->error ? 0 : 1; } sub planos { my ($self) = shift; my @q = split(" ","@_"); return 0 if $self->error; $self->set_error($self->lang(3,'planos')) && return unless $self->num($self->{'plano'}{'id'}); my $sth = $self->select_sql(qq|SELECT * FROM `planos` LEFT JOIN `planos_modules` ON `planos`.`servicos`=`planos_modules`.`plano` WHERE `servicos` = ?|,$self->num($self->{'plano'}{'id'})); while(my $ref = $sth->fetchrow_hashref()) { foreach my $q (@q) { if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) { $self->{'plano'}{lc $q} = $self->date($ref->{$q}); } else { $self->{'plano'}{lc $q} = $ref->{$q}; } } } $self->finish; return $self->error ? 0 : 1; } sub promo { my ($self,$type) = @_; return 0 if $self->error; #types 1 - dias gratis 2 - Sem taxa de setup 3 - Descontos em meses 4 - Nao se orientar pelo vc do usuario 5 - dias para finalizar 6 - fatura exclusiva $self->set_error($self->lang(3,'promocao')) and return unless $self->num($self->sid); $self->set_error($self->lang(3,'promocao')) and return unless $self->num($type); unless (defined $self->service('_promo'.$type)) { my $sth = $self->select_sql(qq|SELECT * FROM `promocao` WHERE `servico` = ?|,$self->sid); while (my $ref = $sth->fetchrow_hashref()) { my $r = $ref->{'value'}; $r = 0 if $r < 0 && $ref->{'type'} != 3; $self->service('_promo'.$ref->{'type'}, $r); } } if ($type == 1 || $type == 2 || $type == 4 || $type == 5 || $type == 6) { my $r = $self->num($self->service('_promo'.$type)); $r = 0 if $r < 0; return $r } return split("::",$self->service('_promo'.$type),3) if $type == 3; return undef; } sub _feriados { #put in memory for fast access my ($self) = @_; my $sth = $self->select_sql(qq|SELECT * FROM `feriados`|); while(my $ref = $sth->fetchrow_hashref()) { $self->{'feriados'}{$ref->{'mes'}}{$ref->{'dia'}} = $ref->{'desc'}; } $self->finish; return $self->error ? 0 : 1; } sub _settings { #put in memory for fast access my ($self) = @_; my $sth = $self->select_sql(qq|SELECT * FROM `settings`|); while(my $ref = $sth->fetchrow_hashref()) { my $setting = $ref->{'setting'}; $self->{settings}{$setting} = $ref->{'value'}; } $self->finish; return $self->error ? 0 : 1; } sub _setskin { my ($self,$skin) = @_; return 0 if !$skin; my $sth = $self->select_sql(qq|SELECT * FROM `skins` WHERE `name` = ?|,$skin); while(my $ref = $sth->fetchrow_hashref()) { my $setting = $ref->{'setting'}; $self->{skin}{$setting} = $ref->{'value'}; } $self->finish; #set name $self->{skin}{name} = $skin; return $self->error ? 0 : 1; } sub _templates { my ($self) = shift; $self->template('lang',$self->{_setlang}); $self->template('data',$self->setting('data')); $self->template('title',$self->setting('title')); $self->template('baseurl',$self->setting('baseurl')); $self->template('timen',$self->calendar('timenow')); $self->template('data_tpl',$self->skin('data_tpl')); $self->template('url_tpl',$self->skin('url_tpl')); $self->template('imgbase',$self->skin('imgbase')); $self->template('logo',$self->skin('logo_url')); return 1; } sub _country_codes { #put in memory for fast access my ($self) = @_; my $sth = $self->select_sql(qq|SELECT * FROM `countrycode`|); while(my $ref = $sth->fetchrow_hashref()) { my $country = $ref->{'id'}; $self->{country_codes}{uc $country} = { code => $ref->{'call'}, name => $ref->{'nome'} }; } $self->finish; return $self->error ? 0 : 1; } sub _setswitchs { our %SWITCH; #Defaults switchs $SWITCH{skip_sql} = 0; $SWITCH{skip_log} = 0; $SWITCH{skip_mail} = 0; $SWITCH{skip_logmail} = 0; $SWITCH{skip_error} = 0; return 1; } sub _setCGI { my ($self) = shift; require CGI; my $q = CGI->new(); my @pairs = split(/;/, $q->query_string()); foreach my $pair (@pairs) { my ($name, $value) = split(/=/, $pair); #Problema de charset era o binmode utf8 que escrevia no arquivo errado e a tela do terminal tbm, mudei pra UTF8 $self->param($name,Controller::URLDecode($value)); } foreach my $name ($q->cookie()) { $self->cookie($name,$q->cookie($name)); } return 1; } sub variable { @_=@_; my ($self) = shift; $self->{_variables}{$_[0]} = $_[1] if exists $_[1]; return $self->{_variables}{$_[0]}; } sub variables { my ($self) = shift; return keys %{$self->{_variables}}; } sub param { @_=@_; my ($self) = shift; $self->{_params}{$_[0]} = trim($_[1]) if exists $_[1]; return $self->{_params}{$_[0]}; } sub params { my ($self) = shift; return keys %{$self->{_params}}; } sub cookie { @_=@_; my ($self) = shift; $self->{_cookies}{$_[0]} = $_[1] if exists $_[1]; return $self->{_cookies}{$_[0]}; } sub cookies { my ($self) = shift; return keys %{$self->{_cookies}}; } sub country_code { my ($self, $key, $value) = @_; $self->{country_codes}{$key} = $value if $value; if (exists $self->{country_codes}{$key}) { return $self->{country_codes}{$key}; } $self->set_error($self->lang(14, $key)); die; #break, uma configuracao é essencial para o sistema } sub country_codes { my ($self) = shift; return sort keys %{$self->{country_codes}}; } sub setting { my ($self, $key, $value) = @_; $self->{settings}{$key} = $value if defined $value; if (exists $self->{settings}{$key}) { return $self->{settings}{$key}; } $self->set_error($self->lang(2, $key)); die $key if $self->connected; #break, uma configuracao é essencial para o sistema } sub settings { my ($self) = @_; return keys %{$self->{settings}}; } sub skin { my ($self, $key) = @_; if (exists $self->{'skin'}{$key}) { return $self->{'skin'}{$key}; } $self->set_error($self->lang(4, $key, $self->{'skin'}{'name'})); die; #break, uma configuracao é essencial para o sistema } sub skins { my $self = shift; my $sth = $self->select_sql(qq|SELECT DISTINCT `name` FROM `skins`|); my @skins = map {@{$_}} @{ $sth->fetchall_arrayref() }; $self->finish; return @skins; } sub gonext { my $self = @_; $self->{'_next'} = 1; return 1; } sub golast { my $self = @_; $self->{'_last'} = 1; return 1; } sub next { my $self = @_; if ($self->{'_next'} == 1) { $self->{'_next'} = undef; next; } if ($self->{'_last'} == 1) { $self->{'_last'} = undef; last; } } sub list_langs { my $self = shift; my @mods; my $base = $self->setting('app') .'/lang/'; opendir(F, $base ) || return undef; my @list = readdir(F); closedir F; foreach my $item (@list) { if (-d $base.$item) { push (@dirs, $item) if (-e $base.$item.'/lang.inc'); } } @{ $self->{list_langs} } = sort {lc($a) cmp lc($b)} @dirs; iUnique( $self->{list_langs} ); return @{ $self->{list_langs} }; } sub list_modules { my $self = shift; my @mods; my $match = sub { if ($File::Find::name =~ /\.pm$/) { open(F, $File::Find::name) || return undef; my $is_module; while(<F>) { $is_module = 1 if /^# Use: Module/; if ($is_module == 1 && /^ *package +(([^\s:]+(::)?){4}([^\s:]+){0,1});/) { push (@mods, $1); last; } } close(F); } }; find( $match, $self->setting('data').'/sistema/'.$self->setting('modules'), $self->setting('app').'/modules'); @{ $self->{list_modules} } = sort {lc($a) cmp lc($b)} @mods; iUnique( $self->{list_modules} ); return @{ $self->{list_modules} }; } sub DESTROY { my $self = @_; #warn 'Controller was closed'; } sub traceback { #TODO enviar trace pra admin e die_nice pro usuário my $self = shift; my $err = shift; my @trace; #FIXME: empty list? # Skip the first frame [0], because it's the call to dotb. # Skip the second frame [1], because it's the call to die, with redirection my $frame = 2; my $tab = 1; while (my ($package, $filename, $line, $sub) = caller($frame++)) { if ($package eq 'main') { $sub =~ s/main:://; push(@trace, trim("$sub() called from $filename on line $line")); } else { return undef if $sub eq '(eval)'; #O Pacote tem direito de chamar um eval para fazer seu próprio handle de erro #CASO: cPanel::PublicAPI.pm eval { require $module; } if ( !$@ ) { }; push(@trace, trim("$package::$sub() called from $filename on line $line\n")); } } #print STDERR "Content-type: text/plain\n\n" unless $mod_perl; my $mess .= "Traceback (most recent call last):\n"; $mess .= join("\n", map { " "x$tab++ . $_ } reverse(@trace) )."\n"; $mess .= "Package error: ".$self->error()."\n"; $mess .= "Error: $err"; #already has \n at end my $mod_perl = exists $ENV{MOD_PERL}; if ($mod_perl) { my $r; if ($ENV{MOD_PERL_API_VERSION} && $ENV{MOD_PERL_API_VERSION} == 2) { $mod_perl = 2; require Apache2::RequestRec; require Apache2::RequestIO; require Apache2::RequestUtil; require APR::Pool; require ModPerl::Util; require Apache2::Response; $r = Apache2::RequestUtil->request; } else { $r = Apache->request; } # If bytes have already been sent, then # we print the message out directly. # Otherwise we make a custom error # handler to produce the doc for us. if ($r->bytes_sent) { $r->print($mess); $mod_perl == 2 ? ModPerl::Util::exit(0) : $r->exit; } else { # MSIE won't display a custom 500 response unless it is >512 bytes! if ($ENV{HTTP_USER_AGENT} =~ /MSIE/) { $mess = "<!-- " . (' ' x 513) . " -->\n$mess"; } $r->custom_response(500,$mess); } } else { # my $bytes_written = eval{tell STDERR}; # if (defined $bytes_written && $bytes_written > 0) { # print STDERR $mess; # } # else { # print STDERR "Status: 500\n"; # print STDERR "Content-type: text/plain\n\n"; # print STDERR $mess; # } } $self->logevent($mess); #send message to cron lock $self->logcron($err) if $self->connected; #send a nice message to user $self->script_error($err); } sub script_error { my ($self) = shift; my $error = "@_"; $error ||= $self->error; #TODO estudar se o script_error pode ficar em um arquivo html print "Content-type: text/html\n\n"; print qq~<html><head><title>Erro</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head><body bgcolor="#FFFFFF"><p>&nbsp;</p><table width="600" border="0" cellspacing="0" cellpadding="0" align="center"><tr><td colspan="3"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b>Controller: <font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b><font color="#990000">Erro de </font></b></font><font color="#990000">Script </font></b></font></td></tr><tr> <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr><tr> <td colspan="3"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Controller n&atilde;o pode ser rodado pelos seguintes erros:</font></td> </tr><tr><td colspan="3" height="40"><font face="Courier New, Courier, mono" size="2"><br>$error<br></td></tr></table><p align="center">&nbsp;</p></body></html> ~; exit(1); } __END__; Diagnostics Find @ISA: use Class::ISA; print "Food::Fishstick path is:\n ", join(", ", Class::ISA::super_path($class)), "\n"; 1;
Java
core:import( "CoreMissionScriptElement" ) ElementPlayerSpawner = ElementPlayerSpawner or class( CoreMissionScriptElement.MissionScriptElement ) function ElementPlayerSpawner:init( ... ) ElementPlayerSpawner.super.init( self, ... ) managers.player:preload() end -- Returns a value function ElementPlayerSpawner:value( name ) return self._values[ name ] end function ElementPlayerSpawner:client_on_executed( ... ) if not self._values.enabled then return end managers.player:set_player_state( self._values.state or managers.player:default_player_state() ) end function ElementPlayerSpawner:on_executed( instigator ) if not self._values.enabled then return end managers.player:set_player_state( self._values.state or managers.player:default_player_state() ) managers.groupai:state():on_player_spawn_state_set( self._values.state or managers.player:default_player_state() ) managers.network:register_spawn_point( self._id, { position = self._values.position, rotation = self._values.rotation } ) ElementPlayerSpawner.super.on_executed( self, self._unit or instigator ) end
Java
#ifndef __CODEC_COM_ETSI_OP_H__ #define __CODEC_COM_ETSI_OP_H__ /***************************************************************************** 1 ÆäËûÍ·Îļþ°üº¬ *****************************************************************************/ #ifndef _MED_C89_ #include "codec_op_etsi_hifi.h" #endif #ifdef __cplusplus #if __cplusplus extern "C" { #endif #endif /***************************************************************************** 2 Êý¾ÝÀàÐͶ¨Òå *****************************************************************************/ /* ±ê×¼Cƽ̨¶¨Òå */ #ifdef _MED_C89_ /* »ù±¾Êý¾ÝÀàÐͶ¨Òå */ typedef char Char; typedef signed char Word8; typedef unsigned char UWord8; typedef short Word16; typedef unsigned short UWord16; typedef long Word32; typedef unsigned long UWord32; typedef int Flag; #endif /***************************************************************************** 3 ºê¶¨Òå *****************************************************************************/ #define MAX_32 ((Word32)0x7fffffffL) /*×î´óµÄ32λÊý*/ #define MIN_32 ((Word32)0x80000000L) /*×îСµÄ32λÊý*/ #define MAX_16 ((Word16)0x7fff) /*×î´óµÄ16λÊý*/ #define MIN_16 ((Word16)0x8000) /*×îСµÄ16λÊý*/ /* ±ê×¼Cƽ̨¶¨Òå */ #ifdef _MED_C89_ #define CODEC_OpSetOverflow(swFlag) (Overflow = swFlag) #define CODEC_OpGetOverflow() (Overflow) #define CODEC_OpSetCarry(swFlag) (Carry = swFlag) #define CODEC_OpGetCarry() (Carry) #define XT_INLINE static #endif /***************************************************************************** 4 ö¾Ù¶¨Òå *****************************************************************************/ /***************************************************************************** 5 ÏûϢͷ¶¨Òå *****************************************************************************/ /***************************************************************************** 6 ÏûÏ¢¶¨Òå *****************************************************************************/ /***************************************************************************** 7 STRUCT¶¨Òå *****************************************************************************/ /***************************************************************************** 8 UNION¶¨Òå *****************************************************************************/ /***************************************************************************** 9 OTHERS¶¨Òå *****************************************************************************/ #define round(L_var1) round_etsi(L_var1) /***************************************************************************** 10 È«¾Ö±äÁ¿ÉùÃ÷ *****************************************************************************/ /* ±ê×¼Cƽ̨¶¨Òå */ #ifdef _MED_C89_ extern Flag Overflow; extern Flag Carry; #endif /***************************************************************************** 11 º¯ÊýÉùÃ÷ *****************************************************************************/ #ifdef _MED_C89_ /* ETSI : basic_op.h */ extern Word16 saturate (Word32 swVar); /* 32bit->16bit */ extern Word16 add(Word16 shwVar1, Word16 shwVar2); /* Short add */ extern Word16 sub(Word16 shwVar1, Word16 shwVar2); /* Short sub */ extern Word16 abs_s(Word16 shwVar1); /* Short abs */ extern Word16 shl(Word16 shwVar1, Word16 shwVar2); /* Short shift left */ extern Word16 shr(Word16 shwVar1, Word16 shwVar2); /* Short shift right*/ extern Word16 mult(Word16 shwVar1, Word16 shwVar2); /* Short mult */ extern Word32 L_mult(Word16 shwVar1, Word16 shwVar2); /* Long mult */ extern Word16 negate(Word16 shwVar1); /* Short negate */ extern Word16 extract_h(Word32 swVar1); /* Extract high */ extern Word16 extract_l(Word32 swVar1); /* Extract low */ extern Word16 round_etsi(Word32 swVar1); /* Round */ extern Word32 L_mac(Word32 swVar3, Word16 shwVar1, Word16 shwVar2); /* Mac */ extern Word32 L_msu(Word32 swVar3, Word16 shwVar1, Word16 shwVar2); /* Msu */ extern Word32 L_macNs(Word32 swVar3, Word16 shwVar1, Word16 shwVar2); /* Mac without sat */ extern Word32 L_msuNs(Word32 swVar3, Word16 shwVar1, Word16 shwVar2); /* Msu without sat */ extern Word32 L_add(Word32 swVar1, Word32 swVar2); /* Long add */ extern Word32 L_sub(Word32 swVar1, Word32 swVar2); /* Long sub */ extern Word32 L_add_c(Word32 swVar1, Word32 swVar2); /* Long add with c */ extern Word32 L_sub_c(Word32 swVar1, Word32 swVar2); /* Long sub with c */ extern Word32 L_negate(Word32 swVar1); /* Long negate */ extern Word16 mult_r(Word16 shwVar1, Word16 shwVar2); /* Mult with round */ extern Word32 L_shl(Word32 swVar1, Word16 shwVar2); /* Long shift left */ extern Word32 L_shr(Word32 swVar1, Word16 shwVar2); /* Long shift right */ extern Word16 shr_r(Word16 shwVar1, Word16 shwVar2); /* Shift right with round */ extern Word16 mac_r(Word32 swVar3, Word16 shwVar1, Word16 shwVar2); /* Mac with rounding */ extern Word16 msu_r(Word32 swVar3, Word16 shwVar1, Word16 shwVar2); /* Msu with rounding */ extern Word32 L_deposit_h(Word16 shwVar1); /* 16 bit shwVar1 -> MSB */ extern Word32 L_deposit_l(Word16 shwVar1); /* 16 bit shwVar1 -> LSB */ extern Word32 L_shr_r(Word32 swVar1, Word16 shwVar2); /* Long shift right with round */ extern Word32 L_abs(Word32 swVar1); /* Long abs */ extern Word32 L_sat(Word32 swVar1); /* Long saturation */ extern Word16 norm_s(Word16 shwVar1); /* Short norm */ extern Word16 div_s(Word16 shwVar1, Word16 shwVar2); /* Short division */ extern Word16 norm_l(Word32 swVar1); /* Long norm */ /* ETSI : oper_32b.h */ /* Extract from a 32 bit integer two 16 bit DPF */ extern void L_Extract(Word32 swVar32, Word16 *pshwHi, Word16 *pshwLo); /* Compose from two 16 bit DPF a 32 bit integer */ extern Word32 L_Comp(Word16 shwHi, Word16 shwLo); /* Multiply two 32 bit integers (DPF). The result is divided by 2**31 */ extern Word32 Mpy_32(Word16 shwHi1, Word16 shwLo1, Word16 shwHi2, Word16 shwLo2); /* Multiply a 16 bit integer by a 32 bit (DPF). The result is divided by 2**15 */ extern Word32 Mpy_32_16(Word16 shwHi, Word16 shwLo, Word16 shwN); /* Fractional integer division of two 32 bit numbers */ extern Word32 Div_32(Word32 swNum, Word16 denom_hi, Word16 denom_lo); /* ETSI : mac_32.h */ /* Multiply two 32 bit integers (DPF) and accumulate with (normal) 32 bit integer. The multiplication result is divided by 2**31 */ extern Word32 Mac_32(Word32 swVar32, Word16 shwHi1, Word16 shwLo1, Word16 shwHi2, Word16 shwLo2); /* Multiply a 16 bit integer by a 32 bit (DPF) and accumulate with (normal)32 bit integer. The multiplication result is divided by 2**15 */ extern Word32 Mac_32_16(Word32 swVar32, Word16 shwHi, Word16 shwLo, Word16 shwN); #endif /* ifdef _MED_C89_ */ #ifdef __cplusplus #if __cplusplus } #endif #endif #endif /* end of med_com_etsi_op.h */
Java
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.ext.flac; import android.os.Handler; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.audio.AudioProcessor; import com.google.android.exoplayer2.audio.AudioRendererEventListener; import com.google.android.exoplayer2.audio.SimpleDecoderAudioRenderer; import com.google.android.exoplayer2.drm.DrmSessionManager; import com.google.android.exoplayer2.drm.ExoMediaCrypto; import com.google.android.exoplayer2.util.MimeTypes; /** * Decodes and renders audio using the native Flac decoder. */ public class LibflacAudioRenderer extends SimpleDecoderAudioRenderer { private static final int NUM_BUFFERS = 16; public LibflacAudioRenderer() { this(null, null); } /** * @param eventHandler A handler to use when delivering events to {@code eventListener}. May be * null if delivery of events is not required. * @param eventListener A listener of events. May be null if delivery of events is not required. * @param audioProcessors Optional {@link AudioProcessor}s that will process audio before output. */ public LibflacAudioRenderer( Handler eventHandler, AudioRendererEventListener eventListener, AudioProcessor... audioProcessors) { super(eventHandler, eventListener, audioProcessors); } @Override protected int supportsFormatInternal(DrmSessionManager<ExoMediaCrypto> drmSessionManager, Format format) { if (!MimeTypes.AUDIO_FLAC.equalsIgnoreCase(format.sampleMimeType)) { return FORMAT_UNSUPPORTED_TYPE; } else if (!supportsOutput(format.channelCount, C.ENCODING_PCM_16BIT)) { return FORMAT_UNSUPPORTED_SUBTYPE; } else if (!supportsFormatDrm(drmSessionManager, format.drmInitData)) { return FORMAT_UNSUPPORTED_DRM; } else { return FORMAT_HANDLED; } } @Override protected FlacDecoder createDecoder(Format format, ExoMediaCrypto mediaCrypto) throws FlacDecoderException { return new FlacDecoder( NUM_BUFFERS, NUM_BUFFERS, format.maxInputSize, format.initializationData); } }
Java
/* * Compiler error handler * Copyright * (C) 1992 Joseph H. Allen * * This file is part of JOE (Joe's Own Editor) */ #include "types.h" /* Error database */ typedef struct error ERROR; struct error { LINK(ERROR) link; /* Linked list of errors */ long line; /* Target line number */ long org; /* Original target line number */ unsigned char *file; /* Target file name */ long src; /* Error-file line number */ unsigned char *msg; /* The message */ } errors = { { &errors, &errors} }; ERROR *errptr = &errors; /* Current error row */ B *errbuf = NULL; /* Buffer with error messages */ /* Function which allows stepping through all error buffers, for multi-file search and replace. Give it a buffer. It finds next buffer in error list. Look at 'berror' for error information. */ /* This is made to work like bafter: it does not increment refcount of buffer */ B *beafter(B *b) { struct error *e; unsigned char *name = b->name; if (!name) name = USTR ""; for (e = errors.link.next; e != &errors; e = e->link.next) if (!zcmp(name, e->file)) break; if (e == &errors) { /* Given buffer is not in list? Return first buffer in list. */ e = errors.link.next; } while (e != &errors && !zcmp(name, e->file)) e = e->link.next; berror = 0; if (e != &errors) { B *b = bfind(e->file); /* bfind bumps refcount, so we have to unbump it */ if (b->count == 1) b->orphan = 1; /* Oops */ else --b->count; return b; } return 0; } /* Insert and delete notices */ void inserr(unsigned char *name, long int where, long int n, int bol) { ERROR *e; if (!n) return; if (name) { for (e = errors.link.next; e != &errors; e = e->link.next) { if (!zcmp(e->file, name)) { if (e->line > where) e->line += n; else if (e->line == where && bol) e->line += n; } } } } void delerr(unsigned char *name, long int where, long int n) { ERROR *e; if (!n) return; if (name) { for (e = errors.link.next; e != &errors; e = e->link.next) { if (!zcmp(e->file, name)) { if (e->line > where + n) e->line -= n; else if (e->line > where) e->line = where; } } } } /* Abort notice */ void abrerr(unsigned char *name) { ERROR *e; if (name) for (e = errors.link.next; e != &errors; e = e->link.next) if (!zcmp(e->file, name)) e->line = e->org; } /* Save notice */ void saverr(unsigned char *name) { ERROR *e; if (name) for (e = errors.link.next; e != &errors; e = e->link.next) if (!zcmp(e->file, name)) e->org = e->line; } /* Pool of free error nodes */ ERROR errnodes = { {&errnodes, &errnodes} }; /* Free an error node */ static void freeerr(ERROR *n) { vsrm(n->file); vsrm(n->msg); enquef(ERROR, link, &errnodes, n); } /* Free all errors */ static int freeall(void) { int count = 0; while (!qempty(ERROR, link, &errors)) { freeerr(deque_f(ERROR, link, errors.link.next)); ++count; } errptr = &errors; return count; } /* Parse error messages into database */ /* From joe's joe 2.9 */ /* First word (allowing ., /, _ and -) with a . is the file name. Next number is line number. Then there should be a ':' */ static void parseone(struct charmap *map,unsigned char *s,unsigned char **rtn_name,long *rtn_line) { int x, y, flg; unsigned char *name = NULL; long line = -1; y=0; flg=0; if (s[0] == 'J' && s[1] == 'O' && s[2] == 'E' && s[3] == ':') goto bye; do { /* Skip to first word */ for (x = y; s[x] && !(joe_isalnum_(map,s[x]) || s[x] == '.' || s[x] == '/'); ++x) ; /* Skip to end of first word */ for (y = x; joe_isalnum_(map,s[y]) || s[y] == '.' || s[y] == '/' || s[y]=='-'; ++y) if (s[y] == '.') flg = 1; } while (!flg && x!=y); /* Save file name */ if (x != y) name = vsncpy(NULL, 0, s + x, y - x); /* Skip to first number */ for (x = y; s[x] && (s[x] < '0' || s[x] > '9'); ++x) ; /* Skip to end of first number */ for (y = x; s[y] >= '0' && s[y] <= '9'; ++y) ; /* Save line number */ if (x != y) sscanf((char *)(s + x), "%ld", &line); if (line != -1) --line; /* Look for ':' */ flg = 0; while (s[y]) { /* Allow : anywhere on line: works for MIPS C compiler */ /* for (y = 0; s[y];) */ if (s[y]==':') { flg = 1; break; } ++y; } bye: if (!flg) line = -1; *rtn_name = name; *rtn_line = line; } /* Parser for file name lists from grep, find and ls. * * filename * filename:* * filename:line-number:* */ void parseone_grep(struct charmap *map,unsigned char *s,unsigned char **rtn_name,long *rtn_line) { int y; unsigned char *name = NULL; long line = -1; if (s[0] == 'J' && s[1] == 'O' && s[2] == 'E' && s[3] == ':') goto bye; /* Skip to first : or end of line */ for (y = 0;s[y] && s[y] != ':';++y); if (y) { /* This should be the file name */ name = vsncpy(NULL,0,s,y); line = 0; if (s[y] == ':') { /* Maybe there's a line number */ ++y; while (s[y] >= '0' && s[y] <= '9') line = line * 10 + (s[y++] - '0'); --line; if (line < 0 || s[y] != ':') { /* Line number is only valid if there's a second : */ line = 0; } } } bye: *rtn_name = name; *rtn_line = line; } static int parseit(struct charmap *map,unsigned char *s, long int row, void (*parseone)(struct charmap *map, unsigned char *s, unsigned char **rtn_name, long *rtn_line), unsigned char *current_dir) { unsigned char *name = NULL; long line = -1; ERROR *err; parseone(map,s,&name,&line); if (name) { if (line != -1) { /* We have an error */ err = (ERROR *) alitem(&errnodes, sizeof(ERROR)); err->file = name; if (current_dir) { err->file = vsncpy(NULL, 0, sv(current_dir)); err->file = vsncpy(sv(err->file), sv(name)); err->file = canonical(err->file); vsrm(name); } else { err->file = name; } err->org = err->line = line; err->src = row; err->msg = vsncpy(NULL, 0, sc("\\i")); err->msg = vsncpy(sv(err->msg), sv(s)); enqueb(ERROR, link, &errors, err); return 1; } else vsrm(name); } return 0; } /* Parse the error output contained in a buffer */ void kill_ansi(unsigned char *s); static long parserr(B *b) { if (markv(1)) { P *p = pdup(markb, USTR "parserr1"); P *q = pdup(markb, USTR "parserr2"); long nerrs = 0; errbuf = markb->b; freeall(); p_goto_bol(p); do { unsigned char *s; pset(q, p); p_goto_eol(p); s = brvs(q, (int) (p->byte - q->byte)); if (s) { kill_ansi(s); nerrs += parseit(q->b->o.charmap, s, q->line, (q->b->parseone ? q->b->parseone : parseone),q->b->current_dir); vsrm(s); } pgetc(p); } while (p->byte < markk->byte); prm(p); prm(q); return nerrs; } else { P *p = pdup(b->bof, USTR "parserr3"); P *q = pdup(p, USTR "parserr4"); long nerrs = 0; errbuf = b; freeall(); do { unsigned char *s; pset(q, p); p_goto_eol(p); s = brvs(q, (int) (p->byte - q->byte)); if (s) { kill_ansi(s); nerrs += parseit(q->b->o.charmap, s, q->line, (q->b->parseone ? q->b->parseone : parseone), q->b->current_dir); vsrm(s); } } while (pgetc(p) != NO_MORE_DATA); prm(p); prm(q); return nerrs; } } BW *find_a_good_bw(B *b) { W *w; BW *bw = 0; /* Find lowest window with buffer */ if ((w = maint->topwin) != NULL) { do { if ((w->watom->what&TYPETW) && ((BW *)w->object)->b==b && w->y>=0) bw = (BW *)w->object; w = w->link.next; } while (w != maint->topwin); } if (bw) return bw; /* Otherwise just find lowest window */ if ((w = maint->topwin) != NULL) { do { if ((w->watom->what&TYPETW) && w->y>=0) bw = (BW *)w->object; w = w->link.next; } while (w != maint->topwin); } return bw; } int parserrb(B *b) { BW *bw; int n; freeall(); bw = find_a_good_bw(b); unmark(bw); n = parserr(b); if (n) joe_snprintf_1(msgbuf, JOE_MSGBUFSIZE, joe_gettext(_("%d messages found")), n); else joe_snprintf_0(msgbuf, sizeof(msgbuf), joe_gettext(_("No messages found"))); msgnw(bw->parent, msgbuf); return 0; } int urelease(BW *bw) { bw->b->parseone = 0; if (qempty(ERROR, link, &errors) && !errbuf) { joe_snprintf_0(msgbuf, sizeof(msgbuf), joe_gettext(_("No messages"))); } else { int count = freeall(); errbuf = NULL; joe_snprintf_1(msgbuf, sizeof(msgbuf), joe_gettext(_("%d messages cleared")), count); } msgnw(bw->parent, msgbuf); updall(); return 0; } int uparserr(BW *bw) { int n; freeall(); bw->b->parseone = parseone; n = parserr(bw->b); if (n) joe_snprintf_1(msgbuf, JOE_MSGBUFSIZE, joe_gettext(_("%d messages found")), n); else joe_snprintf_0(msgbuf, sizeof(msgbuf), joe_gettext(_("No messages found"))); msgnw(bw->parent, msgbuf); return 0; } int ugparse(BW *bw) { int n; freeall(); bw->b->parseone = parseone_grep; n = parserr(bw->b); if (n) joe_snprintf_1(msgbuf, JOE_MSGBUFSIZE, joe_gettext(_("%d messages found")), n); else joe_snprintf_0(msgbuf, sizeof(msgbuf), joe_gettext(_("No messages found"))); msgnw(bw->parent, msgbuf); return 0; } int jump_to_file_line(BW *bw,unsigned char *file,int line,unsigned char *msg) { int omid; if (!bw->b->name || zcmp(file, bw->b->name)) { if (doswitch(bw, vsdup(file), NULL, NULL)) return -1; bw = (BW *) maint->curwin->object; } omid = mid; mid = 1; pline(bw->cursor, line); dofollows(); mid = omid; bw->cursor->xcol = piscol(bw->cursor); msgnw(bw->parent, msg); return 0; } /* Show current message */ int ucurrent_msg(BW *bw) { if (errptr != &errors) { msgnw(bw->parent, errptr->msg); return 0; } else { msgnw(bw->parent, joe_gettext(_("No messages"))); return -1; } } /* Find line in error database: return pointer to message */ ERROR *srcherr(BW *bw,unsigned char *file,long line) { ERROR *p; for (p = errors.link.next; p != &errors; p=p->link.next) if (!zcmp(p->file,file) && p->org == line) { errptr = p; setline(errbuf, errptr->src); return errptr; } return 0; } /* Delete ansi formatting */ void kill_ansi(unsigned char *s) { unsigned char *d = s; while (*s) if (*s == 27) { while (*s && (*s == 27 || *s == '[' || (*s >= '0' && *s <= '9') || *s == ';')) ++s; if (*s) ++s; } else *d++ = *s++; *d = 0; } int ujump(BW *bw) { int rtn = -1; P *p = pdup(bw->cursor, USTR "ujump"); P *q = pdup(p, USTR "ujump"); unsigned char *s; p_goto_bol(p); p_goto_eol(q); s = brvs(p, (int) (q->byte - p->byte)); kill_ansi(s); prm(p); prm(q); if (s) { unsigned char *name = NULL; unsigned char *fullname = NULL; unsigned char *curd = get_cd(bw->parent); long line = -1; if (bw->b->parseone) bw->b->parseone(bw->b->o.charmap,s,&name,&line); else parseone_grep(bw->b->o.charmap,s,&name,&line); /* Prepend current directory.. */ fullname = vsncpy(NULL, 0, sv(curd)); fullname = vsncpy(sv(fullname), sv(name)); vsrm(name); name = canonical(fullname); if (name && line != -1) { ERROR *p = srcherr(bw, name, line); uprevw((BASE *)bw); /* Check that we made it to a tw */ if (p) rtn = jump_to_file_line(maint->curwin->object,name,p->line,NULL /* p->msg */); else rtn = jump_to_file_line(maint->curwin->object,name,line,NULL); vsrm(name); } vsrm(s); } return rtn; } int unxterr(BW *bw) { if (errptr->link.next == &errors) { msgnw(bw->parent, joe_gettext(_("No more errors"))); return -1; } errptr = errptr->link.next; setline(errbuf, errptr->src); return jump_to_file_line(bw,errptr->file,errptr->line,NULL /* errptr->msg */); } int uprverr(BW *bw) { if (errptr->link.prev == &errors) { msgnw(bw->parent, joe_gettext(_("No more errors"))); return -1; } errptr = errptr->link.prev; setline(errbuf, errptr->src); return jump_to_file_line(bw,errptr->file,errptr->line,NULL /* errptr->msg */); }
Java
<HTML> <HEAD> <META HTTP-EQUIV="content-type" CONTENT="text/html;charset=iso-8859-1"> <TITLE>Using mission packs by dragging them onto the Quake II application icon</TITLE> <META NAME="copyright" CONTENT="Copyright 2002 Fruitz Of Dojo. All Rights Reserved."> <META NAME="description" CONTENT="Learn how to use mission packs with Quake II via drag'n'drop."> </HEAD> <BODY BGCOLOR="#ffffff"><A NAME="itns1003"></A><A NAME="xicnitn"></A> <DIV ALIGN="left"> <TABLE WIDTH="352" BORDER="0" CELLSPACING="0" CELLPADDING="0"> <TR ALIGN="left" VALIGN="top" HEIGHT="20"> <TD ALIGN="left" VALIGN="top" WIDTH="7" HEIGHT="20"> </TD> <TD ALIGN="left" VALIGN="top" WIDTH="22" HEIGHT="20"> <IMG SRC="../gfx/quake2.gif" ALT="Quake II" HEIGHT="16" WIDTH="16"> </TD> <TD ALIGN="left" VALIGN="top" WIDTH="308" HEIGHT="20"> <FONT SIZE="2" FACE="Lucida Grande,Geneva,Arial"> <A HREF="../Quake%20II%20Help.html"> Quake II Help </A> </FONT> </TD> </TR> </TABLE> <TABLE WIDTH="100%" BORDER="0" CELLSPACING="0" CELLPADDING="0"> <TR HEIGHT="40"> <TD VALIGN="middle" WIDTH="7" HEIGHT="40"> </TD> <TD WIDTH="100%" HEIGHT="40"> <FONT SIZE="4" FACE="Lucida Grande,Helvetica,Arial"> <B>Using mission packs by dragging them onto the Quake II application icon</B> </FONT> </TD> </TR> </TABLE> <TABLE WIDTH="100%" BORDER="0" CELLSPACING="0" CELLPADDING="7"> <TR> <TD> <P> <FONT SIZE="2" FACE="Lucida Grande,Geneva,Arial"> Please follow this steps to use mission packs or mods via drag'n'drop: </FONT> </P> </TD> </TR> </TABLE> <TABLE WIDTH="100%" BORDER="0" CELLSPACING="0" CELLPADDING="7" BGCOLOR="#ffffcc"> <TR VALIGN="top" BGCOLOR="#ffffcc"> <TD BGCOLOR="#ffffcc" WIDTH="98%"> <FONT SIZE="2" FACE="Lucida Grande,Geneva,Arial"> <TABLE BORDER="0" CELLSPACING="0" CELLPADDING="3"> <TR VALIGN="top"> <TD WIDTH="16"> <FONT SIZE="2" FACE="Lucida Grande,Helvetica,Arial"> <B>1</B> </FONT> </TD> <TD> <FONT SIZE="2" FACE="Lucida Grande,Geneva,Arial"> Quit Quake II. </FONT> </TD> </TR> </TABLE> <TABLE BORDER="0" CELLSPACING="0" CELLPADDING="3"> <TR VALIGN="top"> <TD WIDTH="16"> <FONT SIZE="2" FACE="Lucida Grande,Helvetica,Arial"> <B>2</B> </FONT> </TD> <TD> <FONT SIZE="2" FACE="Lucida Grande,Geneva,Arial"> Copy the folder of the mission pack to your &quot;Quake II&quot; folder. The &quot;Quake II&quot; folder is the folder that holds the &quot;baseq2&quot; folder. </FONT> </TD> </TR> </TABLE> <TABLE BORDER="0" CELLSPACING="0" CELLPADDING="3"> <TR VALIGN="top"> <TD WIDTH="16"> <FONT SIZE="2" FACE="Lucida Grande,Helvetica,Arial"> <B>3</B> </FONT> </TD> <TD> <FONT SIZE="2" FACE="Lucida Grande,Geneva,Arial"> Drag the folder which contains the mission pack onto the Quake II application icon. </FONT> </TD> </TR> </TABLE> </FONT> </TD> </TR> </TABLE> <FONT SIZE="1">&nbsp;</FONT> <TABLE WIDTH="100%" BORDER="0" CELLSPACING="0" CELLPADDING="7"> <TR VALIGN="top"> <TD ALIGN="left"> <FONT SIZE="2" FACE="Lucida Grande,Geneva,Arial"> </FONT> </TD> <TD ALIGN="right"> <FONT SIZE="2" FACE="Lucida Grande,Geneva,Arial"> <A HREF="help:search='using mission packs' bookID=Quake%20II%20Help"> Tell me more </A> </FONT> </TD> </TR> </TABLE> </DIV> </BODY> </HTML>
Java
# PryGitHub Proyecto para usa desde Github
Java
<?php /** * @package Windwalker.Framework * @subpackage class * * @copyright Copyright (C) 2012 Asikart. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * @author Generated by AKHelper - http://asikart.com */ // no direct access defined('_JEXEC') or die; /** * AKGrid class to dynamically generate HTML tables * * @package Windwalker.Framework * @subpackage class * @since 11.3 */ class AKGrid { /** * Array of columns * @var array * @since 11.3 */ protected $columns = array(); /** * Current active row * @var int * @since 11.3 */ protected $activeRow = 0; /** * Rows of the table (including header and footer rows) * @var array * @since 11.3 */ protected $rows = array(); /** * Header and Footer row-IDs * @var array * @since 11.3 */ protected $specialRows = array('header' => array(), 'footer' => array()); /** * Associative array of attributes for the table-tag * @var array * @since 11.3 */ protected $options; /** * Constructor for a AKGrid object * * @param array $options Associative array of attributes for the table-tag * * @since 11.3 */ public function __construct($options = array()) { $this->setTableOptions($options, true); } /** * Magic function to render this object as a table. * * @return string * * @since 11.3 */ public function __toString() { return $this->toString(); } /** * Method to set the attributes for a table-tag * * @param array $options Associative array of attributes for the table-tag * @param bool $replace Replace possibly existing attributes * * @return AKGrid This object for chaining * * @since 11.3 */ public function setTableOptions($options = array(), $replace = false) { if ($replace) { $this->options = $options; } else { $this->options = array_merge($this->options, $options); } return $this; } /** * Get the Attributes of the current table * * @return array Associative array of attributes * * @since 11.3 */ public function getTableOptions() { return $this->options; } /** * Add new column name to process * * @param string $name Internal column name * * @return AKGrid This object for chaining * * @since 11.3 */ public function addColumn($name) { $this->columns[] = $name; return $this; } /** * Returns the list of internal columns * * @return array List of internal columns * * @since 11.3 */ public function getColumns() { return $this->columns; } /** * Delete column by name * * @param string $name Name of the column to be deleted * * @return AKGrid This object for chaining * * @since 11.3 */ public function deleteColumn($name) { $index = array_search($name, $this->columns); if ($index !== false) { unset($this->columns[$index]); $this->columns = array_values($this->columns); } return $this; } /** * Method to set a whole range of columns at once * This can be used to re-order the columns, too * * @param array $columns List of internal column names * * @return AKGrid This object for chaining * * @since 11.3 */ public function setColumns($columns) { $this->columns = array_values($columns); return $this; } /** * Adds a row to the table and sets the currently * active row to the new row * * @param array $options Associative array of attributes for the row * @param int $special 1 for a new row in the header, 2 for a new row in the footer * * @return AKGrid This object for chaining * * @since 11.3 */ public function addRow($options = array(), $special = false) { $this->rows[]['_row'] = $options; $this->activeRow = count($this->rows) - 1; if ($special) { if ($special === 1) { $this->specialRows['header'][] = $this->activeRow; } else { $this->specialRows['footer'][] = $this->activeRow; } } return $this; } /** * Method to get the attributes of the currently active row * * @return array Associative array of attributes * * @since 11.3 */ public function getRowOptions() { return $this->rows[$this->activeRow]['_row']; } /** * Method to set the attributes of the currently active row * * @param array $options Associative array of attributes * * @return AKGrid This object for chaining * * @since 11.3 */ public function setRowOptions($options) { $this->rows[$this->activeRow]['_row'] = $options; return $this; } /** * Get the currently active row ID * * @return int ID of the currently active row * * @since 11.3 */ public function getActiveRow() { return $this->activeRow; } /** * Set the currently active row * * @param int $id ID of the row to be set to current * * @return AKGrid This object for chaining * * @since 11.3 */ public function setActiveRow($id) { $this->activeRow = (int) $id; return $this; } /** * Set cell content for a specific column for the * currently active row * * @param string $name Name of the column * @param string $content Content for the cell * @param array $option Associative array of attributes for the td-element * @param bool $replace If false, the content is appended to the current content of the cell * * @return AKGrid This object for chaining * * @since 11.3 */ public function setRowCell($name, $content, $option = array(), $replace = true) { if ($replace || !isset($this->rows[$this->activeRow][$name])) { $cell = new stdClass; $cell->options = $option; $cell->content = $content; $this->rows[$this->activeRow][$name] = $cell; } else { $this->rows[$this->activeRow][$name]->content .= $content; $this->rows[$this->activeRow][$name]->options = $option; } return $this; } /** * Get all data for a row * * @param int $id ID of the row to return * * @return array Array of columns of a table row * * @since 11.3 */ public function getRow($id = false) { if ($id === false) { $id = $this->activeRow; } if (isset($this->rows[(int) $id])) { return $this->rows[(int) $id]; } else { return false; } } /** * Get the IDs of all rows in the table * * @param int $special false for the standard rows, 1 for the header rows, 2 for the footer rows * * @return array Array of IDs * * @since 11.3 */ public function getRows($special = false) { if ($special) { if ($special === 1) { return $this->specialRows['header']; } else { return $this->specialRows['footer']; } } return array_diff(array_keys($this->rows), array_merge($this->specialRows['header'], $this->specialRows['footer'])); } /** * Delete a row from the object * * @param int $id ID of the row to be deleted * * @return AKGrid This object for chaining * * @since 11.3 */ public function deleteRow($id) { unset($this->rows[$id]); if (in_array($id, $this->specialRows['header'])) { unset($this->specialRows['header'][array_search($id, $this->specialRows['header'])]); } if (in_array($id, $this->specialRows['footer'])) { unset($this->specialRows['footer'][array_search($id, $this->specialRows['footer'])]); } if ($this->activeRow == $id) { end($this->rows); $this->activeRow = key($this->rows); } return $this; } /** * Render the HTML table * * @return string The rendered HTML table * * @since 11.3 */ public function toString() { $output = array(); $output[] = '<table' . $this->renderAttributes($this->getTableOptions()) . '>'; if (count($this->specialRows['header'])) { $output[] = $this->renderArea($this->specialRows['header'], 'thead', 'th'); } if (count($this->specialRows['footer'])) { $output[] = $this->renderArea($this->specialRows['footer'], 'tfoot'); } $ids = array_diff(array_keys($this->rows), array_merge($this->specialRows['header'], $this->specialRows['footer'])); if (count($ids)) { $output[] = $this->renderArea($ids); } $output[] = '</table>'; return implode('', $output); } /** * Render an area of the table * * @param array $ids IDs of the rows to render * @param string $area Name of the area to render. Valid: tbody, tfoot, thead * @param string $cell Name of the cell to render. Valid: td, th * * @return string The rendered table area * * @since 11.3 */ protected function renderArea($ids, $area = 'tbody', $cell = 'td') { $output = array(); $output[] = '<' . $area . ">\n"; foreach ($ids as $id) { $output[] = "\t<tr" . $this->renderAttributes($this->rows[$id]['_row']) . ">\n"; foreach ($this->getColumns() as $name) { if (isset($this->rows[$id][$name])) { $column = $this->rows[$id][$name]; $output[] = "\t\t<" . $cell . $this->renderAttributes($column->options) . '>' . $column->content . '</' . $cell . ">\n"; } } $output[] = "\t</tr>\n"; } $output[] = '</' . $area . '>'; return implode('', $output); } /** * Renders an HTML attribute from an associative array * * @param array $attributes Associative array of attributes * * @return string The HTML attribute string * * @since 11.3 */ protected function renderAttributes($attributes) { if (count((array) $attributes) == 0) { return ''; } $return = array(); foreach ($attributes as $key => $option) { $return[] = $key . '="' . $option . '"'; } return ' ' . implode(' ', $return); } }
Java
<?php class Metabox { public static $boxes = array(); /** * @static * @param $type * @param $options * @return Metabox */ public static function factory($type, $options = null) { $parts = explode('_', $type); array_walk( $parts, function(&$item){ $item = ucfirst($item); } ); $class = 'Metabox_'.implode('_', $parts); if(class_exists($class)) { if( ! isset($options['type']) ) { $options['type'] = $type; } return new $class($options); } return false; } /** * @static * @param $key * @return Metabox */ public static function get($key) { return (isset(self::$boxes[$key]) ? self::$boxes[$key] : null); } public static function attr($box, $attr) { return (isset(self::$boxes[$box]->$attr) ? self::$boxes[$box]->$attr : null); } }
Java
/* * tseries.h * * specific parts for B&R T-Series Motherboard * * Copyright (C) 2013 Hannes Schmelzer <oe5hpm@oevsv.at> - * Bernecker & Rainer Industrieelektronik GmbH - http://www.br-automation.com * * SPDX-License-Identifier: GPL-2.0+ */ #ifndef __CONFIG_TSERIES_H__ #define __CONFIG_TSERIES_H__ #include <configs/bur_cfg_common.h> #include <configs/bur_am335x_common.h> /* ------------------------------------------------------------------------- */ #define CONFIG_AM335X_LCD #define CONFIG_LCD #define CONFIG_LCD_ROTATION #define CONFIG_LCD_DT_SIMPLEFB #define CONFIG_SYS_WHITE_ON_BLACK #define LCD_BPP LCD_COLOR32 #define CONFIG_HW_WATCHDOG #define CONFIG_OMAP_WATCHDOG #define CONFIG_SPL_WATCHDOG_SUPPORT #define CONFIG_SPL_GPIO_SUPPORT /* Bootcount using the RTC block */ #define CONFIG_SYS_BOOTCOUNT_ADDR 0x44E3E000 #define CONFIG_BOOTCOUNT_LIMIT #define CONFIG_BOOTCOUNT_AM33XX /* memory */ #define CONFIG_SYS_MALLOC_LEN (5 * 1024 * 1024) /* Clock Defines */ #define V_OSCK 26000000 /* Clock output from T2 */ #define V_SCLK (V_OSCK) #define CONFIG_POWER_TPS65217 /* Support both device trees and ATAGs. */ #define CONFIG_OF_LIBFDT #define CONFIG_USE_FDT /* use fdt within board code */ #define CONFIG_OF_BOARD_SETUP #define CONFIG_CMDLINE_TAG #define CONFIG_SETUP_MEMORY_TAGS #define CONFIG_INITRD_TAG #define CONFIG_CMD_BOOTZ /*#define CONFIG_MACH_TYPE 3589*/ #define CONFIG_MACH_TYPE 0xFFFFFFFF /* TODO: check with kernel*/ /* MMC/SD IP block */ #if defined(CONFIG_EMMC_BOOT) #define CONFIG_MMC #define CONFIG_GENERIC_MMC #define CONFIG_OMAP_HSMMC #define CONFIG_CMD_MMC #define CONFIG_SUPPORT_EMMC_BOOT /* RAW SD card / eMMC locations. */ #define CONFIG_SYS_MMCSD_RAW_MODE_U_BOOT_SECTOR 0x300 /*addr. 0x60000 */ #define CONFIG_SYS_U_BOOT_MAX_SIZE_SECTORS 0x200 /* 256 KB */ #define CONFIG_SPL_MMC_SUPPORT #endif /* CONFIG_EMMC_BOOT */ /* * When we have SPI or NAND flash we expect to be making use of mtdparts, * both for ease of use in U-Boot and for passing information on to * the Linux kernel. */ #if defined(CONFIG_SPI_BOOT) || defined(CONFIG_NAND) #define CONFIG_MTD_DEVICE /* Required for mtdparts */ #define CONFIG_CMD_MTDPARTS #endif /* CONFIG_SPI_BOOT, ... */ #undef CONFIG_SPL_OS_BOOT #ifdef CONFIG_SPL_OS_BOOT #define CONFIG_SYS_SPL_ARGS_ADDR 0x80F80000 /* RAW SD card / eMMC */ #define CONFIG_SYS_MMCSD_RAW_MODE_KERNEL_SECTOR 0x900 /* address 0x120000 */ #define CONFIG_SYS_MMCSD_RAW_MODE_ARGS_SECTOR 0x80 /* address 0x10000 */ #define CONFIG_SYS_MMCSD_RAW_MODE_ARGS_SECTORS 0x80 /* 64KiB */ /* NAND */ #ifdef CONFIG_NAND #define CONFIG_CMD_SPL_NAND_OFS 0x080000 /* end of u-boot */ #define CONFIG_SYS_NAND_SPL_KERNEL_OFFS 0x140000 #define CONFIG_CMD_SPL_WRITE_SIZE 0x2000 #endif /* CONFIG_NAND */ #endif /* CONFIG_SPL_OS_BOOT */ #ifdef CONFIG_NAND #define CONFIG_SPL_NAND_AM33XX_BCH /* OMAP4 and later ELM support */ #define CONFIG_SPL_NAND_SUPPORT #define CONFIG_SPL_NAND_BASE #define CONFIG_SPL_NAND_DRIVERS #define CONFIG_SPL_NAND_ECC #define CONFIG_SYS_NAND_U_BOOT_START CONFIG_SYS_TEXT_BASE #define CONFIG_SYS_NAND_U_BOOT_OFFS 0x80000 #endif /* CONFIG_NAND */ /* Always 64 KiB env size */ #define CONFIG_ENV_SIZE (64 << 10) #ifdef CONFIG_NAND #define NANDARGS \ "mtdids=" MTDIDS_DEFAULT "\0" \ "mtdparts=" MTDPARTS_DEFAULT "\0" \ "nandargs=setenv bootargs console=${console} " \ "${optargs} " \ "${optargs_rot} " \ "root=mtd6 " \ "rootfstype=jffs2\0" \ "kernelsize=0x400000\0" \ "nandboot=echo booting from nand ...; " \ "run nandargs; " \ "nand read ${loadaddr} kernel ${kernelsize}; " \ "bootz ${loadaddr} - ${dtbaddr}\0" \ "defboot=run nandboot\0" \ "bootlimit=1\0" \ "simplefb=1\0 " \ "altbootcmd=run usbscript\0" #else #define NANDARGS "" #endif /* CONFIG_NAND */ #ifdef CONFIG_MMC #define MMCARGS \ "dtbdev=mmc\0" \ "dtbpart=0:1\0" \ "mmcroot0=setenv bootargs ${optargs_rot} ${optargs} console=${console}\0" \ "mmcroot1=setenv bootargs ${optargs_rot} ${optargs} console=${console} " \ "root=/dev/mmcblk0p2 rootfstype=ext4\0" \ "mmcboot0=echo booting Updatesystem from mmc (ext4-fs) ...; " \ "setenv simplefb 1; " \ "ext4load mmc 0:1 ${loadaddr} /${kernel}; " \ "ext4load mmc 0:1 ${ramaddr} /${ramdisk}; " \ "run mmcroot0; bootz ${loadaddr} ${ramaddr} ${dtbaddr};\0" \ "mmcboot1=echo booting PPT-OS from mmc (ext4-fs) ...; " \ "setenv simplefb 0; " \ "ext4load mmc 0:2 ${loadaddr} /boot/${kernel}; " \ "run mmcroot1; bootz ${loadaddr} - ${dtbaddr};\0" \ "defboot=ext4load mmc 0:2 ${loadaddr} /boot/PPTImage.md5 && run mmcboot1; " \ "ext4load mmc 0:1 ${dtbaddr} /$dtb && run mmcboot0; " \ "run ramboot; run usbscript;\0" \ "bootlimit=1\0" \ "altbootcmd=run mmcboot0;\0" \ "upduboot=dhcp; " \ "tftp ${loadaddr} MLO && mmc write ${loadaddr} 100 100; " \ "tftp ${loadaddr} u-boot.img && mmc write ${loadaddr} 300 400;\0" #else #define MMCARGS "" #endif /* CONFIG_MMC */ #ifndef CONFIG_SPL_BUILD #define CONFIG_EXTRA_ENV_SETTINGS \ BUR_COMMON_ENV \ "verify=no\0" \ "autoload=0\0" \ "dtb=bur-ppt-ts30.dtb\0" \ "dtbaddr=0x80100000\0" \ "loadaddr=0x80200000\0" \ "ramaddr=0x80A00000\0" \ "kernel=zImage\0" \ "ramdisk=rootfs.cpio.uboot\0" \ "console=ttyO0,115200n8\0" \ "optargs=consoleblank=0 quiet panic=2\0" \ "nfsroot=/tftpboot/tseries/rootfs-small\0" \ "nfsopts=nolock\0" \ "ramargs=setenv bootargs ${optargs} console=${console} root=/dev/ram0\0" \ "netargs=setenv bootargs console=${console} " \ "${optargs} " \ "root=/dev/nfs " \ "nfsroot=${serverip}:${nfsroot},${nfsopts} rw " \ "ip=dhcp\0" \ "netboot=echo Booting from network ...; " \ "dhcp; " \ "tftp ${loadaddr} ${kernel}; " \ "tftp ${dtbaddr} ${dtb}; " \ "run netargs; " \ "bootz ${loadaddr} - ${dtbaddr}\0" \ "ramboot=echo Booting from network into RAM ...; "\ "if dhcp; then; " \ "tftp ${loadaddr} ${kernel}; " \ "tftp ${ramaddr} ${ramdisk}; " \ "if ext4load ${dtbdev} ${dtbpart} ${dtbaddr} /${dtb}; " \ "then; else tftp ${dtbaddr} ${dtb}; fi;" \ "run mmcroot0; " \ "bootz ${loadaddr} ${ramaddr} ${dtbaddr}; fi;\0" \ "netupdate=echo Updating UBOOT from Network (TFTP) ...; " \ "setenv autoload 0; " \ "dhcp && tftp 0x80000000 updateUBOOT.img && source;\0" \ NANDARGS \ MMCARGS #endif /* !CONFIG_SPL_BUILD*/ #define CONFIG_BOOTCOMMAND \ "run defboot;" #define CONFIG_BOOTDELAY 0 #ifdef CONFIG_NAND /* * GPMC block. We support 1 device and the physical address to * access CS0 at is 0x8000000. */ #define CONFIG_SYS_MAX_NAND_DEVICE 1 #define CONFIG_SYS_NAND_BASE 0x8000000 #define CONFIG_NAND_OMAP_GPMC /* don't change OMAP_ELM, ECCSCHEME. ROM code only supports this */ #define CONFIG_NAND_OMAP_ELM #define CONFIG_NAND_OMAP_ECCSCHEME OMAP_ECC_BCH8_CODE_HW #define CONFIG_SYS_NAND_5_ADDR_CYCLE #define CONFIG_SYS_NAND_BLOCK_SIZE (128*1024) #define CONFIG_SYS_NAND_PAGE_SIZE 2048 #define CONFIG_SYS_NAND_PAGE_COUNT (CONFIG_SYS_NAND_BLOCK_SIZE / \ CONFIG_SYS_NAND_PAGE_SIZE) #define CONFIG_SYS_NAND_OOBSIZE 64 #define CONFIG_SYS_NAND_BAD_BLOCK_POS NAND_LARGE_BADBLOCK_POS #define CONFIG_SYS_NAND_ECCPOS {2, 3, 4, 5, 6, 7, 8, 9, \ 10, 11, 12, 13, 14, 15, 16, 17, \ 18, 19, 20, 21, 22, 23, 24, 25, \ 26, 27, 28, 29, 30, 31, 32, 33, \ 34, 35, 36, 37, 38, 39, 40, 41, \ 42, 43, 44, 45, 46, 47, 48, 49, \ 50, 51, 52, 53, 54, 55, 56, 57, } #define CONFIG_SYS_NAND_ECCSIZE 512 #define CONFIG_SYS_NAND_ECCBYTES 14 #define CONFIG_SYS_NAND_U_BOOT_START CONFIG_SYS_TEXT_BASE #define CONFIG_SYS_NAND_U_BOOT_OFFS 0x80000 #define MTDIDS_DEFAULT "nand0=omap2-nand.0" #define MTDPARTS_DEFAULT "mtdparts=omap2-nand.0:" \ "128k(MLO)," \ "128k(MLO.backup)," \ "128k(dtb)," \ "128k(u-boot-env)," \ "512k(u-boot)," \ "4m(kernel),"\ "128m(rootfs),"\ "-(user)" #define CONFIG_NAND_OMAP_GPMC_WSCFG 1 #endif /* CONFIG_NAND */ /* USB configuration */ #define CONFIG_USB_MUSB_DSPS #define CONFIG_ARCH_MISC_INIT #define CONFIG_USB_MUSB_PIO_ONLY #define CONFIG_USB_MUSB_DISABLE_BULK_COMBINE_SPLIT /* attention! not only for gadget, enables also highspeed in hostmode */ #define CONFIG_USB_GADGET_DUALSPEED #define CONFIG_AM335X_USB0 #define CONFIG_AM335X_USB0_MODE MUSB_HOST #define CONFIG_AM335X_USB1 #define CONFIG_AM335X_USB1_MODE MUSB_HOST #if defined(CONFIG_SPI_BOOT) /* McSPI IP block */ #define CONFIG_SPI #define CONFIG_OMAP3_SPI #define CONFIG_SF_DEFAULT_SPEED 24000000 #define CONFIG_SPL_SPI_SUPPORT #define CONFIG_SPL_SPI_FLASH_SUPPORT #define CONFIG_SPL_SPI_LOAD #define CONFIG_SYS_SPI_U_BOOT_OFFS 0x20000 #undef CONFIG_ENV_IS_NOWHERE #define CONFIG_ENV_IS_IN_SPI_FLASH #define CONFIG_SYS_REDUNDAND_ENVIRONMENT #define CONFIG_ENV_SPI_MAX_HZ CONFIG_SF_DEFAULT_SPEED #define CONFIG_ENV_SECT_SIZE (4 << 10) /* 4 KB sectors */ #define CONFIG_ENV_OFFSET (768 << 10) /* 768 KiB in */ #define CONFIG_ENV_OFFSET_REDUND (896 << 10) /* 896 KiB in */ #elif defined(CONFIG_EMMC_BOOT) #undef CONFIG_ENV_IS_NOWHERE #define CONFIG_ENV_IS_IN_MMC #define CONFIG_SYS_MMC_ENV_DEV 0 #define CONFIG_SYS_MMC_ENV_PART 2 #define CONFIG_ENV_OFFSET 0x40000 /* TODO: Adresse definieren */ #define CONFIG_ENV_OFFSET_REDUND (CONFIG_ENV_OFFSET + CONFIG_ENV_SIZE) #define CONFIG_SYS_REDUNDAND_ENVIRONMENT #elif defined(CONFIG_NAND) /* No NAND env support in SPL */ #ifdef CONFIG_SPL_BUILD #define CONFIG_ENV_IS_NOWHERE #else #define CONFIG_ENV_IS_IN_NAND #endif #define CONFIG_ENV_OFFSET 0x60000 #define CONFIG_SYS_ENV_SECT_SIZE CONFIG_ENV_SIZE #else #error "no storage for Environment defined!" #endif /* * Common filesystems support. When we have removable storage we * enabled a number of useful commands and support. */ #if defined(CONFIG_MMC) || defined(CONFIG_USB_STORAGE) #define CONFIG_DOS_PARTITION #define CONFIG_CMD_FAT #define CONFIG_FAT_WRITE #define CONFIG_FS_EXT4 #define CONFIG_EXT4_WRITE #define CONFIG_CMD_EXT4 #define CONFIG_CMD_EXT4_WRITE #define CONFIG_CMD_FS_GENERIC #endif /* CONFIG_MMC, ... */ #endif /* ! __CONFIG_TSERIES_H__ */
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_25) on Sun Oct 26 12:20:02 GMT+02:00 2014 --> <title>Item</title> <meta name="date" content="2014-10-26"> <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Item"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":10,"i7":10,"i8":10,"i9":9,"i10":10,"i11":10,"i12":10,"i13":10,"i14":10,"i15":10,"i16":10,"i17":10}; var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Item.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../index.html?eshop/entity/Item.html" target="_top">Frames</a></li> <li><a href="Item.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">eshop.entity</div> <h2 title="Class Item" class="title">Class Item</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>eshop.entity.Item</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="typeNameLabel">Item</span> extends java.lang.Object</pre> <div class="block">Item class models a stock item in eShop program. Items can be interactively produced using <a href="../../eshop/parser/Parser.html#inputItem--"><code>eshop.parser.Parser#inputItem() factory method</code></a></div> <dl> <dt><span class="simpleTagLabel">Since:</span></dt> <dd>0.1</dd> <dt><span class="simpleTagLabel">Version:</span></dt> <dd>0.1</dd> <dt><span class="simpleTagLabel">Author:</span></dt> <dd>Trayan Iliev, http://iproduct.org</dd> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../eshop/parser/Parser.html" title="class in eshop.parser"><code>Parser</code></a></dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#Item--">Item</a></span>()</code> <div class="block">No argument constructor</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#Item-long-java.lang.String-java.lang.String-">Item</a></span>(long&nbsp;id, java.lang.String&nbsp;name, java.lang.String&nbsp;manufacturer)</code> <div class="block">Constructor with mandatory arguments</div> </td> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#Item-long-java.lang.String-java.lang.String-java.lang.String-java.lang.String-double-int-">Item</a></span>(long&nbsp;id, java.lang.String&nbsp;name, java.lang.String&nbsp;manufacturer, java.lang.String&nbsp;category, java.lang.String&nbsp;description, double&nbsp;price, int&nbsp;stockQuantity)</code> <div class="block">Full constructor</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#equals-java.lang.Object-">equals</a></span>(java.lang.Object&nbsp;obj)</code>&nbsp;</td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#getCategory--">getCategory</a></span>()</code> <div class="block">Return item category.</div> </td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#getDescription--">getDescription</a></span>()</code> <div class="block">Return item description</div> </td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>long</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#getId--">getId</a></span>()</code> <div class="block">Returns item id</div> </td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#getManufacturer--">getManufacturer</a></span>()</code> <div class="block">Return item manufacturer</div> </td> </tr> <tr id="i5" class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#getName--">getName</a></span>()</code> <div class="block">Returns item name</div> </td> </tr> <tr id="i6" class="altColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#getPrice--">getPrice</a></span>()</code> <div class="block">Return item price in default currency</div> </td> </tr> <tr id="i7" class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#getStockQuantity--">getStockQuantity</a></span>()</code> <div class="block">Returns stock quantity available for the item</div> </td> </tr> <tr id="i8" class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#hashCode--">hashCode</a></span>()</code>&nbsp;</td> </tr> <tr id="i9" class="rowColor"> <td class="colFirst"><code>static void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#main-java.lang.String:A-">main</a></span>(java.lang.String[]&nbsp;args)</code>&nbsp;</td> </tr> <tr id="i10" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#setCategory-java.lang.String-">setCategory</a></span>(java.lang.String&nbsp;category)</code> <div class="block">Sets item category from a predefined list of categories.</div> </td> </tr> <tr id="i11" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#setDescription-java.lang.String-">setDescription</a></span>(java.lang.String&nbsp;description)</code> <div class="block">Sets item description</div> </td> </tr> <tr id="i12" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#setId-long-">setId</a></span>(long&nbsp;id)</code> <div class="block">Sets item id</div> </td> </tr> <tr id="i13" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#setManufacturer-java.lang.String-">setManufacturer</a></span>(java.lang.String&nbsp;manufacturer)</code> <div class="block">Sets item manufacturer</div> </td> </tr> <tr id="i14" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#setName-java.lang.String-">setName</a></span>(java.lang.String&nbsp;name)</code> <div class="block">Sets item name</div> </td> </tr> <tr id="i15" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#setPrice-double-">setPrice</a></span>(double&nbsp;price)</code> <div class="block">Sets item price in default currency</div> </td> </tr> <tr id="i16" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#setStockQuantity-int-">setStockQuantity</a></span>(int&nbsp;stockQuantity)</code> <div class="block">Modifies the stock quantity available for the item</div> </td> </tr> <tr id="i17" class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#toString--">toString</a></span>()</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>getClass, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="Item--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>Item</h4> <pre>public&nbsp;Item()</pre> <div class="block">No argument constructor</div> </li> </ul> <a name="Item-long-java.lang.String-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>Item</h4> <pre>public&nbsp;Item(long&nbsp;id, java.lang.String&nbsp;name, java.lang.String&nbsp;manufacturer)</pre> <div class="block">Constructor with mandatory arguments</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>id</code> - item it</dd> <dd><code>name</code> - item name</dd> <dd><code>manufacturer</code> - item manufacturer</dd> </dl> </li> </ul> <a name="Item-long-java.lang.String-java.lang.String-java.lang.String-java.lang.String-double-int-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>Item</h4> <pre>public&nbsp;Item(long&nbsp;id, java.lang.String&nbsp;name, java.lang.String&nbsp;manufacturer, java.lang.String&nbsp;category, java.lang.String&nbsp;description, double&nbsp;price, int&nbsp;stockQuantity)</pre> <div class="block">Full constructor</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>@param</code> - id item it</dd> <dd><code>name</code> - item name</dd> <dd><code>manufacturer</code> - item manufacturer</dd> <dd><code>category</code> - category name from a predefined list of categories</dd> <dd><code>description</code> - optional item description</dd> <dd><code>price</code> - optional standard price for the item</dd> <dd><code>stockQuantity</code> - optional available stock quantity for the item</dd> </dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getId--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getId</h4> <pre>public&nbsp;long&nbsp;getId()</pre> <div class="block">Returns item id</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the id</dd> </dl> </li> </ul> <a name="setId-long-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setId</h4> <pre>public&nbsp;void&nbsp;setId(long&nbsp;id)</pre> <div class="block">Sets item id</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>id</code> - the id to set</dd> </dl> </li> </ul> <a name="getName--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getName</h4> <pre>public&nbsp;java.lang.String&nbsp;getName()</pre> <div class="block">Returns item name</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the name</dd> </dl> </li> </ul> <a name="setName-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setName</h4> <pre>public&nbsp;void&nbsp;setName(java.lang.String&nbsp;name)</pre> <div class="block">Sets item name</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>name</code> - the name to set</dd> </dl> </li> </ul> <a name="getManufacturer--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getManufacturer</h4> <pre>public&nbsp;java.lang.String&nbsp;getManufacturer()</pre> <div class="block">Return item manufacturer</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the manufacturer</dd> </dl> </li> </ul> <a name="setManufacturer-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setManufacturer</h4> <pre>public&nbsp;void&nbsp;setManufacturer(java.lang.String&nbsp;manufacturer)</pre> <div class="block">Sets item manufacturer</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>manufacturer</code> - the manufacturer to set</dd> </dl> </li> </ul> <a name="getCategory--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getCategory</h4> <pre>public&nbsp;java.lang.String&nbsp;getCategory()</pre> <div class="block">Return item category. See <a href="../../eshop/entity/Item.html#setCategory-java.lang.String-"><code>examples in #setCategory(String)</code></a></div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the category</dd> </dl> </li> </ul> <a name="setCategory-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setCategory</h4> <pre>public&nbsp;void&nbsp;setCategory(java.lang.String&nbsp;category)</pre> <div class="block">Sets item category from a predefined list of categories. Example: <ul> <li>Processors</li> <li>Moteherboards</li> <li>Accessories</li> <li>etc.</li> </ul></div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>category</code> - the category to set</dd> </dl> </li> </ul> <a name="getDescription--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getDescription</h4> <pre>public&nbsp;java.lang.String&nbsp;getDescription()</pre> <div class="block">Return item description</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the description</dd> </dl> </li> </ul> <a name="setDescription-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setDescription</h4> <pre>public&nbsp;void&nbsp;setDescription(java.lang.String&nbsp;description)</pre> <div class="block">Sets item description</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>description</code> - the description to set</dd> </dl> </li> </ul> <a name="getPrice--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getPrice</h4> <pre>public&nbsp;double&nbsp;getPrice()</pre> <div class="block">Return item price in default currency</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the price</dd> </dl> </li> </ul> <a name="setPrice-double-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setPrice</h4> <pre>public&nbsp;void&nbsp;setPrice(double&nbsp;price)</pre> <div class="block">Sets item price in default currency</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>price</code> - the price to set</dd> </dl> </li> </ul> <a name="getStockQuantity--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getStockQuantity</h4> <pre>public&nbsp;int&nbsp;getStockQuantity()</pre> <div class="block">Returns stock quantity available for the item</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the stockQuantity</dd> </dl> </li> </ul> <a name="setStockQuantity-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setStockQuantity</h4> <pre>public&nbsp;void&nbsp;setStockQuantity(int&nbsp;stockQuantity)</pre> <div class="block">Modifies the stock quantity available for the item</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>stockQuantity</code> - the stockQuantity to set</dd> </dl> </li> </ul> <a name="hashCode--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>hashCode</h4> <pre>public&nbsp;int&nbsp;hashCode()</pre> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code>hashCode</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="equals-java.lang.Object-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>equals</h4> <pre>public&nbsp;boolean&nbsp;equals(java.lang.Object&nbsp;obj)</pre> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code>equals</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="toString--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>toString</h4> <pre>public&nbsp;java.lang.String&nbsp;toString()</pre> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code>toString</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="main-java.lang.String:A-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>main</h4> <pre>public static&nbsp;void&nbsp;main(java.lang.String[]&nbsp;args)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Item.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../index.html?eshop/entity/Item.html" target="_top">Frames</a></li> <li><a href="Item.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Java
<!DOCTYPE html> <html> <head> <title>Asterisk Project : Asterisk 12 ManagerEvent_ConfbridgeEnd</title> <link rel="stylesheet" href="styles/site.css" type="text/css" /> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body class="theme-default aui-theme-default"> <div id="page"> <div id="main" class="aui-page-panel"> <div id="main-header"> <div id="breadcrumb-section"> <ol id="breadcrumbs"> <li class="first"> <span><a href="index.html">Asterisk Project</a></span> </li> <li> <span><a href="Asterisk-12-Documentation_25919697.html">Asterisk 12 Documentation</a></span> </li> <li> <span><a href="Asterisk-12-Command-Reference_26476688.html">Asterisk 12 Command Reference</a></span> </li> <li> <span><a href="Asterisk-12-AMI-Events_26476694.html">Asterisk 12 AMI Events</a></span> </li> </ol> </div> <h1 id="title-heading" class="pagetitle"> <span id="title-text"> Asterisk Project : Asterisk 12 ManagerEvent_ConfbridgeEnd </span> </h1> </div> <div id="content" class="view"> <div class="page-metadata"> Added by wikibot , edited by wikibot on Dec 18, 2013 </div> <div id="main-content" class="wiki-content group"> <h1 id="Asterisk12ManagerEvent_ConfbridgeEnd-ConfbridgeEnd">ConfbridgeEnd</h1> <h3 id="Asterisk12ManagerEvent_ConfbridgeEnd-Synopsis">Synopsis</h3> <p>Raised when a conference ends.</p> <h3 id="Asterisk12ManagerEvent_ConfbridgeEnd-Description">Description</h3> <h3 id="Asterisk12ManagerEvent_ConfbridgeEnd-Syntax">Syntax</h3> <div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent panelContent"> <pre>Action: Conference: &lt;value&gt; BridgeUniqueid: &lt;value&gt; BridgeType: &lt;value&gt; BridgeTechnology: &lt;value&gt; BridgeCreator: &lt;value&gt; BridgeName: &lt;value&gt; BridgeNumChannels: &lt;value&gt; </pre> </div></div> <h5 id="Asterisk12ManagerEvent_ConfbridgeEnd-Arguments">Arguments</h5> <ul> <li><code>Conference</code> - The name of the Confbridge conference.</li> <li><code>BridgeUniqueid</code></li> <li><code>BridgeType</code> - The type of bridge</li> <li><code>BridgeTechnology</code> - Technology in use by the bridge</li> <li><code>BridgeCreator</code> - Entity that created the bridge if applicable</li> <li><code>BridgeName</code> - Name used to refer to the bridge by its BridgeCreator if applicable</li> <li><code>BridgeNumChannels</code> - Number of channels in the bridge</li> </ul> <h3 id="Asterisk12ManagerEvent_ConfbridgeEnd-SeeAlso">See Also</h3> <ul> <li><a href="Asterisk-12-ManagerEvent_ConfbridgeStart_26478095.html">Asterisk 12 ManagerEvent_ConfbridgeStart</a></li> <li><a href="Asterisk-12-Application_ConfBridge_26476812.html">Asterisk 12 Application_ConfBridge</a></li> </ul> <h3 id="Asterisk12ManagerEvent_ConfbridgeEnd-ImportVersion">Import Version</h3> <p>This documentation was imported from Asterisk Version SVN-branch-12-r404099</p> </div> </div> </div> <div id="footer"> <section class="footer-body"> <p>Document generated by Confluence on Dec 20, 2013 14:14</p> </section> </div> </div> </body> </html>
Java
<?php /** * General API for generating and formatting diffs - the differences between * two sequences of strings. * * The original PHP version of this code was written by Geoffrey T. Dairiki * <dairiki@dairiki.org>, and is used/adapted with his permission. * * Copyright 2004 Geoffrey T. Dairiki <dairiki@dairiki.org> * Copyright 2004-2010 The Horde Project (http://www.horde.org/) * * See the enclosed file COPYING for license information (LGPL). If you did * not receive this file, see http://opensource.org/licenses/lgpl-license.php. * * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> */ class Text_Diff { /** * Array of changes. * * @var array */ var $_edits; /** * Computes diffs between sequences of strings. * * @param string $engine Name of the diffing engine to use. 'auto' * will automatically select the best. * @param array $params Parameters to pass to the diffing engine. * Normally an array of two arrays, each * containing the lines from a file. */ function Text_Diff($engine, $params) { // Backward compatibility workaround. if (!is_string($engine)) { $params = array($engine, $params); $engine = 'auto'; } if ($engine == 'auto') { $engine = extension_loaded('xdiff') ? 'xdiff' : 'native'; } else { $engine = basename($engine); } // WP #7391 require_once dirname(__FILE__) . '/Diff/Engine/' . $engine . '.php'; $class = 'Text_Diff_Engine_' . $engine; $diff_engine = new $class(); $this->_edits = call_user_func_array(array($diff_engine, 'diff'), $params); } /** * Returns the array of differences. */ function getDiff() { return $this->_edits; } /** * returns the number of new (added) lines in a given diff. * * @since Text_Diff 1.1.0 * * @return integer The number of new lines */ function countAddedLines() { $count = 0; foreach ($this->_edits as $edit) { if (is_a($edit, 'Text_Diff_Op_add') || is_a($edit, 'Text_Diff_Op_change')) { $count += $edit->nfinal(); } } return $count; } /** * Returns the number of deleted (removed) lines in a given diff. * * @since Text_Diff 1.1.0 * * @return integer The number of deleted lines */ function countDeletedLines() { $count = 0; foreach ($this->_edits as $edit) { if (is_a($edit, 'Text_Diff_Op_delete') || is_a($edit, 'Text_Diff_Op_change')) { $count += $edit->norig(); } } return $count; } /** * Computes a reversed diff. * * Example: * <code> * $diff = new Text_Diff($lines1, $lines2); * $rev = $diff->reverse(); * </code> * * @return Text_Diff A Diff object representing the inverse of the * original diff. Note that we purposely don't return a * reference here, since this essentially is a clone() * method. */ function reverse() { if (version_compare(zend_version(), '2', '>')) { $rev = clone($this); } else { $rev = $this; } $rev->_edits = array(); foreach ($this->_edits as $edit) { $rev->_edits[] = $edit->reverse(); } return $rev; } /** * Checks for an empty diff. * * @return boolean True if two sequences were identical. */ function isEmpty() { foreach ($this->_edits as $edit) { if (!is_a($edit, 'Text_Diff_Op_copy')) { return false; } } return true; } /** * Computes the length of the Longest Common Subsequence (LCS). * * This is mostly for diagnostic purposes. * * @return integer The length of the LCS. */ function lcs() { $lcs = 0; foreach ($this->_edits as $edit) { if (is_a($edit, 'Text_Diff_Op_copy')) { $lcs += count($edit->orig); } } return $lcs; } /** * Gets the original set of lines. * * This reconstructs the $from_lines parameter passed to the constructor. * * @return array The original sequence of strings. */ function getOriginal() { $lines = array(); foreach ($this->_edits as $edit) { if ($edit->orig) { array_splice($lines, count($lines), 0, $edit->orig); } } return $lines; } /** * Gets the final set of lines. * * This reconstructs the $to_lines parameter passed to the constructor. * * @return array The sequence of strings. */ function getFinal() { $lines = array(); foreach ($this->_edits as $edit) { if ($edit->final) { array_splice($lines, count($lines), 0, $edit->final); } } return $lines; } /** * Removes trailing newlines from a line of text. This is meant to be used * with array_walk(). * * @param string $line The line to trim. * @param integer $key The index of the line in the array. Not used. */ static function trimNewlines(&$line, $key) { $line = str_replace(array("\n", "\r"), '', $line); } /** * Determines the location of the system temporary directory. * * @static * * @access protected * * @return string A directory name which can be used for temp files. * Returns false if one could not be found. */ function _getTempDir() { $tmp_locations = array('/tmp', '/var/tmp', 'c:\WUTemp', 'c:\temp', 'c:\windows\temp', 'c:\winnt\temp'); /* Try PHP's upload_tmp_dir directive. */ $tmp = ini_get('upload_tmp_dir'); /* Otherwise, try to determine the TMPDIR environment variable. */ if (!strlen($tmp)) { $tmp = getenv('TMPDIR'); } /* If we still cannot determine a value, then cycle through a list of * preset possibilities. */ while (!strlen($tmp) && count($tmp_locations)) { $tmp_check = array_shift($tmp_locations); if (@is_dir($tmp_check)) { $tmp = $tmp_check; } } /* If it is still empty, we have failed, so return false; otherwise * return the directory determined. */ return strlen($tmp) ? $tmp : false; } /** * Checks a diff for validity. * * This is here only for debugging purposes. */ function _check($from_lines, $to_lines) { if (serialize($from_lines) != serialize($this->getOriginal())) { trigger_error("Reconstructed original doesn't match", E_USER_ERROR); } if (serialize($to_lines) != serialize($this->getFinal())) { trigger_error("Reconstructed final doesn't match", E_USER_ERROR); } $rev = $this->reverse(); if (serialize($to_lines) != serialize($rev->getOriginal())) { trigger_error("Reversed original doesn't match", E_USER_ERROR); } if (serialize($from_lines) != serialize($rev->getFinal())) { trigger_error("Reversed final doesn't match", E_USER_ERROR); } $prevtype = null; foreach ($this->_edits as $edit) { if ($prevtype == get_class($edit)) { trigger_error("Edit sequence is non-optimal", E_USER_ERROR); } $prevtype = get_class($edit); } return true; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> */ class Text_MappedDiff extends Text_Diff { /** * Computes a diff between sequences of strings. * * This can be used to compute things like case-insensitve diffs, or diffs * which ignore changes in white-space. * * @param array $from_lines An array of strings. * @param array $to_lines An array of strings. * @param array $mapped_from_lines This array should have the same size * number of elements as $from_lines. The * elements in $mapped_from_lines and * $mapped_to_lines are what is actually * compared when computing the diff. * @param array $mapped_to_lines This array should have the same number * of elements as $to_lines. */ function Text_MappedDiff($from_lines, $to_lines, $mapped_from_lines, $mapped_to_lines) { assert(count($from_lines) == count($mapped_from_lines)); assert(count($to_lines) == count($mapped_to_lines)); parent::Text_Diff($mapped_from_lines, $mapped_to_lines); $xi = $yi = 0; for ($i = 0; $i < count($this->_edits); $i++) { $orig = &$this->_edits[$i]->orig; if (is_array($orig)) { $orig = array_slice($from_lines, $xi, count($orig)); $xi += count($orig); } $final = &$this->_edits[$i]->final; if (is_array($final)) { $final = array_slice($to_lines, $yi, count($final)); $yi += count($final); } } } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op { var $orig; var $final; function &reverse() { trigger_error('Abstract method', E_USER_ERROR); } function norig() { return $this->orig ? count($this->orig) : 0; } function nfinal() { return $this->final ? count($this->final) : 0; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op_copy extends Text_Diff_Op { function Text_Diff_Op_copy($orig, $final = false) { if (!is_array($final)) { $final = $orig; } $this->orig = $orig; $this->final = $final; } function &reverse() { $reverse = new Text_Diff_Op_copy($this->final, $this->orig); return $reverse; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op_delete extends Text_Diff_Op { function Text_Diff_Op_delete($lines) { $this->orig = $lines; $this->final = false; } function &reverse() { $reverse = new Text_Diff_Op_add($this->orig); return $reverse; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op_add extends Text_Diff_Op { function Text_Diff_Op_add($lines) { $this->final = $lines; $this->orig = false; } function &reverse() { $reverse = new Text_Diff_Op_delete($this->final); return $reverse; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op_change extends Text_Diff_Op { function Text_Diff_Op_change($orig, $final) { $this->orig = $orig; $this->final = $final; } function &reverse() { $reverse = new Text_Diff_Op_change($this->final, $this->orig); return $reverse; } }
Java